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.
 
 
 
 

417 lines
12 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. 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. Tag.find_or_create_by_names(tag['name']) do |hashtag|
  118. @tags << hashtag unless @tags.include?(hashtag)
  119. end
  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']) 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 && updated >= emoji.updated_at)
  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'], blurhash: supported_blurhash?(attachment['blurhash']) ? attachment['blurhash'] : nil)
  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 process_poll
  161. return unless @object['type'] == 'Question' && (@object['anyOf'].is_a?(Array) || @object['oneOf'].is_a?(Array))
  162. expires_at = begin
  163. if @object['closed'].is_a?(String)
  164. @object['closed']
  165. elsif !@object['closed'].nil? && !@object['closed'].is_a?(FalseClass)
  166. Time.now.utc
  167. else
  168. @object['endTime']
  169. end
  170. end
  171. if @object['anyOf'].is_a?(Array)
  172. multiple = true
  173. items = @object['anyOf']
  174. else
  175. multiple = false
  176. items = @object['oneOf']
  177. end
  178. @account.polls.new(
  179. multiple: multiple,
  180. expires_at: expires_at,
  181. options: items.map { |item| item['name'].presence || item['content'] }.compact,
  182. cached_tallies: items.map { |item| item.dig('replies', 'totalItems') || 0 }
  183. )
  184. end
  185. def poll_vote?
  186. 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'])
  187. unless replied_to_status.preloadable_poll.expired?
  188. replied_to_status.preloadable_poll.votes.create!(account: @account, choice: replied_to_status.preloadable_poll.options.index(@object['name']), uri: @object['id'])
  189. ActivityPub::DistributePollUpdateWorker.perform_in(3.minutes, replied_to_status.id) unless replied_to_status.preloadable_poll.hide_totals?
  190. end
  191. true
  192. end
  193. def resolve_thread(status)
  194. return unless status.reply? && status.thread.nil? && Request.valid_url?(in_reply_to_uri)
  195. ThreadResolveWorker.perform_async(status.id, in_reply_to_uri)
  196. end
  197. def fetch_replies(status)
  198. collection = @object['replies']
  199. return if collection.nil?
  200. replies = ActivityPub::FetchRepliesService.new.call(status, collection, false)
  201. return unless replies.nil?
  202. uri = value_or_id(collection)
  203. ActivityPub::FetchRepliesWorker.perform_async(status.id, uri) unless uri.nil?
  204. end
  205. def visibility_from_audience
  206. if equals_or_includes?(@object['to'], ActivityPub::TagManager::COLLECTIONS[:public])
  207. :public
  208. elsif equals_or_includes?(@object['cc'], ActivityPub::TagManager::COLLECTIONS[:public])
  209. :unlisted
  210. elsif equals_or_includes?(@object['to'], @account.followers_url)
  211. :private
  212. else
  213. :direct
  214. end
  215. end
  216. def audience_includes?(account)
  217. uri = ActivityPub::TagManager.instance.uri_for(account)
  218. equals_or_includes?(@object['to'], uri) || equals_or_includes?(@object['cc'], uri)
  219. end
  220. def replied_to_status
  221. return @replied_to_status if defined?(@replied_to_status)
  222. if in_reply_to_uri.blank?
  223. @replied_to_status = nil
  224. else
  225. @replied_to_status = status_from_uri(in_reply_to_uri)
  226. @replied_to_status ||= status_from_uri(@object['inReplyToAtomUri']) if @object['inReplyToAtomUri'].present?
  227. @replied_to_status
  228. end
  229. end
  230. def in_reply_to_uri
  231. value_or_id(@object['inReplyTo'])
  232. end
  233. def text_from_content
  234. return Formatter.instance.linkify([[text_from_name, text_from_summary.presence].compact.join("\n\n"), object_url || @object['id']].join(' ')) if converted_object_type?
  235. if @object['content'].present?
  236. @object['content']
  237. elsif content_language_map?
  238. @object['contentMap'].values.first
  239. end
  240. end
  241. def text_from_summary
  242. if @object['summary'].present?
  243. @object['summary']
  244. elsif summary_language_map?
  245. @object['summaryMap'].values.first
  246. end
  247. end
  248. def text_from_name
  249. if @object['name'].present?
  250. @object['name']
  251. elsif name_language_map?
  252. @object['nameMap'].values.first
  253. end
  254. end
  255. def detected_language
  256. if content_language_map?
  257. @object['contentMap'].keys.first
  258. elsif name_language_map?
  259. @object['nameMap'].keys.first
  260. elsif summary_language_map?
  261. @object['summaryMap'].keys.first
  262. elsif supported_object_type?
  263. LanguageDetector.instance.detect(text_from_content, @account)
  264. end
  265. end
  266. def object_url
  267. return if @object['url'].blank?
  268. url_candidate = url_to_href(@object['url'], 'text/html')
  269. if invalid_origin?(url_candidate)
  270. nil
  271. else
  272. url_candidate
  273. end
  274. end
  275. def summary_language_map?
  276. @object['summaryMap'].is_a?(Hash) && !@object['summaryMap'].empty?
  277. end
  278. def content_language_map?
  279. @object['contentMap'].is_a?(Hash) && !@object['contentMap'].empty?
  280. end
  281. def name_language_map?
  282. @object['nameMap'].is_a?(Hash) && !@object['nameMap'].empty?
  283. end
  284. def unsupported_media_type?(mime_type)
  285. mime_type.present? && !MediaAttachment.supported_mime_types.include?(mime_type)
  286. end
  287. def supported_blurhash?(blurhash)
  288. components = blurhash.blank? ? nil : Blurhash.components(blurhash)
  289. components.present? && components.none? { |comp| comp > 5 }
  290. end
  291. def skip_download?
  292. return @skip_download if defined?(@skip_download)
  293. @skip_download ||= DomainBlock.reject_media?(@account.domain)
  294. end
  295. def reply_to_local?
  296. !replied_to_status.nil? && replied_to_status.account.local?
  297. end
  298. def related_to_local_activity?
  299. fetch? || followed_by_local_accounts? || requested_through_relay? ||
  300. responds_to_followed_account? || addresses_local_accounts?
  301. end
  302. def responds_to_followed_account?
  303. !replied_to_status.nil? && (replied_to_status.account.local? || replied_to_status.account.passive_relationships.exists?)
  304. end
  305. def addresses_local_accounts?
  306. return true if @options[:delivered_to_account_id]
  307. 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) }
  308. return false if local_usernames.empty?
  309. Account.local.where(username: local_usernames).exists?
  310. end
  311. def check_for_spam
  312. spam_check = SpamCheck.new(@status)
  313. return if spam_check.skip?
  314. if spam_check.spam?
  315. spam_check.flag!
  316. else
  317. spam_check.remember!
  318. end
  319. end
  320. def forward_for_reply
  321. return unless @json['signature'].present? && reply_to_local?
  322. ActivityPub::RawDistributionWorker.perform_async(Oj.dump(@json), replied_to_status.account_id, [@account.preferred_inbox_url])
  323. end
  324. def lock_options
  325. { redis: Redis.current, key: "create:#{@object['id']}" }
  326. end
  327. end