2023-03-05 13:48:59 +01:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2020-04-19 00:59:18 +02:00
|
|
|
class Subscription < ApplicationRecord
|
2015-04-21 03:12:11 +02:00
|
|
|
belongs_to :user
|
|
|
|
belongs_to :answer
|
|
|
|
|
|
|
|
class << self
|
2023-03-04 20:42:51 +01:00
|
|
|
def subscribe(recipient, target)
|
2015-04-21 14:22:32 +02:00
|
|
|
existing = Subscription.find_by(user: recipient, answer: target)
|
2023-03-04 20:42:51 +01:00
|
|
|
return true if existing.present?
|
|
|
|
|
|
|
|
Subscription.create!(user: recipient, answer: target)
|
2015-04-21 03:12:11 +02:00
|
|
|
end
|
|
|
|
|
|
|
|
def unsubscribe(recipient, target)
|
2023-03-05 13:48:59 +01:00
|
|
|
return nil if recipient.nil? || target.nil?
|
2015-04-21 03:12:11 +02:00
|
|
|
|
|
|
|
subs = Subscription.find_by(user: recipient, answer: target)
|
2023-03-04 20:42:51 +01:00
|
|
|
subs&.destroy
|
2015-04-21 03:12:11 +02:00
|
|
|
end
|
|
|
|
|
|
|
|
def destruct(target)
|
2023-03-05 13:48:59 +01:00
|
|
|
return nil if target.nil?
|
|
|
|
|
2015-04-21 03:12:11 +02:00
|
|
|
Subscription.where(answer: target).destroy_all
|
|
|
|
end
|
|
|
|
|
|
|
|
def notify(source, target)
|
2023-03-05 13:47:46 +01:00
|
|
|
return nil if source.nil? || target.nil?
|
2015-04-21 03:12:11 +02:00
|
|
|
|
2023-03-29 15:35:16 +02: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 19:43:59 +02: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-21 03:12:11 +02:00
|
|
|
end
|
2023-03-05 13:47:46 +01:00
|
|
|
|
2023-06-16 18:18:40 +02: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-21 03:12:11 +02:00
|
|
|
end
|
|
|
|
|
|
|
|
def denotify(source, target)
|
2023-03-05 13:48:59 +01:00
|
|
|
return nil if source.nil? || target.nil?
|
2023-03-05 13:47:46 +01:00
|
|
|
|
|
|
|
subs = Subscription.where(answer: target)
|
|
|
|
Notification.where(target:, recipient: subs.map(&:user)).delete_all
|
2015-04-21 03:12:11 +02:00
|
|
|
end
|
2023-08-18 19:43:59 +02: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-21 03:12:11 +02:00
|
|
|
end
|
|
|
|
end
|