The code powering m.abunchtell.com https://m.abunchtell.com
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.
 
 
 
 

523 lines
17 KiB

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