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.

514 lines
15 KiB

  1. # frozen_string_literal: true
  2. class ActivityPub::Activity::Create < ActivityPub::Activity
  3. def perform
  4. case @object['type']
  5. when 'EncryptedMessage'
  6. create_encrypted_message
  7. else
  8. create_status
  9. end
  10. end
  11. private
  12. def create_encrypted_message
  13. return reject_payload! if invalid_origin?(@object['id']) || @options[:delivered_to_account_id].blank?
  14. target_account = Account.find(@options[:delivered_to_account_id])
  15. target_device = target_account.devices.find_by(device_id: @object.dig('to', 'deviceId'))
  16. return if target_device.nil?
  17. target_device.encrypted_messages.create!(
  18. from_account: @account,
  19. from_device_id: @object.dig('attributedTo', 'deviceId'),
  20. type: @object['messageType'],
  21. body: @object['cipherText'],
  22. digest: @object.dig('digest', 'digestValue'),
  23. message_franking: message_franking.to_token
  24. )
  25. end
  26. def message_franking
  27. MessageFranking.new(
  28. hmac: @object.dig('digest', 'digestValue'),
  29. original_franking: @object['messageFranking'],
  30. source_account_id: @account.id,
  31. target_account_id: @options[:delivered_to_account_id],
  32. timestamp: Time.now.utc
  33. )
  34. end
  35. def create_status
  36. return reject_payload! if unsupported_object_type? || invalid_origin?(@object['id']) || Tombstone.exists?(uri: @object['id']) || !related_to_local_activity?
  37. RedisLock.acquire(lock_options) do |lock|
  38. if lock.acquired?
  39. return if delete_arrived_first?(object_uri) || poll_vote? # rubocop:disable Lint/NonLocalExitFromIterator
  40. @status = find_existing_status
  41. if @status.nil?
  42. process_status
  43. elsif @options[:delivered_to_account_id].present?
  44. postprocess_audience_and_deliver
  45. end
  46. else
  47. raise Mastodon::RaceConditionError
  48. end
  49. end
  50. @status
  51. end
  52. def audience_to
  53. @object['to'] || @json['to']
  54. end
  55. def audience_cc
  56. @object['cc'] || @json['cc']
  57. end
  58. def process_status
  59. @tags = []
  60. @mentions = []
  61. @params = {}
  62. process_status_params
  63. process_tags
  64. process_audience
  65. ApplicationRecord.transaction do
  66. @status = Status.create!(@params)
  67. attach_tags(@status)
  68. end
  69. resolve_thread(@status)
  70. fetch_replies(@status)
  71. check_for_spam
  72. distribute(@status)
  73. forward_for_reply if @status.distributable?
  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['id'],
  84. url: object_url || @object['id'],
  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: @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. (as_array(audience_to) + as_array(audience_cc)).uniq.each do |audience|
  103. next if audience == ActivityPub::TagManager::COLLECTIONS[:public]
  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. end
  181. def process_attachments
  182. return [] if @object['attachment'].nil?
  183. media_attachments = []
  184. as_array(@object['attachment']).each do |attachment|
  185. next if attachment['url'].blank? || media_attachments.size >= 4
  186. begin
  187. href = Addressable::URI.parse(attachment['url']).normalize.to_s
  188. 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)
  189. media_attachments << media_attachment
  190. next if unsupported_media_type?(attachment['mediaType']) || skip_download?
  191. media_attachment.download_file!
  192. media_attachment.download_thumbnail!
  193. media_attachment.save
  194. rescue Mastodon::UnexpectedResponseError, HTTP::TimeoutError, HTTP::ConnectionError, OpenSSL::SSL::SSLError
  195. RedownloadMediaWorker.perform_in(rand(30..600).seconds, media_attachment.id)
  196. end
  197. end
  198. media_attachments
  199. rescue Addressable::URI::InvalidURIError => e
  200. Rails.logger.debug "Invalid URL in attachment: #{e}"
  201. media_attachments
  202. end
  203. def icon_url_from_attachment(attachment)
  204. url = attachment['icon'].is_a?(Hash) ? attachment['icon']['url'] : attachment['icon']
  205. Addressable::URI.parse(url).normalize.to_s if url.present?
  206. rescue Addressable::URI::InvalidURIError
  207. nil
  208. end
  209. def process_poll
  210. return unless @object['type'] == 'Question' && (@object['anyOf'].is_a?(Array) || @object['oneOf'].is_a?(Array))
  211. expires_at = begin
  212. if @object['closed'].is_a?(String)
  213. @object['closed']
  214. elsif !@object['closed'].nil? && !@object['closed'].is_a?(FalseClass)
  215. Time.now.utc
  216. else
  217. @object['endTime']
  218. end
  219. end
  220. if @object['anyOf'].is_a?(Array)
  221. multiple = true
  222. items = @object['anyOf']
  223. else
  224. multiple = false
  225. items = @object['oneOf']
  226. end
  227. voters_count = @object['votersCount']
  228. @account.polls.new(
  229. multiple: multiple,
  230. expires_at: expires_at,
  231. options: items.map { |item| item['name'].presence || item['content'] }.compact,
  232. cached_tallies: items.map { |item| item.dig('replies', 'totalItems') || 0 },
  233. voters_count: voters_count
  234. )
  235. end
  236. def poll_vote?
  237. 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'])
  238. poll_vote! unless replied_to_status.preloadable_poll.expired?
  239. true
  240. end
  241. def poll_vote!
  242. poll = replied_to_status.preloadable_poll
  243. already_voted = true
  244. RedisLock.acquire(poll_lock_options) do |lock|
  245. if lock.acquired?
  246. already_voted = poll.votes.where(account: @account).exists?
  247. poll.votes.create!(account: @account, choice: poll.options.index(@object['name']), uri: @object['id'])
  248. else
  249. raise Mastodon::RaceConditionError
  250. end
  251. end
  252. increment_voters_count! unless already_voted
  253. ActivityPub::DistributePollUpdateWorker.perform_in(3.minutes, replied_to_status.id) unless replied_to_status.preloadable_poll.hide_totals?
  254. end
  255. def resolve_thread(status)
  256. return unless status.reply? && status.thread.nil? && Request.valid_url?(in_reply_to_uri)
  257. ThreadResolveWorker.perform_async(status.id, in_reply_to_uri)
  258. end
  259. def fetch_replies(status)
  260. collection = @object['replies']
  261. return if collection.nil?
  262. replies = ActivityPub::FetchRepliesService.new.call(status, collection, false)
  263. return unless replies.nil?
  264. uri = value_or_id(collection)
  265. ActivityPub::FetchRepliesWorker.perform_async(status.id, uri) unless uri.nil?
  266. end
  267. def conversation_from_uri(uri)
  268. return nil if uri.nil?
  269. return Conversation.find_by(id: OStatus::TagManager.instance.unique_tag_to_local_id(uri, 'Conversation')) if OStatus::TagManager.instance.local_id?(uri)
  270. begin
  271. Conversation.find_or_create_by!(uri: uri)
  272. rescue ActiveRecord::RecordInvalid, ActiveRecord::RecordNotUnique
  273. retry
  274. end
  275. end
  276. def visibility_from_audience
  277. if equals_or_includes?(audience_to, ActivityPub::TagManager::COLLECTIONS[:public])
  278. :public
  279. elsif equals_or_includes?(audience_cc, ActivityPub::TagManager::COLLECTIONS[:public])
  280. :unlisted
  281. elsif equals_or_includes?(audience_to, @account.followers_url)
  282. :private
  283. else
  284. :direct
  285. end
  286. end
  287. def audience_includes?(account)
  288. uri = ActivityPub::TagManager.instance.uri_for(account)
  289. equals_or_includes?(audience_to, uri) || equals_or_includes?(audience_cc, uri)
  290. end
  291. def replied_to_status
  292. return @replied_to_status if defined?(@replied_to_status)
  293. if in_reply_to_uri.blank?
  294. @replied_to_status = nil
  295. else
  296. @replied_to_status = status_from_uri(in_reply_to_uri)
  297. @replied_to_status ||= status_from_uri(@object['inReplyToAtomUri']) if @object['inReplyToAtomUri'].present?
  298. @replied_to_status
  299. end
  300. end
  301. def in_reply_to_uri
  302. value_or_id(@object['inReplyTo'])
  303. end
  304. def text_from_content
  305. return Formatter.instance.linkify([[text_from_name, text_from_summary.presence].compact.join("\n\n"), object_url || @object['id']].join(' ')) if converted_object_type?
  306. if @object['content'].present?
  307. @object['content']
  308. elsif content_language_map?
  309. @object['contentMap'].values.first
  310. end
  311. end
  312. def text_from_summary
  313. if @object['summary'].present?
  314. @object['summary']
  315. elsif summary_language_map?
  316. @object['summaryMap'].values.first
  317. end
  318. end
  319. def text_from_name
  320. if @object['name'].present?
  321. @object['name']
  322. elsif name_language_map?
  323. @object['nameMap'].values.first
  324. end
  325. end
  326. def detected_language
  327. if content_language_map?
  328. @object['contentMap'].keys.first
  329. elsif name_language_map?
  330. @object['nameMap'].keys.first
  331. elsif summary_language_map?
  332. @object['summaryMap'].keys.first
  333. elsif supported_object_type?
  334. LanguageDetector.instance.detect(text_from_content, @account)
  335. end
  336. end
  337. def object_url
  338. return if @object['url'].blank?
  339. url_candidate = url_to_href(@object['url'], 'text/html')
  340. if invalid_origin?(url_candidate)
  341. nil
  342. else
  343. url_candidate
  344. end
  345. end
  346. def summary_language_map?
  347. @object['summaryMap'].is_a?(Hash) && !@object['summaryMap'].empty?
  348. end
  349. def content_language_map?
  350. @object['contentMap'].is_a?(Hash) && !@object['contentMap'].empty?
  351. end
  352. def name_language_map?
  353. @object['nameMap'].is_a?(Hash) && !@object['nameMap'].empty?
  354. end
  355. def unsupported_media_type?(mime_type)
  356. mime_type.present? && !MediaAttachment.supported_mime_types.include?(mime_type)
  357. end
  358. def supported_blurhash?(blurhash)
  359. components = blurhash.blank? ? nil : Blurhash.components(blurhash)
  360. components.present? && components.none? { |comp| comp > 5 }
  361. end
  362. def skip_download?
  363. return @skip_download if defined?(@skip_download)
  364. @skip_download ||= DomainBlock.reject_media?(@account.domain)
  365. end
  366. def reply_to_local?
  367. !replied_to_status.nil? && replied_to_status.account.local?
  368. end
  369. def related_to_local_activity?
  370. fetch? || followed_by_local_accounts? || requested_through_relay? ||
  371. responds_to_followed_account? || addresses_local_accounts?
  372. end
  373. def responds_to_followed_account?
  374. !replied_to_status.nil? && (replied_to_status.account.local? || replied_to_status.account.passive_relationships.exists?)
  375. end
  376. def addresses_local_accounts?
  377. return true if @options[:delivered_to_account_id]
  378. local_usernames = (as_array(audience_to) + as_array(audience_cc)).uniq.select { |uri| ActivityPub::TagManager.instance.local_uri?(uri) }.map { |uri| ActivityPub::TagManager.instance.uri_to_local_id(uri, :username) }
  379. return false if local_usernames.empty?
  380. Account.local.where(username: local_usernames).exists?
  381. end
  382. def check_for_spam
  383. SpamCheck.perform(@status)
  384. end
  385. def forward_for_reply
  386. return unless @json['signature'].present? && reply_to_local?
  387. ActivityPub::RawDistributionWorker.perform_async(Oj.dump(@json), replied_to_status.account_id, [@account.preferred_inbox_url])
  388. end
  389. def increment_voters_count!
  390. poll = replied_to_status.preloadable_poll
  391. unless poll.voters_count.nil?
  392. poll.voters_count = poll.voters_count + 1
  393. poll.save
  394. end
  395. rescue ActiveRecord::StaleObjectError
  396. poll.reload
  397. retry
  398. end
  399. def lock_options
  400. { redis: Redis.current, key: "create:#{@object['id']}" }
  401. end
  402. def poll_lock_options
  403. { redis: Redis.current, key: "vote:#{replied_to_status.poll_id}:#{@account.id}" }
  404. end
  405. end