闭社主体 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.

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