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.

100 lines
2.5 KiB

  1. # frozen_string_literal: true
  2. class FetchOEmbedService
  3. ENDPOINT_CACHE_EXPIRES_IN = 24.hours.freeze
  4. attr_reader :url, :options, :format, :endpoint_url
  5. def call(url, options = {})
  6. @url = url
  7. @options = options
  8. if @options[:cached_endpoint]
  9. parse_cached_endpoint!
  10. else
  11. discover_endpoint!
  12. end
  13. fetch!
  14. end
  15. private
  16. def discover_endpoint!
  17. return if html.nil?
  18. @format = @options[:format]
  19. page = Nokogiri::HTML(html)
  20. if @format.nil? || @format == :json
  21. @endpoint_url ||= page.at_xpath('//link[@type="application/json+oembed"]')&.attribute('href')&.value
  22. @format ||= :json if @endpoint_url
  23. end
  24. if @format.nil? || @format == :xml
  25. @endpoint_url ||= page.at_xpath('//link[@type="text/xml+oembed"]')&.attribute('href')&.value
  26. @format ||= :xml if @endpoint_url
  27. end
  28. return if @endpoint_url.blank?
  29. @endpoint_url = (Addressable::URI.parse(@url) + @endpoint_url).to_s
  30. cache_endpoint!
  31. rescue Addressable::URI::InvalidURIError
  32. @endpoint_url = nil
  33. end
  34. def parse_cached_endpoint!
  35. cached = @options[:cached_endpoint]
  36. return if cached[:endpoint].nil? || cached[:format].nil?
  37. @endpoint_url = Addressable::Template.new(cached[:endpoint]).expand(url: @url).to_s
  38. @format = cached[:format]
  39. end
  40. def cache_endpoint!
  41. url_domain = Addressable::URI.parse(@url).normalized_host
  42. endpoint_hash = {
  43. endpoint: @endpoint_url.gsub(/(=(http[s]?(%3A|:)(\/\/|%2F%2F)))([^&]*)/i, '={url}'),
  44. format: @format,
  45. }
  46. Rails.cache.write("oembed_endpoint:#{url_domain}", endpoint_hash, expires_in: ENDPOINT_CACHE_EXPIRES_IN)
  47. end
  48. def fetch!
  49. return if @endpoint_url.blank?
  50. body = Request.new(:get, @endpoint_url).perform do |res|
  51. res.code != 200 ? nil : res.body_with_limit
  52. end
  53. validate(parse_for_format(body)) if body.present?
  54. rescue Oj::ParseError, Ox::ParseError
  55. nil
  56. end
  57. def parse_for_format(body)
  58. case @format
  59. when :json
  60. Oj.load(body, mode: :strict)&.with_indifferent_access
  61. when :xml
  62. Ox.load(body, mode: :hash_no_attrs)&.with_indifferent_access&.dig(:oembed)
  63. end
  64. end
  65. def validate(oembed)
  66. oembed if oembed[:version] == '1.0' && oembed[:type].present?
  67. end
  68. def html
  69. return @html if defined?(@html)
  70. @html = @options[:html] || Request.new(:get, @url).add_headers('Accept' => 'text/html').perform do |res|
  71. res.code != 200 || res.mime_type != 'text/html' ? nil : res.body_with_limit
  72. end
  73. end
  74. end