provider_discovery.rb 1.1 KB

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