fetch_remote_status_service.rb 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. # frozen_string_literal: true
  2. class ActivityPub::FetchRemoteStatusService < BaseService
  3. include JsonLdHelper
  4. # Should be called when uri has already been checked for locality
  5. def call(uri, id: true, prefetched_body: nil, on_behalf_of: nil)
  6. @json = begin
  7. if prefetched_body.nil?
  8. fetch_resource(uri, id, on_behalf_of)
  9. else
  10. body_to_json(prefetched_body, compare_id: id ? uri : nil)
  11. end
  12. end
  13. return unless supported_context?
  14. actor_uri = nil
  15. activity_json = nil
  16. object_uri = nil
  17. if expected_object_type?
  18. actor_uri = value_or_id(first_of_value(@json['attributedTo']))
  19. activity_json = { 'type' => 'Create', 'actor' => actor_uri, 'object' => @json }
  20. object_uri = uri_from_bearcap(@json['id'])
  21. elsif expected_activity_type?
  22. actor_uri = value_or_id(first_of_value(@json['actor']))
  23. activity_json = @json
  24. object_uri = uri_from_bearcap(value_or_id(@json['object']))
  25. end
  26. return if activity_json.nil? || object_uri.nil? || !trustworthy_attribution?(@json['id'], actor_uri)
  27. return ActivityPub::TagManager.instance.uri_to_resource(object_uri, Status) if ActivityPub::TagManager.instance.local_uri?(object_uri)
  28. actor = account_from_uri(actor_uri)
  29. return if actor.nil? || actor.suspended?
  30. # If we fetched a status that already exists, then we need to treat the
  31. # activity as an update rather than create
  32. activity_json['type'] = 'Update' if equals_or_includes_any?(activity_json['type'], %w(Create)) && Status.where(uri: object_uri, account_id: actor.id).exists?
  33. ActivityPub::Activity.factory(activity_json, actor).perform
  34. end
  35. private
  36. def trustworthy_attribution?(uri, attributed_to)
  37. return false if uri.nil? || attributed_to.nil?
  38. Addressable::URI.parse(uri).normalized_host.casecmp(Addressable::URI.parse(attributed_to).normalized_host).zero?
  39. end
  40. def account_from_uri(uri)
  41. actor = ActivityPub::TagManager.instance.uri_to_resource(uri, Account)
  42. actor = ActivityPub::FetchRemoteAccountService.new.call(uri, id: true) if actor.nil? || actor.possibly_stale?
  43. actor
  44. end
  45. def supported_context?
  46. super(@json)
  47. end
  48. def expected_activity_type?
  49. equals_or_includes_any?(@json['type'], %w(Create Announce))
  50. end
  51. def expected_object_type?
  52. equals_or_includes_any?(@json['type'], ActivityPub::Activity::Create::SUPPORTED_TYPES + ActivityPub::Activity::Create::CONVERTED_TYPES)
  53. end
  54. end