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.

516 lines
17 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
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. #
  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 :poll, 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 :owned_poll, class_name: '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. validates_associated :owned_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: false }) }
  72. scope :including_silenced_accounts, -> { left_outer_joins(:account).where(accounts: { silenced: true }) }
  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. :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. :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. @emojis ||= CustomEmoji.from_text([spoiler_text, text].join(' '), account.domain)
  179. end
  180. def mark_for_mass_destruction!
  181. @marked_for_mass_destruction = true
  182. end
  183. def marked_for_mass_destruction?
  184. @marked_for_mass_destruction
  185. end
  186. def replies_count
  187. status_stat&.replies_count || 0
  188. end
  189. def reblogs_count
  190. status_stat&.reblogs_count || 0
  191. end
  192. def favourites_count
  193. status_stat&.favourites_count || 0
  194. end
  195. def increment_count!(key)
  196. update_status_stat!(key => public_send(key) + 1)
  197. end
  198. def decrement_count!(key)
  199. update_status_stat!(key => [public_send(key) - 1, 0].max)
  200. end
  201. after_create_commit :increment_counter_caches
  202. after_destroy_commit :decrement_counter_caches
  203. after_create_commit :store_uri, if: :local?
  204. after_create_commit :update_statistics, if: :local?
  205. around_create Mastodon::Snowflake::Callbacks
  206. before_validation :prepare_contents, if: :local?
  207. before_validation :set_reblog
  208. before_validation :set_visibility
  209. before_validation :set_conversation
  210. before_validation :set_local
  211. after_create :set_poll_id
  212. class << self
  213. def selectable_visibilities
  214. visibilities.keys - %w(direct limited)
  215. end
  216. def in_chosen_languages(account)
  217. where(language: nil).or where(language: account.chosen_languages)
  218. end
  219. def as_home_timeline(account)
  220. where(account: [account] + account.following).where(visibility: [:public, :unlisted, :private])
  221. end
  222. def as_direct_timeline(account, limit = 20, max_id = nil, since_id = nil, cache_ids = false)
  223. # direct timeline is mix of direct message from_me and to_me.
  224. # 2 queries are executed with pagination.
  225. # constant expression using arel_table is required for partial index
  226. # _from_me part does not require any timeline filters
  227. query_from_me = where(account_id: account.id)
  228. .where(Status.arel_table[:visibility].eq(3))
  229. .limit(limit)
  230. .order('statuses.id DESC')
  231. # _to_me part requires mute and block filter.
  232. # FIXME: may we check mutes.hide_notifications?
  233. query_to_me = Status
  234. .joins(:mentions)
  235. .merge(Mention.where(account_id: account.id))
  236. .where(Status.arel_table[:visibility].eq(3))
  237. .limit(limit)
  238. .order('mentions.status_id DESC')
  239. .not_excluded_by_account(account)
  240. if max_id.present?
  241. query_from_me = query_from_me.where('statuses.id < ?', max_id)
  242. query_to_me = query_to_me.where('mentions.status_id < ?', max_id)
  243. end
  244. if since_id.present?
  245. query_from_me = query_from_me.where('statuses.id > ?', since_id)
  246. query_to_me = query_to_me.where('mentions.status_id > ?', since_id)
  247. end
  248. if cache_ids
  249. # returns array of cache_ids object that have id and updated_at
  250. (query_from_me.cache_ids.to_a + query_to_me.cache_ids.to_a).uniq(&:id).sort_by(&:id).reverse.take(limit)
  251. else
  252. # returns ActiveRecord.Relation
  253. items = (query_from_me.select(:id).to_a + query_to_me.select(:id).to_a).uniq(&:id).sort_by(&:id).reverse.take(limit)
  254. Status.where(id: items.map(&:id))
  255. end
  256. end
  257. def as_public_timeline(account = nil, local_only = false)
  258. query = timeline_scope(local_only).without_replies
  259. apply_timeline_filters(query, account, local_only)
  260. end
  261. def as_tag_timeline(tag, account = nil, local_only = false)
  262. query = timeline_scope(local_only).tagged_with(tag)
  263. apply_timeline_filters(query, account, local_only)
  264. end
  265. def as_outbox_timeline(account)
  266. where(account: account, visibility: :public)
  267. end
  268. def favourites_map(status_ids, account_id)
  269. Favourite.select('status_id').where(status_id: status_ids).where(account_id: account_id).each_with_object({}) { |f, h| h[f.status_id] = true }
  270. end
  271. def reblogs_map(status_ids, account_id)
  272. 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 }
  273. end
  274. def mutes_map(conversation_ids, account_id)
  275. ConversationMute.select('conversation_id').where(conversation_id: conversation_ids).where(account_id: account_id).each_with_object({}) { |m, h| h[m.conversation_id] = true }
  276. end
  277. def pins_map(status_ids, account_id)
  278. StatusPin.select('status_id').where(status_id: status_ids).where(account_id: account_id).each_with_object({}) { |p, h| h[p.status_id] = true }
  279. end
  280. def reload_stale_associations!(cached_items)
  281. account_ids = []
  282. cached_items.each do |item|
  283. account_ids << item.account_id
  284. account_ids << item.reblog.account_id if item.reblog?
  285. end
  286. account_ids.uniq!
  287. return if account_ids.empty?
  288. accounts = Account.where(id: account_ids).includes(:account_stat).each_with_object({}) { |a, h| h[a.id] = a }
  289. cached_items.each do |item|
  290. item.account = accounts[item.account_id]
  291. item.reblog.account = accounts[item.reblog.account_id] if item.reblog?
  292. end
  293. end
  294. def permitted_for(target_account, account)
  295. visibility = [:public, :unlisted]
  296. if account.nil?
  297. where(visibility: visibility)
  298. elsif target_account.blocking?(account) # get rid of blocked peeps
  299. none
  300. elsif account.id == target_account.id # author can see own stuff
  301. all
  302. else
  303. # followers can see followers-only stuff, but also things they are mentioned in.
  304. # non-followers can see everything that isn't private/direct, but can see stuff they are mentioned in.
  305. visibility.push(:private) if account.following?(target_account)
  306. scope = left_outer_joins(:reblog)
  307. scope.where(visibility: visibility)
  308. .or(scope.where(id: account.mentions.select(:status_id)))
  309. .merge(scope.where(reblog_of_id: nil).or(scope.where.not(reblogs_statuses: { account_id: account.excluded_from_timeline_account_ids })))
  310. end
  311. end
  312. private
  313. def timeline_scope(local_only = false)
  314. starting_scope = local_only ? Status.local : Status
  315. starting_scope
  316. .with_public_visibility
  317. .without_reblogs
  318. end
  319. def apply_timeline_filters(query, account, local_only)
  320. if account.nil?
  321. filter_timeline_default(query)
  322. else
  323. filter_timeline_for_account(query, account, local_only)
  324. end
  325. end
  326. def filter_timeline_for_account(query, account, local_only)
  327. query = query.not_excluded_by_account(account)
  328. query = query.not_domain_blocked_by_account(account) unless local_only
  329. query = query.in_chosen_languages(account) if account.chosen_languages.present?
  330. query.merge(account_silencing_filter(account))
  331. end
  332. def filter_timeline_default(query)
  333. query.excluding_silenced_accounts
  334. end
  335. def account_silencing_filter(account)
  336. if account.silenced?
  337. including_myself = left_outer_joins(:account).where(account_id: account.id).references(:accounts)
  338. excluding_silenced_accounts.or(including_myself)
  339. else
  340. excluding_silenced_accounts
  341. end
  342. end
  343. end
  344. private
  345. def update_status_stat!(attrs)
  346. return if marked_for_destruction? || destroyed?
  347. record = status_stat || build_status_stat
  348. record.update(attrs)
  349. end
  350. def store_uri
  351. update_column(:uri, ActivityPub::TagManager.instance.uri_for(self)) if uri.nil?
  352. end
  353. def prepare_contents
  354. text&.strip!
  355. spoiler_text&.strip!
  356. end
  357. def set_reblog
  358. self.reblog = reblog.reblog if reblog? && reblog.reblog?
  359. end
  360. def set_poll_id
  361. update_column(:poll_id, owned_poll.id) unless owned_poll.nil?
  362. end
  363. def set_visibility
  364. self.visibility = (account.locked? ? :private : :public) if visibility.nil?
  365. self.visibility = reblog.visibility if reblog?
  366. self.sensitive = false if sensitive.nil?
  367. end
  368. def set_conversation
  369. self.thread = thread.reblog if thread&.reblog?
  370. self.reply = !(in_reply_to_id.nil? && thread.nil?) unless reply
  371. if reply? && !thread.nil?
  372. self.in_reply_to_account_id = carried_over_reply_to_account_id
  373. self.conversation_id = thread.conversation_id if conversation_id.nil?
  374. elsif conversation_id.nil?
  375. self.conversation = Conversation.new
  376. end
  377. end
  378. def carried_over_reply_to_account_id
  379. if thread.account_id == account_id && thread.reply?
  380. thread.in_reply_to_account_id
  381. else
  382. thread.account_id
  383. end
  384. end
  385. def set_local
  386. self.local = account.local?
  387. end
  388. def update_statistics
  389. return unless public_visibility? || unlisted_visibility?
  390. ActivityTracker.increment('activity:statuses:local')
  391. end
  392. def increment_counter_caches
  393. return if direct_visibility?
  394. account&.increment_count!(:statuses_count)
  395. reblog&.increment_count!(:reblogs_count) if reblog? && (public_visibility? || unlisted_visibility?)
  396. thread&.increment_count!(:replies_count) if in_reply_to_id.present? && (public_visibility? || unlisted_visibility?)
  397. end
  398. def decrement_counter_caches
  399. return if direct_visibility? || marked_for_mass_destruction?
  400. account&.decrement_count!(:statuses_count)
  401. reblog&.decrement_count!(:reblogs_count) if reblog? && (public_visibility? || unlisted_visibility?)
  402. thread&.decrement_count!(:replies_count) if in_reply_to_id.present? && (public_visibility? || unlisted_visibility?)
  403. end
  404. def unlink_from_conversations
  405. return unless direct_visibility?
  406. mentioned_accounts = mentions.includes(:account).map(&:account)
  407. inbox_owners = mentioned_accounts.select(&:local?) + (account.local? ? [account] : [])
  408. inbox_owners.each do |inbox_owner|
  409. AccountConversation.remove_status(inbox_owner, self)
  410. end
  411. end
  412. end