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.

444 lines
14 KiB

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