2020-04-18 15:59:18 -07:00
|
|
|
class Subscription < ApplicationRecord
|
2015-04-20 18:12:11 -07:00
|
|
|
belongs_to :user
|
|
|
|
belongs_to :answer
|
|
|
|
|
|
|
|
class << self
|
2015-04-21 05:22:32 -07:00
|
|
|
def for(target)
|
|
|
|
Subscription.where(answer: target)
|
|
|
|
end
|
|
|
|
|
|
|
|
def subscribe(recipient, target, force = true)
|
|
|
|
existing = Subscription.find_by(user: recipient, answer: target)
|
|
|
|
if existing.nil?
|
2015-04-20 18:12:11 -07:00
|
|
|
Subscription.new(user: recipient, answer: target).save!
|
2015-04-21 05:22:32 -07:00
|
|
|
elsif force
|
|
|
|
existing.update(is_active: true)
|
2015-04-20 18:12:11 -07:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def unsubscribe(recipient, target)
|
|
|
|
if recipient.nil? or target.nil?
|
|
|
|
return nil
|
|
|
|
end
|
|
|
|
|
|
|
|
subs = Subscription.find_by(user: recipient, answer: target)
|
2015-04-21 05:22:32 -07:00
|
|
|
subs.update(is_active: false) unless subs.nil?
|
2015-04-20 18:12:11 -07:00
|
|
|
end
|
|
|
|
|
|
|
|
def destruct(target)
|
|
|
|
if target.nil?
|
|
|
|
return nil
|
|
|
|
end
|
|
|
|
Subscription.where(answer: target).destroy_all
|
|
|
|
end
|
|
|
|
|
2015-04-21 05:22:32 -07:00
|
|
|
def destruct_by(recipient, target)
|
|
|
|
if recipient.nil? or target.nil?
|
|
|
|
return nil
|
|
|
|
end
|
|
|
|
|
|
|
|
subs = Subscription.find_by(user: recipient, answer: target)
|
|
|
|
subs.destroy unless subs.nil?
|
|
|
|
end
|
|
|
|
|
2015-04-20 18:12:11 -07:00
|
|
|
def notify(source, target)
|
|
|
|
if source.nil? or target.nil?
|
|
|
|
return nil
|
|
|
|
end
|
|
|
|
|
2015-04-21 05:22:32 -07:00
|
|
|
Subscription.where(answer: target, is_active: true).each do |subs|
|
2015-04-20 18:12:11 -07:00
|
|
|
next unless not subs.user == source.user
|
|
|
|
Notification.notify subs.user, source
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def denotify(source, target)
|
|
|
|
if source.nil? or target.nil?
|
|
|
|
return nil
|
|
|
|
end
|
|
|
|
Subscription.where(answer: target).each do |subs|
|
|
|
|
Notification.denotify subs.user, source
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|