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.

69 lines
2.3 KiB

  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. actor = account_from_uri(actor_uri)
  28. return if actor.nil? || actor.suspended?
  29. # If we fetched a status that already exists, then we need to treat the
  30. # activity as an update rather than create
  31. activity_json['type'] = 'Update' if equals_or_includes_any?(activity_json['type'], %w(Create)) && Status.where(uri: object_uri, account_id: actor.id).exists?
  32. ActivityPub::Activity.factory(activity_json, actor).perform
  33. end
  34. private
  35. def trustworthy_attribution?(uri, attributed_to)
  36. return false if uri.nil? || attributed_to.nil?
  37. Addressable::URI.parse(uri).normalized_host.casecmp(Addressable::URI.parse(attributed_to).normalized_host).zero?
  38. end
  39. def account_from_uri(uri)
  40. actor = ActivityPub::TagManager.instance.uri_to_resource(uri, Account)
  41. actor = ActivityPub::FetchRemoteAccountService.new.call(uri, id: true) if actor.nil? || actor.possibly_stale?
  42. actor
  43. end
  44. def supported_context?
  45. super(@json)
  46. end
  47. def expected_activity_type?
  48. equals_or_includes_any?(@json['type'], %w(Create Announce))
  49. end
  50. def expected_object_type?
  51. equals_or_includes_any?(@json['type'], ActivityPub::Activity::Create::SUPPORTED_TYPES + ActivityPub::Activity::Create::CONVERTED_TYPES)
  52. end
  53. end