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.

47 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. html = if options[:html]
  12. Nokogiri::HTML(options[:html])
  13. else
  14. Request.new(:get, url).perform do |res|
  15. raise OEmbed::NotFound, url if res.code != 200 || res.mime_type != 'text/html'
  16. Nokogiri::HTML(res.body_with_limit)
  17. end
  18. end
  19. if format.nil? || format == :json
  20. provider_endpoint ||= html.at_xpath('//link[@type="application/json+oembed"]')&.attribute('href')&.value
  21. format ||= :json if provider_endpoint
  22. end
  23. if format.nil? || format == :xml
  24. provider_endpoint ||= html.at_xpath('//link[@type="text/xml+oembed"]')&.attribute('href')&.value
  25. format ||= :xml if provider_endpoint
  26. end
  27. raise OEmbed::NotFound, url if provider_endpoint.nil?
  28. begin
  29. provider_endpoint = Addressable::URI.parse(provider_endpoint)
  30. provider_endpoint.query = nil
  31. provider_endpoint = provider_endpoint.to_s
  32. rescue Addressable::URI::InvalidURIError
  33. raise OEmbed::NotFound, url
  34. end
  35. OEmbed::Provider.new(provider_endpoint, format)
  36. end
  37. end
  38. end