process_status_update_service.rb 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  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_redis_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_redis_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. @media_attachments_changed = true if media_attachment_parser.significantly_changes?(media_attachment)
  66. media_attachment.description = media_attachment_parser.description
  67. media_attachment.focus = media_attachment_parser.focus
  68. media_attachment.thumbnail_remote_url = media_attachment_parser.thumbnail_remote_url
  69. media_attachment.blurhash = media_attachment_parser.blurhash
  70. media_attachment.status_id = @status.id
  71. media_attachment.skip_download = unsupported_media_type?(media_attachment_parser.file_content_type) || skip_download?
  72. media_attachment.save!
  73. @next_media_attachments << media_attachment
  74. rescue Addressable::URI::InvalidURIError => e
  75. Rails.logger.debug { "Invalid URL in attachment: #{e}" }
  76. end
  77. end
  78. @status.ordered_media_attachment_ids = @next_media_attachments.map(&:id)
  79. @media_attachments_changed = true if @status.ordered_media_attachment_ids != previous_media_attachments_ids
  80. end
  81. def download_media_files!
  82. @next_media_attachments.each do |media_attachment|
  83. next if media_attachment.skip_download
  84. media_attachment.download_file! if media_attachment.remote_url_previously_changed?
  85. media_attachment.download_thumbnail! if media_attachment.thumbnail_remote_url_previously_changed?
  86. media_attachment.save
  87. rescue Mastodon::UnexpectedResponseError, HTTP::TimeoutError, HTTP::ConnectionError, OpenSSL::SSL::SSLError
  88. RedownloadMediaWorker.perform_in(rand(30..600).seconds, media_attachment.id)
  89. rescue Seahorse::Client::NetworkingError => e
  90. Rails.logger.warn "Error storing media attachment: #{e}"
  91. end
  92. @status.media_attachments.reload
  93. end
  94. def update_poll!(allow_significant_changes: true)
  95. previous_poll = @status.preloadable_poll
  96. @previous_expires_at = previous_poll&.expires_at
  97. poll_parser = ActivityPub::Parser::PollParser.new(@json)
  98. if poll_parser.valid?
  99. poll = previous_poll || @account.polls.new(status: @status)
  100. # If for some reasons the options were changed, it invalidates all previous
  101. # votes, so we need to remove them
  102. @poll_changed = true if poll_parser.significantly_changes?(poll)
  103. return if @poll_changed && !allow_significant_changes
  104. poll.last_fetched_at = Time.now.utc
  105. poll.options = poll_parser.options
  106. poll.multiple = poll_parser.multiple
  107. poll.expires_at = poll_parser.expires_at
  108. poll.voters_count = poll_parser.voters_count
  109. poll.cached_tallies = poll_parser.cached_tallies
  110. poll.reset_votes! if @poll_changed
  111. poll.save!
  112. @status.poll_id = poll.id
  113. elsif previous_poll.present?
  114. return unless allow_significant_changes
  115. previous_poll.destroy!
  116. @poll_changed = true
  117. @status.poll_id = nil
  118. end
  119. end
  120. def update_immediate_attributes!
  121. @status.text = @status_parser.text || ''
  122. @status.spoiler_text = @status_parser.spoiler_text || ''
  123. @status.sensitive = @account.sensitized? || @status_parser.sensitive || false
  124. @status.language = @status_parser.language
  125. @significant_changes = text_significantly_changed? || @status.spoiler_text_changed? || @media_attachments_changed || @poll_changed
  126. @status.edited_at = @status_parser.edited_at if significant_changes?
  127. @status.save!
  128. end
  129. def update_metadata!
  130. @raw_tags = []
  131. @raw_mentions = []
  132. @raw_emojis = []
  133. as_array(@json['tag']).each do |tag|
  134. if equals_or_includes?(tag['type'], 'Hashtag')
  135. @raw_tags << tag['name']
  136. elsif equals_or_includes?(tag['type'], 'Mention')
  137. @raw_mentions << tag['href']
  138. elsif equals_or_includes?(tag['type'], 'Emoji')
  139. @raw_emojis << tag
  140. end
  141. end
  142. update_tags!
  143. update_mentions!
  144. update_emojis!
  145. end
  146. def update_tags!
  147. @status.tags = Tag.find_or_create_by_names(@raw_tags)
  148. end
  149. def update_mentions!
  150. previous_mentions = @status.active_mentions.includes(:account).to_a
  151. current_mentions = []
  152. @raw_mentions.each do |href|
  153. next if href.blank?
  154. account = ActivityPub::TagManager.instance.uri_to_resource(href, Account)
  155. account ||= ActivityPub::FetchRemoteAccountService.new.call(href, request_id: @request_id)
  156. next if account.nil?
  157. mention = previous_mentions.find { |x| x.account_id == account.id }
  158. mention ||= account.mentions.new(status: @status)
  159. current_mentions << mention
  160. end
  161. current_mentions.each do |mention|
  162. mention.save if mention.new_record?
  163. end
  164. # If previous mentions are no longer contained in the text, convert them
  165. # to silent mentions, since withdrawing access from someone who already
  166. # received a notification might be more confusing
  167. removed_mentions = previous_mentions - current_mentions
  168. Mention.where(id: removed_mentions.map(&:id)).update_all(silent: true) unless removed_mentions.empty?
  169. end
  170. def update_emojis!
  171. return if skip_download?
  172. @raw_emojis.each do |raw_emoji|
  173. custom_emoji_parser = ActivityPub::Parser::CustomEmojiParser.new(raw_emoji)
  174. next if custom_emoji_parser.shortcode.blank? || custom_emoji_parser.image_remote_url.blank?
  175. emoji = CustomEmoji.find_by(shortcode: custom_emoji_parser.shortcode, domain: @account.domain)
  176. 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)
  177. begin
  178. emoji ||= CustomEmoji.new(domain: @account.domain, shortcode: custom_emoji_parser.shortcode, uri: custom_emoji_parser.uri)
  179. emoji.image_remote_url = custom_emoji_parser.image_remote_url
  180. emoji.save
  181. rescue Seahorse::Client::NetworkingError => e
  182. Rails.logger.warn "Error storing emoji: #{e}"
  183. end
  184. end
  185. end
  186. def expected_type?
  187. equals_or_includes_any?(@json['type'], %w(Note Question))
  188. end
  189. def record_previous_edit!
  190. @previous_edit = @status.build_snapshot(at_time: @status.created_at, rate_limit: false) if @status.edits.empty?
  191. end
  192. def create_edits!
  193. return unless significant_changes?
  194. @previous_edit&.save!
  195. @status.snapshot!(account_id: @account.id, rate_limit: false)
  196. end
  197. def skip_download?
  198. return @skip_download if defined?(@skip_download)
  199. @skip_download ||= DomainBlock.reject_media?(@account.domain)
  200. end
  201. def unsupported_media_type?(mime_type)
  202. mime_type.present? && !MediaAttachment.supported_mime_types.include?(mime_type)
  203. end
  204. def significant_changes?
  205. @significant_changes
  206. end
  207. def text_significantly_changed?
  208. return false unless @status.text_changed?
  209. old, new = @status.text_change
  210. HtmlAwareFormatter.new(old, false).to_s != HtmlAwareFormatter.new(new, false).to_s
  211. end
  212. def already_updated_more_recently?
  213. @status.edited_at.present? && @status_parser.edited_at.present? && @status.edited_at > @status_parser.edited_at
  214. end
  215. def reset_preview_card!
  216. @status.preview_cards.clear
  217. LinkCrawlWorker.perform_in(rand(1..59).seconds, @status.id)
  218. end
  219. def broadcast_updates!
  220. ::DistributionWorker.perform_async(@status.id, { 'update' => true })
  221. end
  222. def queue_poll_notifications!
  223. poll = @status.preloadable_poll
  224. # If the poll had no expiration date set but now has, or now has a sooner
  225. # expiration date, and people have voted, schedule a notification
  226. return unless poll.present? && poll.expires_at.present? && poll.votes.exists?
  227. PollExpirationNotifyWorker.remove_from_scheduled(poll.id) if @previous_expires_at.present? && @previous_expires_at > poll.expires_at
  228. PollExpirationNotifyWorker.perform_at(poll.expires_at + 5.minutes, poll.id)
  229. end
  230. def forward_activity!
  231. forwarder.forward! if forwarder.forwardable?
  232. end
  233. def forwarder
  234. @forwarder ||= ActivityPub::Forwarder.new(@account, @activity_json, @status)
  235. end
  236. end