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.

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