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.

519 lines
16 KiB

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