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.

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