status.rb 15 KB

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