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.

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