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