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.

610 lines
20 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. # local_only :boolean
  25. # poll_id :bigint(8)
  26. # content_type :string
  27. # deleted_at :datetime
  28. # edited_at :datetime
  29. # trendable :boolean
  30. # ordered_media_attachment_ids :bigint(8) is an Array
  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: 0, unlisted: 1, private: 2, direct: 3, limited: 4 }, _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, 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. validates :content_type, inclusion: { in: %w(text/plain text/markdown text/html) }, allow_nil: true
  76. accepts_nested_attributes_for :poll
  77. default_scope { recent.kept }
  78. scope :recent, -> { reorder(id: :desc) }
  79. scope :remote, -> { where(local: false).where.not(uri: nil) }
  80. scope :local, -> { where(local: true).or(where(uri: nil)) }
  81. scope :with_accounts, ->(ids) { where(id: ids).includes(:account) }
  82. scope :without_replies, -> { where('statuses.reply = FALSE OR statuses.in_reply_to_account_id = statuses.account_id') }
  83. scope :without_reblogs, -> { where(statuses: { reblog_of_id: 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, lambda { |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, lambda { |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. scope :not_local_only, -> { where(local_only: [false, nil]) }
  99. cache_associated :application,
  100. :media_attachments,
  101. :conversation,
  102. :status_stat,
  103. :tags,
  104. :preview_cards,
  105. :preloadable_poll,
  106. account: [:account_stat, user: :role],
  107. active_mentions: { account: :account_stat },
  108. reblog: [
  109. :application,
  110. :tags,
  111. :preview_cards,
  112. :media_attachments,
  113. :conversation,
  114. :status_stat,
  115. :preloadable_poll,
  116. account: [:account_stat, user: :role],
  117. active_mentions: { account: :account_stat },
  118. ],
  119. thread: { account: :account_stat }
  120. delegate :domain, to: :account, prefix: true
  121. REAL_TIME_WINDOW = 6.hours
  122. def searchable_by(preloaded = nil)
  123. ids = []
  124. ids << account_id if local?
  125. if preloaded.nil?
  126. ids += mentions.joins(:account).merge(Account.local).active.pluck(:account_id)
  127. ids += favourites.joins(:account).merge(Account.local).pluck(:account_id)
  128. ids += reblogs.joins(:account).merge(Account.local).pluck(:account_id)
  129. ids += bookmarks.joins(:account).merge(Account.local).pluck(:account_id)
  130. ids += poll.votes.joins(:account).merge(Account.local).pluck(:account_id) if poll.present?
  131. else
  132. ids += preloaded.mentions[id] || []
  133. ids += preloaded.favourites[id] || []
  134. ids += preloaded.reblogs[id] || []
  135. ids += preloaded.bookmarks[id] || []
  136. ids += preloaded.votes[id] || []
  137. end
  138. ids.uniq
  139. end
  140. def searchable_text
  141. [
  142. spoiler_text,
  143. FormattingHelper.extract_status_plain_text(self),
  144. preloadable_poll ? preloadable_poll.options.join("\n\n") : nil,
  145. ordered_media_attachments.map(&:description).join("\n\n"),
  146. ].compact.join("\n\n")
  147. end
  148. def to_log_human_identifier
  149. account.acct
  150. end
  151. def to_log_permalink
  152. ActivityPub::TagManager.instance.uri_for(self)
  153. end
  154. def reply?
  155. !in_reply_to_id.nil? || attributes['reply']
  156. end
  157. def local?
  158. attributes['local'] || uri.nil?
  159. end
  160. def in_reply_to_local_account?
  161. reply? && thread&.account&.local?
  162. end
  163. def reblog?
  164. !reblog_of_id.nil?
  165. end
  166. def within_realtime_window?
  167. created_at >= REAL_TIME_WINDOW.ago
  168. end
  169. def verb
  170. if destroyed?
  171. :delete
  172. else
  173. reblog? ? :share : :post
  174. end
  175. end
  176. def object_type
  177. reply? ? :comment : :note
  178. end
  179. def proper
  180. reblog? ? reblog : self
  181. end
  182. def content
  183. proper.text
  184. end
  185. def target
  186. reblog
  187. end
  188. def preview_card
  189. preview_cards.first
  190. end
  191. def hidden?
  192. !distributable?
  193. end
  194. def distributable?
  195. public_visibility? || unlisted_visibility?
  196. end
  197. def translatable?
  198. translate_target_locale = I18n.locale.to_s.split(/[_-]/).first
  199. distributable? &&
  200. content.present? &&
  201. language != translate_target_locale &&
  202. TranslationService.configured? &&
  203. TranslationService.configured.supported?(language, translate_target_locale)
  204. end
  205. alias sign? distributable?
  206. def with_media?
  207. ordered_media_attachments.any?
  208. end
  209. def with_preview_card?
  210. preview_cards.any?
  211. end
  212. def non_sensitive_with_media?
  213. !sensitive? && with_media?
  214. end
  215. def reported?
  216. @reported ||= Report.where(target_account: account).unresolved.where('? = ANY(status_ids)', id).exists?
  217. end
  218. def emojis
  219. return @emojis if defined?(@emojis)
  220. fields = [spoiler_text, text]
  221. fields += preloadable_poll.options unless preloadable_poll.nil?
  222. @emojis = CustomEmoji.from_text(fields.join(' '), account.domain)
  223. end
  224. def ordered_media_attachments
  225. if ordered_media_attachment_ids.nil?
  226. media_attachments
  227. else
  228. map = media_attachments.index_by(&:id)
  229. ordered_media_attachment_ids.filter_map { |media_attachment_id| map[media_attachment_id] }
  230. end
  231. end
  232. def replies_count
  233. status_stat&.replies_count || 0
  234. end
  235. def reblogs_count
  236. status_stat&.reblogs_count || 0
  237. end
  238. def favourites_count
  239. status_stat&.favourites_count || 0
  240. end
  241. def increment_count!(key)
  242. update_status_stat!(key => public_send(key) + 1)
  243. end
  244. def decrement_count!(key)
  245. update_status_stat!(key => [public_send(key) - 1, 0].max)
  246. end
  247. def trendable?
  248. if attributes['trendable'].nil?
  249. account.trendable?
  250. else
  251. attributes['trendable']
  252. end
  253. end
  254. def requires_review?
  255. attributes['trendable'].nil? && account.requires_review?
  256. end
  257. def requires_review_notification?
  258. attributes['trendable'].nil? && account.requires_review_notification?
  259. end
  260. after_create_commit :increment_counter_caches
  261. after_destroy_commit :decrement_counter_caches
  262. after_create_commit :store_uri, if: :local?
  263. after_create_commit :update_statistics, if: :local?
  264. before_validation :prepare_contents, if: :local?
  265. before_validation :set_reblog
  266. before_validation :set_visibility
  267. before_validation :set_conversation
  268. before_validation :set_local
  269. before_create :set_locality
  270. around_create Mastodon::Snowflake::Callbacks
  271. after_create :set_poll_id
  272. class << self
  273. def selectable_visibilities
  274. visibilities.keys - %w(direct limited)
  275. end
  276. def as_direct_timeline(account, limit = 20, max_id = nil, since_id = nil, cache_ids = false)
  277. # direct timeline is mix of direct message from_me and to_me.
  278. # 2 queries are executed with pagination.
  279. # constant expression using arel_table is required for partial index
  280. # _from_me part does not require any timeline filters
  281. query_from_me = where(account_id: account.id)
  282. .where(Status.arel_table[:visibility].eq(3))
  283. .limit(limit)
  284. .order('statuses.id DESC')
  285. # _to_me part requires mute and block filter.
  286. # FIXME: may we check mutes.hide_notifications?
  287. query_to_me = Status
  288. .joins(:mentions)
  289. .merge(Mention.where(account_id: account.id))
  290. .where(Status.arel_table[:visibility].eq(3))
  291. .limit(limit)
  292. .order('mentions.status_id DESC')
  293. .not_excluded_by_account(account)
  294. if max_id.present?
  295. query_from_me = query_from_me.where('statuses.id < ?', max_id)
  296. query_to_me = query_to_me.where('mentions.status_id < ?', max_id)
  297. end
  298. if since_id.present?
  299. query_from_me = query_from_me.where('statuses.id > ?', since_id)
  300. query_to_me = query_to_me.where('mentions.status_id > ?', since_id)
  301. end
  302. if cache_ids
  303. # returns array of cache_ids object that have id and updated_at
  304. (query_from_me.cache_ids.to_a + query_to_me.cache_ids.to_a).uniq(&:id).sort_by(&:id).reverse.take(limit)
  305. else
  306. # returns ActiveRecord.Relation
  307. items = (query_from_me.select(:id).to_a + query_to_me.select(:id).to_a).uniq(&:id).sort_by(&:id).reverse.take(limit)
  308. Status.where(id: items.map(&:id))
  309. end
  310. end
  311. def favourites_map(status_ids, account_id)
  312. Favourite.select('status_id').where(status_id: status_ids).where(account_id: account_id).each_with_object({}) { |f, h| h[f.status_id] = true }
  313. end
  314. def bookmarks_map(status_ids, account_id)
  315. Bookmark.select('status_id').where(status_id: status_ids).where(account_id: account_id).map { |f| [f.status_id, true] }.to_h
  316. end
  317. def reblogs_map(status_ids, account_id)
  318. 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 }
  319. end
  320. def mutes_map(conversation_ids, account_id)
  321. ConversationMute.select('conversation_id').where(conversation_id: conversation_ids).where(account_id: account_id).each_with_object({}) { |m, h| h[m.conversation_id] = true }
  322. end
  323. def pins_map(status_ids, account_id)
  324. StatusPin.select('status_id').where(status_id: status_ids).where(account_id: account_id).each_with_object({}) { |p, h| h[p.status_id] = true }
  325. end
  326. def reload_stale_associations!(cached_items)
  327. account_ids = []
  328. cached_items.each do |item|
  329. account_ids << item.account_id
  330. account_ids << item.reblog.account_id if item.reblog?
  331. end
  332. account_ids.uniq!
  333. return if account_ids.empty?
  334. accounts = Account.where(id: account_ids).includes(:account_stat, :user).index_by(&:id)
  335. cached_items.each do |item|
  336. item.account = accounts[item.account_id]
  337. item.reblog.account = accounts[item.reblog.account_id] if item.reblog?
  338. end
  339. end
  340. def from_text(text)
  341. return [] if text.blank?
  342. text.scan(FetchLinkCardService::URL_PATTERN).map(&:second).uniq.filter_map do |url|
  343. status = if TagManager.instance.local_url?(url)
  344. ActivityPub::TagManager.instance.uri_to_resource(url, Status)
  345. else
  346. EntityCache.instance.status(url)
  347. end
  348. status&.distributable? ? status : nil
  349. end
  350. end
  351. end
  352. def marked_local_only?
  353. # match both with and without U+FE0F (the emoji variation selector)
  354. /#{local_only_emoji}\ufe0f?\z/.match?(content)
  355. end
  356. def local_only_emoji
  357. '👁'
  358. end
  359. def status_stat
  360. super || build_status_stat
  361. end
  362. # Hack to use a "INSERT INTO ... SELECT ..." query instead of "INSERT INTO ... VALUES ..." query
  363. def self._insert_record(values)
  364. if values.is_a?(Hash) && values['reblog_of_id'].present?
  365. primary_key = self.primary_key
  366. primary_key_value = nil
  367. if primary_key
  368. primary_key_value = values[primary_key]
  369. if !primary_key_value && prefetch_primary_key?
  370. primary_key_value = next_sequence_value
  371. values[primary_key] = primary_key_value
  372. end
  373. end
  374. # The following line is where we differ from stock ActiveRecord implementation
  375. im = _compile_reblog_insert(values)
  376. # Since we are using SELECT instead of VALUES, a non-error `nil` return is possible.
  377. # For our purposes, it's equivalent to a foreign key constraint violation
  378. result = connection.insert(im, "#{self} Create", primary_key || false, primary_key_value)
  379. raise ActiveRecord::InvalidForeignKey, "(reblog_of_id)=(#{values['reblog_of_id']}) is not present in table \"statuses\"" if result.nil?
  380. result
  381. else
  382. super
  383. end
  384. end
  385. def self._compile_reblog_insert(values)
  386. # This is somewhat equivalent to the following code of ActiveRecord::Persistence:
  387. # `arel_table.compile_insert(_substitute_values(values))`
  388. # The main difference is that we use a `SELECT` instead of a `VALUES` clause,
  389. # which means we have to build the `SELECT` clause ourselves and do a bit more
  390. # manual work.
  391. # Instead of using Arel::InsertManager#values, we are going to use Arel::InsertManager#select
  392. im = Arel::InsertManager.new
  393. im.into(arel_table)
  394. binds = []
  395. reblog_bind = nil
  396. values.each do |name, value|
  397. attr = arel_table[name]
  398. bind = predicate_builder.build_bind_attribute(attr.name, value)
  399. im.columns << attr
  400. binds << bind
  401. reblog_bind = bind if name == 'reblog_of_id'
  402. end
  403. im.select(arel_table.where(arel_table[:id].eq(reblog_bind)).where(arel_table[:deleted_at].eq(nil)).project(*binds))
  404. im
  405. end
  406. def discard_with_reblogs
  407. discard_time = Time.current
  408. Status.unscoped.where(reblog_of_id: id, deleted_at: [nil, deleted_at]).in_batches.update_all(deleted_at: discard_time) unless reblog?
  409. update_attribute(:deleted_at, discard_time)
  410. end
  411. def unlink_from_conversations!
  412. return unless direct_visibility?
  413. inbox_owners = mentioned_accounts.local
  414. inbox_owners += [account] if account.local?
  415. inbox_owners.each do |inbox_owner|
  416. AccountConversation.remove_status(inbox_owner, self)
  417. end
  418. end
  419. private
  420. def update_status_stat!(attrs)
  421. return if marked_for_destruction? || destroyed?
  422. status_stat.update(attrs)
  423. end
  424. def store_uri
  425. update_column(:uri, ActivityPub::TagManager.instance.uri_for(self)) if uri.nil?
  426. end
  427. def prepare_contents
  428. text&.strip!
  429. spoiler_text&.strip!
  430. end
  431. def set_reblog
  432. self.reblog = reblog.reblog if reblog? && reblog.reblog?
  433. end
  434. def set_poll_id
  435. update_column(:poll_id, poll.id) if association(:poll).loaded? && poll.present?
  436. end
  437. def set_visibility
  438. self.visibility = reblog.visibility if reblog? && visibility.nil?
  439. self.visibility = (account.locked? ? :private : :public) if visibility.nil?
  440. self.sensitive = false if sensitive.nil?
  441. end
  442. def set_locality
  443. if account.domain.nil? && !attribute_changed?(:local_only)
  444. self.local_only = marked_local_only?
  445. end
  446. end
  447. def set_conversation
  448. self.thread = thread.reblog if thread&.reblog?
  449. self.reply = !(in_reply_to_id.nil? && thread.nil?) unless reply
  450. if reply? && !thread.nil?
  451. self.in_reply_to_account_id = carried_over_reply_to_account_id
  452. self.conversation_id = thread.conversation_id if conversation_id.nil?
  453. elsif conversation_id.nil?
  454. self.conversation = Conversation.new
  455. end
  456. end
  457. def carried_over_reply_to_account_id
  458. if thread.account_id == account_id && thread.reply?
  459. thread.in_reply_to_account_id
  460. else
  461. thread.account_id
  462. end
  463. end
  464. def set_local
  465. self.local = account.local?
  466. end
  467. def update_statistics
  468. return unless distributable?
  469. ActivityTracker.increment('activity:statuses:local')
  470. end
  471. def increment_counter_caches
  472. return if direct_visibility?
  473. account&.increment_count!(:statuses_count)
  474. reblog&.increment_count!(:reblogs_count) if reblog?
  475. thread&.increment_count!(:replies_count) if in_reply_to_id.present? && distributable?
  476. end
  477. def decrement_counter_caches
  478. return if direct_visibility? || new_record?
  479. account&.decrement_count!(:statuses_count)
  480. reblog&.decrement_count!(:reblogs_count) if reblog?
  481. thread&.decrement_count!(:replies_count) if in_reply_to_id.present? && distributable?
  482. end
  483. end