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
|
2023-03-04 11:42:51 -08:00
|
|
|
def subscribe(recipient, target)
|
2015-04-21 05:22:32 -07:00
|
|
|
existing = Subscription.find_by(user: recipient, answer: target)
|
2023-03-04 11:42:51 -08:00
|
|
|
return true if existing.present?
|
|
|
|
|
|
|
|
Subscription.create!(user: recipient, answer: target)
|
2015-04-20 18:12:11 -07:00
|
|
|
end
|
|
|
|
|
|
|
|
def unsubscribe(recipient, target)
|
|
|
|
if recipient.nil? or target.nil?
|
|
|
|
return nil
|
|
|
|
end
|
|
|
|
|
|
|
|
subs = Subscription.find_by(user: recipient, answer: target)
|
2023-03-04 11:42:51 -08:00
|
|
|
subs&.destroy
|
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
|
|
|
|
|
|
|
|
def notify(source, target)
|
2023-03-05 04:47:46 -08:00
|
|
|
return nil if source.nil? || target.nil?
|
2015-04-20 18:12:11 -07:00
|
|
|
|
2023-03-05 04:47:46 -08:00
|
|
|
notifications = Subscription.where(answer: target).where.not(user: target.user).map do |s|
|
|
|
|
{ target_id: source.id, target_type: Comment, recipient_id: s.user_id, new: true, type: Notification::Commented }
|
2015-04-20 18:12:11 -07:00
|
|
|
end
|
2023-03-05 04:47:46 -08:00
|
|
|
|
|
|
|
Notification.insert_all!(notifications)
|
2015-04-20 18:12:11 -07:00
|
|
|
end
|
|
|
|
|
|
|
|
def denotify(source, target)
|
2023-03-05 04:47:46 -08:00
|
|
|
return nil if source.nil? or target.nil?
|
|
|
|
|
|
|
|
subs = Subscription.where(answer: target)
|
|
|
|
Notification.where(target:, recipient: subs.map(&:user)).delete_all
|
2015-04-20 18:12:11 -07:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|