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.

515 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
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. # local_only :boolean
  25. # full_status_text :text default(""), not null
  26. #
  27. class Status < ApplicationRecord
  28. before_destroy :unlink_from_conversations
  29. include Paginable
  30. include Streamable
  31. include Cacheable
  32. include StatusThreadingConcern
  33. # If `override_timestamps` is set at creation time, Snowflake ID creation
  34. # will be based on current time instead of `created_at`
  35. attr_accessor :override_timestamps
  36. update_index('statuses#status', :proper) if Chewy.enabled?
  37. enum visibility: [:public, :unlisted, :private, :direct], _suffix: :visibility
  38. belongs_to :application, class_name: 'Doorkeeper::Application', optional: true
  39. belongs_to :account, inverse_of: :statuses
  40. belongs_to :in_reply_to_account, foreign_key: 'in_reply_to_account_id', class_name: 'Account', optional: true
  41. belongs_to :conversation, 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 :bookmarks, inverse_of: :status, dependent: :destroy
  46. has_many :reblogs, foreign_key: 'reblog_of_id', class_name: 'Status', inverse_of: :reblog, dependent: :destroy
  47. has_many :replies, foreign_key: 'in_reply_to_id', class_name: 'Status', inverse_of: :thread
  48. has_many :mentions, dependent: :destroy
  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. validates :uri, uniqueness: true, presence: true, unless: :local?
  56. validates :text, presence: true, unless: -> { with_media? || reblog? }
  57. validates_with StatusLengthValidator
  58. validates_with DisallowedHashtagsValidator
  59. validates :reblog, uniqueness: { scope: :account }, if: :reblog?
  60. default_scope { recent }
  61. scope :recent, -> { reorder(id: :desc) }
  62. scope :remote, -> { where(local: false).or(where.not(uri: nil)) }
  63. scope :local, -> { where(local: true).or(where(uri: nil)) }
  64. scope :without_replies, -> { where('statuses.reply = FALSE OR statuses.in_reply_to_account_id = statuses.account_id') }
  65. scope :without_reblogs, -> { where('statuses.reblog_of_id IS NULL') }
  66. scope :with_public_visibility, -> { where(visibility: :public) }
  67. scope :tagged_with, ->(tag) { joins(:statuses_tags).where(statuses_tags: { tag_id: tag }) }
  68. scope :excluding_silenced_accounts, -> { left_outer_joins(:account).where(accounts: { silenced: false }) }
  69. scope :including_silenced_accounts, -> { left_outer_joins(:account).where(accounts: { silenced: true }) }
  70. scope :not_excluded_by_account, ->(account) { where.not(account_id: account.excluded_from_timeline_account_ids) }
  71. 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) }
  72. scope :not_local_only, -> { where(local_only: [false, nil]) }
  73. cache_associated :account,
  74. :application,
  75. :media_attachments,
  76. :conversation,
  77. :status_stat,
  78. :tags,
  79. :stream_entry,
  80. mentions: :account,
  81. reblog: [
  82. :account,
  83. :application,
  84. :stream_entry,
  85. :tags,
  86. :media_attachments,
  87. :conversation,
  88. :status_stat,
  89. mentions: :account,
  90. ],
  91. thread: :account
  92. delegate :domain, to: :account, prefix: true
  93. REAL_TIME_WINDOW = 6.hours
  94. def searchable_by(preloaded = nil)
  95. ids = [account_id]
  96. if preloaded.nil?
  97. ids += mentions.pluck(:account_id)
  98. ids += favourites.pluck(:account_id)
  99. ids += reblogs.pluck(:account_id)
  100. else
  101. ids += preloaded.mentions[id] || []
  102. ids += preloaded.favourites[id] || []
  103. ids += preloaded.reblogs[id] || []
  104. end
  105. ids.uniq
  106. end
  107. def reply?
  108. !in_reply_to_id.nil? || attributes['reply']
  109. end
  110. def local?
  111. attributes['local'] || uri.nil?
  112. end
  113. def reblog?
  114. !reblog_of_id.nil?
  115. end
  116. def within_realtime_window?
  117. created_at >= REAL_TIME_WINDOW.ago
  118. end
  119. def verb
  120. if destroyed?
  121. :delete
  122. else
  123. reblog? ? :share : :post
  124. end
  125. end
  126. def object_type
  127. reply? ? :comment : :note
  128. end
  129. def proper
  130. reblog? ? reblog : self
  131. end
  132. def content
  133. proper.text
  134. end
  135. def target
  136. reblog
  137. end
  138. def title
  139. if destroyed?
  140. "#{account.acct} deleted status"
  141. else
  142. reblog? ? "#{account.acct} shared a status by #{reblog.account.acct}" : "New status by #{account.acct}"
  143. end
  144. end
  145. def hidden?
  146. private_visibility? || direct_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_create :set_locality
  184. before_validation :prepare_contents, if: :local?
  185. before_validation :set_reblog
  186. before_validation :set_visibility
  187. before_validation :set_conversation
  188. before_validation :set_local
  189. class << self
  190. def cache_ids
  191. left_outer_joins(:status_stat).select('statuses.id, greatest(statuses.updated_at, status_stats.updated_at) AS updated_at')
  192. end
  193. def in_chosen_languages(account)
  194. where(language: nil).or where(language: account.chosen_languages)
  195. end
  196. def as_home_timeline(account)
  197. where(account: [account] + account.following).where(visibility: [:public, :unlisted, :private])
  198. end
  199. def as_direct_timeline(account, limit = 20, max_id = nil, since_id = nil, cache_ids = false)
  200. # direct timeline is mix of direct message from_me and to_me.
  201. # 2 queries are executed with pagination.
  202. # constant expression using arel_table is required for partial index
  203. # _from_me part does not require any timeline filters
  204. query_from_me = where(account_id: account.id)
  205. .where(Status.arel_table[:visibility].eq(3))
  206. .limit(limit)
  207. .order('statuses.id DESC')
  208. # _to_me part requires mute and block filter.
  209. # FIXME: may we check mutes.hide_notifications?
  210. query_to_me = Status
  211. .joins(:mentions)
  212. .merge(Mention.where(account_id: account.id))
  213. .where(Status.arel_table[:visibility].eq(3))
  214. .limit(limit)
  215. .order('mentions.status_id DESC')
  216. .not_excluded_by_account(account)
  217. if max_id.present?
  218. query_from_me = query_from_me.where('statuses.id < ?', max_id)
  219. query_to_me = query_to_me.where('mentions.status_id < ?', max_id)
  220. end
  221. if since_id.present?
  222. query_from_me = query_from_me.where('statuses.id > ?', since_id)
  223. query_to_me = query_to_me.where('mentions.status_id > ?', since_id)
  224. end
  225. if cache_ids
  226. # returns array of cache_ids object that have id and updated_at
  227. (query_from_me.cache_ids.to_a + query_to_me.cache_ids.to_a).uniq(&:id).sort_by(&:id).reverse.take(limit)
  228. else
  229. # returns ActiveRecord.Relation
  230. items = (query_from_me.select(:id).to_a + query_to_me.select(:id).to_a).uniq(&:id).sort_by(&:id).reverse.take(limit)
  231. Status.where(id: items.map(&:id))
  232. end
  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).map { |f| [f.status_id, true] }.to_h
  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. 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
  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).map { |m| [m.conversation_id, true] }.to_h
  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).map { |p| [p.status_id, true] }.to_h
  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).map { |a| [a.id, a] }.to_h
  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).not_local_only
  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.not_local_only.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 marked_local_only?
  325. # match both with and without U+FE0F (the emoji variation selector)
  326. /#{local_only_emoji}\ufe0f?\z/.match?(content)
  327. end
  328. def local_only_emoji
  329. '👁'
  330. end
  331. private
  332. def update_status_stat!(attrs)
  333. return if marked_for_destruction? || destroyed?
  334. record = status_stat || build_status_stat
  335. record.update(attrs)
  336. end
  337. def store_uri
  338. update_attribute(:uri, ActivityPub::TagManager.instance.uri_for(self)) if uri.nil?
  339. end
  340. def prepare_contents
  341. text&.strip!
  342. spoiler_text&.strip!
  343. end
  344. def set_reblog
  345. self.reblog = reblog.reblog if reblog? && reblog.reblog?
  346. end
  347. def set_visibility
  348. self.visibility = (account.locked? ? :private : :public) if visibility.nil?
  349. self.visibility = reblog.visibility if reblog?
  350. self.sensitive = false if sensitive.nil?
  351. end
  352. def set_locality
  353. if account.domain.nil? && !attribute_changed?(:local_only)
  354. self.local_only = marked_local_only?
  355. end
  356. end
  357. def set_conversation
  358. self.reply = !(in_reply_to_id.nil? && thread.nil?) unless reply
  359. if reply? && !thread.nil?
  360. self.in_reply_to_account_id = carried_over_reply_to_account_id
  361. self.conversation_id = thread.conversation_id if conversation_id.nil?
  362. elsif conversation_id.nil?
  363. self.conversation = Conversation.new
  364. end
  365. end
  366. def carried_over_reply_to_account_id
  367. if thread.account_id == account_id && thread.reply?
  368. thread.in_reply_to_account_id
  369. else
  370. thread.account_id
  371. end
  372. end
  373. def set_local
  374. self.local = account.local?
  375. end
  376. def update_statistics
  377. return unless public_visibility? || unlisted_visibility?
  378. ActivityTracker.increment('activity:statuses:local')
  379. end
  380. def increment_counter_caches
  381. return if direct_visibility?
  382. if association(:account).loaded?
  383. account.update_attribute(:statuses_count, account.statuses_count + 1)
  384. else
  385. Account.where(id: account_id).update_all('statuses_count = COALESCE(statuses_count, 0) + 1')
  386. end
  387. reblog&.increment_count!(:reblogs_count) if reblog?
  388. thread&.increment_count!(:replies_count) if in_reply_to_id.present? && (public_visibility? || unlisted_visibility?)
  389. end
  390. def decrement_counter_caches
  391. return if direct_visibility? || marked_for_mass_destruction?
  392. if association(:account).loaded?
  393. account.update_attribute(:statuses_count, [account.statuses_count - 1, 0].max)
  394. else
  395. Account.where(id: account_id).update_all('statuses_count = GREATEST(COALESCE(statuses_count, 0) - 1, 0)')
  396. end
  397. reblog&.decrement_count!(:reblogs_count) if reblog?
  398. thread&.decrement_count!(:replies_count) if in_reply_to_id.present? && (public_visibility? || unlisted_visibility?)
  399. end
  400. def unlink_from_conversations
  401. return unless direct_visibility?
  402. mentioned_accounts = mentions.includes(:account).map(&:account)
  403. inbox_owners = mentioned_accounts.select(&:local?) + (account.local? ? [account] : [])
  404. inbox_owners.each do |inbox_owner|
  405. AccountConversation.remove_status(inbox_owner, self)
  406. end
  407. end
  408. end