process_status_update_service.rb 10 KB

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