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.

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