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.

300 lines
10 KiB

  1. # frozen_string_literal: true
  2. class ActivityPub::ProcessStatusUpdateService < BaseService
  3. include JsonLdHelper
  4. include Redisable
  5. include Lockable
  6. def call(status, json)
  7. raise ArgumentError, 'Status has unsaved changes' if status.changed?
  8. @json = json
  9. @status_parser = ActivityPub::Parser::StatusParser.new(@json)
  10. @uri = @status_parser.uri
  11. @status = status
  12. @account = status.account
  13. @media_attachments_changed = false
  14. @poll_changed = false
  15. # Only native types can be updated at the moment
  16. return @status if !expected_type? || already_updated_more_recently?
  17. if @status_parser.edited_at.present? && (@status.edited_at.nil? || @status_parser.edited_at > @status.edited_at)
  18. handle_explicit_update!
  19. else
  20. handle_implicit_update!
  21. end
  22. @status
  23. end
  24. private
  25. def handle_explicit_update!
  26. last_edit_date = @status.edited_at.presence || @status.created_at
  27. # Only allow processing one create/update per status at a time
  28. with_lock("create:#{@uri}") do
  29. Status.transaction do
  30. record_previous_edit!
  31. update_media_attachments!
  32. update_poll!
  33. update_immediate_attributes!
  34. update_metadata!
  35. create_edits!
  36. end
  37. queue_poll_notifications!
  38. next unless significant_changes?
  39. reset_preview_card!
  40. broadcast_updates!
  41. end
  42. forward_activity! if significant_changes? && @status_parser.edited_at > last_edit_date
  43. end
  44. def handle_implicit_update!
  45. with_lock("create:#{@uri}") do
  46. update_poll!(allow_significant_changes: false)
  47. queue_poll_notifications!
  48. end
  49. end
  50. def update_media_attachments!
  51. previous_media_attachments = @status.media_attachments.to_a
  52. previous_media_attachments_ids = @status.ordered_media_attachment_ids || previous_media_attachments.map(&:id)
  53. next_media_attachments = []
  54. as_array(@json['attachment']).each do |attachment|
  55. media_attachment_parser = ActivityPub::Parser::MediaAttachmentParser.new(attachment)
  56. next if media_attachment_parser.remote_url.blank? || next_media_attachments.size > 4
  57. begin
  58. media_attachment = previous_media_attachments.find { |previous_media_attachment| previous_media_attachment.remote_url == media_attachment_parser.remote_url }
  59. media_attachment ||= MediaAttachment.new(account: @account, remote_url: media_attachment_parser.remote_url)
  60. # If a previously existing media attachment was significantly updated, mark
  61. # media attachments as changed even if none were added or removed
  62. if media_attachment_parser.significantly_changes?(media_attachment)
  63. @media_attachments_changed = true
  64. end
  65. media_attachment.description = media_attachment_parser.description
  66. media_attachment.focus = media_attachment_parser.focus
  67. media_attachment.thumbnail_remote_url = media_attachment_parser.thumbnail_remote_url
  68. media_attachment.blurhash = media_attachment_parser.blurhash
  69. media_attachment.save!
  70. next_media_attachments << media_attachment
  71. next if unsupported_media_type?(media_attachment_parser.file_content_type) || skip_download?
  72. RedownloadMediaWorker.perform_async(media_attachment.id) if media_attachment.remote_url_previously_changed? || media_attachment.thumbnail_remote_url_previously_changed?
  73. rescue Addressable::URI::InvalidURIError => e
  74. Rails.logger.debug "Invalid URL in attachment: #{e}"
  75. end
  76. end
  77. added_media_attachments = next_media_attachments - previous_media_attachments
  78. MediaAttachment.where(id: added_media_attachments.map(&:id)).update_all(status_id: @status.id)
  79. @status.ordered_media_attachment_ids = next_media_attachments.map(&:id)
  80. @status.media_attachments.reload
  81. @media_attachments_changed = true if @status.ordered_media_attachment_ids != previous_media_attachments_ids
  82. end
  83. def update_poll!(allow_significant_changes: true)
  84. previous_poll = @status.preloadable_poll
  85. @previous_expires_at = previous_poll&.expires_at
  86. poll_parser = ActivityPub::Parser::PollParser.new(@json)
  87. if poll_parser.valid?
  88. poll = previous_poll || @account.polls.new(status: @status)
  89. # If for some reasons the options were changed, it invalidates all previous
  90. # votes, so we need to remove them
  91. @poll_changed = true if poll_parser.significantly_changes?(poll)
  92. return if @poll_changed && !allow_significant_changes
  93. poll.last_fetched_at = Time.now.utc
  94. poll.options = poll_parser.options
  95. poll.multiple = poll_parser.multiple
  96. poll.expires_at = poll_parser.expires_at
  97. poll.voters_count = poll_parser.voters_count
  98. poll.cached_tallies = poll_parser.cached_tallies
  99. poll.reset_votes! if @poll_changed
  100. poll.save!
  101. @status.poll_id = poll.id
  102. elsif previous_poll.present?
  103. return unless allow_significant_changes
  104. previous_poll.destroy!
  105. @poll_changed = true
  106. @status.poll_id = nil
  107. end
  108. end
  109. def update_immediate_attributes!
  110. @status.text = @status_parser.text || ''
  111. @status.spoiler_text = @status_parser.spoiler_text || ''
  112. @status.sensitive = @account.sensitized? || @status_parser.sensitive || false
  113. @status.language = @status_parser.language
  114. @significant_changes = text_significantly_changed? || @status.spoiler_text_changed? || @media_attachments_changed || @poll_changed
  115. @status.edited_at = @status_parser.edited_at if significant_changes?
  116. @status.save!
  117. end
  118. def update_metadata!
  119. @raw_tags = []
  120. @raw_mentions = []
  121. @raw_emojis = []
  122. as_array(@json['tag']).each do |tag|
  123. if equals_or_includes?(tag['type'], 'Hashtag')
  124. @raw_tags << tag['name']
  125. elsif equals_or_includes?(tag['type'], 'Mention')
  126. @raw_mentions << tag['href']
  127. elsif equals_or_includes?(tag['type'], 'Emoji')
  128. @raw_emojis << tag
  129. end
  130. end
  131. update_tags!
  132. update_mentions!
  133. update_emojis!
  134. end
  135. def update_tags!
  136. @status.tags = Tag.find_or_create_by_names(@raw_tags)
  137. end
  138. def update_mentions!
  139. previous_mentions = @status.active_mentions.includes(:account).to_a
  140. current_mentions = []
  141. @raw_mentions.each do |href|
  142. next if href.blank?
  143. account = ActivityPub::TagManager.instance.uri_to_resource(href, Account)
  144. account ||= ActivityPub::FetchRemoteAccountService.new.call(href)
  145. next if account.nil?
  146. mention = previous_mentions.find { |x| x.account_id == account.id }
  147. mention ||= account.mentions.new(status: @status)
  148. current_mentions << mention
  149. end
  150. current_mentions.each do |mention|
  151. mention.save if mention.new_record?
  152. end
  153. # If previous mentions are no longer contained in the text, convert them
  154. # to silent mentions, since withdrawing access from someone who already
  155. # received a notification might be more confusing
  156. removed_mentions = previous_mentions - current_mentions
  157. Mention.where(id: removed_mentions.map(&:id)).update_all(silent: true) unless removed_mentions.empty?
  158. end
  159. def update_emojis!
  160. return if skip_download?
  161. @raw_emojis.each do |raw_emoji|
  162. custom_emoji_parser = ActivityPub::Parser::CustomEmojiParser.new(raw_emoji)
  163. next if custom_emoji_parser.shortcode.blank? || custom_emoji_parser.image_remote_url.blank?
  164. emoji = CustomEmoji.find_by(shortcode: custom_emoji_parser.shortcode, domain: @account.domain)
  165. next unless emoji.nil? || custom_emoji_parser.image_remote_url != emoji.image_remote_url || (custom_emoji_parser.updated_at && custom_emoji_parser.updated_at >= emoji.updated_at)
  166. begin
  167. emoji ||= CustomEmoji.new(domain: @account.domain, shortcode: custom_emoji_parser.shortcode, uri: custom_emoji_parser.uri)
  168. emoji.image_remote_url = custom_emoji_parser.image_remote_url
  169. emoji.save
  170. rescue Seahorse::Client::NetworkingError => e
  171. Rails.logger.warn "Error storing emoji: #{e}"
  172. end
  173. end
  174. end
  175. def expected_type?
  176. equals_or_includes_any?(@json['type'], %w(Note Question))
  177. end
  178. def record_previous_edit!
  179. @previous_edit = @status.build_snapshot(at_time: @status.created_at, rate_limit: false) if @status.edits.empty?
  180. end
  181. def create_edits!
  182. return unless significant_changes?
  183. @previous_edit&.save!
  184. @status.snapshot!(account_id: @account.id, rate_limit: false)
  185. end
  186. def skip_download?
  187. return @skip_download if defined?(@skip_download)
  188. @skip_download ||= DomainBlock.reject_media?(@account.domain)
  189. end
  190. def unsupported_media_type?(mime_type)
  191. mime_type.present? && !MediaAttachment.supported_mime_types.include?(mime_type)
  192. end
  193. def significant_changes?
  194. @significant_changes
  195. end
  196. def text_significantly_changed?
  197. return false unless @status.text_changed?
  198. old, new = @status.text_change
  199. HtmlAwareFormatter.new(old, false).to_s != HtmlAwareFormatter.new(new, false).to_s
  200. end
  201. def already_updated_more_recently?
  202. @status.edited_at.present? && @status_parser.edited_at.present? && @status.edited_at > @status_parser.edited_at
  203. end
  204. def reset_preview_card!
  205. @status.preview_cards.clear
  206. LinkCrawlWorker.perform_in(rand(1..59).seconds, @status.id)
  207. end
  208. def broadcast_updates!
  209. ::DistributionWorker.perform_async(@status.id, { 'update' => true })
  210. end
  211. def queue_poll_notifications!
  212. poll = @status.preloadable_poll
  213. # If the poll had no expiration date set but now has, or now has a sooner
  214. # expiration date, and people have voted, schedule a notification
  215. return unless poll.present? && poll.expires_at.present? && poll.votes.exists?
  216. PollExpirationNotifyWorker.remove_from_scheduled(poll.id) if @previous_expires_at.present? && @previous_expires_at > poll.expires_at
  217. PollExpirationNotifyWorker.perform_at(poll.expires_at + 5.minutes, poll.id)
  218. end
  219. def forward_activity!
  220. forwarder.forward! if forwarder.forwardable?
  221. end
  222. def forwarder
  223. @forwarder ||= ActivityPub::Forwarder.new(@account, @json, @status)
  224. end
  225. end