create.rb 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  1. # frozen_string_literal: true
  2. class ActivityPub::Activity::Create < ActivityPub::Activity
  3. SUPPORTED_TYPES = %w(Note).freeze
  4. CONVERTED_TYPES = %w(Image Video Article Page).freeze
  5. def perform
  6. return if delete_arrived_first?(object_uri) || unsupported_object_type? || invalid_origin?(@object['id'])
  7. RedisLock.acquire(lock_options) do |lock|
  8. if lock.acquired?
  9. @status = find_existing_status
  10. if @status.nil?
  11. process_status
  12. elsif @options[:delivered_to_account_id].present?
  13. postprocess_audience_and_deliver
  14. end
  15. else
  16. raise Mastodon::RaceConditionError
  17. end
  18. end
  19. @status
  20. end
  21. private
  22. def process_status
  23. @tags = []
  24. @mentions = []
  25. @params = {}
  26. process_status_params
  27. process_tags
  28. process_audience
  29. ApplicationRecord.transaction do
  30. @status = Status.create!(@params)
  31. attach_tags(@status)
  32. end
  33. resolve_thread(@status)
  34. distribute(@status)
  35. forward_for_reply if @status.public_visibility? || @status.unlisted_visibility?
  36. end
  37. def find_existing_status
  38. status = status_from_uri(object_uri)
  39. status ||= Status.find_by(uri: @object['atomUri']) if @object['atomUri'].present?
  40. status
  41. end
  42. def process_status_params
  43. @params = begin
  44. {
  45. uri: @object['id'],
  46. url: object_url || @object['id'],
  47. account: @account,
  48. text: text_from_content || '',
  49. language: detected_language,
  50. spoiler_text: text_from_summary || '',
  51. created_at: @object['published'],
  52. override_timestamps: @options[:override_timestamps],
  53. reply: @object['inReplyTo'].present?,
  54. sensitive: @object['sensitive'] || false,
  55. visibility: visibility_from_audience,
  56. thread: replied_to_status,
  57. conversation: conversation_from_uri(@object['conversation']),
  58. media_attachment_ids: process_attachments.take(4).map(&:id),
  59. }
  60. end
  61. end
  62. def process_audience
  63. (as_array(@object['to']) + as_array(@object['cc'])).uniq.each do |audience|
  64. next if audience == ActivityPub::TagManager::COLLECTIONS[:public]
  65. # Unlike with tags, there is no point in resolving accounts we don't already
  66. # know here, because silent mentions would only be used for local access
  67. # control anyway
  68. account = account_from_uri(audience)
  69. next if account.nil? || @mentions.any? { |mention| mention.account_id == account.id }
  70. @mentions << Mention.new(account: account, silent: true)
  71. # If there is at least one silent mention, then the status can be considered
  72. # as a limited-audience status, and not strictly a direct message, but only
  73. # if we considered a direct message in the first place
  74. next unless @params[:visibility] == :direct
  75. @params[:visibility] = :limited
  76. end
  77. # If the payload was delivered to a specific inbox, the inbox owner must have
  78. # access to it, unless they already have access to it anyway
  79. return if @options[:delivered_to_account_id].nil? || @mentions.any? { |mention| mention.account_id == @options[:delivered_to_account_id] }
  80. @mentions << Mention.new(account_id: @options[:delivered_to_account_id], silent: true)
  81. return unless @params[:visibility] == :direct
  82. @params[:visibility] = :limited
  83. end
  84. def postprocess_audience_and_deliver
  85. return if @status.mentions.find_by(account_id: @options[:delivered_to_account_id])
  86. delivered_to_account = Account.find(@options[:delivered_to_account_id])
  87. @status.mentions.create(account: delivered_to_account, silent: true)
  88. @status.update(visibility: :limited) if @status.direct_visibility?
  89. return unless delivered_to_account.following?(@account)
  90. FeedInsertWorker.perform_async(@status.id, delivered_to_account.id, :home)
  91. end
  92. def attach_tags(status)
  93. @tags.each do |tag|
  94. status.tags << tag
  95. TrendingTags.record_use!(tag, status.account, status.created_at) if status.public_visibility?
  96. end
  97. @mentions.each do |mention|
  98. mention.status = status
  99. mention.save
  100. end
  101. end
  102. def process_tags
  103. return if @object['tag'].nil?
  104. as_array(@object['tag']).each do |tag|
  105. if equals_or_includes?(tag['type'], 'Hashtag')
  106. process_hashtag tag
  107. elsif equals_or_includes?(tag['type'], 'Mention')
  108. process_mention tag
  109. elsif equals_or_includes?(tag['type'], 'Emoji')
  110. process_emoji tag
  111. end
  112. end
  113. end
  114. def process_hashtag(tag)
  115. return if tag['name'].blank?
  116. hashtag = tag['name'].gsub(/\A#/, '').mb_chars.downcase
  117. hashtag = Tag.where(name: hashtag).first_or_create!(name: hashtag)
  118. return if @tags.include?(hashtag)
  119. @tags << hashtag
  120. rescue ActiveRecord::RecordInvalid
  121. nil
  122. end
  123. def process_mention(tag)
  124. return if tag['href'].blank?
  125. account = account_from_uri(tag['href'])
  126. account = ::FetchRemoteAccountService.new.call(tag['href'], id: false) if account.nil?
  127. return if account.nil?
  128. @mentions << Mention.new(account: account, silent: false)
  129. end
  130. def process_emoji(tag)
  131. return if skip_download?
  132. return if tag['name'].blank? || tag['icon'].blank? || tag['icon']['url'].blank?
  133. shortcode = tag['name'].delete(':')
  134. image_url = tag['icon']['url']
  135. uri = tag['id']
  136. updated = tag['updated']
  137. emoji = CustomEmoji.find_by(shortcode: shortcode, domain: @account.domain)
  138. return unless emoji.nil? || image_url != emoji.image_remote_url || (updated && emoji.updated_at >= updated)
  139. emoji ||= CustomEmoji.new(domain: @account.domain, shortcode: shortcode, uri: uri)
  140. emoji.image_remote_url = image_url
  141. emoji.save
  142. end
  143. def process_attachments
  144. return [] if @object['attachment'].nil?
  145. media_attachments = []
  146. as_array(@object['attachment']).each do |attachment|
  147. next if attachment['url'].blank?
  148. href = Addressable::URI.parse(attachment['url']).normalize.to_s
  149. media_attachment = MediaAttachment.create(account: @account, remote_url: href, description: attachment['name'].presence, focus: attachment['focalPoint'])
  150. media_attachments << media_attachment
  151. next if unsupported_media_type?(attachment['mediaType']) || skip_download?
  152. media_attachment.file_remote_url = href
  153. media_attachment.save
  154. end
  155. media_attachments
  156. rescue Addressable::URI::InvalidURIError => e
  157. Rails.logger.debug e
  158. media_attachments
  159. end
  160. def resolve_thread(status)
  161. return unless status.reply? && status.thread.nil?
  162. ThreadResolveWorker.perform_async(status.id, in_reply_to_uri)
  163. end
  164. def conversation_from_uri(uri)
  165. return nil if uri.nil?
  166. return Conversation.find_by(id: OStatus::TagManager.instance.unique_tag_to_local_id(uri, 'Conversation')) if OStatus::TagManager.instance.local_id?(uri)
  167. Conversation.find_by(uri: uri) || Conversation.create(uri: uri)
  168. end
  169. def visibility_from_audience
  170. if equals_or_includes?(@object['to'], ActivityPub::TagManager::COLLECTIONS[:public])
  171. :public
  172. elsif equals_or_includes?(@object['cc'], ActivityPub::TagManager::COLLECTIONS[:public])
  173. :unlisted
  174. elsif equals_or_includes?(@object['to'], @account.followers_url)
  175. :private
  176. else
  177. :direct
  178. end
  179. end
  180. def audience_includes?(account)
  181. uri = ActivityPub::TagManager.instance.uri_for(account)
  182. equals_or_includes?(@object['to'], uri) || equals_or_includes?(@object['cc'], uri)
  183. end
  184. def replied_to_status
  185. return @replied_to_status if defined?(@replied_to_status)
  186. if in_reply_to_uri.blank?
  187. @replied_to_status = nil
  188. else
  189. @replied_to_status = status_from_uri(in_reply_to_uri)
  190. @replied_to_status ||= status_from_uri(@object['inReplyToAtomUri']) if @object['inReplyToAtomUri'].present?
  191. @replied_to_status
  192. end
  193. end
  194. def in_reply_to_uri
  195. value_or_id(@object['inReplyTo'])
  196. end
  197. def text_from_content
  198. return Formatter.instance.linkify([text_from_name, object_url || @object['id']].join(' ')) if converted_object_type?
  199. if @object['content'].present?
  200. @object['content']
  201. elsif content_language_map?
  202. @object['contentMap'].values.first
  203. end
  204. end
  205. def text_from_summary
  206. if @object['summary'].present?
  207. @object['summary']
  208. elsif summary_language_map?
  209. @object['summaryMap'].values.first
  210. end
  211. end
  212. def text_from_name
  213. if @object['name'].present?
  214. @object['name']
  215. elsif name_language_map?
  216. @object['nameMap'].values.first
  217. end
  218. end
  219. def detected_language
  220. if content_language_map?
  221. @object['contentMap'].keys.first
  222. elsif name_language_map?
  223. @object['nameMap'].keys.first
  224. elsif summary_language_map?
  225. @object['summaryMap'].keys.first
  226. elsif supported_object_type?
  227. LanguageDetector.instance.detect(text_from_content, @account)
  228. end
  229. end
  230. def object_url
  231. return if @object['url'].blank?
  232. url_candidate = url_to_href(@object['url'], 'text/html')
  233. if invalid_origin?(url_candidate)
  234. nil
  235. else
  236. url_candidate
  237. end
  238. end
  239. def summary_language_map?
  240. @object['summaryMap'].is_a?(Hash) && !@object['summaryMap'].empty?
  241. end
  242. def content_language_map?
  243. @object['contentMap'].is_a?(Hash) && !@object['contentMap'].empty?
  244. end
  245. def name_language_map?
  246. @object['nameMap'].is_a?(Hash) && !@object['nameMap'].empty?
  247. end
  248. def unsupported_object_type?
  249. @object.is_a?(String) || !(supported_object_type? || converted_object_type?)
  250. end
  251. def unsupported_media_type?(mime_type)
  252. mime_type.present? && !(MediaAttachment::IMAGE_MIME_TYPES + MediaAttachment::VIDEO_MIME_TYPES).include?(mime_type)
  253. end
  254. def supported_object_type?
  255. equals_or_includes_any?(@object['type'], SUPPORTED_TYPES)
  256. end
  257. def converted_object_type?
  258. equals_or_includes_any?(@object['type'], CONVERTED_TYPES)
  259. end
  260. def skip_download?
  261. return @skip_download if defined?(@skip_download)
  262. @skip_download ||= DomainBlock.find_by(domain: @account.domain)&.reject_media?
  263. end
  264. def invalid_origin?(url)
  265. return true if unsupported_uri_scheme?(url)
  266. needle = Addressable::URI.parse(url).host
  267. haystack = Addressable::URI.parse(@account.uri).host
  268. !haystack.casecmp(needle).zero?
  269. end
  270. def reply_to_local?
  271. !replied_to_status.nil? && replied_to_status.account.local?
  272. end
  273. def forward_for_reply
  274. return unless @json['signature'].present? && reply_to_local?
  275. ActivityPub::RawDistributionWorker.perform_async(Oj.dump(@json), replied_to_status.account_id, [@account.preferred_inbox_url])
  276. end
  277. def lock_options
  278. { redis: Redis.current, key: "create:#{@object['id']}" }
  279. end
  280. end