status.rb 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  1. # frozen_string_literal: true
  2. # == Schema Information
  3. #
  4. # Table name: statuses
  5. #
  6. # id :bigint(8) not null, primary key
  7. # uri :string
  8. # text :text default(""), not null
  9. # created_at :datetime not null
  10. # updated_at :datetime not null
  11. # in_reply_to_id :bigint(8)
  12. # reblog_of_id :bigint(8)
  13. # url :string
  14. # sensitive :boolean default(FALSE), not null
  15. # visibility :integer default("public"), not null
  16. # spoiler_text :text default(""), not null
  17. # reply :boolean default(FALSE), not null
  18. # language :string
  19. # conversation_id :bigint(8)
  20. # local :boolean
  21. # account_id :bigint(8) not null
  22. # application_id :bigint(8)
  23. # in_reply_to_account_id :bigint(8)
  24. # poll_id :bigint(8)
  25. # deleted_at :datetime
  26. # edited_at :datetime
  27. # trendable :boolean
  28. # ordered_media_attachment_ids :bigint(8) is an Array
  29. #
  30. class Status < ApplicationRecord
  31. include Cacheable
  32. include Discard::Model
  33. include Paginable
  34. include RateLimitable
  35. include Status::SafeReblogInsert
  36. include Status::SearchConcern
  37. include Status::SnapshotConcern
  38. include Status::ThreadingConcern
  39. rate_limit by: :account, family: :statuses
  40. self.discard_column = :deleted_at
  41. # If `override_timestamps` is set at creation time, Snowflake ID creation
  42. # will be based on current time instead of `created_at`
  43. attr_accessor :override_timestamps
  44. update_index('statuses', :proper)
  45. update_index('public_statuses', :proper)
  46. enum :visibility, { public: 0, unlisted: 1, private: 2, direct: 3, limited: 4 }, suffix: :visibility
  47. belongs_to :application, class_name: 'Doorkeeper::Application', optional: true
  48. belongs_to :account, inverse_of: :statuses
  49. belongs_to :in_reply_to_account, class_name: 'Account', optional: true
  50. belongs_to :conversation, optional: true
  51. belongs_to :preloadable_poll, class_name: 'Poll', foreign_key: 'poll_id', optional: true, inverse_of: false
  52. with_options class_name: 'Status', optional: true do
  53. belongs_to :thread, foreign_key: 'in_reply_to_id', inverse_of: :replies
  54. belongs_to :reblog, foreign_key: 'reblog_of_id', inverse_of: :reblogs
  55. end
  56. has_many :favourites, inverse_of: :status, dependent: :destroy
  57. has_many :bookmarks, inverse_of: :status, dependent: :destroy
  58. has_many :reblogs, foreign_key: 'reblog_of_id', class_name: 'Status', inverse_of: :reblog, dependent: :destroy
  59. has_many :reblogged_by_accounts, through: :reblogs, class_name: 'Account', source: :account
  60. has_many :replies, foreign_key: 'in_reply_to_id', class_name: 'Status', inverse_of: :thread, dependent: nil
  61. has_many :mentions, dependent: :destroy, inverse_of: :status
  62. has_many :mentioned_accounts, through: :mentions, source: :account, class_name: 'Account'
  63. has_many :media_attachments, dependent: :nullify
  64. # The `dependent` option is enabled by the initial `mentions` association declaration
  65. has_many :active_mentions, -> { active }, class_name: 'Mention', inverse_of: :status # rubocop:disable Rails/HasManyOrHasOneDependent
  66. # Those associations are used for the private search index
  67. has_many :local_mentioned, -> { merge(Account.local) }, through: :active_mentions, source: :account
  68. has_many :local_favorited, -> { merge(Account.local) }, through: :favourites, source: :account
  69. has_many :local_reblogged, -> { merge(Account.local) }, through: :reblogs, source: :account
  70. has_many :local_bookmarked, -> { merge(Account.local) }, through: :bookmarks, source: :account
  71. has_and_belongs_to_many :tags
  72. has_one :preview_cards_status, inverse_of: :status, dependent: :delete
  73. has_one :local_preview_card, inverse_of: :status, dependent: :delete
  74. has_one :notification, as: :activity, dependent: :destroy
  75. has_one :status_stat, inverse_of: :status, dependent: nil
  76. has_one :poll, inverse_of: :status, dependent: :destroy
  77. has_one :trend, class_name: 'StatusTrend', inverse_of: :status, dependent: nil
  78. validates :uri, uniqueness: true, presence: true, unless: :local?
  79. validates :text, presence: true, unless: -> { with_media? || reblog? }
  80. validates_with StatusLengthValidator
  81. validates_with DisallowedHashtagsValidator
  82. validates :reblog, uniqueness: { scope: :account }, if: :reblog?
  83. validates :visibility, exclusion: { in: %w(direct limited) }, if: :reblog?
  84. accepts_nested_attributes_for :poll
  85. default_scope { recent.kept }
  86. scope :recent, -> { reorder(id: :desc) }
  87. scope :remote, -> { where(local: false).where.not(uri: nil) }
  88. scope :local, -> { where(local: true).or(where(uri: nil)) }
  89. scope :with_accounts, ->(ids) { where(id: ids).includes(:account) }
  90. scope :without_replies, -> { where('statuses.reply = FALSE OR statuses.in_reply_to_account_id = statuses.account_id') }
  91. scope :without_reblogs, -> { where(statuses: { reblog_of_id: nil }) }
  92. scope :with_public_visibility, -> { where(visibility: :public) }
  93. scope :tagged_with, ->(tag_ids) { joins(:statuses_tags).where(statuses_tags: { tag_id: tag_ids }) }
  94. scope :not_excluded_by_account, ->(account) { where.not(account_id: account.excluded_from_timeline_account_ids) }
  95. scope :not_domain_blocked_by_account, ->(account) { account.excluded_from_timeline_domains.blank? ? left_outer_joins(:account) : left_outer_joins(:account).where('accounts.domain IS NULL OR accounts.domain NOT IN (?)', account.excluded_from_timeline_domains) }
  96. scope :tagged_with_all, lambda { |tag_ids|
  97. Array(tag_ids).map(&:to_i).reduce(self) do |result, id|
  98. result.where(<<~SQL.squish, tag_id: id)
  99. EXISTS(SELECT 1 FROM statuses_tags WHERE statuses_tags.status_id = statuses.id AND statuses_tags.tag_id = :tag_id)
  100. SQL
  101. end
  102. }
  103. scope :tagged_with_none, lambda { |tag_ids|
  104. where('NOT EXISTS (SELECT * FROM statuses_tags forbidden WHERE forbidden.status_id = statuses.id AND forbidden.tag_id IN (?))', tag_ids)
  105. }
  106. after_create_commit :trigger_create_webhooks
  107. after_update_commit :trigger_update_webhooks
  108. after_create_commit :increment_counter_caches
  109. after_destroy_commit :decrement_counter_caches
  110. after_create_commit :store_uri, if: :local?
  111. after_create_commit :update_statistics, if: :local?
  112. before_validation :prepare_contents, if: :local?
  113. before_validation :set_reblog
  114. before_validation :set_visibility
  115. before_validation :set_conversation
  116. before_validation :set_local
  117. around_create Mastodon::Snowflake::Callbacks
  118. after_create :set_poll_id
  119. # The `prepend: true` option below ensures this runs before
  120. # the `dependent: destroy` callbacks remove relevant records
  121. before_destroy :unlink_from_conversations!, prepend: true
  122. cache_associated :application,
  123. :media_attachments,
  124. :conversation,
  125. :status_stat,
  126. :tags,
  127. :preloadable_poll,
  128. :local_preview_card,
  129. preview_cards_status: [:preview_card],
  130. account: [:account_stat, user: :role],
  131. active_mentions: { account: :account_stat },
  132. reblog: [
  133. :application,
  134. :tags,
  135. :media_attachments,
  136. :conversation,
  137. :status_stat,
  138. :preloadable_poll,
  139. :local_preview_card,
  140. preview_cards_status: [:preview_card],
  141. account: [:account_stat, user: :role],
  142. active_mentions: { account: :account_stat },
  143. ],
  144. thread: { account: :account_stat }
  145. delegate :domain, to: :account, prefix: true
  146. REAL_TIME_WINDOW = 6.hours
  147. def cache_key
  148. "v3:#{super}"
  149. end
  150. def to_log_human_identifier
  151. account.acct
  152. end
  153. def to_log_permalink
  154. ActivityPub::TagManager.instance.uri_for(self)
  155. end
  156. def reply?
  157. !in_reply_to_id.nil? || attributes['reply']
  158. end
  159. def local?
  160. attributes['local'] || uri.nil?
  161. end
  162. def in_reply_to_local_account?
  163. reply? && thread&.account&.local?
  164. end
  165. def reblog?
  166. !reblog_of_id.nil?
  167. end
  168. def within_realtime_window?
  169. created_at >= REAL_TIME_WINDOW.ago
  170. end
  171. def verb
  172. if destroyed?
  173. :delete
  174. else
  175. reblog? ? :share : :post
  176. end
  177. end
  178. def object_type
  179. reply? ? :comment : :note
  180. end
  181. def proper
  182. reblog? ? reblog : self
  183. end
  184. def content
  185. proper.text
  186. end
  187. def target
  188. reblog
  189. end
  190. def preview_card
  191. local_preview_card || preview_cards_status&.preview_card&.tap { |x| x.original_url = preview_cards_status.url }
  192. end
  193. def reset_preview_card!
  194. LocalPreviewCard.where(status_id: id).delete_all
  195. PreviewCardsStatus.where(status_id: id).delete_all
  196. end
  197. def hidden?
  198. !distributable?
  199. end
  200. def distributable?
  201. public_visibility? || unlisted_visibility?
  202. end
  203. alias sign? distributable?
  204. def with_media?
  205. ordered_media_attachments.any?
  206. end
  207. def with_preview_card?
  208. local_preview_card.present? || preview_cards_status.present?
  209. end
  210. def with_poll?
  211. preloadable_poll.present?
  212. end
  213. def non_sensitive_with_media?
  214. !sensitive? && with_media?
  215. end
  216. def reported?
  217. @reported ||= Report.where(target_account: account).unresolved.exists?(['? = ANY(status_ids)', id])
  218. end
  219. def emojis
  220. return @emojis if defined?(@emojis)
  221. fields = [spoiler_text, text]
  222. fields += preloadable_poll.options unless preloadable_poll.nil?
  223. @emojis = CustomEmoji.from_text(fields.join(' '), account.domain)
  224. end
  225. def ordered_media_attachments
  226. if ordered_media_attachment_ids.nil?
  227. # NOTE: sort Ruby-side to avoid hitting the database when the status is
  228. # not persisted to database yet
  229. media_attachments.sort_by(&:id)
  230. else
  231. map = media_attachments.index_by(&:id)
  232. ordered_media_attachment_ids.filter_map { |media_attachment_id| map[media_attachment_id] }
  233. end
  234. end
  235. def replies_count
  236. status_stat&.replies_count || 0
  237. end
  238. def reblogs_count
  239. status_stat&.reblogs_count || 0
  240. end
  241. def favourites_count
  242. status_stat&.favourites_count || 0
  243. end
  244. def increment_count!(key)
  245. update_status_stat!(key => public_send(key) + 1)
  246. end
  247. def decrement_count!(key)
  248. update_status_stat!(key => [public_send(key) - 1, 0].max)
  249. end
  250. def trendable?
  251. if attributes['trendable'].nil?
  252. account.trendable?
  253. else
  254. attributes['trendable']
  255. end
  256. end
  257. def requires_review?
  258. attributes['trendable'].nil? && account.requires_review?
  259. end
  260. def requires_review_notification?
  261. attributes['trendable'].nil? && account.requires_review_notification?
  262. end
  263. class << self
  264. def selectable_visibilities
  265. visibilities.keys - %w(direct limited)
  266. end
  267. def favourites_map(status_ids, account_id)
  268. Favourite.select('status_id').where(status_id: status_ids).where(account_id: account_id).each_with_object({}) { |f, h| h[f.status_id] = true }
  269. end
  270. def bookmarks_map(status_ids, account_id)
  271. Bookmark.select('status_id').where(status_id: status_ids).where(account_id: account_id).map { |f| [f.status_id, true] }.to_h
  272. end
  273. def reblogs_map(status_ids, account_id)
  274. unscoped.select('reblog_of_id').where(reblog_of_id: status_ids).where(account_id: account_id).each_with_object({}) { |s, h| h[s.reblog_of_id] = true }
  275. end
  276. def mutes_map(conversation_ids, account_id)
  277. ConversationMute.select('conversation_id').where(conversation_id: conversation_ids).where(account_id: account_id).each_with_object({}) { |m, h| h[m.conversation_id] = true }
  278. end
  279. def pins_map(status_ids, account_id)
  280. StatusPin.select('status_id').where(status_id: status_ids).where(account_id: account_id).each_with_object({}) { |p, h| h[p.status_id] = true }
  281. end
  282. def reload_stale_associations!(cached_items)
  283. account_ids = []
  284. cached_items.each do |item|
  285. account_ids << item.account_id
  286. account_ids << item.reblog.account_id if item.reblog?
  287. end
  288. account_ids.uniq!
  289. status_ids = cached_items.map { |item| item.reblog? ? item.reblog_of_id : item.id }.uniq
  290. return if account_ids.empty?
  291. accounts = Account.where(id: account_ids).includes(:account_stat, :user).index_by(&:id)
  292. status_stats = StatusStat.where(status_id: status_ids).index_by(&:status_id)
  293. cached_items.each do |item|
  294. item.account = accounts[item.account_id]
  295. item.reblog.account = accounts[item.reblog.account_id] if item.reblog?
  296. if item.reblog?
  297. status_stat = status_stats[item.reblog.id]
  298. item.reblog.status_stat = status_stat if status_stat.present?
  299. else
  300. status_stat = status_stats[item.id]
  301. item.status_stat = status_stat if status_stat.present?
  302. end
  303. end
  304. end
  305. def from_text(text)
  306. return [] if text.blank?
  307. text.scan(FetchLinkCardService::URL_PATTERN).map(&:second).uniq.filter_map do |url|
  308. status = if TagManager.instance.local_url?(url)
  309. ActivityPub::TagManager.instance.uri_to_resource(url, Status)
  310. else
  311. EntityCache.instance.status(url)
  312. end
  313. status&.distributable? ? status : nil
  314. end
  315. end
  316. end
  317. def status_stat
  318. super || build_status_stat
  319. end
  320. def discard_with_reblogs
  321. discard_time = Time.current
  322. Status.unscoped.where(reblog_of_id: id, deleted_at: [nil, deleted_at]).in_batches.update_all(deleted_at: discard_time) unless reblog?
  323. update_attribute(:deleted_at, discard_time)
  324. end
  325. def unlink_from_conversations!
  326. return unless direct_visibility?
  327. inbox_owners = mentioned_accounts.local
  328. inbox_owners += [account] if account.local?
  329. inbox_owners.each do |inbox_owner|
  330. AccountConversation.remove_status(inbox_owner, self)
  331. end
  332. end
  333. private
  334. def update_status_stat!(attrs)
  335. return if marked_for_destruction? || destroyed?
  336. status_stat.update(attrs)
  337. end
  338. def store_uri
  339. update_column(:uri, ActivityPub::TagManager.instance.uri_for(self)) if uri.nil?
  340. end
  341. def prepare_contents
  342. text&.strip!
  343. spoiler_text&.strip!
  344. end
  345. def set_reblog
  346. self.reblog = reblog.reblog if reblog? && reblog.reblog?
  347. end
  348. def set_poll_id
  349. update_column(:poll_id, poll.id) if association(:poll).loaded? && poll.present?
  350. end
  351. def set_visibility
  352. self.visibility = reblog.visibility if reblog? && visibility.nil?
  353. self.visibility = (account.locked? ? :private : :public) if visibility.nil?
  354. self.sensitive = false if sensitive.nil?
  355. end
  356. def set_conversation
  357. self.thread = thread.reblog if thread&.reblog?
  358. self.reply = !(in_reply_to_id.nil? && thread.nil?) unless reply
  359. if reply? && !thread.nil?
  360. self.in_reply_to_account_id = carried_over_reply_to_account_id
  361. self.conversation_id = thread.conversation_id if conversation_id.nil?
  362. elsif conversation_id.nil?
  363. self.conversation = Conversation.new
  364. end
  365. end
  366. def carried_over_reply_to_account_id
  367. if thread.account_id == account_id && thread.reply?
  368. thread.in_reply_to_account_id
  369. else
  370. thread.account_id
  371. end
  372. end
  373. def set_local
  374. self.local = account.local?
  375. end
  376. def update_statistics
  377. return unless distributable?
  378. ActivityTracker.increment('activity:statuses:local')
  379. end
  380. def increment_counter_caches
  381. return if direct_visibility?
  382. account&.increment_count!(:statuses_count)
  383. reblog&.increment_count!(:reblogs_count) if reblog?
  384. thread&.increment_count!(:replies_count) if in_reply_to_id.present? && distributable?
  385. end
  386. def decrement_counter_caches
  387. return if direct_visibility? || new_record?
  388. account&.decrement_count!(:statuses_count)
  389. reblog&.decrement_count!(:reblogs_count) if reblog?
  390. thread&.decrement_count!(:replies_count) if in_reply_to_id.present? && distributable?
  391. end
  392. def trigger_create_webhooks
  393. TriggerWebhookWorker.perform_async('status.created', 'Status', id) if local?
  394. end
  395. def trigger_update_webhooks
  396. TriggerWebhookWorker.perform_async('status.updated', 'Status', id) if local?
  397. end
  398. end