process_status_update_service.rb 11 KB

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