闭社主体 forked from https://github.com/tootsuite/mastodon
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.

290 lines
8.8 KiB

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