闭社主体 forked from https://github.com/tootsuite/mastodon
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.

442 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_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,
  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,
  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 reblog?
  138. !reblog_of_id.nil?
  139. end
  140. def within_realtime_window?
  141. created_at >= REAL_TIME_WINDOW.ago
  142. end
  143. def verb
  144. if destroyed?
  145. :delete
  146. else
  147. reblog? ? :share : :post
  148. end
  149. end
  150. def object_type
  151. reply? ? :comment : :note
  152. end
  153. def proper
  154. reblog? ? reblog : self
  155. end
  156. def content
  157. proper.text
  158. end
  159. def target
  160. reblog
  161. end
  162. def preview_card
  163. preview_cards.first
  164. end
  165. def hidden?
  166. !distributable?
  167. end
  168. def distributable?
  169. public_visibility? || unlisted_visibility?
  170. end
  171. alias sign? distributable?
  172. def with_media?
  173. media_attachments.any?
  174. end
  175. def non_sensitive_with_media?
  176. !sensitive? && with_media?
  177. end
  178. def reported?
  179. @reported ||= Report.where(target_account: account).unresolved.where('? = ANY(status_ids)', id).exists?
  180. end
  181. def emojis
  182. return @emojis if defined?(@emojis)
  183. fields = [spoiler_text, text]
  184. fields += preloadable_poll.options unless preloadable_poll.nil?
  185. @emojis = CustomEmoji.from_text(fields.join(' '), account.domain)
  186. end
  187. def replies_count
  188. status_stat&.replies_count || 0
  189. end
  190. def reblogs_count
  191. status_stat&.reblogs_count || 0
  192. end
  193. def favourites_count
  194. status_stat&.favourites_count || 0
  195. end
  196. def increment_count!(key)
  197. update_status_stat!(key => public_send(key) + 1)
  198. end
  199. def decrement_count!(key)
  200. update_status_stat!(key => [public_send(key) - 1, 0].max)
  201. end
  202. after_create_commit :increment_counter_caches
  203. after_destroy_commit :decrement_counter_caches
  204. after_create_commit :store_uri, if: :local?
  205. after_create_commit :update_statistics, if: :local?
  206. around_create Mastodon::Snowflake::Callbacks
  207. before_validation :prepare_contents, if: :local?
  208. before_validation :set_reblog
  209. before_validation :set_visibility
  210. before_validation :set_conversation
  211. before_validation :set_local
  212. after_create :set_poll_id
  213. class << self
  214. def selectable_visibilities
  215. visibilities.keys - %w(direct limited)
  216. end
  217. def favourites_map(status_ids, account_id)
  218. Favourite.select('status_id').where(status_id: status_ids).where(account_id: account_id).each_with_object({}) { |f, h| h[f.status_id] = true }
  219. end
  220. def bookmarks_map(status_ids, account_id)
  221. Bookmark.select('status_id').where(status_id: status_ids).where(account_id: account_id).map { |f| [f.status_id, true] }.to_h
  222. end
  223. def reblogs_map(status_ids, account_id)
  224. 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 }
  225. end
  226. def mutes_map(conversation_ids, account_id)
  227. ConversationMute.select('conversation_id').where(conversation_id: conversation_ids).where(account_id: account_id).each_with_object({}) { |m, h| h[m.conversation_id] = true }
  228. end
  229. def pins_map(status_ids, account_id)
  230. StatusPin.select('status_id').where(status_id: status_ids).where(account_id: account_id).each_with_object({}) { |p, h| h[p.status_id] = true }
  231. end
  232. def reload_stale_associations!(cached_items)
  233. account_ids = []
  234. cached_items.each do |item|
  235. account_ids << item.account_id
  236. account_ids << item.reblog.account_id if item.reblog?
  237. end
  238. account_ids.uniq!
  239. return if account_ids.empty?
  240. accounts = Account.where(id: account_ids).includes(:account_stat).index_by(&:id)
  241. cached_items.each do |item|
  242. item.account = accounts[item.account_id]
  243. item.reblog.account = accounts[item.reblog.account_id] if item.reblog?
  244. end
  245. end
  246. def permitted_for(target_account, account)
  247. visibility = [:public, :unlisted]
  248. if account.nil?
  249. where(visibility: visibility)
  250. elsif target_account.blocking?(account) || (account.domain.present? && target_account.domain_blocking?(account.domain)) # get rid of blocked peeps
  251. none
  252. elsif account.id == target_account.id # author can see own stuff
  253. all
  254. else
  255. # followers can see followers-only stuff, but also things they are mentioned in.
  256. # non-followers can see everything that isn't private/direct, but can see stuff they are mentioned in.
  257. visibility.push(:private) if account.following?(target_account)
  258. scope = left_outer_joins(:reblog)
  259. scope.where(visibility: visibility)
  260. .or(scope.where(id: account.mentions.select(:status_id)))
  261. .merge(scope.where(reblog_of_id: nil).or(scope.where.not(reblogs_statuses: { account_id: account.excluded_from_timeline_account_ids })))
  262. end
  263. end
  264. def from_text(text)
  265. return [] if text.blank?
  266. text.scan(FetchLinkCardService::URL_PATTERN).map(&:first).uniq.filter_map do |url|
  267. status = begin
  268. if TagManager.instance.local_url?(url)
  269. ActivityPub::TagManager.instance.uri_to_resource(url, Status)
  270. else
  271. EntityCache.instance.status(url)
  272. end
  273. end
  274. status&.distributable? ? status : nil
  275. end
  276. end
  277. end
  278. def status_stat
  279. super || build_status_stat
  280. end
  281. private
  282. def update_status_stat!(attrs)
  283. return if marked_for_destruction? || destroyed?
  284. status_stat.update(attrs)
  285. end
  286. def store_uri
  287. update_column(:uri, ActivityPub::TagManager.instance.uri_for(self)) if uri.nil?
  288. end
  289. def prepare_contents
  290. text&.strip!
  291. spoiler_text&.strip!
  292. end
  293. def set_reblog
  294. self.reblog = reblog.reblog if reblog? && reblog.reblog?
  295. end
  296. def set_poll_id
  297. update_column(:poll_id, poll.id) unless poll.nil?
  298. end
  299. def set_visibility
  300. self.visibility = reblog.visibility if reblog? && visibility.nil?
  301. self.visibility = (account.locked? ? :private : :public) if visibility.nil?
  302. self.sensitive = false if sensitive.nil?
  303. end
  304. def set_conversation
  305. self.thread = thread.reblog if thread&.reblog?
  306. self.reply = !(in_reply_to_id.nil? && thread.nil?) unless reply
  307. if reply? && !thread.nil?
  308. self.in_reply_to_account_id = carried_over_reply_to_account_id
  309. self.conversation_id = thread.conversation_id if conversation_id.nil?
  310. elsif conversation_id.nil?
  311. self.conversation = Conversation.new
  312. end
  313. end
  314. def carried_over_reply_to_account_id
  315. if thread.account_id == account_id && thread.reply?
  316. thread.in_reply_to_account_id
  317. else
  318. thread.account_id
  319. end
  320. end
  321. def set_local
  322. self.local = account.local?
  323. end
  324. def update_statistics
  325. return unless distributable?
  326. ActivityTracker.increment('activity:statuses:local')
  327. end
  328. def increment_counter_caches
  329. return if direct_visibility?
  330. account&.increment_count!(:statuses_count)
  331. reblog&.increment_count!(:reblogs_count) if reblog?
  332. thread&.increment_count!(:replies_count) if in_reply_to_id.present? && distributable?
  333. end
  334. def decrement_counter_caches
  335. return if direct_visibility?
  336. account&.decrement_count!(:statuses_count)
  337. reblog&.decrement_count!(:reblogs_count) if reblog?
  338. thread&.decrement_count!(:replies_count) if in_reply_to_id.present? && distributable?
  339. end
  340. def unlink_from_conversations
  341. return unless direct_visibility?
  342. mentioned_accounts = (association(:mentions).loaded? ? mentions : mentions.includes(:account)).map(&:account)
  343. inbox_owners = mentioned_accounts.select(&:local?) + (account.local? ? [account] : [])
  344. inbox_owners.each do |inbox_owner|
  345. AccountConversation.remove_status(inbox_owner, self)
  346. end
  347. end
  348. end