The code powering m.abunchtell.com https://m.abunchtell.com
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.
 
 
 
 

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