create.rb 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  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. with_lock("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_inline_images if @object['content'].present? && @object['type'] == 'Article'
  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. distribute
  72. forward_for_reply
  73. end
  74. def distribute
  75. # Spread out crawling randomly to avoid DDoSing the link
  76. LinkCrawlWorker.perform_in(rand(1..59).seconds, @status.id)
  77. # Distribute into home and list feeds and notify mentioned accounts
  78. ::DistributionWorker.perform_async(@status.id, { 'silenced_account_ids' => @silenced_account_ids }) if @options[:override_timestamps] || @status.within_realtime_window?
  79. end
  80. def find_existing_status
  81. status = status_from_uri(object_uri)
  82. status ||= Status.find_by(uri: @object['atomUri']) if @object['atomUri'].present?
  83. status
  84. end
  85. def process_status_params
  86. @status_parser = ActivityPub::Parser::StatusParser.new(@json, followers_collection: @account.followers_url)
  87. @params = begin
  88. {
  89. uri: @status_parser.uri,
  90. url: @status_parser.url || @status_parser.uri,
  91. account: @account,
  92. text: text_from_content || '',
  93. language: @status_parser.language,
  94. spoiler_text: converted_object_type? ? '' : (@status_parser.spoiler_text || (@object['type'] == 'Article' && text_from_name) || ''),
  95. created_at: @status_parser.created_at,
  96. edited_at: @status_parser.edited_at && @status_parser.edited_at != @status_parser.created_at ? @status_parser.edited_at : nil,
  97. override_timestamps: @options[:override_timestamps],
  98. reply: @status_parser.reply,
  99. sensitive: @account.sensitized? || @status_parser.sensitive || false,
  100. visibility: @status_parser.visibility,
  101. thread: replied_to_status,
  102. conversation: conversation_from_uri(@object['conversation']),
  103. media_attachment_ids: process_attachments.take(4).map(&:id),
  104. poll: process_poll,
  105. activity_pub_type: @object['type']
  106. }
  107. end
  108. end
  109. class Handler < ::Ox::Sax
  110. attr_reader :srcs
  111. attr_reader :alts
  112. def initialize(block)
  113. @stack = []
  114. @srcs = []
  115. @alts = {}
  116. end
  117. def start_element(element_name)
  118. @stack << [element_name, {}]
  119. end
  120. def end_element(element_name)
  121. self_name, self_attributes = @stack[-1]
  122. if self_name == :img && !self_attributes[:src].nil?
  123. @srcs << self_attributes[:src]
  124. @alts[self_attributes[:src]] = self_attributes[:alt]
  125. end
  126. @stack.pop
  127. end
  128. def attr(attribute_name, attribute_value)
  129. _name, attributes = @stack.last
  130. attributes[attribute_name] = attribute_value
  131. end
  132. end
  133. def process_inline_images
  134. proc = Proc.new { |name| puts name }
  135. handler = Handler.new(proc)
  136. Ox.sax_parse(handler, @object['content'])
  137. handler.srcs.each do |src|
  138. # Handle images where the src is formatted as "/foo/bar.png"
  139. # we assume that the `url` field is populated which lets us infer
  140. # the protocol and domain of the _original_ article, as though
  141. # we were looking at it via a web browser
  142. if src[0] == '/' && !@object['url'].nil?
  143. site = Addressable::URI.parse(@object['url']).site
  144. src = site + src
  145. end
  146. if skip_download?
  147. @object['content'].gsub!(src, '')
  148. next
  149. end
  150. media_attachment = MediaAttachment.create(account: @account, remote_url: src, description: handler.alts[src], focus: nil)
  151. media_attachment.download_file!
  152. media_attachment.save
  153. if unsupported_media_type?(media_attachment.file.content_type)
  154. @object['content'].gsub!(src, '')
  155. media_attachment.delete
  156. else
  157. @object['content'].gsub!(src, media_attachment.file.url(:small))
  158. end
  159. end
  160. end
  161. def process_audience
  162. # Unlike with tags, there is no point in resolving accounts we don't already
  163. # know here, because silent mentions would only be used for local access control anyway
  164. accounts_in_audience = (audience_to + audience_cc).uniq.filter_map do |audience|
  165. account_from_uri(audience) unless ActivityPub::TagManager.instance.public_collection?(audience)
  166. end
  167. # If the payload was delivered to a specific inbox, the inbox owner must have
  168. # access to it, unless they already have access to it anyway
  169. if @options[:delivered_to_account_id]
  170. accounts_in_audience << delivered_to_account
  171. accounts_in_audience.uniq!
  172. end
  173. accounts_in_audience.each do |account|
  174. # This runs after tags are processed, and those translate into non-silent
  175. # mentions, which take precedence
  176. next if @mentions.any? { |mention| mention.account_id == account.id }
  177. @mentions << Mention.new(account: account, silent: true)
  178. # If there is at least one silent mention, then the status can be considered
  179. # as a limited-audience status, and not strictly a direct message, but only
  180. # if we considered a direct message in the first place
  181. @params[:visibility] = :limited if @params[:visibility] == :direct
  182. end
  183. # Accounts that are tagged but are not in the audience are not
  184. # supposed to be notified explicitly
  185. @silenced_account_ids = @mentions.map(&:account_id) - accounts_in_audience.map(&:id)
  186. end
  187. def postprocess_audience_and_deliver
  188. return if @status.mentions.find_by(account_id: @options[:delivered_to_account_id])
  189. @status.mentions.create(account: delivered_to_account, silent: true)
  190. @status.update(visibility: :limited) if @status.direct_visibility?
  191. return unless delivered_to_account.following?(@account)
  192. FeedInsertWorker.perform_async(@status.id, delivered_to_account.id, 'home')
  193. end
  194. def delivered_to_account
  195. @delivered_to_account ||= Account.find(@options[:delivered_to_account_id])
  196. end
  197. def attach_tags(status)
  198. @tags.each do |tag|
  199. status.tags << tag
  200. 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)
  201. end
  202. # If we're processing an old status, this may register tags as being used now
  203. # as opposed to when the status was really published, but this is probably
  204. # not a big deal
  205. Trends.tags.register(status)
  206. @mentions.each do |mention|
  207. mention.status = status
  208. mention.save
  209. end
  210. end
  211. def process_tags
  212. return if @object['tag'].nil?
  213. as_array(@object['tag']).each do |tag|
  214. if equals_or_includes?(tag['type'], 'Hashtag')
  215. process_hashtag tag
  216. elsif equals_or_includes?(tag['type'], 'Mention')
  217. process_mention tag
  218. elsif equals_or_includes?(tag['type'], 'Emoji')
  219. process_emoji tag
  220. end
  221. end
  222. end
  223. def process_hashtag(tag)
  224. return if tag['name'].blank?
  225. Tag.find_or_create_by_names(tag['name']) do |hashtag|
  226. @tags << hashtag unless @tags.include?(hashtag) || !hashtag.valid?
  227. end
  228. rescue ActiveRecord::RecordInvalid
  229. nil
  230. end
  231. def process_mention(tag)
  232. return if tag['href'].blank?
  233. account = account_from_uri(tag['href'])
  234. account = ActivityPub::FetchRemoteAccountService.new.call(tag['href'], request_id: @options[:request_id]) if account.nil?
  235. return if account.nil?
  236. @mentions << Mention.new(account: account, silent: false)
  237. end
  238. def process_emoji(tag)
  239. return if skip_download?
  240. custom_emoji_parser = ActivityPub::Parser::CustomEmojiParser.new(tag)
  241. return if custom_emoji_parser.shortcode.blank? || custom_emoji_parser.image_remote_url.blank?
  242. emoji = CustomEmoji.find_by(shortcode: custom_emoji_parser.shortcode, domain: @account.domain)
  243. 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)
  244. begin
  245. emoji ||= CustomEmoji.new(domain: @account.domain, shortcode: custom_emoji_parser.shortcode, uri: custom_emoji_parser.uri)
  246. emoji.image_remote_url = custom_emoji_parser.image_remote_url
  247. emoji.save
  248. rescue Seahorse::Client::NetworkingError => e
  249. Rails.logger.warn "Error storing emoji: #{e}"
  250. end
  251. end
  252. def process_attachments
  253. return [] if @object['attachment'].nil?
  254. media_attachments = []
  255. as_array(@object['attachment']).each do |attachment|
  256. media_attachment_parser = ActivityPub::Parser::MediaAttachmentParser.new(attachment)
  257. next if media_attachment_parser.remote_url.blank? || media_attachments.size >= 4
  258. begin
  259. media_attachment = MediaAttachment.create(
  260. account: @account,
  261. remote_url: media_attachment_parser.remote_url,
  262. thumbnail_remote_url: media_attachment_parser.thumbnail_remote_url,
  263. description: media_attachment_parser.description,
  264. focus: media_attachment_parser.focus,
  265. blurhash: media_attachment_parser.blurhash
  266. )
  267. media_attachments << media_attachment
  268. next if unsupported_media_type?(media_attachment_parser.file_content_type) || skip_download?
  269. media_attachment.download_file!
  270. media_attachment.download_thumbnail!
  271. media_attachment.save
  272. rescue Mastodon::UnexpectedResponseError, HTTP::TimeoutError, HTTP::ConnectionError, OpenSSL::SSL::SSLError
  273. RedownloadMediaWorker.perform_in(rand(30..600).seconds, media_attachment.id)
  274. rescue Seahorse::Client::NetworkingError => e
  275. Rails.logger.warn "Error storing media attachment: #{e}"
  276. end
  277. end
  278. media_attachments
  279. rescue Addressable::URI::InvalidURIError => e
  280. Rails.logger.debug "Invalid URL in attachment: #{e}"
  281. media_attachments
  282. end
  283. def process_poll
  284. poll_parser = ActivityPub::Parser::PollParser.new(@object)
  285. return unless poll_parser.valid?
  286. @account.polls.new(
  287. multiple: poll_parser.multiple,
  288. expires_at: poll_parser.expires_at,
  289. options: poll_parser.options,
  290. cached_tallies: poll_parser.cached_tallies,
  291. voters_count: poll_parser.voters_count
  292. )
  293. end
  294. def poll_vote?
  295. 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'])
  296. poll_vote! unless replied_to_status.preloadable_poll.expired?
  297. true
  298. end
  299. def poll_vote!
  300. poll = replied_to_status.preloadable_poll
  301. already_voted = true
  302. with_lock("vote:#{replied_to_status.poll_id}:#{@account.id}") do
  303. already_voted = poll.votes.where(account: @account).exists?
  304. poll.votes.create!(account: @account, choice: poll.options.index(@object['name']), uri: object_uri)
  305. end
  306. increment_voters_count! unless already_voted
  307. ActivityPub::DistributePollUpdateWorker.perform_in(3.minutes, replied_to_status.id) unless replied_to_status.preloadable_poll.hide_totals?
  308. end
  309. def resolve_thread(status)
  310. return unless status.reply? && status.thread.nil? && Request.valid_url?(in_reply_to_uri)
  311. ThreadResolveWorker.perform_async(status.id, in_reply_to_uri)
  312. end
  313. def fetch_replies(status)
  314. collection = @object['replies']
  315. return if collection.nil?
  316. replies = ActivityPub::FetchRepliesService.new.call(status, collection, false)
  317. return unless replies.nil?
  318. uri = value_or_id(collection)
  319. ActivityPub::FetchRepliesWorker.perform_async(status.id, uri) unless uri.nil?
  320. end
  321. def conversation_from_uri(uri)
  322. return nil if uri.nil?
  323. return Conversation.find_by(id: OStatus::TagManager.instance.unique_tag_to_local_id(uri, 'Conversation')) if OStatus::TagManager.instance.local_id?(uri)
  324. begin
  325. Conversation.find_or_create_by!(uri: uri)
  326. rescue ActiveRecord::RecordInvalid, ActiveRecord::RecordNotUnique
  327. retry
  328. end
  329. end
  330. def replied_to_status
  331. return @replied_to_status if defined?(@replied_to_status)
  332. if in_reply_to_uri.blank?
  333. @replied_to_status = nil
  334. else
  335. @replied_to_status = status_from_uri(in_reply_to_uri)
  336. @replied_to_status ||= status_from_uri(@object['inReplyToAtomUri']) if @object['inReplyToAtomUri'].present?
  337. @replied_to_status
  338. end
  339. end
  340. def in_reply_to_uri
  341. value_or_id(@object['inReplyTo'])
  342. end
  343. def text_from_content
  344. return converted_text if converted_object_type?
  345. return article_format(@object['content']) if @object['content'].present? && @object['type'] == 'Article'
  346. return @status_parser.text || ''
  347. end
  348. def text_from_name
  349. if @object['name'].present?
  350. @object['name']
  351. elsif name_language_map?
  352. @object['nameMap'].values.first
  353. end
  354. end
  355. def name_language_map?
  356. @object['nameMap'].is_a?(Hash) && !@object['nameMap'].empty?
  357. end
  358. def converted_text
  359. linkify([@status_parser.title.presence, @status_parser.spoiler_text.presence, @status_parser.url || @status_parser.uri].compact.join("\n\n"))
  360. end
  361. def unsupported_media_type?(mime_type)
  362. mime_type.present? && !MediaAttachment.supported_mime_types.include?(mime_type)
  363. end
  364. def blurhash_valid_chars?(blurhash)
  365. /^[\w#$%*+-.:;=?@\[\]^{|}~]+$/.match?(blurhash)
  366. end
  367. def skip_download?
  368. return @skip_download if defined?(@skip_download)
  369. @skip_download ||= DomainBlock.reject_media?(@account.domain)
  370. end
  371. def reply_to_local?
  372. !replied_to_status.nil? && replied_to_status.account.local?
  373. end
  374. def related_to_local_activity?
  375. fetch? || followed_by_local_accounts? || requested_through_relay? ||
  376. responds_to_followed_account? || addresses_local_accounts?
  377. end
  378. def responds_to_followed_account?
  379. !replied_to_status.nil? && (replied_to_status.account.local? || replied_to_status.account.passive_relationships.exists?)
  380. end
  381. def addresses_local_accounts?
  382. return true if @options[:delivered_to_account_id]
  383. 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) }
  384. return false if local_usernames.empty?
  385. Account.local.where(username: local_usernames).exists?
  386. end
  387. def tombstone_exists?
  388. Tombstone.exists?(uri: object_uri)
  389. end
  390. def forward_for_reply
  391. return unless @status.distributable? && @json['signature'].present? && reply_to_local?
  392. ActivityPub::RawDistributionWorker.perform_async(Oj.dump(@json), replied_to_status.account_id, [@account.preferred_inbox_url])
  393. end
  394. def increment_voters_count!
  395. poll = replied_to_status.preloadable_poll
  396. unless poll.voters_count.nil?
  397. poll.voters_count = poll.voters_count + 1
  398. poll.save
  399. end
  400. rescue ActiveRecord::StaleObjectError
  401. poll.reload
  402. retry
  403. end
  404. end