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.

452 lines
14 KiB

  1. # frozen_string_literal: true
  2. class ActivityPub::Activity::Create < ActivityPub::Activity
  3. def perform
  4. return reject_payload! if unsupported_object_type? || invalid_origin?(@object['id']) || Tombstone.exists?(uri: @object['id']) || !related_to_local_activity?
  5. RedisLock.acquire(lock_options) do |lock|
  6. if lock.acquired?
  7. return if delete_arrived_first?(object_uri) || poll_vote?
  8. @status = find_existing_status
  9. if @status.nil?
  10. process_status
  11. elsif @options[:delivered_to_account_id].present?
  12. postprocess_audience_and_deliver
  13. end
  14. else
  15. raise Mastodon::RaceConditionError
  16. end
  17. end
  18. @status
  19. end
  20. private
  21. def process_status
  22. @tags = []
  23. @mentions = []
  24. @params = {}
  25. process_status_params
  26. process_tags
  27. process_audience
  28. ApplicationRecord.transaction do
  29. @status = Status.create!(@params)
  30. attach_tags(@status)
  31. end
  32. resolve_thread(@status)
  33. fetch_replies(@status)
  34. check_for_spam
  35. distribute(@status)
  36. forward_for_reply if @status.distributable?
  37. end
  38. def find_existing_status
  39. status = status_from_uri(object_uri)
  40. status ||= Status.find_by(uri: @object['atomUri']) if @object['atomUri'].present?
  41. status
  42. end
  43. def process_status_params
  44. @params = begin
  45. {
  46. uri: @object['id'],
  47. url: object_url || @object['id'],
  48. account: @account,
  49. text: text_from_content || '',
  50. language: detected_language,
  51. spoiler_text: converted_object_type? ? '' : (text_from_summary || ''),
  52. created_at: @object['published'],
  53. override_timestamps: @options[:override_timestamps],
  54. reply: @object['inReplyTo'].present?,
  55. sensitive: @object['sensitive'] || false,
  56. visibility: visibility_from_audience,
  57. thread: replied_to_status,
  58. conversation: conversation_from_uri(@object['conversation']),
  59. media_attachment_ids: process_attachments.take(4).map(&:id),
  60. poll: process_poll,
  61. }
  62. end
  63. end
  64. def process_audience
  65. (as_array(@object['to']) + as_array(@object['cc'])).uniq.each do |audience|
  66. next if audience == ActivityPub::TagManager::COLLECTIONS[:public]
  67. # Unlike with tags, there is no point in resolving accounts we don't already
  68. # know here, because silent mentions would only be used for local access
  69. # control anyway
  70. account = account_from_uri(audience)
  71. next if account.nil? || @mentions.any? { |mention| mention.account_id == account.id }
  72. @mentions << Mention.new(account: account, silent: true)
  73. # If there is at least one silent mention, then the status can be considered
  74. # as a limited-audience status, and not strictly a direct message, but only
  75. # if we considered a direct message in the first place
  76. next unless @params[:visibility] == :direct
  77. @params[:visibility] = :limited
  78. end
  79. # If the payload was delivered to a specific inbox, the inbox owner must have
  80. # access to it, unless they already have access to it anyway
  81. return if @options[:delivered_to_account_id].nil? || @mentions.any? { |mention| mention.account_id == @options[:delivered_to_account_id] }
  82. @mentions << Mention.new(account_id: @options[:delivered_to_account_id], silent: true)
  83. return unless @params[:visibility] == :direct
  84. @params[:visibility] = :limited
  85. end
  86. def postprocess_audience_and_deliver
  87. return if @status.mentions.find_by(account_id: @options[:delivered_to_account_id])
  88. delivered_to_account = Account.find(@options[:delivered_to_account_id])
  89. @status.mentions.create(account: delivered_to_account, silent: true)
  90. @status.update(visibility: :limited) if @status.direct_visibility?
  91. return unless delivered_to_account.following?(@account)
  92. FeedInsertWorker.perform_async(@status.id, delivered_to_account.id, :home)
  93. end
  94. def attach_tags(status)
  95. @tags.each do |tag|
  96. status.tags << tag
  97. TrendingTags.record_use!(tag, status.account, status.created_at) if status.public_visibility?
  98. end
  99. @mentions.each do |mention|
  100. mention.status = status
  101. mention.save
  102. end
  103. end
  104. def process_tags
  105. return if @object['tag'].nil?
  106. as_array(@object['tag']).each do |tag|
  107. if equals_or_includes?(tag['type'], 'Hashtag')
  108. process_hashtag tag
  109. elsif equals_or_includes?(tag['type'], 'Mention')
  110. process_mention tag
  111. elsif equals_or_includes?(tag['type'], 'Emoji')
  112. process_emoji tag
  113. end
  114. end
  115. end
  116. def process_hashtag(tag)
  117. return if tag['name'].blank?
  118. Tag.find_or_create_by_names(tag['name']) do |hashtag|
  119. @tags << hashtag unless @tags.include?(hashtag)
  120. end
  121. rescue ActiveRecord::RecordInvalid
  122. nil
  123. end
  124. def process_mention(tag)
  125. return if tag['href'].blank?
  126. account = account_from_uri(tag['href'])
  127. account = ::FetchRemoteAccountService.new.call(tag['href']) if account.nil?
  128. return if account.nil?
  129. @mentions << Mention.new(account: account, silent: false)
  130. end
  131. def process_emoji(tag)
  132. return if skip_download?
  133. return if tag['name'].blank? || tag['icon'].blank? || tag['icon']['url'].blank?
  134. shortcode = tag['name'].delete(':')
  135. image_url = tag['icon']['url']
  136. uri = tag['id']
  137. updated = tag['updated']
  138. emoji = CustomEmoji.find_by(shortcode: shortcode, domain: @account.domain)
  139. return unless emoji.nil? || image_url != emoji.image_remote_url || (updated && updated >= emoji.updated_at)
  140. emoji ||= CustomEmoji.new(domain: @account.domain, shortcode: shortcode, uri: uri)
  141. emoji.image_remote_url = image_url
  142. emoji.save
  143. end
  144. def process_attachments
  145. return [] if @object['attachment'].nil?
  146. media_attachments = []
  147. as_array(@object['attachment']).each do |attachment|
  148. next if attachment['url'].blank? || media_attachments.size >= 4
  149. begin
  150. href = Addressable::URI.parse(attachment['url']).normalize.to_s
  151. media_attachment = MediaAttachment.create(account: @account, remote_url: href, description: attachment['name'].presence, focus: attachment['focalPoint'], blurhash: supported_blurhash?(attachment['blurhash']) ? attachment['blurhash'] : nil)
  152. media_attachments << media_attachment
  153. next if unsupported_media_type?(attachment['mediaType']) || skip_download?
  154. media_attachment.file_remote_url = href
  155. media_attachment.save
  156. rescue Mastodon::UnexpectedResponseError, HTTP::TimeoutError, HTTP::ConnectionError, OpenSSL::SSL::SSLError
  157. RedownloadMediaWorker.perform_in(rand(30..600).seconds, media_attachment.id)
  158. end
  159. end
  160. media_attachments
  161. rescue Addressable::URI::InvalidURIError => e
  162. Rails.logger.debug "Invalid URL in attachment: #{e}"
  163. media_attachments
  164. end
  165. def process_poll
  166. return unless @object['type'] == 'Question' && (@object['anyOf'].is_a?(Array) || @object['oneOf'].is_a?(Array))
  167. expires_at = begin
  168. if @object['closed'].is_a?(String)
  169. @object['closed']
  170. elsif !@object['closed'].nil? && !@object['closed'].is_a?(FalseClass)
  171. Time.now.utc
  172. else
  173. @object['endTime']
  174. end
  175. end
  176. if @object['anyOf'].is_a?(Array)
  177. multiple = true
  178. items = @object['anyOf']
  179. else
  180. multiple = false
  181. items = @object['oneOf']
  182. end
  183. voters_count = @object['votersCount']
  184. @account.polls.new(
  185. multiple: multiple,
  186. expires_at: expires_at,
  187. options: items.map { |item| item['name'].presence || item['content'] }.compact,
  188. cached_tallies: items.map { |item| item.dig('replies', 'totalItems') || 0 },
  189. voters_count: voters_count
  190. )
  191. end
  192. def poll_vote?
  193. return false if replied_to_status.nil? || replied_to_status.preloadable_poll.nil? || !replied_to_status.local? || !replied_to_status.preloadable_poll.options.include?(@object['name'])
  194. poll_vote! unless replied_to_status.preloadable_poll.expired?
  195. true
  196. end
  197. def poll_vote!
  198. poll = replied_to_status.preloadable_poll
  199. already_voted = true
  200. RedisLock.acquire(poll_lock_options) do |lock|
  201. if lock.acquired?
  202. already_voted = poll.votes.where(account: @account).exists?
  203. poll.votes.create!(account: @account, choice: poll.options.index(@object['name']), uri: @object['id'])
  204. else
  205. raise Mastodon::RaceConditionError
  206. end
  207. end
  208. increment_voters_count! unless already_voted
  209. ActivityPub::DistributePollUpdateWorker.perform_in(3.minutes, replied_to_status.id) unless replied_to_status.preloadable_poll.hide_totals?
  210. end
  211. def resolve_thread(status)
  212. return unless status.reply? && status.thread.nil? && Request.valid_url?(in_reply_to_uri)
  213. ThreadResolveWorker.perform_async(status.id, in_reply_to_uri)
  214. end
  215. def fetch_replies(status)
  216. collection = @object['replies']
  217. return if collection.nil?
  218. replies = ActivityPub::FetchRepliesService.new.call(status, collection, false)
  219. return unless replies.nil?
  220. uri = value_or_id(collection)
  221. ActivityPub::FetchRepliesWorker.perform_async(status.id, uri) unless uri.nil?
  222. end
  223. def conversation_from_uri(uri)
  224. return nil if uri.nil?
  225. return Conversation.find_by(id: OStatus::TagManager.instance.unique_tag_to_local_id(uri, 'Conversation')) if OStatus::TagManager.instance.local_id?(uri)
  226. begin
  227. Conversation.find_or_create_by!(uri: uri)
  228. rescue ActiveRecord::RecordInvalid, ActiveRecord::RecordNotUnique
  229. retry
  230. end
  231. end
  232. def visibility_from_audience
  233. if equals_or_includes?(@object['to'], ActivityPub::TagManager::COLLECTIONS[:public])
  234. :public
  235. elsif equals_or_includes?(@object['cc'], ActivityPub::TagManager::COLLECTIONS[:public])
  236. :unlisted
  237. elsif equals_or_includes?(@object['to'], @account.followers_url)
  238. :private
  239. else
  240. :direct
  241. end
  242. end
  243. def audience_includes?(account)
  244. uri = ActivityPub::TagManager.instance.uri_for(account)
  245. equals_or_includes?(@object['to'], uri) || equals_or_includes?(@object['cc'], uri)
  246. end
  247. def replied_to_status
  248. return @replied_to_status if defined?(@replied_to_status)
  249. if in_reply_to_uri.blank?
  250. @replied_to_status = nil
  251. else
  252. @replied_to_status = status_from_uri(in_reply_to_uri)
  253. @replied_to_status ||= status_from_uri(@object['inReplyToAtomUri']) if @object['inReplyToAtomUri'].present?
  254. @replied_to_status
  255. end
  256. end
  257. def in_reply_to_uri
  258. value_or_id(@object['inReplyTo'])
  259. end
  260. def text_from_content
  261. return Formatter.instance.linkify([[text_from_name, text_from_summary.presence].compact.join("\n\n"), object_url || @object['id']].join(' ')) if converted_object_type?
  262. if @object['content'].present?
  263. @object['content']
  264. elsif content_language_map?
  265. @object['contentMap'].values.first
  266. end
  267. end
  268. def text_from_summary
  269. if @object['summary'].present?
  270. @object['summary']
  271. elsif summary_language_map?
  272. @object['summaryMap'].values.first
  273. end
  274. end
  275. def text_from_name
  276. if @object['name'].present?
  277. @object['name']
  278. elsif name_language_map?
  279. @object['nameMap'].values.first
  280. end
  281. end
  282. def detected_language
  283. if content_language_map?
  284. @object['contentMap'].keys.first
  285. elsif name_language_map?
  286. @object['nameMap'].keys.first
  287. elsif summary_language_map?
  288. @object['summaryMap'].keys.first
  289. elsif supported_object_type?
  290. LanguageDetector.instance.detect(text_from_content, @account)
  291. end
  292. end
  293. def object_url
  294. return if @object['url'].blank?
  295. url_candidate = url_to_href(@object['url'], 'text/html')
  296. if invalid_origin?(url_candidate)
  297. nil
  298. else
  299. url_candidate
  300. end
  301. end
  302. def summary_language_map?
  303. @object['summaryMap'].is_a?(Hash) && !@object['summaryMap'].empty?
  304. end
  305. def content_language_map?
  306. @object['contentMap'].is_a?(Hash) && !@object['contentMap'].empty?
  307. end
  308. def name_language_map?
  309. @object['nameMap'].is_a?(Hash) && !@object['nameMap'].empty?
  310. end
  311. def unsupported_media_type?(mime_type)
  312. mime_type.present? && !MediaAttachment.supported_mime_types.include?(mime_type)
  313. end
  314. def supported_blurhash?(blurhash)
  315. components = blurhash.blank? ? nil : Blurhash.components(blurhash)
  316. components.present? && components.none? { |comp| comp > 5 }
  317. end
  318. def skip_download?
  319. return @skip_download if defined?(@skip_download)
  320. @skip_download ||= DomainBlock.reject_media?(@account.domain)
  321. end
  322. def reply_to_local?
  323. !replied_to_status.nil? && replied_to_status.account.local?
  324. end
  325. def related_to_local_activity?
  326. fetch? || followed_by_local_accounts? || requested_through_relay? ||
  327. responds_to_followed_account? || addresses_local_accounts?
  328. end
  329. def responds_to_followed_account?
  330. !replied_to_status.nil? && (replied_to_status.account.local? || replied_to_status.account.passive_relationships.exists?)
  331. end
  332. def addresses_local_accounts?
  333. return true if @options[:delivered_to_account_id]
  334. local_usernames = (as_array(@object['to']) + as_array(@object['cc'])).uniq.select { |uri| ActivityPub::TagManager.instance.local_uri?(uri) }.map { |uri| ActivityPub::TagManager.instance.uri_to_local_id(uri, :username) }
  335. return false if local_usernames.empty?
  336. Account.local.where(username: local_usernames).exists?
  337. end
  338. def check_for_spam
  339. SpamCheck.perform(@status)
  340. end
  341. def forward_for_reply
  342. return unless @json['signature'].present? && reply_to_local?
  343. ActivityPub::RawDistributionWorker.perform_async(Oj.dump(@json), replied_to_status.account_id, [@account.preferred_inbox_url])
  344. end
  345. def increment_voters_count!
  346. poll = replied_to_status.preloadable_poll
  347. unless poll.voters_count.nil?
  348. poll.voters_count = poll.voters_count + 1
  349. poll.save
  350. end
  351. rescue ActiveRecord::StaleObjectError
  352. poll.reload
  353. retry
  354. end
  355. def lock_options
  356. { redis: Redis.current, key: "create:#{@object['id']}" }
  357. end
  358. def poll_lock_options
  359. { redis: Redis.current, key: "vote:#{replied_to_status.poll_id}:#{@account.id}" }
  360. end
  361. end