You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

91 lines
2.6 KiB

  1. # frozen_string_literal: true
  2. class Notification < ApplicationRecord
  3. include Paginable
  4. include Cacheable
  5. belongs_to :account
  6. belongs_to :from_account, class_name: 'Account'
  7. belongs_to :activity, polymorphic: true
  8. belongs_to :mention, foreign_type: 'Mention', foreign_key: 'activity_id'
  9. belongs_to :status, foreign_type: 'Status', foreign_key: 'activity_id'
  10. belongs_to :follow, foreign_type: 'Follow', foreign_key: 'activity_id'
  11. belongs_to :follow_request, foreign_type: 'FollowRequest', foreign_key: 'activity_id'
  12. belongs_to :favourite, foreign_type: 'Favourite', foreign_key: 'activity_id'
  13. validates :account_id, uniqueness: { scope: [:activity_type, :activity_id] }
  14. TYPE_CLASS_MAP = {
  15. mention: 'Mention',
  16. reblog: 'Status',
  17. follow: 'Follow',
  18. follow_request: 'FollowRequest',
  19. favourite: 'Favourite',
  20. }.freeze
  21. STATUS_INCLUDES = [:account, :stream_entry, :media_attachments, :tags, mentions: :account, reblog: [:stream_entry, :account, :media_attachments, :tags, mentions: :account]].freeze
  22. scope :cache_ids, -> { select(:id, :updated_at, :activity_type, :activity_id) }
  23. cache_associated :from_account, status: STATUS_INCLUDES, mention: [status: STATUS_INCLUDES], favourite: [:account, status: STATUS_INCLUDES], follow: :account
  24. def activity(eager_loaded = true)
  25. eager_loaded ? send(activity_type.downcase) : super
  26. end
  27. def type
  28. @type ||= TYPE_CLASS_MAP.invert[activity_type].to_sym
  29. end
  30. def target_status
  31. case type
  32. when :reblog
  33. activity&.reblog
  34. when :favourite, :mention
  35. activity&.status
  36. end
  37. end
  38. def browserable?
  39. type != :follow_request
  40. end
  41. class << self
  42. def browserable(types = [])
  43. types.concat([:follow_request])
  44. where.not(activity_type: activity_types_from_types(types))
  45. end
  46. def reload_stale_associations!(cached_items)
  47. account_ids = cached_items.map(&:from_account_id).uniq
  48. accounts = Account.where(id: account_ids).map { |a| [a.id, a] }.to_h
  49. cached_items.each do |item|
  50. item.from_account = accounts[item.from_account_id]
  51. end
  52. end
  53. private
  54. def activity_types_from_types(types)
  55. types.map { |type| TYPE_CLASS_MAP[type.to_sym] }.compact
  56. end
  57. end
  58. after_initialize :set_from_account
  59. before_validation :set_from_account
  60. private
  61. def set_from_account
  62. return unless new_record?
  63. case activity_type
  64. when 'Status', 'Follow', 'Favourite', 'FollowRequest'
  65. self.from_account_id = activity(false)&.account_id
  66. when 'Mention'
  67. self.from_account_id = activity(false)&.status&.account_id
  68. end
  69. end
  70. end