jsonld_helper.rb 1.4 KB

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