status.rb 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  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. #
  27. class Status < ApplicationRecord
  28. before_destroy :unlink_from_conversations
  29. include Discard::Model
  30. include Paginable
  31. include Cacheable
  32. include StatusThreadingConcern
  33. include RateLimitable
  34. rate_limit by: :account, family: :statuses
  35. self.discard_column = :deleted_at
  36. # If `override_timestamps` is set at creation time, Snowflake ID creation
  37. # will be based on current time instead of `created_at`
  38. attr_accessor :override_timestamps
  39. update_index('statuses#status', :proper)
  40. enum visibility: [:public, :unlisted, :private, :direct, :limited], _suffix: :visibility
  41. belongs_to :application, class_name: 'Doorkeeper::Application', optional: true
  42. belongs_to :account, inverse_of: :statuses
  43. belongs_to :in_reply_to_account, foreign_key: 'in_reply_to_account_id', class_name: 'Account', optional: true
  44. belongs_to :conversation, optional: true
  45. belongs_to :preloadable_poll, class_name: 'Poll', foreign_key: 'poll_id', optional: true
  46. belongs_to :thread, foreign_key: 'in_reply_to_id', class_name: 'Status', inverse_of: :replies, optional: true
  47. belongs_to :reblog, foreign_key: 'reblog_of_id', class_name: 'Status', inverse_of: :reblogs, optional: true
  48. has_many :favourites, inverse_of: :status, dependent: :destroy
  49. has_many :bookmarks, inverse_of: :status, dependent: :destroy
  50. has_many :reblogs, foreign_key: 'reblog_of_id', class_name: 'Status', inverse_of: :reblog, dependent: :destroy
  51. has_many :replies, foreign_key: 'in_reply_to_id', class_name: 'Status', inverse_of: :thread
  52. has_many :mentions, dependent: :destroy, inverse_of: :status
  53. has_many :active_mentions, -> { active }, class_name: 'Mention', inverse_of: :status
  54. has_many :media_attachments, dependent: :nullify
  55. has_and_belongs_to_many :tags
  56. has_and_belongs_to_many :preview_cards
  57. has_one :notification, as: :activity, dependent: :destroy
  58. has_one :status_stat, inverse_of: :status
  59. has_one :poll, inverse_of: :status, dependent: :destroy
  60. validates :uri, uniqueness: true, presence: true, unless: :local?
  61. validates :text, presence: true, unless: -> { with_media? || reblog? }
  62. validates_with StatusLengthValidator
  63. validates_with DisallowedHashtagsValidator
  64. validates :reblog, uniqueness: { scope: :account }, if: :reblog?
  65. validates :visibility, exclusion: { in: %w(direct limited) }, if: :reblog?
  66. accepts_nested_attributes_for :poll
  67. default_scope { recent.kept }
  68. scope :recent, -> { reorder(id: :desc) }
  69. scope :remote, -> { where(local: false).where.not(uri: nil) }
  70. scope :local, -> { where(local: true).or(where(uri: nil)) }
  71. scope :with_accounts, ->(ids) { where(id: ids).includes(:account) }
  72. scope :without_replies, -> { where('statuses.reply = FALSE OR statuses.in_reply_to_account_id = statuses.account_id') }
  73. scope :without_reblogs, -> { where('statuses.reblog_of_id IS NULL') }
  74. scope :with_public_visibility, -> { where(visibility: :public) }
  75. scope :tagged_with, ->(tag) { joins(:statuses_tags).where(statuses_tags: { tag_id: tag }) }
  76. scope :excluding_silenced_accounts, -> { left_outer_joins(:account).where(accounts: { silenced_at: nil }) }
  77. scope :including_silenced_accounts, -> { left_outer_joins(:account).where.not(accounts: { silenced_at: nil }) }
  78. scope :not_excluded_by_account, ->(account) { where.not(account_id: account.excluded_from_timeline_account_ids) }
  79. 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) }
  80. scope :tagged_with_all, ->(tags) {
  81. Array(tags).map(&:id).map(&:to_i).reduce(self) do |result, id|
  82. result.joins("INNER JOIN statuses_tags t#{id} ON t#{id}.status_id = statuses.id AND t#{id}.tag_id = #{id}")
  83. end
  84. }
  85. scope :tagged_with_none, ->(tags) {
  86. Array(tags).map(&:id).map(&:to_i).reduce(self) do |result, id|
  87. result.joins("LEFT OUTER JOIN statuses_tags t#{id} ON t#{id}.status_id = statuses.id AND t#{id}.tag_id = #{id}")
  88. .where("t#{id}.tag_id IS NULL")
  89. end
  90. }
  91. cache_associated :application,
  92. :media_attachments,
  93. :conversation,
  94. :status_stat,
  95. :tags,
  96. :preview_cards,
  97. :preloadable_poll,
  98. account: :account_stat,
  99. active_mentions: { account: :account_stat },
  100. reblog: [
  101. :application,
  102. :tags,
  103. :preview_cards,
  104. :media_attachments,
  105. :conversation,
  106. :status_stat,
  107. :preloadable_poll,
  108. account: :account_stat,
  109. active_mentions: { account: :account_stat },
  110. ],
  111. thread: { account: :account_stat }
  112. delegate :domain, to: :account, prefix: true
  113. REAL_TIME_WINDOW = 6.hours
  114. def searchable_by(preloaded = nil)
  115. ids = []
  116. ids << account_id if local?
  117. if preloaded.nil?
  118. ids += mentions.where(account: Account.local).pluck(:account_id)
  119. ids += favourites.where(account: Account.local).pluck(:account_id)
  120. ids += reblogs.where(account: Account.local).pluck(:account_id)
  121. ids += bookmarks.where(account: Account.local).pluck(:account_id)
  122. else
  123. ids += preloaded.mentions[id] || []
  124. ids += preloaded.favourites[id] || []
  125. ids += preloaded.reblogs[id] || []
  126. ids += preloaded.bookmarks[id] || []
  127. end
  128. ids.uniq
  129. end
  130. def reply?
  131. !in_reply_to_id.nil? || attributes['reply']
  132. end
  133. def local?
  134. attributes['local'] || uri.nil?
  135. end
  136. def reblog?
  137. !reblog_of_id.nil?
  138. end
  139. def within_realtime_window?
  140. created_at >= REAL_TIME_WINDOW.ago
  141. end
  142. def verb
  143. if destroyed?
  144. :delete
  145. else
  146. reblog? ? :share : :post
  147. end
  148. end
  149. def object_type
  150. reply? ? :comment : :note
  151. end
  152. def proper
  153. reblog? ? reblog : self
  154. end
  155. def content
  156. proper.text
  157. end
  158. def target
  159. reblog
  160. end
  161. def preview_card
  162. preview_cards.first
  163. end
  164. def title
  165. if destroyed?
  166. "#{account.acct} deleted status"
  167. elsif reblog?
  168. preview = sensitive ? '<sensitive>' : text.slice(0, 10).split("\n")[0]
  169. "#{account.acct} shared #{reblog.account.acct}'s: #{preview}"
  170. else
  171. preview = sensitive ? '<sensitive>' : text.slice(0, 20).split("\n")[0]
  172. "#{account.acct}: #{preview}"
  173. end
  174. end
  175. def hidden?
  176. !distributable?
  177. end
  178. def distributable?
  179. public_visibility? || unlisted_visibility?
  180. end
  181. alias sign? distributable?
  182. def with_media?
  183. media_attachments.any?
  184. end
  185. def non_sensitive_with_media?
  186. !sensitive? && with_media?
  187. end
  188. def reported?
  189. @reported ||= Report.where(target_account: account).unresolved.where('? = ANY(status_ids)', id).exists?
  190. end
  191. def emojis
  192. return @emojis if defined?(@emojis)
  193. fields = [spoiler_text, text]
  194. fields += preloadable_poll.options unless preloadable_poll.nil?
  195. @emojis = CustomEmoji.from_text(fields.join(' '), account.domain)
  196. end
  197. def mark_for_mass_destruction!
  198. @marked_for_mass_destruction = true
  199. end
  200. def marked_for_mass_destruction?
  201. @marked_for_mass_destruction
  202. end
  203. def replies_count
  204. status_stat&.replies_count || 0
  205. end
  206. def reblogs_count
  207. status_stat&.reblogs_count || 0
  208. end
  209. def favourites_count
  210. status_stat&.favourites_count || 0
  211. end
  212. def increment_count!(key)
  213. update_status_stat!(key => public_send(key) + 1)
  214. end
  215. def decrement_count!(key)
  216. update_status_stat!(key => [public_send(key) - 1, 0].max)
  217. end
  218. after_create_commit :increment_counter_caches
  219. after_destroy_commit :decrement_counter_caches
  220. after_create_commit :store_uri, if: :local?
  221. after_create_commit :update_statistics, if: :local?
  222. around_create Mastodon::Snowflake::Callbacks
  223. before_validation :prepare_contents, if: :local?
  224. before_validation :set_reblog
  225. before_validation :set_visibility
  226. before_validation :set_conversation
  227. before_validation :set_local
  228. after_create :set_poll_id
  229. class << self
  230. def selectable_visibilities
  231. visibilities.keys - %w(direct limited)
  232. end
  233. def in_chosen_languages(account)
  234. where(language: nil).or where(language: account.chosen_languages)
  235. end
  236. def as_public_timeline(account = nil, local_only = false)
  237. query = timeline_scope(local_only).without_replies
  238. apply_timeline_filters(query, account, local_only)
  239. end
  240. def as_tag_timeline(tag, account = nil, local_only = false)
  241. query = timeline_scope(local_only).tagged_with(tag)
  242. apply_timeline_filters(query, account, local_only)
  243. end
  244. def as_outbox_timeline(account)
  245. where(account: account, visibility: :public)
  246. end
  247. def favourites_map(status_ids, account_id)
  248. Favourite.select('status_id').where(status_id: status_ids).where(account_id: account_id).each_with_object({}) { |f, h| h[f.status_id] = true }
  249. end
  250. def bookmarks_map(status_ids, account_id)
  251. Bookmark.select('status_id').where(status_id: status_ids).where(account_id: account_id).map { |f| [f.status_id, true] }.to_h
  252. end
  253. def reblogs_map(status_ids, account_id)
  254. 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 }
  255. end
  256. def mutes_map(conversation_ids, account_id)
  257. ConversationMute.select('conversation_id').where(conversation_id: conversation_ids).where(account_id: account_id).each_with_object({}) { |m, h| h[m.conversation_id] = true }
  258. end
  259. def pins_map(status_ids, account_id)
  260. StatusPin.select('status_id').where(status_id: status_ids).where(account_id: account_id).each_with_object({}) { |p, h| h[p.status_id] = true }
  261. end
  262. def reload_stale_associations!(cached_items)
  263. account_ids = []
  264. cached_items.each do |item|
  265. account_ids << item.account_id
  266. account_ids << item.reblog.account_id if item.reblog?
  267. end
  268. account_ids.uniq!
  269. return if account_ids.empty?
  270. accounts = Account.where(id: account_ids).includes(:account_stat).each_with_object({}) { |a, h| h[a.id] = a }
  271. cached_items.each do |item|
  272. item.account = accounts[item.account_id]
  273. item.reblog.account = accounts[item.reblog.account_id] if item.reblog?
  274. end
  275. end
  276. def permitted_for(target_account, account)
  277. visibility = [:public, :unlisted]
  278. if account.nil?
  279. where(visibility: visibility)
  280. elsif target_account.blocking?(account) # get rid of blocked peeps
  281. none
  282. elsif account.id == target_account.id # author can see own stuff
  283. all
  284. else
  285. # followers can see followers-only stuff, but also things they are mentioned in.
  286. # non-followers can see everything that isn't private/direct, but can see stuff they are mentioned in.
  287. visibility.push(:private) if account.following?(target_account)
  288. scope = left_outer_joins(:reblog)
  289. scope.where(visibility: visibility)
  290. .or(scope.where(id: account.mentions.select(:status_id)))
  291. .merge(scope.where(reblog_of_id: nil).or(scope.where.not(reblogs_statuses: { account_id: account.excluded_from_timeline_account_ids })))
  292. end
  293. end
  294. def from_text(text)
  295. return [] if text.blank?
  296. text.scan(FetchLinkCardService::URL_PATTERN).map(&:first).uniq.map do |url|
  297. status = begin
  298. if TagManager.instance.local_url?(url)
  299. ActivityPub::TagManager.instance.uri_to_resource(url, Status)
  300. else
  301. Status.find_by(uri: url) || Status.find_by(url: url)
  302. end
  303. end
  304. status&.distributable? ? status : nil
  305. end.compact
  306. end
  307. private
  308. def timeline_scope(local_only = false)
  309. starting_scope = local_only ? Status.local : Status
  310. starting_scope
  311. .with_public_visibility
  312. .without_reblogs
  313. end
  314. def apply_timeline_filters(query, account, local_only)
  315. if account.nil?
  316. filter_timeline_default(query)
  317. else
  318. filter_timeline_for_account(query, account, local_only)
  319. end
  320. end
  321. def filter_timeline_for_account(query, account, local_only)
  322. query = query.not_excluded_by_account(account)
  323. query = query.not_domain_blocked_by_account(account) unless local_only
  324. query = query.in_chosen_languages(account) if account.chosen_languages.present?
  325. query.merge(account_silencing_filter(account))
  326. end
  327. def filter_timeline_default(query)
  328. query.excluding_silenced_accounts
  329. end
  330. def account_silencing_filter(account)
  331. if account.silenced?
  332. including_myself = left_outer_joins(:account).where(account_id: account.id).references(:accounts)
  333. excluding_silenced_accounts.or(including_myself)
  334. else
  335. excluding_silenced_accounts
  336. end
  337. end
  338. end
  339. def status_stat
  340. super || build_status_stat
  341. end
  342. private
  343. def update_status_stat!(attrs)
  344. return if marked_for_destruction? || destroyed?
  345. status_stat.update(attrs)
  346. end
  347. def store_uri
  348. update_column(:uri, ActivityPub::TagManager.instance.uri_for(self)) if uri.nil?
  349. end
  350. def prepare_contents
  351. text&.strip!
  352. spoiler_text&.strip!
  353. end
  354. def set_reblog
  355. self.reblog = reblog.reblog if reblog? && reblog.reblog?
  356. end
  357. def set_poll_id
  358. update_column(:poll_id, poll.id) unless poll.nil?
  359. end
  360. def set_visibility
  361. self.visibility = reblog.visibility if reblog? && visibility.nil?
  362. self.visibility = (account.locked? ? :private : :public) if visibility.nil?
  363. self.sensitive = false if sensitive.nil?
  364. end
  365. def set_conversation
  366. self.thread = thread.reblog if thread&.reblog?
  367. self.reply = !(in_reply_to_id.nil? && thread.nil?) unless reply
  368. if reply? && !thread.nil?
  369. self.in_reply_to_account_id = carried_over_reply_to_account_id
  370. self.conversation_id = thread.conversation_id if conversation_id.nil?
  371. elsif conversation_id.nil?
  372. self.conversation = Conversation.new
  373. end
  374. end
  375. def carried_over_reply_to_account_id
  376. if thread.account_id == account_id && thread.reply?
  377. thread.in_reply_to_account_id
  378. else
  379. thread.account_id
  380. end
  381. end
  382. def set_local
  383. self.local = account.local?
  384. end
  385. def update_statistics
  386. return unless distributable?
  387. ActivityTracker.increment('activity:statuses:local')
  388. end
  389. def increment_counter_caches
  390. return if direct_visibility?
  391. account&.increment_count!(:statuses_count)
  392. reblog&.increment_count!(:reblogs_count) if reblog?
  393. thread&.increment_count!(:replies_count) if in_reply_to_id.present? && distributable?
  394. end
  395. def decrement_counter_caches
  396. return if direct_visibility? || marked_for_mass_destruction?
  397. account&.decrement_count!(:statuses_count)
  398. reblog&.decrement_count!(:reblogs_count) if reblog?
  399. thread&.decrement_count!(:replies_count) if in_reply_to_id.present? && distributable?
  400. end
  401. def unlink_from_conversations
  402. return unless direct_visibility?
  403. mentioned_accounts = mentions.includes(:account).map(&:account)
  404. inbox_owners = mentioned_accounts.select(&:local?) + (account.local? ? [account] : [])
  405. inbox_owners.each do |inbox_owner|
  406. AccountConversation.remove_status(inbox_owner, self)
  407. end
  408. end
  409. end