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.

502 lines
16 KiB

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