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.

48 lines
1.4 KiB

  1. # frozen_string_literal: true
  2. class ProviderDiscovery < OEmbed::ProviderDiscovery
  3. class << self
  4. def get(url, **options)
  5. provider = discover_provider(url, options)
  6. options.delete(:html)
  7. provider.get(url, options)
  8. end
  9. def discover_provider(url, **options)
  10. format = options[:format]
  11. if options[:html]
  12. html = Nokogiri::HTML(options[:html])
  13. else
  14. res = Request.new(:get, url).perform
  15. raise OEmbed::NotFound, url if res.code != 200 || res.mime_type != 'text/html'
  16. html = Nokogiri::HTML(res.to_s)
  17. end
  18. if format.nil? || format == :json
  19. provider_endpoint ||= html.at_xpath('//link[@type="application/json+oembed"]')&.attribute('href')&.value
  20. format ||= :json if provider_endpoint
  21. end
  22. if format.nil? || format == :xml
  23. provider_endpoint ||= html.at_xpath('//link[@type="text/xml+oembed"]')&.attribute('href')&.value
  24. format ||= :xml if provider_endpoint
  25. end
  26. raise OEmbed::NotFound, url if provider_endpoint.nil?
  27. begin
  28. provider_endpoint = Addressable::URI.parse(provider_endpoint)
  29. provider_endpoint.query = nil
  30. provider_endpoint = provider_endpoint.to_s
  31. rescue Addressable::URI::InvalidURIError
  32. raise OEmbed::NotFound, url
  33. end
  34. OEmbed::Provider.new(provider_endpoint, format)
  35. end
  36. end
  37. end