-
Notifications
You must be signed in to change notification settings - Fork 0
/
user.rb
79 lines (67 loc) · 2.62 KB
/
user.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
class User < ApplicationRecord
self.primary_key = :id
include Moderatable
ALLOWED_LOGIN_CHARACTERS = '\w\-\.'.freeze
has_many :mentions, as: :mentionable
has_many :roles
has_many :user_conversations
has_many :conversations, through: :user_conversations
has_many :notifications
has_many :subscriptions
has_many :subscription_preferences
has_many :blocked_users
has_one :unsubscribe_token
scope :with_roles, ->(*roles, on:){ joins(:roles).merge Role.where(section: on, name: roles) }
scope :admins, ->(on:){ with_roles 'admin', on: on }
scope :moderators, ->(on:){ with_roles 'moderator', on: on }
scope :scientists, ->(on:){ with_roles 'scientist', on: on }
singleton_class.send :alias_method, :researchers, :scientists
scope :team, ->(on:){ with_roles 'moderator', 'admin', 'scientist', 'team', on: on }
moderatable_with :ignore, by: [:moderator, :admin]
moderatable_with :report, by: [:all]
moderatable_with :watch, by: [:moderator, :admin]
def self.from_panoptes(bearer_token)
token = OauthAccessToken.find_by_token bearer_token
token.resource_owner
rescue
nil
end
def mentioned_by(comment)
subscription = subscribe_to comment.discussion, :mentions
Notification.create({
source: comment,
user_id: id,
message: "You were mentioned by #{ comment.user.display_name } in #{ comment.discussion.title }",
url: FrontEnd.link_to(comment),
section: comment.section,
subscription: subscription
}) if subscription.try(:enabled?)
end
def group_mentioned_by(group_mention)
subscription = subscribe_to group_mention.comment.discussion, :group_mentions
Notification.create({
source: group_mention.comment,
user_id: id,
message: "You were mentioned as @#{ group_mention.name.singularize } by #{ group_mention.user.display_name } in #{ group_mention.comment.discussion.title }",
url: FrontEnd.link_to(group_mention.comment),
section: group_mention.section,
subscription: subscription
}) if subscription.try(:enabled?)
end
def preference_for(category)
SubscriptionPreference.find_or_default_for self, category
end
def subscribe_to(source, category)
preference = preference_for category
return unless preference.enabled?
category = Subscription.categories[category]
Subscription.where(user: self, category: category, source: source).first_or_create
rescue
nil
end
def unsubscribe_from(source, category = nil)
query = { user: self, source: source }
query[:category] = Subscription.categories[category] if category
Subscription.where(query).update_all enabled: false
end
end