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.

554 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. def with_media?
  178. media_attachments.any?
  179. end
  180. def non_sensitive_with_media?
  181. !sensitive? && with_media?
  182. end
  183. def emojis
  184. return @emojis if defined?(@emojis)
  185. fields = [spoiler_text, text]
  186. fields += preloadable_poll.options unless preloadable_poll.nil?
  187. @emojis = CustomEmoji.from_text(fields.join(' '), account.domain)
  188. end
  189. def mark_for_mass_destruction!
  190. @marked_for_mass_destruction = true
  191. end
  192. def marked_for_mass_destruction?
  193. @marked_for_mass_destruction
  194. end
  195. def replies_count
  196. status_stat&.replies_count || 0
  197. end
  198. def reblogs_count
  199. status_stat&.reblogs_count || 0
  200. end
  201. def favourites_count
  202. status_stat&.favourites_count || 0
  203. end
  204. def increment_count!(key)
  205. update_status_stat!(key => public_send(key) + 1)
  206. end
  207. def decrement_count!(key)
  208. update_status_stat!(key => [public_send(key) - 1, 0].max)
  209. end
  210. after_create_commit :increment_counter_caches
  211. after_destroy_commit :decrement_counter_caches
  212. after_create_commit :store_uri, if: :local?
  213. after_create_commit :update_statistics, if: :local?
  214. around_create Mastodon::Snowflake::Callbacks
  215. before_create :set_locality
  216. before_validation :prepare_contents, if: :local?
  217. before_validation :set_reblog
  218. before_validation :set_visibility
  219. before_validation :set_conversation
  220. before_validation :set_local
  221. after_create :set_poll_id
  222. class << self
  223. def selectable_visibilities
  224. visibilities.keys - %w(direct limited)
  225. end
  226. def in_chosen_languages(account)
  227. where(language: nil).or where(language: account.chosen_languages)
  228. end
  229. def as_home_timeline(account)
  230. where(account: [account] + account.following).where(visibility: [:public, :unlisted, :private])
  231. end
  232. def as_direct_timeline(account, limit = 20, max_id = nil, since_id = nil, cache_ids = false)
  233. # direct timeline is mix of direct message from_me and to_me.
  234. # 2 queries are executed with pagination.
  235. # constant expression using arel_table is required for partial index
  236. # _from_me part does not require any timeline filters
  237. query_from_me = where(account_id: account.id)
  238. .where(Status.arel_table[:visibility].eq(3))
  239. .limit(limit)
  240. .order('statuses.id DESC')
  241. # _to_me part requires mute and block filter.
  242. # FIXME: may we check mutes.hide_notifications?
  243. query_to_me = Status
  244. .joins(:mentions)
  245. .merge(Mention.where(account_id: account.id))
  246. .where(Status.arel_table[:visibility].eq(3))
  247. .limit(limit)
  248. .order('mentions.status_id DESC')
  249. .not_excluded_by_account(account)
  250. if max_id.present?
  251. query_from_me = query_from_me.where('statuses.id < ?', max_id)
  252. query_to_me = query_to_me.where('mentions.status_id < ?', max_id)
  253. end
  254. if since_id.present?
  255. query_from_me = query_from_me.where('statuses.id > ?', since_id)
  256. query_to_me = query_to_me.where('mentions.status_id > ?', since_id)
  257. end
  258. if cache_ids
  259. # returns array of cache_ids object that have id and updated_at
  260. (query_from_me.cache_ids.to_a + query_to_me.cache_ids.to_a).uniq(&:id).sort_by(&:id).reverse.take(limit)
  261. else
  262. # returns ActiveRecord.Relation
  263. items = (query_from_me.select(:id).to_a + query_to_me.select(:id).to_a).uniq(&:id).sort_by(&:id).reverse.take(limit)
  264. Status.where(id: items.map(&:id))
  265. end
  266. end
  267. def as_public_timeline(account = nil, local_only = false)
  268. query = timeline_scope(local_only)
  269. query = query.without_replies unless Setting.show_replies_in_public_timelines
  270. apply_timeline_filters(query, account, local_only)
  271. end
  272. def as_tag_timeline(tag, account = nil, local_only = false)
  273. query = timeline_scope(local_only).tagged_with(tag)
  274. apply_timeline_filters(query, account, local_only)
  275. end
  276. def as_outbox_timeline(account)
  277. where(account: account, visibility: :public)
  278. end
  279. def favourites_map(status_ids, account_id)
  280. Favourite.select('status_id').where(status_id: status_ids).where(account_id: account_id).each_with_object({}) { |f, h| h[f.status_id] = true }
  281. end
  282. def bookmarks_map(status_ids, account_id)
  283. Bookmark.select('status_id').where(status_id: status_ids).where(account_id: account_id).map { |f| [f.status_id, true] }.to_h
  284. end
  285. def reblogs_map(status_ids, account_id)
  286. 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 }
  287. end
  288. def mutes_map(conversation_ids, account_id)
  289. ConversationMute.select('conversation_id').where(conversation_id: conversation_ids).where(account_id: account_id).each_with_object({}) { |m, h| h[m.conversation_id] = true }
  290. end
  291. def pins_map(status_ids, account_id)
  292. StatusPin.select('status_id').where(status_id: status_ids).where(account_id: account_id).each_with_object({}) { |p, h| h[p.status_id] = true }
  293. end
  294. def reload_stale_associations!(cached_items)
  295. account_ids = []
  296. cached_items.each do |item|
  297. account_ids << item.account_id
  298. account_ids << item.reblog.account_id if item.reblog?
  299. end
  300. account_ids.uniq!
  301. return if account_ids.empty?
  302. accounts = Account.where(id: account_ids).includes(:account_stat).each_with_object({}) { |a, h| h[a.id] = a }
  303. cached_items.each do |item|
  304. item.account = accounts[item.account_id]
  305. item.reblog.account = accounts[item.reblog.account_id] if item.reblog?
  306. end
  307. end
  308. def permitted_for(target_account, account)
  309. visibility = [:public, :unlisted]
  310. if account.nil?
  311. where(visibility: visibility).not_local_only
  312. elsif target_account.blocking?(account) # get rid of blocked peeps
  313. none
  314. elsif account.id == target_account.id # author can see own stuff
  315. all
  316. else
  317. # followers can see followers-only stuff, but also things they are mentioned in.
  318. # non-followers can see everything that isn't private/direct, but can see stuff they are mentioned in.
  319. visibility.push(:private) if account.following?(target_account)
  320. scope = left_outer_joins(:reblog)
  321. scope.where(visibility: visibility)
  322. .or(scope.where(id: account.mentions.select(:status_id)))
  323. .merge(scope.where(reblog_of_id: nil).or(scope.where.not(reblogs_statuses: { account_id: account.excluded_from_timeline_account_ids })))
  324. end
  325. end
  326. private
  327. def timeline_scope(local_only = false)
  328. starting_scope = local_only ? Status.local : Status
  329. starting_scope = starting_scope.with_public_visibility
  330. if Setting.show_reblogs_in_public_timelines
  331. starting_scope
  332. else
  333. starting_scope.without_reblogs
  334. end
  335. end
  336. def apply_timeline_filters(query, account, local_only)
  337. if account.nil?
  338. filter_timeline_default(query)
  339. else
  340. filter_timeline_for_account(query, account, local_only)
  341. end
  342. end
  343. def filter_timeline_for_account(query, account, local_only)
  344. query = query.not_excluded_by_account(account)
  345. query = query.not_domain_blocked_by_account(account) unless local_only
  346. query = query.in_chosen_languages(account) if account.chosen_languages.present?
  347. query.merge(account_silencing_filter(account))
  348. end
  349. def filter_timeline_default(query)
  350. query.not_local_only.excluding_silenced_accounts
  351. end
  352. def account_silencing_filter(account)
  353. if account.silenced?
  354. including_myself = left_outer_joins(:account).where(account_id: account.id).references(:accounts)
  355. excluding_silenced_accounts.or(including_myself)
  356. else
  357. excluding_silenced_accounts
  358. end
  359. end
  360. end
  361. def marked_local_only?
  362. # match both with and without U+FE0F (the emoji variation selector)
  363. /#{local_only_emoji}\ufe0f?\z/.match?(content)
  364. end
  365. def local_only_emoji
  366. '👁'
  367. end
  368. private
  369. def update_status_stat!(attrs)
  370. return if marked_for_destruction? || destroyed?
  371. record = status_stat || build_status_stat
  372. record.update(attrs)
  373. end
  374. def store_uri
  375. update_column(:uri, ActivityPub::TagManager.instance.uri_for(self)) if uri.nil?
  376. end
  377. def prepare_contents
  378. text&.strip!
  379. spoiler_text&.strip!
  380. end
  381. def set_reblog
  382. self.reblog = reblog.reblog if reblog? && reblog.reblog?
  383. end
  384. def set_poll_id
  385. update_column(:poll_id, poll.id) unless poll.nil?
  386. end
  387. def set_visibility
  388. self.visibility = reblog.visibility if reblog? && visibility.nil?
  389. self.visibility = (account.locked? ? :private : :public) if visibility.nil?
  390. self.sensitive = false if sensitive.nil?
  391. end
  392. def set_locality
  393. if account.domain.nil? && !attribute_changed?(:local_only)
  394. self.local_only = marked_local_only?
  395. end
  396. end
  397. def set_conversation
  398. self.thread = thread.reblog if thread&.reblog?
  399. self.reply = !(in_reply_to_id.nil? && thread.nil?) unless reply
  400. if reply? && !thread.nil?
  401. self.in_reply_to_account_id = carried_over_reply_to_account_id
  402. self.conversation_id = thread.conversation_id if conversation_id.nil?
  403. elsif conversation_id.nil?
  404. self.conversation = Conversation.new
  405. end
  406. end
  407. def carried_over_reply_to_account_id
  408. if thread.account_id == account_id && thread.reply?
  409. thread.in_reply_to_account_id
  410. else
  411. thread.account_id
  412. end
  413. end
  414. def set_local
  415. self.local = account.local?
  416. end
  417. def update_statistics
  418. return unless public_visibility? || unlisted_visibility?
  419. ActivityTracker.increment('activity:statuses:local')
  420. end
  421. def increment_counter_caches
  422. return if direct_visibility?
  423. account&.increment_count!(:statuses_count)
  424. reblog&.increment_count!(:reblogs_count) if reblog? && (public_visibility? || unlisted_visibility?)
  425. thread&.increment_count!(:replies_count) if in_reply_to_id.present? && (public_visibility? || unlisted_visibility?)
  426. end
  427. def decrement_counter_caches
  428. return if direct_visibility? || marked_for_mass_destruction?
  429. account&.decrement_count!(:statuses_count)
  430. reblog&.decrement_count!(:reblogs_count) if reblog? && (public_visibility? || unlisted_visibility?)
  431. thread&.decrement_count!(:replies_count) if in_reply_to_id.present? && (public_visibility? || unlisted_visibility?)
  432. end
  433. def unlink_from_conversations
  434. return unless direct_visibility?
  435. mentioned_accounts = mentions.includes(:account).map(&:account)
  436. inbox_owners = mentioned_accounts.select(&:local?) + (account.local? ? [account] : [])
  437. inbox_owners.each do |inbox_owner|
  438. AccountConversation.remove_status(inbox_owner, self)
  439. end
  440. end
  441. end