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.

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