闭社主体 forked from https://github.com/tootsuite/mastodon
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.

52 lines
1.2 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 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)
  20. response = build_request(uri).perform
  21. return if response.code != 200
  22. body_to_json(response.to_s)
  23. end
  24. def body_to_json(body)
  25. body.is_a?(String) ? Oj.load(body, mode: :strict) : body
  26. rescue Oj::ParseError
  27. nil
  28. end
  29. def merge_context(context, new_context)
  30. if context.is_a?(Array)
  31. context << new_context
  32. else
  33. [context, new_context]
  34. end
  35. end
  36. private
  37. def build_request(uri)
  38. request = Request.new(:get, uri)
  39. request.add_headers('Accept' => 'application/activity+json, application/ld+json')
  40. request
  41. end
  42. end