闭社主体 forked from https://github.com/tootsuite/mastodon
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.

76 lines
2.3 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. STATUS_INCLUDES = [:account, :stream_entry, :media_attachments, :tags, mentions: :account, reblog: [:stream_entry, :account, :media_attachments, :tags, mentions: :account]].freeze
  15. scope :cache_ids, -> { select(:id, :updated_at, :activity_type, :activity_id) }
  16. scope :browserable, -> { where.not(activity_type: ['FollowRequest']) }
  17. cache_associated :from_account, status: STATUS_INCLUDES, mention: [status: STATUS_INCLUDES], favourite: [:account, status: STATUS_INCLUDES], follow: :account
  18. def activity(eager_loaded = true)
  19. eager_loaded ? send(activity_type.downcase) : super
  20. end
  21. def type
  22. case activity_type
  23. when 'Status'
  24. :reblog
  25. else
  26. activity_type.underscore.to_sym
  27. end
  28. end
  29. def target_status
  30. case type
  31. when :reblog
  32. activity.reblog
  33. when :favourite, :mention
  34. activity.status
  35. end
  36. end
  37. def browserable?
  38. type != :follow_request
  39. end
  40. class << self
  41. def reload_stale_associations!(cached_items)
  42. account_ids = cached_items.map(&:from_account_id).uniq
  43. accounts = Account.where(id: account_ids).map { |a| [a.id, a] }.to_h
  44. cached_items.each do |item|
  45. item.from_account = accounts[item.from_account_id]
  46. end
  47. end
  48. end
  49. after_initialize :set_from_account
  50. before_validation :set_from_account
  51. private
  52. def set_from_account
  53. case activity_type
  54. when 'Status', 'Follow', 'Favourite', 'FollowRequest'
  55. self.from_account_id = activity(false)&.account_id
  56. when 'Mention'
  57. self.from_account_id = activity(false)&.status&.account_id
  58. end
  59. end
  60. end