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.

430 lines
13 KiB

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