1
0

status.rb 16 KB

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