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.

498 lines
16 KiB

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