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.

469 lines
15 KiB

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. # poll_id :bigint(8)
  25. # deleted_at :datetime
  26. # edited_at :datetime
  27. # trendable :boolean
  28. # ordered_media_attachment_ids :bigint(8) is an Array
  29. #
  30. class Status < ApplicationRecord
  31. before_destroy :unlink_from_conversations
  32. include Discard::Model
  33. include Paginable
  34. include Cacheable
  35. include StatusThreadingConcern
  36. include RateLimitable
  37. rate_limit by: :account, family: :statuses
  38. self.discard_column = :deleted_at
  39. # If `override_timestamps` is set at creation time, Snowflake ID creation
  40. # will be based on current time instead of `created_at`
  41. attr_accessor :override_timestamps
  42. update_index('statuses', :proper)
  43. enum visibility: [:public, :unlisted, :private, :direct, :limited], _suffix: :visibility
  44. belongs_to :application, class_name: 'Doorkeeper::Application', optional: true
  45. belongs_to :account, inverse_of: :statuses
  46. belongs_to :in_reply_to_account, foreign_key: 'in_reply_to_account_id', class_name: 'Account', optional: true
  47. belongs_to :conversation, optional: true
  48. belongs_to :preloadable_poll, class_name: 'Poll', foreign_key: 'poll_id', optional: true
  49. belongs_to :thread, foreign_key: 'in_reply_to_id', class_name: 'Status', inverse_of: :replies, optional: true
  50. belongs_to :reblog, foreign_key: 'reblog_of_id', class_name: 'Status', inverse_of: :reblogs, optional: true
  51. has_many :edits, class_name: 'StatusEdit', inverse_of: :status, dependent: :destroy
  52. has_many :favourites, inverse_of: :status, dependent: :destroy
  53. has_many :bookmarks, inverse_of: :status, dependent: :destroy
  54. has_many :reblogs, foreign_key: 'reblog_of_id', class_name: 'Status', inverse_of: :reblog, dependent: :destroy
  55. has_many :reblogged_by_accounts, through: :reblogs, class_name: 'Account', source: :account
  56. has_many :replies, foreign_key: 'in_reply_to_id', class_name: 'Status', inverse_of: :thread
  57. has_many :mentions, dependent: :destroy, inverse_of: :status
  58. has_many :active_mentions, -> { active }, class_name: 'Mention', inverse_of: :status
  59. has_many :media_attachments, dependent: :nullify
  60. has_and_belongs_to_many :tags
  61. has_and_belongs_to_many :preview_cards
  62. has_one :notification, as: :activity, dependent: :destroy
  63. has_one :status_stat, inverse_of: :status
  64. has_one :poll, inverse_of: :status, dependent: :destroy
  65. validates :uri, uniqueness: true, presence: true, unless: :local?
  66. validates :text, presence: true, unless: -> { with_media? || reblog? }
  67. validates_with StatusLengthValidator
  68. validates_with DisallowedHashtagsValidator
  69. validates :reblog, uniqueness: { scope: :account }, if: :reblog?
  70. validates :visibility, exclusion: { in: %w(direct limited) }, if: :reblog?
  71. accepts_nested_attributes_for :poll
  72. default_scope { recent.kept }
  73. scope :recent, -> { reorder(id: :desc) }
  74. scope :remote, -> { where(local: false).where.not(uri: nil) }
  75. scope :local, -> { where(local: true).or(where(uri: nil)) }
  76. scope :with_accounts, ->(ids) { where(id: ids).includes(:account) }
  77. scope :without_replies, -> { where('statuses.reply = FALSE OR statuses.in_reply_to_account_id = statuses.account_id') }
  78. scope :without_reblogs, -> { where('statuses.reblog_of_id IS NULL') }
  79. scope :with_public_visibility, -> { where(visibility: :public) }
  80. scope :tagged_with, ->(tag_ids) { joins(:statuses_tags).where(statuses_tags: { tag_id: tag_ids }) }
  81. scope :in_chosen_languages, ->(account) { where(language: nil).or where(language: account.chosen_languages) }
  82. scope :excluding_silenced_accounts, -> { left_outer_joins(:account).where(accounts: { silenced_at: nil }) }
  83. scope :including_silenced_accounts, -> { left_outer_joins(:account).where.not(accounts: { silenced_at: nil }) }
  84. scope :not_excluded_by_account, ->(account) { where.not(account_id: account.excluded_from_timeline_account_ids) }
  85. 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) }
  86. scope :tagged_with_all, ->(tag_ids) {
  87. Array(tag_ids).map(&:to_i).reduce(self) do |result, id|
  88. result.joins("INNER JOIN statuses_tags t#{id} ON t#{id}.status_id = statuses.id AND t#{id}.tag_id = #{id}")
  89. end
  90. }
  91. scope :tagged_with_none, ->(tag_ids) {
  92. where('NOT EXISTS (SELECT * FROM statuses_tags forbidden WHERE forbidden.status_id = statuses.id AND forbidden.tag_id IN (?))', tag_ids)
  93. }
  94. cache_associated :application,
  95. :media_attachments,
  96. :conversation,
  97. :status_stat,
  98. :tags,
  99. :preview_cards,
  100. :preloadable_poll,
  101. account: [:account_stat, :user],
  102. active_mentions: { account: :account_stat },
  103. reblog: [
  104. :application,
  105. :tags,
  106. :preview_cards,
  107. :media_attachments,
  108. :conversation,
  109. :status_stat,
  110. :preloadable_poll,
  111. account: [:account_stat, :user],
  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 = []
  119. ids << account_id if local?
  120. if preloaded.nil?
  121. ids += mentions.where(account: Account.local, silent: false).pluck(:account_id)
  122. ids += favourites.where(account: Account.local).pluck(:account_id)
  123. ids += reblogs.where(account: Account.local).pluck(:account_id)
  124. ids += bookmarks.where(account: Account.local).pluck(:account_id)
  125. else
  126. ids += preloaded.mentions[id] || []
  127. ids += preloaded.favourites[id] || []
  128. ids += preloaded.reblogs[id] || []
  129. ids += preloaded.bookmarks[id] || []
  130. end
  131. ids.uniq
  132. end
  133. def reply?
  134. !in_reply_to_id.nil? || attributes['reply']
  135. end
  136. def local?
  137. attributes['local'] || uri.nil?
  138. end
  139. def in_reply_to_local_account?
  140. reply? && thread&.account&.local?
  141. end
  142. def reblog?
  143. !reblog_of_id.nil?
  144. end
  145. def within_realtime_window?
  146. created_at >= REAL_TIME_WINDOW.ago
  147. end
  148. def verb
  149. if destroyed?
  150. :delete
  151. else
  152. reblog? ? :share : :post
  153. end
  154. end
  155. def object_type
  156. reply? ? :comment : :note
  157. end
  158. def proper
  159. reblog? ? reblog : self
  160. end
  161. def content
  162. proper.text
  163. end
  164. def target
  165. reblog
  166. end
  167. def preview_card
  168. preview_cards.first
  169. end
  170. def hidden?
  171. !distributable?
  172. end
  173. def distributable?
  174. public_visibility? || unlisted_visibility?
  175. end
  176. def snapshot!(account_id: nil, at_time: nil)
  177. edits.create!(
  178. text: text,
  179. spoiler_text: spoiler_text,
  180. sensitive: sensitive,
  181. ordered_media_attachment_ids: ordered_media_attachment_ids || media_attachments.pluck(:id),
  182. media_descriptions: ordered_media_attachments.map(&:description),
  183. poll_options: preloadable_poll&.options,
  184. account_id: account_id || self.account_id,
  185. created_at: at_time || edited_at
  186. )
  187. end
  188. def edited?
  189. edited_at.present?
  190. end
  191. alias sign? distributable?
  192. def with_media?
  193. ordered_media_attachments.any?
  194. end
  195. def with_preview_card?
  196. preview_cards.any?
  197. end
  198. def non_sensitive_with_media?
  199. !sensitive? && with_media?
  200. end
  201. def reported?
  202. @reported ||= Report.where(target_account: account).unresolved.where('? = ANY(status_ids)', id).exists?
  203. end
  204. def emojis
  205. return @emojis if defined?(@emojis)
  206. fields = [spoiler_text, text]
  207. fields += preloadable_poll.options unless preloadable_poll.nil?
  208. @emojis = CustomEmoji.from_text(fields.join(' '), account.domain)
  209. end
  210. def ordered_media_attachments
  211. if ordered_media_attachment_ids.nil?
  212. media_attachments
  213. else
  214. map = media_attachments.index_by(&:id)
  215. ordered_media_attachment_ids.map { |media_attachment_id| map[media_attachment_id] }
  216. end
  217. end
  218. def replies_count
  219. status_stat&.replies_count || 0
  220. end
  221. def reblogs_count
  222. status_stat&.reblogs_count || 0
  223. end
  224. def favourites_count
  225. status_stat&.favourites_count || 0
  226. end
  227. def increment_count!(key)
  228. update_status_stat!(key => public_send(key) + 1)
  229. end
  230. def decrement_count!(key)
  231. update_status_stat!(key => [public_send(key) - 1, 0].max)
  232. end
  233. def trendable?
  234. if attributes['trendable'].nil?
  235. account.trendable?
  236. else
  237. attributes['trendable']
  238. end
  239. end
  240. def requires_review_notification?
  241. attributes['trendable'].nil? && account.requires_review_notification?
  242. end
  243. after_create_commit :increment_counter_caches
  244. after_destroy_commit :decrement_counter_caches
  245. after_create_commit :store_uri, if: :local?
  246. after_create_commit :update_statistics, if: :local?
  247. around_create Mastodon::Snowflake::Callbacks
  248. before_validation :prepare_contents, if: :local?
  249. before_validation :set_reblog
  250. before_validation :set_visibility
  251. before_validation :set_conversation
  252. before_validation :set_local
  253. after_create :set_poll_id
  254. class << self
  255. def selectable_visibilities
  256. visibilities.keys - %w(direct limited)
  257. end
  258. def favourites_map(status_ids, account_id)
  259. Favourite.select('status_id').where(status_id: status_ids).where(account_id: account_id).each_with_object({}) { |f, h| h[f.status_id] = true }
  260. end
  261. def bookmarks_map(status_ids, account_id)
  262. Bookmark.select('status_id').where(status_id: status_ids).where(account_id: account_id).map { |f| [f.status_id, true] }.to_h
  263. end
  264. def reblogs_map(status_ids, account_id)
  265. unscoped.select('reblog_of_id').where(reblog_of_id: status_ids).where(account_id: account_id).each_with_object({}) { |s, h| h[s.reblog_of_id] = true }
  266. end
  267. def mutes_map(conversation_ids, account_id)
  268. ConversationMute.select('conversation_id').where(conversation_id: conversation_ids).where(account_id: account_id).each_with_object({}) { |m, h| h[m.conversation_id] = true }
  269. end
  270. def pins_map(status_ids, account_id)
  271. StatusPin.select('status_id').where(status_id: status_ids).where(account_id: account_id).each_with_object({}) { |p, h| h[p.status_id] = true }
  272. end
  273. def reload_stale_associations!(cached_items)
  274. account_ids = []
  275. cached_items.each do |item|
  276. account_ids << item.account_id
  277. account_ids << item.reblog.account_id if item.reblog?
  278. end
  279. account_ids.uniq!
  280. return if account_ids.empty?
  281. accounts = Account.where(id: account_ids).includes(:account_stat, :user).index_by(&:id)
  282. cached_items.each do |item|
  283. item.account = accounts[item.account_id]
  284. item.reblog.account = accounts[item.reblog.account_id] if item.reblog?
  285. end
  286. end
  287. def from_text(text)
  288. return [] if text.blank?
  289. text.scan(FetchLinkCardService::URL_PATTERN).map(&:second).uniq.filter_map do |url|
  290. status = begin
  291. if TagManager.instance.local_url?(url)
  292. ActivityPub::TagManager.instance.uri_to_resource(url, Status)
  293. else
  294. EntityCache.instance.status(url)
  295. end
  296. end
  297. status&.distributable? ? status : nil
  298. end
  299. end
  300. end
  301. def status_stat
  302. super || build_status_stat
  303. end
  304. private
  305. def update_status_stat!(attrs)
  306. return if marked_for_destruction? || destroyed?
  307. status_stat.update(attrs)
  308. end
  309. def store_uri
  310. update_column(:uri, ActivityPub::TagManager.instance.uri_for(self)) if uri.nil?
  311. end
  312. def prepare_contents
  313. text&.strip!
  314. spoiler_text&.strip!
  315. end
  316. def set_reblog
  317. self.reblog = reblog.reblog if reblog? && reblog.reblog?
  318. end
  319. def set_poll_id
  320. update_column(:poll_id, poll.id) unless poll.nil?
  321. end
  322. def set_visibility
  323. self.visibility = reblog.visibility if reblog? && visibility.nil?
  324. self.visibility = (account.locked? ? :private : :public) if visibility.nil?
  325. self.sensitive = false if sensitive.nil?
  326. end
  327. def set_conversation
  328. self.thread = thread.reblog if thread&.reblog?
  329. self.reply = !(in_reply_to_id.nil? && thread.nil?) unless reply
  330. if reply? && !thread.nil?
  331. self.in_reply_to_account_id = carried_over_reply_to_account_id
  332. self.conversation_id = thread.conversation_id if conversation_id.nil?
  333. elsif conversation_id.nil?
  334. self.conversation = Conversation.new
  335. end
  336. end
  337. def carried_over_reply_to_account_id
  338. if thread.account_id == account_id && thread.reply?
  339. thread.in_reply_to_account_id
  340. else
  341. thread.account_id
  342. end
  343. end
  344. def set_local
  345. self.local = account.local?
  346. end
  347. def update_statistics
  348. return unless distributable?
  349. ActivityTracker.increment('activity:statuses:local')
  350. end
  351. def increment_counter_caches
  352. return if direct_visibility?
  353. account&.increment_count!(:statuses_count)
  354. reblog&.increment_count!(:reblogs_count) if reblog?
  355. thread&.increment_count!(:replies_count) if in_reply_to_id.present? && distributable?
  356. end
  357. def decrement_counter_caches
  358. return if direct_visibility? || new_record?
  359. account&.decrement_count!(:statuses_count)
  360. reblog&.decrement_count!(:reblogs_count) if reblog?
  361. thread&.decrement_count!(:replies_count) if in_reply_to_id.present? && distributable?
  362. end
  363. def unlink_from_conversations
  364. return unless direct_visibility?
  365. mentioned_accounts = (association(:mentions).loaded? ? mentions : mentions.includes(:account)).map(&:account)
  366. inbox_owners = mentioned_accounts.select(&:local?) + (account.local? ? [account] : [])
  367. inbox_owners.each do |inbox_owner|
  368. AccountConversation.remove_status(inbox_owner, self)
  369. end
  370. end
  371. end