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.

219 lines
6.9 KiB

  1. # frozen_string_literal: true
  2. class OStatus::Activity::Creation < OStatus::Activity::Base
  3. def perform
  4. if redis.exists("delete_upon_arrival:#{@account.id}:#{id}")
  5. Rails.logger.debug "Delete for status #{id} was queued, ignoring"
  6. return [nil, false]
  7. end
  8. return [nil, false] if @account.suspended? || invalid_origin?
  9. RedisLock.acquire(lock_options) do |lock|
  10. if lock.acquired?
  11. # Return early if status already exists in db
  12. @status = find_status(id)
  13. return [@status, false] unless @status.nil?
  14. @status = process_status
  15. else
  16. raise Mastodon::RaceConditionError
  17. end
  18. end
  19. [@status, true]
  20. end
  21. def process_status
  22. Rails.logger.debug "Creating remote status #{id}"
  23. cached_reblog = reblog
  24. status = nil
  25. # Skip if the reblogged status is not public
  26. return if cached_reblog && !(cached_reblog.public_visibility? || cached_reblog.unlisted_visibility?)
  27. media_attachments = save_media.take(4)
  28. ApplicationRecord.transaction do
  29. status = Status.create!(
  30. uri: id,
  31. url: url,
  32. account: @account,
  33. reblog: cached_reblog,
  34. text: content,
  35. spoiler_text: content_warning,
  36. created_at: published,
  37. override_timestamps: @options[:override_timestamps],
  38. reply: thread?,
  39. language: content_language,
  40. visibility: visibility_scope,
  41. conversation: find_or_create_conversation,
  42. thread: thread? ? find_status(thread.first) || find_activitypub_status(thread.first, thread.second) : nil,
  43. media_attachment_ids: media_attachments.map(&:id),
  44. sensitive: sensitive?
  45. )
  46. save_mentions(status)
  47. save_hashtags(status)
  48. save_emojis(status)
  49. end
  50. if thread? && status.thread.nil? && Request.valid_url?(thread.second)
  51. Rails.logger.debug "Trying to attach #{status.id} (#{id}) to #{thread.first}"
  52. ThreadResolveWorker.perform_async(status.id, thread.second)
  53. end
  54. Rails.logger.debug "Queuing remote status #{status.id} (#{id}) for distribution"
  55. LinkCrawlWorker.perform_async(status.id) unless status.spoiler_text?
  56. # Only continue if the status is supposed to have arrived in real-time.
  57. # Note that if @options[:override_timestamps] isn't set, the status
  58. # may have a lower snowflake id than other existing statuses, potentially
  59. # "hiding" it from paginated API calls
  60. return status unless @options[:override_timestamps] || status.within_realtime_window?
  61. DistributionWorker.perform_async(status.id)
  62. status
  63. end
  64. def content
  65. @xml.at_xpath('./xmlns:content', xmlns: OStatus::TagManager::XMLNS).content
  66. end
  67. def content_language
  68. @xml.at_xpath('./xmlns:content', xmlns: OStatus::TagManager::XMLNS)['xml:lang']&.presence || 'en'
  69. end
  70. def content_warning
  71. @xml.at_xpath('./xmlns:summary', xmlns: OStatus::TagManager::XMLNS)&.content || ''
  72. end
  73. def visibility_scope
  74. @xml.at_xpath('./mastodon:scope', mastodon: OStatus::TagManager::MTDN_XMLNS)&.content&.to_sym || :public
  75. end
  76. def published
  77. @xml.at_xpath('./xmlns:published', xmlns: OStatus::TagManager::XMLNS).content
  78. end
  79. def thread?
  80. !@xml.at_xpath('./thr:in-reply-to', thr: OStatus::TagManager::THR_XMLNS).nil?
  81. end
  82. def thread
  83. thr = @xml.at_xpath('./thr:in-reply-to', thr: OStatus::TagManager::THR_XMLNS)
  84. [thr['ref'], thr['href']]
  85. end
  86. private
  87. def sensitive?
  88. # OStatus-specific convention (not standard)
  89. @xml.xpath('./xmlns:category', xmlns: OStatus::TagManager::XMLNS).any? { |category| category['term'] == 'nsfw' }
  90. end
  91. def find_or_create_conversation
  92. uri = @xml.at_xpath('./ostatus:conversation', ostatus: OStatus::TagManager::OS_XMLNS)&.attribute('ref')&.content
  93. return if uri.nil?
  94. if OStatus::TagManager.instance.local_id?(uri)
  95. local_id = OStatus::TagManager.instance.unique_tag_to_local_id(uri, 'Conversation')
  96. return Conversation.find_by(id: local_id)
  97. end
  98. Conversation.find_by(uri: uri) || Conversation.create!(uri: uri)
  99. end
  100. def save_mentions(parent)
  101. processed_account_ids = []
  102. @xml.xpath('./xmlns:link[@rel="mentioned"]', xmlns: OStatus::TagManager::XMLNS).each do |link|
  103. next if [OStatus::TagManager::TYPES[:group], OStatus::TagManager::TYPES[:collection]].include? link['ostatus:object-type']
  104. mentioned_account = account_from_href(link['href'])
  105. next if mentioned_account.nil? || processed_account_ids.include?(mentioned_account.id)
  106. mentioned_account.mentions.where(status: parent).first_or_create(status: parent)
  107. # So we can skip duplicate mentions
  108. processed_account_ids << mentioned_account.id
  109. end
  110. end
  111. def save_hashtags(parent)
  112. tags = @xml.xpath('./xmlns:category', xmlns: OStatus::TagManager::XMLNS).map { |category| category['term'] }.select(&:present?)
  113. ProcessHashtagsService.new.call(parent, tags)
  114. end
  115. def save_media
  116. do_not_download = DomainBlock.reject_media?(@account.domain)
  117. media_attachments = []
  118. @xml.xpath('./xmlns:link[@rel="enclosure"]', xmlns: OStatus::TagManager::XMLNS).each do |link|
  119. next unless link['href']
  120. media = MediaAttachment.where(status: nil, remote_url: link['href']).first_or_initialize(account: @account, status: nil, remote_url: link['href'])
  121. parsed_url = Addressable::URI.parse(link['href']).normalize
  122. next if !%w(http https).include?(parsed_url.scheme) || parsed_url.host.empty?
  123. media.save
  124. media_attachments << media
  125. next if do_not_download
  126. begin
  127. media.file_remote_url = link['href']
  128. media.save!
  129. rescue ActiveRecord::RecordInvalid
  130. next
  131. end
  132. end
  133. media_attachments
  134. end
  135. def save_emojis(parent)
  136. do_not_download = DomainBlock.reject_media?(parent.account.domain)
  137. return if do_not_download
  138. @xml.xpath('./xmlns:link[@rel="emoji"]', xmlns: OStatus::TagManager::XMLNS).each do |link|
  139. next unless link['href'] && link['name']
  140. shortcode = link['name'].delete(':')
  141. emoji = CustomEmoji.find_by(shortcode: shortcode, domain: parent.account.domain)
  142. next unless emoji.nil?
  143. emoji = CustomEmoji.new(shortcode: shortcode, domain: parent.account.domain)
  144. emoji.image_remote_url = link['href']
  145. emoji.save
  146. end
  147. end
  148. def account_from_href(href)
  149. url = Addressable::URI.parse(href).normalize
  150. if TagManager.instance.web_domain?(url.host)
  151. Account.find_local(url.path.gsub('/users/', ''))
  152. else
  153. Account.where(uri: href).or(Account.where(url: href)).first || FetchRemoteAccountService.new.call(href)
  154. end
  155. end
  156. def invalid_origin?
  157. return false unless id.start_with?('http') # Legacy IDs cannot be checked
  158. needle = Addressable::URI.parse(id).normalized_host
  159. !(needle.casecmp(@account.domain).zero? ||
  160. needle.casecmp(Addressable::URI.parse(@account.remote_url.presence || @account.uri).normalized_host).zero?)
  161. end
  162. def lock_options
  163. { redis: Redis.current, key: "create:#{id}" }
  164. end
  165. end