You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

538 lines
17 KiB

refactor(vacuum statuses): reduce amount of db queries and load for each query - improve performance (#21487) * refactor(statuses_vacuum): remove dead code - unused Method is not called inside class and private. Clean up dead code. * refactor(statuses_vacuum): make retention_period present test explicit This private method only hides functionality. It is best practice to be as explicit as possible. * refactor(statuses_vacuum): improve query performance - fix statuses_scope having sub-select for Account.remote scope by `joins(:account).merge(Account.remote)` - fix statuses_scope unnecessary use of `Status.arel_table[:id].lt` because it is inexplicit, bad practice and even slower than normal `.where('statuses.id < ?'` - fix statuses_scope remove select(:id, :visibility) for having reusable active record query batches (no re queries) - fix vacuum_statuses! to use in_batches instead of find_in_batches, because in_batches delivers a full blown active record query result, in stead of an array - no requeries necessary - send(:unlink_from_conversations) not to perform another db query, but reuse the in_batches result instead. - remove now obsolete remove_from_account_conversations method - remove_from_search_index uses array of ids, instead of mapping the ids from an array - this should be more efficient - use the in_batches scope to call delete_all, instead of running another db query for this - because it is again more efficient - add TODO comment for calling models private method with send * refactor(status): simplify unlink_from_conversations - add `has_many through:` relation mentioned_accounts - use model scope local instead of method call `Status#local?` - more readable add account to inbox_owners when account.local? * refactor(status): searchable_by way less sub selects These queries all included a sub-select. Doing the same with a joins should be more efficient. Since this method does 5 such queries, this should be significant, since it technically halves the query count. This is how it was: ```ruby [3] pry(main)> Status.first.mentions.where(account: Account.local, silent: false).explain Status Load (1.6ms) SELECT "statuses".* FROM "statuses" WHERE "statuses"."deleted_at" IS NULL ORDER BY "statuses"."id" DESC LIMIT $1 [["LIMIT", 1]] Mention Load (1.5ms) SELECT "mentions".* FROM "mentions" WHERE "mentions"."status_id" = $1 AND "mentions"."account_id" IN (SELECT "accounts"."id" FROM "accounts" WHERE "accounts"."domain" IS NULL) AND "mentions"."silent" = $2 [["status_id", 109382923142288414], ["silent", false]] => EXPLAIN for: SELECT "mentions".* FROM "mentions" WHERE "mentions"."status_id" = $1 AND "mentions"."account_id" IN (SELECT "accounts"."id" FROM "accounts" WHERE "accounts"."domain" IS NULL) AND "mentions"."silent" = $2 [["status_id", 109382923142288414], ["silent", false]] QUERY PLAN ------------------------------------------------------------------------------------------------------------------ Nested Loop (cost=0.15..23.08 rows=1 width=41) -> Seq Scan on accounts (cost=0.00..10.90 rows=1 width=8) Filter: (domain IS NULL) -> Index Scan using index_mentions_on_account_id_and_status_id on mentions (cost=0.15..8.17 rows=1 width=41) Index Cond: ((account_id = accounts.id) AND (status_id = '109382923142288414'::bigint)) Filter: (NOT silent) (6 rows) ``` This is how it is with this change: ```ruby [4] pry(main)> Status.first.mentions.joins(:account).merge(Account.local).active.explain Status Load (1.7ms) SELECT "statuses".* FROM "statuses" WHERE "statuses"."deleted_at" IS NULL ORDER BY "statuses"."id" DESC LIMIT $1 [["LIMIT", 1]] Mention Load (0.7ms) SELECT "mentions".* FROM "mentions" INNER JOIN "accounts" ON "accounts"."id" = "mentions"."account_id" WHERE "mentions"."status_id" = $1 AND "accounts"."domain" IS NULL AND "mentions"."silent" = $2 [["status_id", 109382923142288414], ["silent", false]] => EXPLAIN for: SELECT "mentions".* FROM "mentions" INNER JOIN "accounts" ON "accounts"."id" = "mentions"."account_id" WHERE "mentions"."status_id" = $1 AND "accounts"."domain" IS NULL AND "mentions"."silent" = $2 [["status_id", 109382923142288414], ["silent", false]] QUERY PLAN ------------------------------------------------------------------------------------------------------------------ Nested Loop (cost=0.15..23.08 rows=1 width=41) -> Seq Scan on accounts (cost=0.00..10.90 rows=1 width=8) Filter: (domain IS NULL) -> Index Scan using index_mentions_on_account_id_and_status_id on mentions (cost=0.15..8.17 rows=1 width=41) Index Cond: ((account_id = accounts.id) AND (status_id = '109382923142288414'::bigint)) Filter: (NOT silent) (6 rows) ```
1 year ago
7 years ago
refactor(vacuum statuses): reduce amount of db queries and load for each query - improve performance (#21487) * refactor(statuses_vacuum): remove dead code - unused Method is not called inside class and private. Clean up dead code. * refactor(statuses_vacuum): make retention_period present test explicit This private method only hides functionality. It is best practice to be as explicit as possible. * refactor(statuses_vacuum): improve query performance - fix statuses_scope having sub-select for Account.remote scope by `joins(:account).merge(Account.remote)` - fix statuses_scope unnecessary use of `Status.arel_table[:id].lt` because it is inexplicit, bad practice and even slower than normal `.where('statuses.id < ?'` - fix statuses_scope remove select(:id, :visibility) for having reusable active record query batches (no re queries) - fix vacuum_statuses! to use in_batches instead of find_in_batches, because in_batches delivers a full blown active record query result, in stead of an array - no requeries necessary - send(:unlink_from_conversations) not to perform another db query, but reuse the in_batches result instead. - remove now obsolete remove_from_account_conversations method - remove_from_search_index uses array of ids, instead of mapping the ids from an array - this should be more efficient - use the in_batches scope to call delete_all, instead of running another db query for this - because it is again more efficient - add TODO comment for calling models private method with send * refactor(status): simplify unlink_from_conversations - add `has_many through:` relation mentioned_accounts - use model scope local instead of method call `Status#local?` - more readable add account to inbox_owners when account.local? * refactor(status): searchable_by way less sub selects These queries all included a sub-select. Doing the same with a joins should be more efficient. Since this method does 5 such queries, this should be significant, since it technically halves the query count. This is how it was: ```ruby [3] pry(main)> Status.first.mentions.where(account: Account.local, silent: false).explain Status Load (1.6ms) SELECT "statuses".* FROM "statuses" WHERE "statuses"."deleted_at" IS NULL ORDER BY "statuses"."id" DESC LIMIT $1 [["LIMIT", 1]] Mention Load (1.5ms) SELECT "mentions".* FROM "mentions" WHERE "mentions"."status_id" = $1 AND "mentions"."account_id" IN (SELECT "accounts"."id" FROM "accounts" WHERE "accounts"."domain" IS NULL) AND "mentions"."silent" = $2 [["status_id", 109382923142288414], ["silent", false]] => EXPLAIN for: SELECT "mentions".* FROM "mentions" WHERE "mentions"."status_id" = $1 AND "mentions"."account_id" IN (SELECT "accounts"."id" FROM "accounts" WHERE "accounts"."domain" IS NULL) AND "mentions"."silent" = $2 [["status_id", 109382923142288414], ["silent", false]] QUERY PLAN ------------------------------------------------------------------------------------------------------------------ Nested Loop (cost=0.15..23.08 rows=1 width=41) -> Seq Scan on accounts (cost=0.00..10.90 rows=1 width=8) Filter: (domain IS NULL) -> Index Scan using index_mentions_on_account_id_and_status_id on mentions (cost=0.15..8.17 rows=1 width=41) Index Cond: ((account_id = accounts.id) AND (status_id = '109382923142288414'::bigint)) Filter: (NOT silent) (6 rows) ``` This is how it is with this change: ```ruby [4] pry(main)> Status.first.mentions.joins(:account).merge(Account.local).active.explain Status Load (1.7ms) SELECT "statuses".* FROM "statuses" WHERE "statuses"."deleted_at" IS NULL ORDER BY "statuses"."id" DESC LIMIT $1 [["LIMIT", 1]] Mention Load (0.7ms) SELECT "mentions".* FROM "mentions" INNER JOIN "accounts" ON "accounts"."id" = "mentions"."account_id" WHERE "mentions"."status_id" = $1 AND "accounts"."domain" IS NULL AND "mentions"."silent" = $2 [["status_id", 109382923142288414], ["silent", false]] => EXPLAIN for: SELECT "mentions".* FROM "mentions" INNER JOIN "accounts" ON "accounts"."id" = "mentions"."account_id" WHERE "mentions"."status_id" = $1 AND "accounts"."domain" IS NULL AND "mentions"."silent" = $2 [["status_id", 109382923142288414], ["silent", false]] QUERY PLAN ------------------------------------------------------------------------------------------------------------------ Nested Loop (cost=0.15..23.08 rows=1 width=41) -> Seq Scan on accounts (cost=0.00..10.90 rows=1 width=8) Filter: (domain IS NULL) -> Index Scan using index_mentions_on_account_id_and_status_id on mentions (cost=0.15..8.17 rows=1 width=41) Index Cond: ((account_id = accounts.id) AND (status_id = '109382923142288414'::bigint)) Filter: (NOT silent) (6 rows) ```
1 year ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
8 years ago
  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 :mentioned_accounts, through: :mentions, source: :account, class_name: 'Account'
  59. has_many :active_mentions, -> { active }, class_name: 'Mention', inverse_of: :status
  60. has_many :media_attachments, dependent: :nullify
  61. has_and_belongs_to_many :tags
  62. has_and_belongs_to_many :preview_cards
  63. has_one :notification, as: :activity, dependent: :destroy
  64. has_one :status_stat, inverse_of: :status
  65. has_one :poll, inverse_of: :status, dependent: :destroy
  66. has_one :trend, class_name: 'StatusTrend', inverse_of: :status
  67. validates :uri, uniqueness: true, presence: true, unless: :local?
  68. validates :text, presence: true, unless: -> { with_media? || reblog? }
  69. validates_with StatusLengthValidator
  70. validates_with DisallowedHashtagsValidator
  71. validates :reblog, uniqueness: { scope: :account }, if: :reblog?
  72. validates :visibility, exclusion: { in: %w(direct limited) }, if: :reblog?
  73. accepts_nested_attributes_for :poll
  74. default_scope { recent.kept }
  75. scope :recent, -> { reorder(id: :desc) }
  76. scope :remote, -> { where(local: false).where.not(uri: nil) }
  77. scope :local, -> { where(local: true).or(where(uri: nil)) }
  78. scope :with_accounts, ->(ids) { where(id: ids).includes(:account) }
  79. scope :without_replies, -> { where('statuses.reply = FALSE OR statuses.in_reply_to_account_id = statuses.account_id') }
  80. scope :without_reblogs, -> { where('statuses.reblog_of_id IS NULL') }
  81. scope :with_public_visibility, -> { where(visibility: :public) }
  82. scope :tagged_with, ->(tag_ids) { joins(:statuses_tags).where(statuses_tags: { tag_id: tag_ids }) }
  83. scope :excluding_silenced_accounts, -> { left_outer_joins(:account).where(accounts: { silenced_at: nil }) }
  84. scope :including_silenced_accounts, -> { left_outer_joins(:account).where.not(accounts: { silenced_at: nil }) }
  85. scope :not_excluded_by_account, ->(account) { where.not(account_id: account.excluded_from_timeline_account_ids) }
  86. 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) }
  87. scope :tagged_with_all, lambda { |tag_ids|
  88. Array(tag_ids).map(&:to_i).reduce(self) do |result, id|
  89. result.joins("INNER JOIN statuses_tags t#{id} ON t#{id}.status_id = statuses.id AND t#{id}.tag_id = #{id}")
  90. end
  91. }
  92. scope :tagged_with_none, lambda { |tag_ids|
  93. where('NOT EXISTS (SELECT * FROM statuses_tags forbidden WHERE forbidden.status_id = statuses.id AND forbidden.tag_id IN (?))', tag_ids)
  94. }
  95. cache_associated :application,
  96. :media_attachments,
  97. :conversation,
  98. :status_stat,
  99. :tags,
  100. :preview_cards,
  101. :preloadable_poll,
  102. account: [:account_stat, user: :role],
  103. active_mentions: { account: :account_stat },
  104. reblog: [
  105. :application,
  106. :tags,
  107. :preview_cards,
  108. :media_attachments,
  109. :conversation,
  110. :status_stat,
  111. :preloadable_poll,
  112. account: [:account_stat, user: :role],
  113. active_mentions: { account: :account_stat },
  114. ],
  115. thread: { account: :account_stat }
  116. delegate :domain, to: :account, prefix: true
  117. REAL_TIME_WINDOW = 6.hours
  118. def searchable_by(preloaded = nil)
  119. ids = []
  120. ids << account_id if local?
  121. if preloaded.nil?
  122. ids += mentions.joins(:account).merge(Account.local).active.pluck(:account_id)
  123. ids += favourites.joins(:account).merge(Account.local).pluck(:account_id)
  124. ids += reblogs.joins(:account).merge(Account.local).pluck(:account_id)
  125. ids += bookmarks.joins(:account).merge(Account.local).pluck(:account_id)
  126. ids += poll.votes.joins(:account).merge(Account.local).pluck(:account_id) if poll.present?
  127. else
  128. ids += preloaded.mentions[id] || []
  129. ids += preloaded.favourites[id] || []
  130. ids += preloaded.reblogs[id] || []
  131. ids += preloaded.bookmarks[id] || []
  132. ids += preloaded.votes[id] || []
  133. end
  134. ids.uniq
  135. end
  136. def searchable_text
  137. [
  138. spoiler_text,
  139. FormattingHelper.extract_status_plain_text(self),
  140. preloadable_poll ? preloadable_poll.options.join("\n\n") : nil,
  141. ordered_media_attachments.map(&:description).join("\n\n"),
  142. ].compact.join("\n\n")
  143. end
  144. def to_log_human_identifier
  145. account.acct
  146. end
  147. def to_log_permalink
  148. ActivityPub::TagManager.instance.uri_for(self)
  149. end
  150. def reply?
  151. !in_reply_to_id.nil? || attributes['reply']
  152. end
  153. def local?
  154. attributes['local'] || uri.nil?
  155. end
  156. def in_reply_to_local_account?
  157. reply? && thread&.account&.local?
  158. end
  159. def reblog?
  160. !reblog_of_id.nil?
  161. end
  162. def within_realtime_window?
  163. created_at >= REAL_TIME_WINDOW.ago
  164. end
  165. def verb
  166. if destroyed?
  167. :delete
  168. else
  169. reblog? ? :share : :post
  170. end
  171. end
  172. def object_type
  173. reply? ? :comment : :note
  174. end
  175. def proper
  176. reblog? ? reblog : self
  177. end
  178. def content
  179. proper.text
  180. end
  181. def target
  182. reblog
  183. end
  184. def preview_card
  185. preview_cards.first
  186. end
  187. def hidden?
  188. !distributable?
  189. end
  190. def distributable?
  191. public_visibility? || unlisted_visibility?
  192. end
  193. alias sign? distributable?
  194. def with_media?
  195. ordered_media_attachments.any?
  196. end
  197. def with_preview_card?
  198. preview_cards.any?
  199. end
  200. def non_sensitive_with_media?
  201. !sensitive? && with_media?
  202. end
  203. def reported?
  204. @reported ||= Report.where(target_account: account).unresolved.where('? = ANY(status_ids)', id).exists?
  205. end
  206. def emojis
  207. return @emojis if defined?(@emojis)
  208. fields = [spoiler_text, text]
  209. fields += preloadable_poll.options unless preloadable_poll.nil?
  210. @emojis = CustomEmoji.from_text(fields.join(' '), account.domain)
  211. end
  212. def ordered_media_attachments
  213. if ordered_media_attachment_ids.nil?
  214. media_attachments
  215. else
  216. map = media_attachments.index_by(&:id)
  217. ordered_media_attachment_ids.filter_map { |media_attachment_id| map[media_attachment_id] }
  218. end
  219. end
  220. def replies_count
  221. status_stat&.replies_count || 0
  222. end
  223. def reblogs_count
  224. status_stat&.reblogs_count || 0
  225. end
  226. def favourites_count
  227. status_stat&.favourites_count || 0
  228. end
  229. def increment_count!(key)
  230. update_status_stat!(key => public_send(key) + 1)
  231. end
  232. def decrement_count!(key)
  233. update_status_stat!(key => [public_send(key) - 1, 0].max)
  234. end
  235. def trendable?
  236. if attributes['trendable'].nil?
  237. account.trendable?
  238. else
  239. attributes['trendable']
  240. end
  241. end
  242. def requires_review?
  243. attributes['trendable'].nil? && account.requires_review?
  244. end
  245. def requires_review_notification?
  246. attributes['trendable'].nil? && account.requires_review_notification?
  247. end
  248. after_create_commit :increment_counter_caches
  249. after_destroy_commit :decrement_counter_caches
  250. after_create_commit :store_uri, if: :local?
  251. after_create_commit :update_statistics, if: :local?
  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. around_create Mastodon::Snowflake::Callbacks
  258. after_create :set_poll_id
  259. class << self
  260. def selectable_visibilities
  261. visibilities.keys - %w(direct limited)
  262. end
  263. def favourites_map(status_ids, account_id)
  264. Favourite.select('status_id').where(status_id: status_ids).where(account_id: account_id).each_with_object({}) { |f, h| h[f.status_id] = true }
  265. end
  266. def bookmarks_map(status_ids, account_id)
  267. Bookmark.select('status_id').where(status_id: status_ids).where(account_id: account_id).map { |f| [f.status_id, true] }.to_h
  268. end
  269. def reblogs_map(status_ids, account_id)
  270. 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 }
  271. end
  272. def mutes_map(conversation_ids, account_id)
  273. ConversationMute.select('conversation_id').where(conversation_id: conversation_ids).where(account_id: account_id).each_with_object({}) { |m, h| h[m.conversation_id] = true }
  274. end
  275. def pins_map(status_ids, account_id)
  276. StatusPin.select('status_id').where(status_id: status_ids).where(account_id: account_id).each_with_object({}) { |p, h| h[p.status_id] = true }
  277. end
  278. def reload_stale_associations!(cached_items)
  279. account_ids = []
  280. cached_items.each do |item|
  281. account_ids << item.account_id
  282. account_ids << item.reblog.account_id if item.reblog?
  283. end
  284. account_ids.uniq!
  285. return if account_ids.empty?
  286. accounts = Account.where(id: account_ids).includes(:account_stat, :user).index_by(&:id)
  287. cached_items.each do |item|
  288. item.account = accounts[item.account_id]
  289. item.reblog.account = accounts[item.reblog.account_id] if item.reblog?
  290. end
  291. end
  292. def from_text(text)
  293. return [] if text.blank?
  294. text.scan(FetchLinkCardService::URL_PATTERN).map(&:second).uniq.filter_map do |url|
  295. status = begin
  296. if TagManager.instance.local_url?(url)
  297. ActivityPub::TagManager.instance.uri_to_resource(url, Status)
  298. else
  299. EntityCache.instance.status(url)
  300. end
  301. end
  302. status&.distributable? ? status : nil
  303. end
  304. end
  305. end
  306. def status_stat
  307. super || build_status_stat
  308. end
  309. # Hack to use a "INSERT INTO ... SELECT ..." query instead of "INSERT INTO ... VALUES ..." query
  310. def self._insert_record(values)
  311. if values.is_a?(Hash) && values['reblog_of_id'].present?
  312. primary_key = self.primary_key
  313. primary_key_value = nil
  314. if primary_key
  315. primary_key_value = values[primary_key]
  316. if !primary_key_value && prefetch_primary_key?
  317. primary_key_value = next_sequence_value
  318. values[primary_key] = primary_key_value
  319. end
  320. end
  321. # The following line is where we differ from stock ActiveRecord implementation
  322. im = _compile_reblog_insert(values)
  323. # Since we are using SELECT instead of VALUES, a non-error `nil` return is possible.
  324. # For our purposes, it's equivalent to a foreign key constraint violation
  325. result = connection.insert(im, "#{self} Create", primary_key || false, primary_key_value)
  326. raise ActiveRecord::InvalidForeignKey, "(reblog_of_id)=(#{values['reblog_of_id']}) is not present in table \"statuses\"" if result.nil?
  327. result
  328. else
  329. super
  330. end
  331. end
  332. def self._compile_reblog_insert(values)
  333. # This is somewhat equivalent to the following code of ActiveRecord::Persistence:
  334. # `arel_table.compile_insert(_substitute_values(values))`
  335. # The main difference is that we use a `SELECT` instead of a `VALUES` clause,
  336. # which means we have to build the `SELECT` clause ourselves and do a bit more
  337. # manual work.
  338. # Instead of using Arel::InsertManager#values, we are going to use Arel::InsertManager#select
  339. im = Arel::InsertManager.new
  340. im.into(arel_table)
  341. binds = []
  342. reblog_bind = nil
  343. values.each do |name, value|
  344. attr = arel_table[name]
  345. bind = predicate_builder.build_bind_attribute(attr.name, value)
  346. im.columns << attr
  347. binds << bind
  348. reblog_bind = bind if name == 'reblog_of_id'
  349. end
  350. im.select(arel_table.where(arel_table[:id].eq(reblog_bind)).where(arel_table[:deleted_at].eq(nil)).project(*binds))
  351. im
  352. end
  353. def discard_with_reblogs
  354. discard_time = Time.current
  355. Status.unscoped.where(reblog_of_id: id, deleted_at: [nil, deleted_at]).in_batches.update_all(deleted_at: discard_time) unless reblog?
  356. update_attribute(:deleted_at, discard_time)
  357. end
  358. def unlink_from_conversations!
  359. return unless direct_visibility?
  360. inbox_owners = mentioned_accounts.local
  361. inbox_owners += [account] if account.local?
  362. inbox_owners.each do |inbox_owner|
  363. AccountConversation.remove_status(inbox_owner, self)
  364. end
  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. end