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.

507 lines
15 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. lock_or_fail("create:#{object_uri}") do
  39. return if delete_arrived_first?(object_uri) || poll_vote?
  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. end
  47. @status
  48. end
  49. def audience_to
  50. as_array(@object['to'] || @json['to']).map { |x| value_or_id(x) }
  51. end
  52. def audience_cc
  53. as_array(@object['cc'] || @json['cc']).map { |x| value_or_id(x) }
  54. end
  55. def process_status
  56. @tags = []
  57. @mentions = []
  58. @params = {}
  59. process_status_params
  60. process_tags
  61. process_audience
  62. ApplicationRecord.transaction do
  63. @status = Status.create!(@params)
  64. attach_tags(@status)
  65. end
  66. resolve_thread(@status)
  67. fetch_replies(@status)
  68. distribute(@status)
  69. forward_for_reply
  70. end
  71. def find_existing_status
  72. status = status_from_uri(object_uri)
  73. status ||= Status.find_by(uri: @object['atomUri']) if @object['atomUri'].present?
  74. status
  75. end
  76. def process_status_params
  77. @params = begin
  78. {
  79. uri: object_uri,
  80. url: object_url || object_uri,
  81. account: @account,
  82. text: text_from_content || '',
  83. language: detected_language,
  84. spoiler_text: converted_object_type? ? '' : (text_from_summary || ''),
  85. created_at: @object['published'],
  86. override_timestamps: @options[:override_timestamps],
  87. reply: @object['inReplyTo'].present?,
  88. sensitive: @account.sensitized? || @object['sensitive'] || false,
  89. visibility: visibility_from_audience,
  90. thread: replied_to_status,
  91. conversation: conversation_from_uri(@object['conversation']),
  92. media_attachment_ids: process_attachments.take(4).map(&:id),
  93. poll: process_poll,
  94. }
  95. end
  96. end
  97. def process_audience
  98. (audience_to + audience_cc).uniq.each do |audience|
  99. next if ActivityPub::TagManager.instance.public_collection?(audience)
  100. # Unlike with tags, there is no point in resolving accounts we don't already
  101. # know here, because silent mentions would only be used for local access
  102. # control anyway
  103. account = account_from_uri(audience)
  104. next if account.nil? || @mentions.any? { |mention| mention.account_id == account.id }
  105. @mentions << Mention.new(account: account, silent: true)
  106. # If there is at least one silent mention, then the status can be considered
  107. # as a limited-audience status, and not strictly a direct message, but only
  108. # if we considered a direct message in the first place
  109. next unless @params[:visibility] == :direct
  110. @params[:visibility] = :limited
  111. end
  112. # If the payload was delivered to a specific inbox, the inbox owner must have
  113. # access to it, unless they already have access to it anyway
  114. return if @options[:delivered_to_account_id].nil? || @mentions.any? { |mention| mention.account_id == @options[:delivered_to_account_id] }
  115. @mentions << Mention.new(account_id: @options[:delivered_to_account_id], silent: true)
  116. return unless @params[:visibility] == :direct
  117. @params[:visibility] = :limited
  118. end
  119. def postprocess_audience_and_deliver
  120. return if @status.mentions.find_by(account_id: @options[:delivered_to_account_id])
  121. delivered_to_account = Account.find(@options[:delivered_to_account_id])
  122. @status.mentions.create(account: delivered_to_account, silent: true)
  123. @status.update(visibility: :limited) if @status.direct_visibility?
  124. return unless delivered_to_account.following?(@account)
  125. FeedInsertWorker.perform_async(@status.id, delivered_to_account.id, :home)
  126. end
  127. def attach_tags(status)
  128. @tags.each do |tag|
  129. status.tags << tag
  130. tag.use!(@account, status: status, at_time: status.created_at) if status.public_visibility?
  131. end
  132. @mentions.each do |mention|
  133. mention.status = status
  134. mention.save
  135. end
  136. end
  137. def process_tags
  138. return if @object['tag'].nil?
  139. as_array(@object['tag']).each do |tag|
  140. if equals_or_includes?(tag['type'], 'Hashtag')
  141. process_hashtag tag
  142. elsif equals_or_includes?(tag['type'], 'Mention')
  143. process_mention tag
  144. elsif equals_or_includes?(tag['type'], 'Emoji')
  145. process_emoji tag
  146. end
  147. end
  148. end
  149. def process_hashtag(tag)
  150. return if tag['name'].blank?
  151. Tag.find_or_create_by_names(tag['name']) do |hashtag|
  152. @tags << hashtag unless @tags.include?(hashtag) || !hashtag.valid?
  153. end
  154. rescue ActiveRecord::RecordInvalid
  155. nil
  156. end
  157. def process_mention(tag)
  158. return if tag['href'].blank?
  159. account = account_from_uri(tag['href'])
  160. account = ActivityPub::FetchRemoteAccountService.new.call(tag['href']) if account.nil?
  161. return if account.nil?
  162. @mentions << Mention.new(account: account, silent: false)
  163. end
  164. def process_emoji(tag)
  165. return if skip_download?
  166. return if tag['name'].blank? || tag['icon'].blank? || tag['icon']['url'].blank?
  167. shortcode = tag['name'].delete(':')
  168. image_url = tag['icon']['url']
  169. uri = tag['id']
  170. updated = tag['updated']
  171. emoji = CustomEmoji.find_by(shortcode: shortcode, domain: @account.domain)
  172. return unless emoji.nil? || image_url != emoji.image_remote_url || (updated && updated >= emoji.updated_at)
  173. emoji ||= CustomEmoji.new(domain: @account.domain, shortcode: shortcode, uri: uri)
  174. emoji.image_remote_url = image_url
  175. emoji.save
  176. rescue Seahorse::Client::NetworkingError
  177. nil
  178. end
  179. def process_attachments
  180. return [] if @object['attachment'].nil?
  181. media_attachments = []
  182. as_array(@object['attachment']).each do |attachment|
  183. next if attachment['url'].blank? || media_attachments.size >= 4
  184. begin
  185. href = Addressable::URI.parse(attachment['url']).normalize.to_s
  186. 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)
  187. media_attachments << media_attachment
  188. next if unsupported_media_type?(attachment['mediaType']) || skip_download?
  189. media_attachment.download_file!
  190. media_attachment.download_thumbnail!
  191. media_attachment.save
  192. rescue Mastodon::UnexpectedResponseError, HTTP::TimeoutError, HTTP::ConnectionError, OpenSSL::SSL::SSLError
  193. RedownloadMediaWorker.perform_in(rand(30..600).seconds, media_attachment.id)
  194. rescue Seahorse::Client::NetworkingError
  195. nil
  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. lock_or_fail("vote:#{replied_to_status.poll_id}:#{@account.id}") do
  245. already_voted = poll.votes.where(account: @account).exists?
  246. poll.votes.create!(account: @account, choice: poll.options.index(@object['name']), uri: object_uri)
  247. end
  248. increment_voters_count! unless already_voted
  249. ActivityPub::DistributePollUpdateWorker.perform_in(3.minutes, replied_to_status.id) unless replied_to_status.preloadable_poll.hide_totals?
  250. end
  251. def resolve_thread(status)
  252. return unless status.reply? && status.thread.nil? && Request.valid_url?(in_reply_to_uri)
  253. ThreadResolveWorker.perform_async(status.id, in_reply_to_uri)
  254. end
  255. def fetch_replies(status)
  256. collection = @object['replies']
  257. return if collection.nil?
  258. replies = ActivityPub::FetchRepliesService.new.call(status, collection, false)
  259. return unless replies.nil?
  260. uri = value_or_id(collection)
  261. ActivityPub::FetchRepliesWorker.perform_async(status.id, uri) unless uri.nil?
  262. end
  263. def conversation_from_uri(uri)
  264. return nil if uri.nil?
  265. return Conversation.find_by(id: OStatus::TagManager.instance.unique_tag_to_local_id(uri, 'Conversation')) if OStatus::TagManager.instance.local_id?(uri)
  266. begin
  267. Conversation.find_or_create_by!(uri: uri)
  268. rescue ActiveRecord::RecordInvalid, ActiveRecord::RecordNotUnique
  269. retry
  270. end
  271. end
  272. def visibility_from_audience
  273. if audience_to.any? { |to| ActivityPub::TagManager.instance.public_collection?(to) }
  274. :public
  275. elsif audience_cc.any? { |cc| ActivityPub::TagManager.instance.public_collection?(cc) }
  276. :unlisted
  277. elsif audience_to.include?(@account.followers_url)
  278. :private
  279. else
  280. :direct
  281. end
  282. end
  283. def audience_includes?(account)
  284. uri = ActivityPub::TagManager.instance.uri_for(account)
  285. audience_to.include?(uri) || audience_cc.include?(uri)
  286. end
  287. def replied_to_status
  288. return @replied_to_status if defined?(@replied_to_status)
  289. if in_reply_to_uri.blank?
  290. @replied_to_status = nil
  291. else
  292. @replied_to_status = status_from_uri(in_reply_to_uri)
  293. @replied_to_status ||= status_from_uri(@object['inReplyToAtomUri']) if @object['inReplyToAtomUri'].present?
  294. @replied_to_status
  295. end
  296. end
  297. def in_reply_to_uri
  298. value_or_id(@object['inReplyTo'])
  299. end
  300. def text_from_content
  301. return Formatter.instance.linkify([[text_from_name, text_from_summary.presence].compact.join("\n\n"), object_url || object_uri].join(' ')) if converted_object_type?
  302. if @object['content'].present?
  303. @object['content']
  304. elsif content_language_map?
  305. @object['contentMap'].values.first
  306. end
  307. end
  308. def text_from_summary
  309. if @object['summary'].present?
  310. @object['summary']
  311. elsif summary_language_map?
  312. @object['summaryMap'].values.first
  313. end
  314. end
  315. def text_from_name
  316. if @object['name'].present?
  317. @object['name']
  318. elsif name_language_map?
  319. @object['nameMap'].values.first
  320. end
  321. end
  322. def detected_language
  323. if content_language_map?
  324. @object['contentMap'].keys.first
  325. elsif name_language_map?
  326. @object['nameMap'].keys.first
  327. elsif summary_language_map?
  328. @object['summaryMap'].keys.first
  329. elsif supported_object_type?
  330. LanguageDetector.instance.detect(text_from_content, @account)
  331. end
  332. end
  333. def object_url
  334. return if @object['url'].blank?
  335. url_candidate = url_to_href(@object['url'], 'text/html')
  336. if invalid_origin?(url_candidate)
  337. nil
  338. else
  339. url_candidate
  340. end
  341. end
  342. def summary_language_map?
  343. @object['summaryMap'].is_a?(Hash) && !@object['summaryMap'].empty?
  344. end
  345. def content_language_map?
  346. @object['contentMap'].is_a?(Hash) && !@object['contentMap'].empty?
  347. end
  348. def name_language_map?
  349. @object['nameMap'].is_a?(Hash) && !@object['nameMap'].empty?
  350. end
  351. def unsupported_media_type?(mime_type)
  352. mime_type.present? && !MediaAttachment.supported_mime_types.include?(mime_type)
  353. end
  354. def supported_blurhash?(blurhash)
  355. components = blurhash.blank? || !blurhash_valid_chars?(blurhash) ? nil : Blurhash.components(blurhash)
  356. components.present? && components.none? { |comp| comp > 5 }
  357. end
  358. def blurhash_valid_chars?(blurhash)
  359. /^[\w#$%*+-.:;=?@\[\]^{|}~]+$/.match?(blurhash)
  360. end
  361. def skip_download?
  362. return @skip_download if defined?(@skip_download)
  363. @skip_download ||= DomainBlock.reject_media?(@account.domain)
  364. end
  365. def reply_to_local?
  366. !replied_to_status.nil? && replied_to_status.account.local?
  367. end
  368. def related_to_local_activity?
  369. fetch? || followed_by_local_accounts? || requested_through_relay? ||
  370. responds_to_followed_account? || addresses_local_accounts?
  371. end
  372. def responds_to_followed_account?
  373. !replied_to_status.nil? && (replied_to_status.account.local? || replied_to_status.account.passive_relationships.exists?)
  374. end
  375. def addresses_local_accounts?
  376. return true if @options[:delivered_to_account_id]
  377. 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) }
  378. return false if local_usernames.empty?
  379. Account.local.where(username: local_usernames).exists?
  380. end
  381. def tombstone_exists?
  382. Tombstone.exists?(uri: object_uri)
  383. end
  384. def forward_for_reply
  385. return unless @status.distributable? && @json['signature'].present? && reply_to_local?
  386. ActivityPub::RawDistributionWorker.perform_async(Oj.dump(@json), replied_to_status.account_id, [@account.preferred_inbox_url])
  387. end
  388. def increment_voters_count!
  389. poll = replied_to_status.preloadable_poll
  390. unless poll.voters_count.nil?
  391. poll.voters_count = poll.voters_count + 1
  392. poll.save
  393. end
  394. rescue ActiveRecord::StaleObjectError
  395. poll.reload
  396. retry
  397. end
  398. end