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.

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