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)
|
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)
|
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)
|
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-29 06:35:16 -07:00
|
|
|
# As we will need to notify for each person subscribed,
|
|
|
|
# it's much faster to bulk insert than to use +Notification.notify+
|
2023-08-18 10:43:59 -07:00
|
|
|
notifications = Subscription.for(source, target).pluck(:user_id).map do |recipient_id|
|
|
|
|
{
|
|
|
|
target_id: source.id,
|
|
|
|
target_type: Comment,
|
|
|
|
recipient_id:,
|
|
|
|
new: true,
|
|
|
|
type: Notification::Commented,
|
|
|
|
created_at: source.created_at,
|
|
|
|
updated_at: source.created_at,
|
|
|
|
}
|
2015-04-20 18:12:11 -07:00
|
|
|
end
|
2023-03-05 04:47:46 -08:00
|
|
|
|
2023-06-16 09:18:40 -07:00
|
|
|
return if notifications.empty?
|
|
|
|
|
|
|
|
# rubocop:disable Rails/SkipsModelValidations
|
|
|
|
Notification.insert_all!(notifications)
|
|
|
|
User.where(id: notifications.pluck(:recipient_id)).touch_all(:notifications_updated_at)
|
|
|
|
# rubocop:enable 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?
|
2023-03-05 04:47:46 -08:00
|
|
|
|
|
|
|
subs = Subscription.where(answer: target)
|
|
|
|
Notification.where(target:, recipient: subs.map(&:user)).delete_all
|
2015-04-20 18:12:11 -07:00
|
|
|
end
|
2023-08-18 10:43:59 -07:00
|
|
|
|
|
|
|
def for(source, target)
|
|
|
|
muted_by = Relationships::Mute.where(target: source.user).pluck(&:source_id)
|
|
|
|
|
|
|
|
Subscription.where(answer: target)
|
|
|
|
.where.not(user: source.user)
|
|
|
|
.where.not(user_id: muted_by)
|
|
|
|
end
|
2015-04-20 18:12:11 -07:00
|
|
|
end
|
|
|
|
end
|