2022-07-21 07:56:05 -07:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2020-04-18 15:59:18 -07:00
|
|
|
class Notification < ApplicationRecord
|
2023-02-25 06:46:11 -08:00
|
|
|
belongs_to :recipient, class_name: "User", touch: :notifications_updated_at
|
2014-12-14 05:49:14 -08:00
|
|
|
belongs_to :target, polymorphic: true
|
2014-12-14 05:34:51 -08:00
|
|
|
|
|
|
|
class << self
|
2020-04-20 14:03:57 -07:00
|
|
|
include CursorPaginatable
|
|
|
|
|
|
|
|
define_cursor_paginator :cursored_for, :for
|
|
|
|
define_cursor_paginator :cursored_for_type, :for_type
|
|
|
|
|
2022-07-21 12:22:23 -07:00
|
|
|
def for(recipient, **kwargs)
|
2023-03-04 08:50:53 -08:00
|
|
|
where(kwargs.merge!(recipient:)).order(:created_at).reverse_order
|
2014-12-14 05:34:51 -08:00
|
|
|
end
|
|
|
|
|
2022-07-21 12:22:23 -07:00
|
|
|
def for_type(recipient, type, **kwargs)
|
2023-03-04 08:50:53 -08:00
|
|
|
where(kwargs.merge!(recipient:)).where(type:).order(:created_at).reverse_order
|
2020-04-20 14:03:57 -07:00
|
|
|
end
|
|
|
|
|
2014-12-14 05:34:51 -08:00
|
|
|
def notify(recipient, target)
|
|
|
|
return nil unless target.respond_to? :notification_type
|
|
|
|
|
|
|
|
notif_type = target.notification_type
|
|
|
|
return nil unless notif_type
|
|
|
|
|
|
|
|
make_notification(recipient, target, notif_type)
|
|
|
|
end
|
|
|
|
|
2014-12-14 06:42:37 -08:00
|
|
|
def denotify(recipient, target)
|
2022-07-14 14:53:02 -07:00
|
|
|
return nil if recipient.blank?
|
2014-12-14 06:42:37 -08:00
|
|
|
return nil unless target.respond_to? :notification_type
|
|
|
|
|
|
|
|
notif_type = target.notification_type
|
|
|
|
return nil unless notif_type
|
|
|
|
|
2022-12-28 20:17:04 -08:00
|
|
|
notif = Notification.find_by(recipient:, target:)
|
2022-07-21 07:56:05 -07:00
|
|
|
notif&.destroy
|
2014-12-14 06:42:37 -08:00
|
|
|
end
|
|
|
|
|
2014-12-14 05:34:51 -08:00
|
|
|
private
|
|
|
|
|
2022-07-21 07:30:04 -07:00
|
|
|
def make_notification(recipient, target, notification_type)
|
2022-12-28 07:33:19 -08:00
|
|
|
return if get_notification_owner(target).present? && recipient.muting?(get_notification_owner(target))
|
|
|
|
|
2022-12-28 20:17:04 -08:00
|
|
|
n = notification_type.new(target:,
|
|
|
|
recipient:,
|
2022-07-21 07:56:05 -07:00
|
|
|
new: true)
|
2022-07-21 07:30:04 -07:00
|
|
|
n.save!
|
|
|
|
n
|
|
|
|
end
|
2022-12-28 07:33:19 -08:00
|
|
|
|
|
|
|
def get_notification_owner(target)
|
|
|
|
if target.is_a? User
|
|
|
|
target
|
2022-12-28 18:31:33 -08:00
|
|
|
elsif target.try(:user) && target.user.is_a?(User)
|
2022-12-28 07:33:19 -08:00
|
|
|
target.user
|
2022-12-28 18:31:33 -08:00
|
|
|
elsif target.try(:source) && target.source.is_a?(User)
|
2022-12-28 07:33:19 -08:00
|
|
|
target.source
|
|
|
|
end
|
|
|
|
end
|
2014-12-14 05:34:51 -08:00
|
|
|
end
|
2014-12-13 10:30:10 -08:00
|
|
|
end
|