status.rb 17 KB

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