status.rb 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  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. before_destroy :unlink_from_conversations
  32. include Discard::Model
  33. include Paginable
  34. include Cacheable
  35. include StatusThreadingConcern
  36. include StatusSnapshotConcern
  37. include RateLimitable
  38. rate_limit by: :account, family: :statuses
  39. self.discard_column = :deleted_at
  40. # If `override_timestamps` is set at creation time, Snowflake ID creation
  41. # will be based on current time instead of `created_at`
  42. attr_accessor :override_timestamps
  43. update_index('statuses', :proper)
  44. enum visibility: [:public, :unlisted, :private, :direct, :limited], _suffix: :visibility
  45. belongs_to :application, class_name: 'Doorkeeper::Application', optional: true
  46. belongs_to :account, inverse_of: :statuses
  47. belongs_to :in_reply_to_account, foreign_key: 'in_reply_to_account_id', class_name: 'Account', optional: true
  48. belongs_to :conversation, optional: true
  49. belongs_to :preloadable_poll, class_name: 'Poll', foreign_key: 'poll_id', optional: true
  50. belongs_to :thread, foreign_key: 'in_reply_to_id', class_name: 'Status', inverse_of: :replies, optional: true
  51. belongs_to :reblog, foreign_key: 'reblog_of_id', class_name: 'Status', inverse_of: :reblogs, optional: true
  52. has_many :favourites, inverse_of: :status, dependent: :destroy
  53. has_many :bookmarks, inverse_of: :status, dependent: :destroy
  54. has_many :reblogs, foreign_key: 'reblog_of_id', class_name: 'Status', inverse_of: :reblog, dependent: :destroy
  55. has_many :reblogged_by_accounts, through: :reblogs, class_name: 'Account', source: :account
  56. has_many :replies, foreign_key: 'in_reply_to_id', class_name: 'Status', inverse_of: :thread
  57. has_many :mentions, dependent: :destroy, inverse_of: :status
  58. has_many :active_mentions, -> { active }, class_name: 'Mention', inverse_of: :status
  59. has_many :media_attachments, dependent: :nullify
  60. has_and_belongs_to_many :tags
  61. has_and_belongs_to_many :preview_cards
  62. has_one :notification, as: :activity, dependent: :destroy
  63. has_one :status_stat, inverse_of: :status
  64. has_one :poll, inverse_of: :status, dependent: :destroy
  65. has_one :trend, class_name: 'StatusTrend', inverse_of: :status
  66. validates :uri, uniqueness: true, presence: true, unless: :local?
  67. validates :text, presence: true, unless: -> { with_media? || reblog? }
  68. validates_with StatusLengthValidator
  69. validates_with DisallowedHashtagsValidator
  70. validates :reblog, uniqueness: { scope: :account }, if: :reblog?
  71. validates :visibility, exclusion: { in: %w(direct limited) }, if: :reblog?
  72. accepts_nested_attributes_for :poll
  73. default_scope { recent.kept }
  74. scope :recent, -> { reorder(id: :desc) }
  75. scope :remote, -> { where(local: false).where.not(uri: nil) }
  76. scope :local, -> { where(local: true).or(where(uri: nil)) }
  77. scope :with_accounts, ->(ids) { where(id: ids).includes(:account) }
  78. scope :without_replies, -> { where('statuses.reply = FALSE OR statuses.in_reply_to_account_id = statuses.account_id') }
  79. scope :without_reblogs, -> { where('statuses.reblog_of_id IS NULL') }
  80. scope :with_public_visibility, -> { where(visibility: :public) }
  81. scope :tagged_with, ->(tag_ids) { joins(:statuses_tags).where(statuses_tags: { tag_id: tag_ids }) }
  82. scope :excluding_silenced_accounts, -> { left_outer_joins(:account).where(accounts: { silenced_at: nil }) }
  83. scope :including_silenced_accounts, -> { left_outer_joins(:account).where.not(accounts: { silenced_at: nil }) }
  84. scope :not_excluded_by_account, ->(account) { where.not(account_id: account.excluded_from_timeline_account_ids) }
  85. 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) }
  86. scope :tagged_with_all, ->(tag_ids) {
  87. Array(tag_ids).map(&:to_i).reduce(self) do |result, id|
  88. result.joins("INNER JOIN statuses_tags t#{id} ON t#{id}.status_id = statuses.id AND t#{id}.tag_id = #{id}")
  89. end
  90. }
  91. scope :tagged_with_none, ->(tag_ids) {
  92. where('NOT EXISTS (SELECT * FROM statuses_tags forbidden WHERE forbidden.status_id = statuses.id AND forbidden.tag_id IN (?))', tag_ids)
  93. }
  94. cache_associated :application,
  95. :media_attachments,
  96. :conversation,
  97. :status_stat,
  98. :tags,
  99. :preview_cards,
  100. :preloadable_poll,
  101. account: [:account_stat, :user],
  102. active_mentions: { account: :account_stat },
  103. reblog: [
  104. :application,
  105. :tags,
  106. :preview_cards,
  107. :media_attachments,
  108. :conversation,
  109. :status_stat,
  110. :preloadable_poll,
  111. account: [:account_stat, :user],
  112. active_mentions: { account: :account_stat },
  113. ],
  114. thread: { account: :account_stat }
  115. delegate :domain, to: :account, prefix: true
  116. REAL_TIME_WINDOW = 6.hours
  117. def searchable_by(preloaded = nil)
  118. ids = []
  119. ids << account_id if local?
  120. if preloaded.nil?
  121. ids += mentions.where(account: Account.local, silent: false).pluck(:account_id)
  122. ids += favourites.where(account: Account.local).pluck(:account_id)
  123. ids += reblogs.where(account: Account.local).pluck(:account_id)
  124. ids += bookmarks.where(account: Account.local).pluck(:account_id)
  125. ids += poll.votes.where(account: Account.local).pluck(:account_id) if poll.present?
  126. else
  127. ids += preloaded.mentions[id] || []
  128. ids += preloaded.favourites[id] || []
  129. ids += preloaded.reblogs[id] || []
  130. ids += preloaded.bookmarks[id] || []
  131. ids += preloaded.votes[id] || []
  132. end
  133. ids.uniq
  134. end
  135. def searchable_text
  136. [
  137. spoiler_text,
  138. FormattingHelper.extract_status_plain_text(self),
  139. preloadable_poll ? preloadable_poll.options.join("\n\n") : nil,
  140. ordered_media_attachments.map(&:description).join("\n\n"),
  141. ].compact.join("\n\n")
  142. end
  143. def to_log_human_identifier
  144. account.acct
  145. end
  146. def to_log_permalink
  147. ActivityPub::TagManager.instance.uri_for(self)
  148. end
  149. def reply?
  150. !in_reply_to_id.nil? || attributes['reply']
  151. end
  152. def local?
  153. attributes['local'] || uri.nil?
  154. end
  155. def in_reply_to_local_account?
  156. reply? && thread&.account&.local?
  157. end
  158. def reblog?
  159. !reblog_of_id.nil?
  160. end
  161. def within_realtime_window?
  162. created_at >= REAL_TIME_WINDOW.ago
  163. end
  164. def verb
  165. if destroyed?
  166. :delete
  167. else
  168. reblog? ? :share : :post
  169. end
  170. end
  171. def object_type
  172. reply? ? :comment : :note
  173. end
  174. def proper
  175. reblog? ? reblog : self
  176. end
  177. def content
  178. proper.text
  179. end
  180. def target
  181. reblog
  182. end
  183. def preview_card
  184. preview_cards.first
  185. end
  186. def hidden?
  187. !distributable?
  188. end
  189. def distributable?
  190. public_visibility? || unlisted_visibility?
  191. end
  192. alias sign? distributable?
  193. def with_media?
  194. ordered_media_attachments.any?
  195. end
  196. def with_preview_card?
  197. preview_cards.any?
  198. end
  199. def non_sensitive_with_media?
  200. !sensitive? && with_media?
  201. end
  202. def reported?
  203. @reported ||= Report.where(target_account: account).unresolved.where('? = ANY(status_ids)', id).exists?
  204. end
  205. def emojis
  206. return @emojis if defined?(@emojis)
  207. fields = [spoiler_text, text]
  208. fields += preloadable_poll.options unless preloadable_poll.nil?
  209. @emojis = CustomEmoji.from_text(fields.join(' '), account.domain)
  210. end
  211. def ordered_media_attachments
  212. if ordered_media_attachment_ids.nil?
  213. media_attachments
  214. else
  215. map = media_attachments.index_by(&:id)
  216. ordered_media_attachment_ids.filter_map { |media_attachment_id| map[media_attachment_id] }
  217. end
  218. end
  219. def replies_count
  220. status_stat&.replies_count || 0
  221. end
  222. def reblogs_count
  223. status_stat&.reblogs_count || 0
  224. end
  225. def favourites_count
  226. status_stat&.favourites_count || 0
  227. end
  228. def increment_count!(key)
  229. update_status_stat!(key => public_send(key) + 1)
  230. end
  231. def decrement_count!(key)
  232. update_status_stat!(key => [public_send(key) - 1, 0].max)
  233. end
  234. def trendable?
  235. if attributes['trendable'].nil?
  236. account.trendable?
  237. else
  238. attributes['trendable']
  239. end
  240. end
  241. def requires_review?
  242. attributes['trendable'].nil? && account.requires_review?
  243. end
  244. def requires_review_notification?
  245. attributes['trendable'].nil? && account.requires_review_notification?
  246. end
  247. after_create_commit :increment_counter_caches
  248. after_destroy_commit :decrement_counter_caches
  249. after_create_commit :store_uri, if: :local?
  250. after_create_commit :update_statistics, if: :local?
  251. around_create Mastodon::Snowflake::Callbacks
  252. before_validation :prepare_contents, if: :local?
  253. before_validation :set_reblog
  254. before_validation :set_visibility
  255. before_validation :set_conversation
  256. before_validation :set_local
  257. after_create :set_poll_id
  258. class << self
  259. def selectable_visibilities
  260. visibilities.keys - %w(direct limited)
  261. end
  262. def favourites_map(status_ids, account_id)
  263. Favourite.select('status_id').where(status_id: status_ids).where(account_id: account_id).each_with_object({}) { |f, h| h[f.status_id] = true }
  264. end
  265. def bookmarks_map(status_ids, account_id)
  266. Bookmark.select('status_id').where(status_id: status_ids).where(account_id: account_id).map { |f| [f.status_id, true] }.to_h
  267. end
  268. def reblogs_map(status_ids, account_id)
  269. 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 }
  270. end
  271. def mutes_map(conversation_ids, account_id)
  272. ConversationMute.select('conversation_id').where(conversation_id: conversation_ids).where(account_id: account_id).each_with_object({}) { |m, h| h[m.conversation_id] = true }
  273. end
  274. def pins_map(status_ids, account_id)
  275. StatusPin.select('status_id').where(status_id: status_ids).where(account_id: account_id).each_with_object({}) { |p, h| h[p.status_id] = true }
  276. end
  277. def reload_stale_associations!(cached_items)
  278. account_ids = []
  279. cached_items.each do |item|
  280. account_ids << item.account_id
  281. account_ids << item.reblog.account_id if item.reblog?
  282. end
  283. account_ids.uniq!
  284. status_ids = cached_items.map { |item| item.reblog? ? item.reblog_of_id : item.id }.uniq
  285. return if account_ids.empty?
  286. accounts = Account.where(id: account_ids).includes(:account_stat, :user).index_by(&:id)
  287. status_stats = StatusStat.where(status_id: status_ids).index_by(&:status_id)
  288. cached_items.each do |item|
  289. item.account = accounts[item.account_id]
  290. item.reblog.account = accounts[item.reblog.account_id] if item.reblog?
  291. if item.reblog?
  292. status_stat = status_stats[item.reblog.id]
  293. item.reblog.status_stat = status_stat if status_stat.present?
  294. else
  295. status_stat = status_stats[item.id]
  296. item.status_stat = status_stat if status_stat.present?
  297. end
  298. end
  299. end
  300. def from_text(text)
  301. return [] if text.blank?
  302. text.scan(FetchLinkCardService::URL_PATTERN).map(&:second).uniq.filter_map do |url|
  303. status = begin
  304. if TagManager.instance.local_url?(url)
  305. ActivityPub::TagManager.instance.uri_to_resource(url, Status)
  306. else
  307. EntityCache.instance.status(url)
  308. end
  309. end
  310. status&.distributable? ? status : nil
  311. end
  312. end
  313. end
  314. def status_stat
  315. super || build_status_stat
  316. end
  317. # Hack to use a "INSERT INTO ... SELECT ..." query instead of "INSERT INTO ... VALUES ..." query
  318. def self._insert_record(values)
  319. if values.is_a?(Hash) && values['reblog_of_id'].present?
  320. primary_key = self.primary_key
  321. primary_key_value = nil
  322. if primary_key
  323. primary_key_value = values[primary_key]
  324. if !primary_key_value && prefetch_primary_key?
  325. primary_key_value = next_sequence_value
  326. values[primary_key] = primary_key_value
  327. end
  328. end
  329. # The following line is where we differ from stock ActiveRecord implementation
  330. im = _compile_reblog_insert(values)
  331. # Since we are using SELECT instead of VALUES, a non-error `nil` return is possible.
  332. # For our purposes, it's equivalent to a foreign key constraint violation
  333. result = connection.insert(im, "#{self} Create", primary_key || false, primary_key_value)
  334. raise ActiveRecord::InvalidForeignKey, "(reblog_of_id)=(#{values['reblog_of_id']}) is not present in table \"statuses\"" if result.nil?
  335. result
  336. else
  337. super
  338. end
  339. end
  340. def self._compile_reblog_insert(values)
  341. # This is somewhat equivalent to the following code of ActiveRecord::Persistence:
  342. # `arel_table.compile_insert(_substitute_values(values))`
  343. # The main difference is that we use a `SELECT` instead of a `VALUES` clause,
  344. # which means we have to build the `SELECT` clause ourselves and do a bit more
  345. # manual work.
  346. # Instead of using Arel::InsertManager#values, we are going to use Arel::InsertManager#select
  347. im = Arel::InsertManager.new
  348. im.into(arel_table)
  349. binds = []
  350. reblog_bind = nil
  351. values.each do |name, value|
  352. attr = arel_table[name]
  353. bind = predicate_builder.build_bind_attribute(attr.name, value)
  354. im.columns << attr
  355. binds << bind
  356. reblog_bind = bind if name == 'reblog_of_id'
  357. end
  358. im.select(arel_table.where(arel_table[:id].eq(reblog_bind)).where(arel_table[:deleted_at].eq(nil)).project(*binds))
  359. im
  360. end
  361. def discard_with_reblogs
  362. discard_time = Time.current
  363. Status.unscoped.where(reblog_of_id: id, deleted_at: [nil, deleted_at]).in_batches.update_all(deleted_at: discard_time) unless reblog?
  364. update_attribute(:deleted_at, discard_time)
  365. end
  366. private
  367. def update_status_stat!(attrs)
  368. return if marked_for_destruction? || destroyed?
  369. status_stat.update(attrs)
  370. end
  371. def store_uri
  372. update_column(:uri, ActivityPub::TagManager.instance.uri_for(self)) if uri.nil?
  373. end
  374. def prepare_contents
  375. text&.strip!
  376. spoiler_text&.strip!
  377. end
  378. def set_reblog
  379. self.reblog = reblog.reblog if reblog? && reblog.reblog?
  380. end
  381. def set_poll_id
  382. update_column(:poll_id, poll.id) if association(:poll).loaded? && poll.present?
  383. end
  384. def set_visibility
  385. self.visibility = reblog.visibility if reblog? && visibility.nil?
  386. self.visibility = (account.locked? ? :private : :public) if visibility.nil?
  387. self.sensitive = false if sensitive.nil?
  388. end
  389. def set_conversation
  390. self.thread = thread.reblog if thread&.reblog?
  391. self.reply = !(in_reply_to_id.nil? && thread.nil?) unless reply
  392. if reply? && !thread.nil?
  393. self.in_reply_to_account_id = carried_over_reply_to_account_id
  394. self.conversation_id = thread.conversation_id if conversation_id.nil?
  395. elsif conversation_id.nil?
  396. self.conversation = Conversation.new
  397. end
  398. end
  399. def carried_over_reply_to_account_id
  400. if thread.account_id == account_id && thread.reply?
  401. thread.in_reply_to_account_id
  402. else
  403. thread.account_id
  404. end
  405. end
  406. def set_local
  407. self.local = account.local?
  408. end
  409. def update_statistics
  410. return unless distributable?
  411. ActivityTracker.increment('activity:statuses:local')
  412. end
  413. def increment_counter_caches
  414. return if direct_visibility?
  415. account&.increment_count!(:statuses_count)
  416. reblog&.increment_count!(:reblogs_count) if reblog?
  417. thread&.increment_count!(:replies_count) if in_reply_to_id.present? && distributable?
  418. end
  419. def decrement_counter_caches
  420. return if direct_visibility? || new_record?
  421. account&.decrement_count!(:statuses_count)
  422. reblog&.decrement_count!(:reblogs_count) if reblog?
  423. thread&.decrement_count!(:replies_count) if in_reply_to_id.present? && distributable?
  424. end
  425. def unlink_from_conversations
  426. return unless direct_visibility?
  427. mentioned_accounts = (association(:mentions).loaded? ? mentions : mentions.includes(:account)).map(&:account)
  428. inbox_owners = mentioned_accounts.select(&:local?) + (account.local? ? [account] : [])
  429. inbox_owners.each do |inbox_owner|
  430. AccountConversation.remove_status(inbox_owner, self)
  431. end
  432. end
  433. end