class OembedProxy::FirstParty
Handles all sites with officially supported oEmbed providers
Constants
- ERROR_CLASS_MAPPING
- MAX_REDIRECTS
- USER_AGENT
Public Class Methods
new()
click to toggle source
# File lib/oembed_proxy/first_party.rb, line 16 def initialize # Import the expected first party providers. @pattern_hash = {} yaml_hash = YAML.load_file(File.expand_path('../providers/first_party.yml', __dir__)) yaml_hash.each_value do |hsh| hsh['pattern_list'].each do |pattern| regex = Utility.clean_pattern(pattern) @pattern_hash[regex] = hsh['endpoint'] end end end
Public Instance Methods
get_data(url, other_params = {})
click to toggle source
# File lib/oembed_proxy/first_party.rb, line 33 def get_data(url, other_params = {}) endpoint = find_endpoint(url) return nil if endpoint.nil? uri = URI(endpoint) new_params = { url: url, format: 'json' } new_params.merge! other_params # Merge in existing params. new_params.merge! CGI.parse(uri.query) if uri.query uri.query = URI.encode_www_form(new_params) fetch(uri) end
handles_url?(url)
click to toggle source
# File lib/oembed_proxy/first_party.rb, line 29 def handles_url?(url) !find_endpoint(url).nil? end
Private Instance Methods
fetch(uri, times_recursed: 0)
click to toggle source
# File lib/oembed_proxy/first_party.rb, line 61 def fetch(uri, times_recursed: 0) # rubocop:disable Metrics/MethodLength raise OembedException, '500 Internal Server Error' if times_recursed > MAX_REDIRECTS res = request_builder(uri) case res when Net::HTTPSuccess JSON[res.body] when Net::HTTPMovedPermanently, Net::HTTPFound fetch(URI(res['location']), times_recursed: (times_recursed + 1)) else raise OembedException, (ERROR_CLASS_MAPPING[res.class] || "Unknown response: #{res.class}") end rescue JSON::ParserError return nil # rubocop:disable Style/RedundantReturn end
find_endpoint(url)
click to toggle source
# File lib/oembed_proxy/first_party.rb, line 87 def find_endpoint(url) @pattern_hash.each_key do |p| return @pattern_hash[p] if url.to_s.match(p) end # If all else fails, return nil. nil end
request_builder(uri)
click to toggle source
# File lib/oembed_proxy/first_party.rb, line 78 def request_builder(uri) req = Net::HTTP::Get.new(uri) req['User-Agent'] = USER_AGENT Net::HTTP.start(uri.hostname, uri.port, use_ssl: (uri.scheme == 'https')) do |http| http.request(req) end end