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.

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