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.

67 lines
1.5 KiB

  1. # frozen_string_literal: true
  2. module JsonLdHelper
  3. def equals_or_includes?(haystack, needle)
  4. haystack.is_a?(Array) ? haystack.include?(needle) : haystack == needle
  5. end
  6. def first_of_value(value)
  7. value.is_a?(Array) ? value.first : value
  8. end
  9. def as_array(value)
  10. value.is_a?(Array) ? value : [value]
  11. end
  12. def value_or_id(value)
  13. value.is_a?(String) || value.nil? ? value : value['id']
  14. end
  15. def supported_context?(json)
  16. !json.nil? && equals_or_includes?(json['@context'], ActivityPub::TagManager::CONTEXT)
  17. end
  18. def canonicalize(json)
  19. graph = RDF::Graph.new << JSON::LD::API.toRdf(json)
  20. graph.dump(:normalize)
  21. end
  22. def fetch_resource(uri, id)
  23. unless id
  24. json = fetch_resource_without_id_validation(uri)
  25. return unless json
  26. uri = json['id']
  27. end
  28. json = fetch_resource_without_id_validation(uri)
  29. json.present? && json['id'] == uri ? json : nil
  30. end
  31. def fetch_resource_without_id_validation(uri)
  32. response = build_request(uri).perform
  33. return if response.code != 200
  34. body_to_json(response.to_s)
  35. end
  36. def body_to_json(body)
  37. body.is_a?(String) ? Oj.load(body, mode: :strict) : body
  38. rescue Oj::ParseError
  39. nil
  40. end
  41. def merge_context(context, new_context)
  42. if context.is_a?(Array)
  43. context << new_context
  44. else
  45. [context, new_context]
  46. end
  47. end
  48. private
  49. def build_request(uri)
  50. request = Request.new(:get, uri)
  51. request.add_headers('Accept' => 'application/activity+json, application/ld+json')
  52. request
  53. end
  54. end