process_account_service.rb 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. # frozen_string_literal: true
  2. class ActivityPub::ProcessAccountService < BaseService
  3. include JsonLdHelper
  4. include DomainControlHelper
  5. include Redisable
  6. include Lockable
  7. # Should be called with confirmed valid JSON
  8. # and WebFinger-resolved username and domain
  9. def call(username, domain, json, options = {})
  10. return if json['inbox'].blank? || unsupported_uri_scheme?(json['id']) || domain_not_allowed?(domain)
  11. @options = options
  12. @json = json
  13. @uri = @json['id']
  14. @username = username
  15. @domain = domain
  16. @collections = {}
  17. with_lock("process_account:#{@uri}") do
  18. @account = Account.remote.find_by(uri: @uri) if @options[:only_key]
  19. @account ||= Account.find_remote(@username, @domain)
  20. @old_public_key = @account&.public_key
  21. @old_protocol = @account&.protocol
  22. @suspension_changed = false
  23. create_account if @account.nil?
  24. update_account
  25. process_tags
  26. process_duplicate_accounts! if @options[:verified_webfinger]
  27. end
  28. return if @account.nil?
  29. after_protocol_change! if protocol_changed?
  30. after_key_change! if key_changed? && !@options[:signed_with_known_key]
  31. clear_tombstones! if key_changed?
  32. after_suspension_change! if suspension_changed?
  33. unless @options[:only_key] || @account.suspended?
  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.suspension_origin = :local if auto_suspend?
  50. @account.silenced_at = domain_block.created_at if auto_silence?
  51. @account.save
  52. end
  53. def update_account
  54. @account.last_webfingered_at = Time.now.utc unless @options[:only_key]
  55. @account.protocol = :activitypub
  56. set_suspension!
  57. set_immediate_protocol_attributes!
  58. set_fetchable_key! unless @account.suspended? && @account.suspension_origin_local?
  59. set_immediate_attributes! unless @account.suspended?
  60. set_fetchable_attributes! unless @options[:only_key] || @account.suspended?
  61. @account.save_with_optional_media!
  62. end
  63. def set_immediate_protocol_attributes!
  64. @account.inbox_url = @json['inbox'] || ''
  65. @account.outbox_url = @json['outbox'] || ''
  66. @account.shared_inbox_url = (@json['endpoints'].is_a?(Hash) ? @json['endpoints']['sharedInbox'] : @json['sharedInbox']) || ''
  67. @account.followers_url = @json['followers'] || ''
  68. @account.url = url || @uri
  69. @account.uri = @uri
  70. @account.actor_type = actor_type
  71. @account.created_at = @json['published'] if @json['published'].present?
  72. end
  73. def set_immediate_attributes!
  74. @account.featured_collection_url = @json['featured'] || ''
  75. @account.devices_url = @json['devices'] || ''
  76. @account.display_name = @json['name'] || ''
  77. @account.note = @json['summary'] || ''
  78. @account.locked = @json['manuallyApprovesFollowers'] || false
  79. @account.fields = property_values || {}
  80. @account.also_known_as = as_array(@json['alsoKnownAs'] || []).map { |item| value_or_id(item) }
  81. @account.discoverable = @json['discoverable'] || false
  82. end
  83. def set_fetchable_key!
  84. @account.public_key = public_key || ''
  85. end
  86. def set_fetchable_attributes!
  87. begin
  88. @account.avatar_remote_url = image_url('icon') || '' unless skip_download?
  89. rescue Mastodon::UnexpectedResponseError, HTTP::TimeoutError, HTTP::ConnectionError, OpenSSL::SSL::SSLError
  90. RedownloadAvatarWorker.perform_in(rand(30..600).seconds, @account.id)
  91. end
  92. begin
  93. @account.header_remote_url = image_url('image') || '' unless skip_download?
  94. rescue Mastodon::UnexpectedResponseError, HTTP::TimeoutError, HTTP::ConnectionError, OpenSSL::SSL::SSLError
  95. RedownloadHeaderWorker.perform_in(rand(30..600).seconds, @account.id)
  96. end
  97. @account.statuses_count = outbox_total_items if outbox_total_items.present?
  98. @account.following_count = following_total_items if following_total_items.present?
  99. @account.followers_count = followers_total_items if followers_total_items.present?
  100. @account.hide_collections = following_private? || followers_private?
  101. @account.moved_to_account = @json['movedTo'].present? ? moved_account : nil
  102. end
  103. def set_suspension!
  104. return if @account.suspended? && @account.suspension_origin_local?
  105. if @account.suspended? && !@json['suspended']
  106. @account.unsuspend!
  107. @suspension_changed = true
  108. elsif !@account.suspended? && @json['suspended']
  109. @account.suspend!(origin: :remote)
  110. @suspension_changed = true
  111. end
  112. end
  113. def after_protocol_change!
  114. ActivityPub::PostUpgradeWorker.perform_async(@account.domain)
  115. end
  116. def after_key_change!
  117. RefollowWorker.perform_async(@account.id)
  118. end
  119. def after_suspension_change!
  120. if @account.suspended?
  121. Admin::SuspensionWorker.perform_async(@account.id)
  122. else
  123. Admin::UnsuspensionWorker.perform_async(@account.id)
  124. end
  125. end
  126. def check_featured_collection!
  127. ActivityPub::SynchronizeFeaturedCollectionWorker.perform_async(@account.id)
  128. end
  129. def check_links!
  130. VerifyAccountLinksWorker.perform_async(@account.id)
  131. end
  132. def process_duplicate_accounts!
  133. return unless Account.where(uri: @account.uri).where.not(id: @account.id).exists?
  134. AccountMergingWorker.perform_async(@account.id)
  135. end
  136. def actor_type
  137. if @json['type'].is_a?(Array)
  138. @json['type'].find { |type| ActivityPub::FetchRemoteAccountService::SUPPORTED_TYPES.include?(type) }
  139. else
  140. @json['type']
  141. end
  142. end
  143. def image_url(key)
  144. value = first_of_value(@json[key])
  145. return if value.nil?
  146. return value['url'] if value.is_a?(Hash)
  147. image = fetch_resource_without_id_validation(value)
  148. image['url'] if image
  149. end
  150. def public_key
  151. value = first_of_value(@json['publicKey'])
  152. return if value.nil?
  153. return value['publicKeyPem'] if value.is_a?(Hash)
  154. key = fetch_resource_without_id_validation(value)
  155. key['publicKeyPem'] if key
  156. end
  157. def url
  158. return if @json['url'].blank?
  159. url_candidate = url_to_href(@json['url'], 'text/html')
  160. if unsupported_uri_scheme?(url_candidate) || mismatching_origin?(url_candidate)
  161. nil
  162. else
  163. url_candidate
  164. end
  165. end
  166. def property_values
  167. return unless @json['attachment'].is_a?(Array)
  168. as_array(@json['attachment']).select { |attachment| attachment['type'] == 'PropertyValue' }.map { |attachment| attachment.slice('name', 'value') }
  169. end
  170. def mismatching_origin?(url)
  171. needle = Addressable::URI.parse(url).host
  172. haystack = Addressable::URI.parse(@uri).host
  173. !haystack.casecmp(needle).zero?
  174. end
  175. def outbox_total_items
  176. collection_info('outbox').first
  177. end
  178. def following_total_items
  179. collection_info('following').first
  180. end
  181. def followers_total_items
  182. collection_info('followers').first
  183. end
  184. def following_private?
  185. !collection_info('following').last
  186. end
  187. def followers_private?
  188. !collection_info('followers').last
  189. end
  190. def collection_info(type)
  191. return [nil, nil] if @json[type].blank?
  192. return @collections[type] if @collections.key?(type)
  193. collection = fetch_resource_without_id_validation(@json[type])
  194. total_items = collection.is_a?(Hash) && collection['totalItems'].present? && collection['totalItems'].is_a?(Numeric) ? collection['totalItems'] : nil
  195. has_first_page = collection.is_a?(Hash) && collection['first'].present?
  196. @collections[type] = [total_items, has_first_page]
  197. rescue HTTP::Error, OpenSSL::SSL::SSLError, Mastodon::LengthValidationError
  198. @collections[type] = [nil, nil]
  199. end
  200. def moved_account
  201. account = ActivityPub::TagManager.instance.uri_to_resource(@json['movedTo'], Account)
  202. account ||= ActivityPub::FetchRemoteAccountService.new.call(@json['movedTo'], id: true, break_on_redirect: true)
  203. account
  204. end
  205. def skip_download?
  206. @account.suspended? || domain_block&.reject_media?
  207. end
  208. def auto_suspend?
  209. domain_block&.suspend?
  210. end
  211. def auto_silence?
  212. domain_block&.silence?
  213. end
  214. def domain_block
  215. return @domain_block if defined?(@domain_block)
  216. @domain_block = DomainBlock.rule_for(@domain)
  217. end
  218. def key_changed?
  219. !@old_public_key.nil? && @old_public_key != @account.public_key
  220. end
  221. def suspension_changed?
  222. @suspension_changed
  223. end
  224. def clear_tombstones!
  225. Tombstone.where(account_id: @account.id).delete_all
  226. end
  227. def protocol_changed?
  228. !@old_protocol.nil? && @old_protocol != @account.protocol
  229. end
  230. def process_tags
  231. return if @json['tag'].blank?
  232. as_array(@json['tag']).each do |tag|
  233. process_emoji tag if equals_or_includes?(tag['type'], 'Emoji')
  234. end
  235. end
  236. def process_emoji(tag)
  237. return if skip_download?
  238. return if tag['name'].blank? || tag['icon'].blank? || tag['icon']['url'].blank?
  239. shortcode = tag['name'].delete(':')
  240. image_url = tag['icon']['url']
  241. uri = tag['id']
  242. updated = tag['updated']
  243. emoji = CustomEmoji.find_by(shortcode: shortcode, domain: @account.domain)
  244. return unless emoji.nil? || image_url != emoji.image_remote_url || (updated && updated >= emoji.updated_at)
  245. emoji ||= CustomEmoji.new(domain: @account.domain, shortcode: shortcode, uri: uri)
  246. emoji.image_remote_url = image_url
  247. emoji.save
  248. end
  249. end