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.

276 lines
8.2 KiB

  1. # frozen_string_literal: true
  2. class ActivityPub::ProcessAccountService < BaseService
  3. include JsonLdHelper
  4. # Should be called with confirmed valid JSON
  5. # and WebFinger-resolved username and domain
  6. def call(username, domain, json, options = {})
  7. return if json['inbox'].blank? || unsupported_uri_scheme?(json['id'])
  8. @options = options
  9. @json = json
  10. @uri = @json['id']
  11. @username = username
  12. @domain = domain
  13. @collections = {}
  14. RedisLock.acquire(lock_options) do |lock|
  15. if lock.acquired?
  16. @account = Account.find_remote(@username, @domain)
  17. @old_public_key = @account&.public_key
  18. @old_protocol = @account&.protocol
  19. create_account if @account.nil?
  20. update_account
  21. process_tags
  22. process_attachments
  23. else
  24. raise Mastodon::RaceConditionError
  25. end
  26. end
  27. return if @account.nil?
  28. after_protocol_change! if protocol_changed?
  29. after_key_change! if key_changed? && !@options[:signed_with_known_key]
  30. clear_tombstones! if key_changed?
  31. unless @options[:only_key]
  32. check_featured_collection! if @account.featured_collection_url.present?
  33. check_links! unless @account.fields.empty?
  34. end
  35. @account
  36. rescue Oj::ParseError
  37. nil
  38. end
  39. private
  40. def create_account
  41. @account = Account.new
  42. @account.protocol = :activitypub
  43. @account.username = @username
  44. @account.domain = @domain
  45. @account.suspended = true if auto_suspend?
  46. @account.silenced = true if auto_silence?
  47. @account.private_key = nil
  48. end
  49. def update_account
  50. @account.last_webfingered_at = Time.now.utc unless @options[:only_key]
  51. @account.protocol = :activitypub
  52. set_immediate_attributes!
  53. set_fetchable_attributes! unless @options[:only_keys]
  54. @account.save_with_optional_media!
  55. end
  56. def set_immediate_attributes!
  57. @account.inbox_url = @json['inbox'] || ''
  58. @account.outbox_url = @json['outbox'] || ''
  59. @account.shared_inbox_url = (@json['endpoints'].is_a?(Hash) ? @json['endpoints']['sharedInbox'] : @json['sharedInbox']) || ''
  60. @account.followers_url = @json['followers'] || ''
  61. @account.featured_collection_url = @json['featured'] || ''
  62. @account.url = url || @uri
  63. @account.uri = @uri
  64. @account.display_name = @json['name'] || ''
  65. @account.note = @json['summary'] || ''
  66. @account.locked = @json['manuallyApprovesFollowers'] || false
  67. @account.fields = property_values || {}
  68. @account.also_known_as = as_array(@json['alsoKnownAs'] || []).map { |item| value_or_id(item) }
  69. @account.actor_type = actor_type
  70. end
  71. def set_fetchable_attributes!
  72. @account.avatar_remote_url = image_url('icon') unless skip_download?
  73. @account.header_remote_url = image_url('image') unless skip_download?
  74. @account.public_key = public_key || ''
  75. @account.statuses_count = outbox_total_items if outbox_total_items.present?
  76. @account.following_count = following_total_items if following_total_items.present?
  77. @account.followers_count = followers_total_items if followers_total_items.present?
  78. @account.moved_to_account = @json['movedTo'].present? ? moved_account : nil
  79. end
  80. def after_protocol_change!
  81. ActivityPub::PostUpgradeWorker.perform_async(@account.domain)
  82. end
  83. def after_key_change!
  84. RefollowWorker.perform_async(@account.id)
  85. end
  86. def check_featured_collection!
  87. ActivityPub::SynchronizeFeaturedCollectionWorker.perform_async(@account.id)
  88. end
  89. def check_links!
  90. VerifyAccountLinksWorker.perform_async(@account.id)
  91. end
  92. def actor_type
  93. if @json['type'].is_a?(Array)
  94. @json['type'].find { |type| ActivityPub::FetchRemoteAccountService::SUPPORTED_TYPES.include?(type) }
  95. else
  96. @json['type']
  97. end
  98. end
  99. def image_url(key)
  100. value = first_of_value(@json[key])
  101. return if value.nil?
  102. return value['url'] if value.is_a?(Hash)
  103. image = fetch_resource_without_id_validation(value)
  104. image['url'] if image
  105. end
  106. def public_key
  107. value = first_of_value(@json['publicKey'])
  108. return if value.nil?
  109. return value['publicKeyPem'] if value.is_a?(Hash)
  110. key = fetch_resource_without_id_validation(value)
  111. key['publicKeyPem'] if key
  112. end
  113. def url
  114. return if @json['url'].blank?
  115. url_candidate = url_to_href(@json['url'], 'text/html')
  116. if unsupported_uri_scheme?(url_candidate) || mismatching_origin?(url_candidate)
  117. nil
  118. else
  119. url_candidate
  120. end
  121. end
  122. def property_values
  123. return unless @json['attachment'].is_a?(Array)
  124. as_array(@json['attachment']).select { |attachment| attachment['type'] == 'PropertyValue' }.map { |attachment| attachment.slice('name', 'value') }
  125. end
  126. def mismatching_origin?(url)
  127. needle = Addressable::URI.parse(url).host
  128. haystack = Addressable::URI.parse(@uri).host
  129. !haystack.casecmp(needle).zero?
  130. end
  131. def outbox_total_items
  132. collection_total_items('outbox')
  133. end
  134. def following_total_items
  135. collection_total_items('following')
  136. end
  137. def followers_total_items
  138. collection_total_items('followers')
  139. end
  140. def collection_total_items(type)
  141. return if @json[type].blank?
  142. return @collections[type] if @collections.key?(type)
  143. collection = fetch_resource_without_id_validation(@json[type])
  144. @collections[type] = collection.is_a?(Hash) && collection['totalItems'].present? && collection['totalItems'].is_a?(Numeric) ? collection['totalItems'] : nil
  145. rescue HTTP::Error, OpenSSL::SSL::SSLError
  146. @collections[type] = nil
  147. end
  148. def moved_account
  149. account = ActivityPub::TagManager.instance.uri_to_resource(@json['movedTo'], Account)
  150. account ||= ActivityPub::FetchRemoteAccountService.new.call(@json['movedTo'], id: true, break_on_redirect: true)
  151. account
  152. end
  153. def skip_download?
  154. @account.suspended? || domain_block&.reject_media?
  155. end
  156. def auto_suspend?
  157. domain_block&.suspend?
  158. end
  159. def auto_silence?
  160. domain_block&.silence?
  161. end
  162. def domain_block
  163. return @domain_block if defined?(@domain_block)
  164. @domain_block = DomainBlock.find_by(domain: @domain)
  165. end
  166. def key_changed?
  167. !@old_public_key.nil? && @old_public_key != @account.public_key
  168. end
  169. def clear_tombstones!
  170. Tombstone.where(account_id: @account.id).delete_all
  171. end
  172. def protocol_changed?
  173. !@old_protocol.nil? && @old_protocol != @account.protocol
  174. end
  175. def lock_options
  176. { redis: Redis.current, key: "process_account:#{@uri}" }
  177. end
  178. def process_tags
  179. return if @json['tag'].blank?
  180. as_array(@json['tag']).each do |tag|
  181. process_emoji tag if equals_or_includes?(tag['type'], 'Emoji')
  182. end
  183. end
  184. def process_attachments
  185. return if @json['attachment'].blank?
  186. previous_proofs = @account.identity_proofs.to_a
  187. current_proofs = []
  188. as_array(@json['attachment']).each do |attachment|
  189. next unless equals_or_includes?(attachment['type'], 'IdentityProof')
  190. current_proofs << process_identity_proof(attachment)
  191. end
  192. previous_proofs.each do |previous_proof|
  193. next if current_proofs.any? { |current_proof| current_proof.id == previous_proof.id }
  194. previous_proof.delete
  195. end
  196. end
  197. def process_emoji(tag)
  198. return if skip_download?
  199. return if tag['name'].blank? || tag['icon'].blank? || tag['icon']['url'].blank?
  200. shortcode = tag['name'].delete(':')
  201. image_url = tag['icon']['url']
  202. uri = tag['id']
  203. updated = tag['updated']
  204. emoji = CustomEmoji.find_by(shortcode: shortcode, domain: @account.domain)
  205. return unless emoji.nil? || image_url != emoji.image_remote_url || (updated && updated >= emoji.updated_at)
  206. emoji ||= CustomEmoji.new(domain: @account.domain, shortcode: shortcode, uri: uri)
  207. emoji.image_remote_url = image_url
  208. emoji.save
  209. end
  210. def process_identity_proof(attachment)
  211. provider = attachment['signatureAlgorithm']
  212. provider_username = attachment['name']
  213. token = attachment['signatureValue']
  214. @account.identity_proofs.where(provider: provider, provider_username: provider_username).find_or_create_by(provider: provider, provider_username: provider_username, token: token)
  215. end
  216. end