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.

429 lines
14 KiB

  1. # frozen_string_literal: true
  2. class ActivityPub::Activity::Create < ActivityPub::Activity
  3. include FormattingHelper
  4. def perform
  5. dereference_object!
  6. case @object['type']
  7. when 'EncryptedMessage'
  8. create_encrypted_message
  9. else
  10. create_status
  11. end
  12. end
  13. private
  14. def create_encrypted_message
  15. return reject_payload! if invalid_origin?(object_uri) || @options[:delivered_to_account_id].blank?
  16. target_account = Account.find(@options[:delivered_to_account_id])
  17. target_device = target_account.devices.find_by(device_id: @object.dig('to', 'deviceId'))
  18. return if target_device.nil?
  19. target_device.encrypted_messages.create!(
  20. from_account: @account,
  21. from_device_id: @object.dig('attributedTo', 'deviceId'),
  22. type: @object['messageType'],
  23. body: @object['cipherText'],
  24. digest: @object.dig('digest', 'digestValue'),
  25. message_franking: message_franking.to_token
  26. )
  27. end
  28. def message_franking
  29. MessageFranking.new(
  30. hmac: @object.dig('digest', 'digestValue'),
  31. original_franking: @object['messageFranking'],
  32. source_account_id: @account.id,
  33. target_account_id: @options[:delivered_to_account_id],
  34. timestamp: Time.now.utc
  35. )
  36. end
  37. def create_status
  38. return reject_payload! if unsupported_object_type? || invalid_origin?(object_uri) || tombstone_exists? || !related_to_local_activity?
  39. lock_or_fail("create:#{object_uri}") do
  40. return if delete_arrived_first?(object_uri) || poll_vote?
  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. end
  48. @status
  49. end
  50. def audience_to
  51. as_array(@object['to'] || @json['to']).map { |x| value_or_id(x) }
  52. end
  53. def audience_cc
  54. as_array(@object['cc'] || @json['cc']).map { |x| value_or_id(x) }
  55. end
  56. def process_status
  57. @tags = []
  58. @mentions = []
  59. @silenced_account_ids = []
  60. @params = {}
  61. process_status_params
  62. process_tags
  63. process_audience
  64. ApplicationRecord.transaction do
  65. @status = Status.create!(@params)
  66. attach_tags(@status)
  67. end
  68. resolve_thread(@status)
  69. fetch_replies(@status)
  70. distribute
  71. forward_for_reply
  72. end
  73. def distribute
  74. # Spread out crawling randomly to avoid DDoSing the link
  75. LinkCrawlWorker.perform_in(rand(1..59).seconds, @status.id)
  76. # Distribute into home and list feeds and notify mentioned accounts
  77. ::DistributionWorker.perform_async(@status.id, { 'silenced_account_ids' => @silenced_account_ids }) if @options[:override_timestamps] || @status.within_realtime_window?
  78. end
  79. def find_existing_status
  80. status = status_from_uri(object_uri)
  81. status ||= Status.find_by(uri: @object['atomUri']) if @object['atomUri'].present?
  82. status
  83. end
  84. def process_status_params
  85. @status_parser = ActivityPub::Parser::StatusParser.new(@json, followers_collection: @account.followers_url)
  86. @params = begin
  87. {
  88. uri: @status_parser.uri,
  89. url: @status_parser.url || @status_parser.uri,
  90. account: @account,
  91. text: converted_object_type? ? converted_text : (@status_parser.text || ''),
  92. language: @status_parser.language,
  93. spoiler_text: converted_object_type? ? '' : (@status_parser.spoiler_text || ''),
  94. created_at: @status_parser.created_at,
  95. edited_at: @status_parser.edited_at && @status_parser.edited_at != @status_parser.created_at ? @status_parser.edited_at : nil,
  96. override_timestamps: @options[:override_timestamps],
  97. reply: @status_parser.reply,
  98. sensitive: @account.sensitized? || @status_parser.sensitive || false,
  99. visibility: @status_parser.visibility,
  100. thread: replied_to_status,
  101. conversation: conversation_from_uri(@object['conversation']),
  102. media_attachment_ids: process_attachments.take(4).map(&:id),
  103. poll: process_poll,
  104. }
  105. end
  106. end
  107. def process_audience
  108. # Unlike with tags, there is no point in resolving accounts we don't already
  109. # know here, because silent mentions would only be used for local access control anyway
  110. accounts_in_audience = (audience_to + audience_cc).uniq.filter_map do |audience|
  111. account_from_uri(audience) unless ActivityPub::TagManager.instance.public_collection?(audience)
  112. end
  113. # If the payload was delivered to a specific inbox, the inbox owner must have
  114. # access to it, unless they already have access to it anyway
  115. if @options[:delivered_to_account_id]
  116. accounts_in_audience << delivered_to_account
  117. accounts_in_audience.uniq!
  118. end
  119. accounts_in_audience.each do |account|
  120. # This runs after tags are processed, and those translate into non-silent
  121. # mentions, which take precedence
  122. next if @mentions.any? { |mention| mention.account_id == account.id }
  123. @mentions << Mention.new(account: account, silent: true)
  124. # If there is at least one silent mention, then the status can be considered
  125. # as a limited-audience status, and not strictly a direct message, but only
  126. # if we considered a direct message in the first place
  127. @params[:visibility] = :limited if @params[:visibility] == :direct
  128. end
  129. # Accounts that are tagged but are not in the audience are not
  130. # supposed to be notified explicitly
  131. @silenced_account_ids = @mentions.map(&:account_id) - accounts_in_audience.map(&:id)
  132. end
  133. def postprocess_audience_and_deliver
  134. return if @status.mentions.find_by(account_id: @options[:delivered_to_account_id])
  135. @status.mentions.create(account: delivered_to_account, silent: true)
  136. @status.update(visibility: :limited) if @status.direct_visibility?
  137. return unless delivered_to_account.following?(@account)
  138. FeedInsertWorker.perform_async(@status.id, delivered_to_account.id, 'home')
  139. end
  140. def delivered_to_account
  141. @delivered_to_account ||= Account.find(@options[:delivered_to_account_id])
  142. end
  143. def attach_tags(status)
  144. @tags.each do |tag|
  145. status.tags << tag
  146. tag.update(last_status_at: status.created_at) if tag.last_status_at.nil? || (tag.last_status_at < status.created_at && tag.last_status_at < 12.hours.ago)
  147. end
  148. # If we're processing an old status, this may register tags as being used now
  149. # as opposed to when the status was really published, but this is probably
  150. # not a big deal
  151. Trends.tags.register(status)
  152. @mentions.each do |mention|
  153. mention.status = status
  154. mention.save
  155. end
  156. end
  157. def process_tags
  158. return if @object['tag'].nil?
  159. as_array(@object['tag']).each do |tag|
  160. if equals_or_includes?(tag['type'], 'Hashtag')
  161. process_hashtag tag
  162. elsif equals_or_includes?(tag['type'], 'Mention')
  163. process_mention tag
  164. elsif equals_or_includes?(tag['type'], 'Emoji')
  165. process_emoji tag
  166. end
  167. end
  168. end
  169. def process_hashtag(tag)
  170. return if tag['name'].blank?
  171. Tag.find_or_create_by_names(tag['name']) do |hashtag|
  172. @tags << hashtag unless @tags.include?(hashtag) || !hashtag.valid?
  173. end
  174. rescue ActiveRecord::RecordInvalid
  175. nil
  176. end
  177. def process_mention(tag)
  178. return if tag['href'].blank?
  179. account = account_from_uri(tag['href'])
  180. account = ActivityPub::FetchRemoteAccountService.new.call(tag['href']) if account.nil?
  181. return if account.nil?
  182. @mentions << Mention.new(account: account, silent: false)
  183. end
  184. def process_emoji(tag)
  185. return if skip_download?
  186. custom_emoji_parser = ActivityPub::Parser::CustomEmojiParser.new(tag)
  187. return if custom_emoji_parser.shortcode.blank? || custom_emoji_parser.image_remote_url.blank?
  188. emoji = CustomEmoji.find_by(shortcode: custom_emoji_parser.shortcode, domain: @account.domain)
  189. return unless emoji.nil? || custom_emoji_parser.image_remote_url != emoji.image_remote_url || (custom_emoji_parser.updated_at && custom_emoji_parser.updated_at >= emoji.updated_at)
  190. begin
  191. emoji ||= CustomEmoji.new(domain: @account.domain, shortcode: custom_emoji_parser.shortcode, uri: custom_emoji_parser.uri)
  192. emoji.image_remote_url = custom_emoji_parser.image_remote_url
  193. emoji.save
  194. rescue Seahorse::Client::NetworkingError => e
  195. Rails.logger.warn "Error storing emoji: #{e}"
  196. end
  197. end
  198. def process_attachments
  199. return [] if @object['attachment'].nil?
  200. media_attachments = []
  201. as_array(@object['attachment']).each do |attachment|
  202. media_attachment_parser = ActivityPub::Parser::MediaAttachmentParser.new(attachment)
  203. next if media_attachment_parser.remote_url.blank? || media_attachments.size >= 4
  204. begin
  205. media_attachment = MediaAttachment.create(
  206. account: @account,
  207. remote_url: media_attachment_parser.remote_url,
  208. thumbnail_remote_url: media_attachment_parser.thumbnail_remote_url,
  209. description: media_attachment_parser.description,
  210. focus: media_attachment_parser.focus,
  211. blurhash: media_attachment_parser.blurhash
  212. )
  213. media_attachments << media_attachment
  214. next if unsupported_media_type?(media_attachment_parser.file_content_type) || skip_download?
  215. media_attachment.download_file!
  216. media_attachment.download_thumbnail!
  217. media_attachment.save
  218. rescue Mastodon::UnexpectedResponseError, HTTP::TimeoutError, HTTP::ConnectionError, OpenSSL::SSL::SSLError
  219. RedownloadMediaWorker.perform_in(rand(30..600).seconds, media_attachment.id)
  220. rescue Seahorse::Client::NetworkingError => e
  221. Rails.logger.warn "Error storing media attachment: #{e}"
  222. end
  223. end
  224. media_attachments
  225. rescue Addressable::URI::InvalidURIError => e
  226. Rails.logger.debug "Invalid URL in attachment: #{e}"
  227. media_attachments
  228. end
  229. def process_poll
  230. poll_parser = ActivityPub::Parser::PollParser.new(@object)
  231. return unless poll_parser.valid?
  232. @account.polls.new(
  233. multiple: poll_parser.multiple,
  234. expires_at: poll_parser.expires_at,
  235. options: poll_parser.options,
  236. cached_tallies: poll_parser.cached_tallies,
  237. voters_count: poll_parser.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. lock_or_fail("vote:#{replied_to_status.poll_id}:#{@account.id}") do
  249. already_voted = poll.votes.where(account: @account).exists?
  250. poll.votes.create!(account: @account, choice: poll.options.index(@object['name']), uri: object_uri)
  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 replied_to_status
  277. return @replied_to_status if defined?(@replied_to_status)
  278. if in_reply_to_uri.blank?
  279. @replied_to_status = nil
  280. else
  281. @replied_to_status = status_from_uri(in_reply_to_uri)
  282. @replied_to_status ||= status_from_uri(@object['inReplyToAtomUri']) if @object['inReplyToAtomUri'].present?
  283. @replied_to_status
  284. end
  285. end
  286. def in_reply_to_uri
  287. value_or_id(@object['inReplyTo'])
  288. end
  289. def converted_text
  290. linkify([@status_parser.title.presence, @status_parser.spoiler_text.presence, @status_parser.url || @status_parser.uri].compact.join("\n\n"))
  291. end
  292. def unsupported_media_type?(mime_type)
  293. mime_type.present? && !MediaAttachment.supported_mime_types.include?(mime_type)
  294. end
  295. def skip_download?
  296. return @skip_download if defined?(@skip_download)
  297. @skip_download ||= DomainBlock.reject_media?(@account.domain)
  298. end
  299. def reply_to_local?
  300. !replied_to_status.nil? && replied_to_status.account.local?
  301. end
  302. def related_to_local_activity?
  303. fetch? || followed_by_local_accounts? || requested_through_relay? ||
  304. responds_to_followed_account? || addresses_local_accounts?
  305. end
  306. def responds_to_followed_account?
  307. !replied_to_status.nil? && (replied_to_status.account.local? || replied_to_status.account.passive_relationships.exists?)
  308. end
  309. def addresses_local_accounts?
  310. return true if @options[:delivered_to_account_id]
  311. 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) }
  312. return false if local_usernames.empty?
  313. Account.local.where(username: local_usernames).exists?
  314. end
  315. def tombstone_exists?
  316. Tombstone.exists?(uri: object_uri)
  317. end
  318. def forward_for_reply
  319. return unless @status.distributable? && @json['signature'].present? && reply_to_local?
  320. ActivityPub::RawDistributionWorker.perform_async(Oj.dump(@json), replied_to_status.account_id, [@account.preferred_inbox_url])
  321. end
  322. def increment_voters_count!
  323. poll = replied_to_status.preloadable_poll
  324. unless poll.voters_count.nil?
  325. poll.voters_count = poll.voters_count + 1
  326. poll.save
  327. end
  328. rescue ActiveRecord::StaleObjectError
  329. poll.reload
  330. retry
  331. end
  332. end