Retrospring/app/models/subscription.rb

53 lines
1.6 KiB
Ruby
Raw Normal View History

2023-03-05 04:48:59 -08:00
# frozen_string_literal: true
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)
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)
2023-03-05 04:48:59 -08:00
return nil if recipient.nil? || target.nil?
2015-04-20 18:12:11 -07:00
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)
2023-03-05 04:48:59 -08:00
return nil if target.nil?
2015-04-20 18:12:11 -07:00
Subscription.where(answer: target).destroy_all
end
def notify(source, target)
return nil if source.nil? || target.nil?
2015-04-20 18:12:11 -07:00
muted_by = Relationships::Mute.where(target: source.user).pluck(&:source_id)
# As we will need to notify for each person subscribed,
# it's much faster to bulk insert than to use +Notification.notify+
notifications = Subscription.where(answer: target)
.where.not(user: source.user)
.where.not(user_id: muted_by)
.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
Notification.insert_all!(notifications) unless notifications.empty? # rubocop:disable Rails/SkipsModelValidations
2015-04-20 18:12:11 -07:00
end
def denotify(source, target)
2023-03-05 04:48:59 -08:00
return nil if source.nil? || 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