class Flavicon::Finder

Constants

TooManyRedirects

Attributes

url[R]

Public Class Methods

new(url) click to toggle source
# File lib/flavicon/finder.rb, line 13
def initialize(url)
  @url = url
end

Public Instance Methods

default_path(url) click to toggle source
# File lib/flavicon/finder.rb, line 38
def default_path(url)
  URI.join(url, '/favicon.ico').to_s
end
extract_from_html(html, url) click to toggle source
# File lib/flavicon/finder.rb, line 30
def extract_from_html(html, url)
  link = Nokogiri::HTML(html).css('head link').find do |node|
    node[:rel] =~ /\A(shortcut )?icon\z/i
  end

  URI.join(url, link[:href]).to_s if link
end
extract_location(response, url) click to toggle source

While the soon-to-be obsolete IETF standard RFC 2616 (HTTP 1.1) requires a complete absolute URI for redirection, the most popular web browsers tolerate the passing of a relative URL as the value for a Location header field. Consequently, the current revision of HTTP/1.1 makes relative URLs conforming.

# File lib/flavicon/finder.rb, line 68
def extract_location(response, url)
  URI.join(url, response['location']).to_s
end
find() click to toggle source
# File lib/flavicon/finder.rb, line 17
def find
  response, resolved = request(url)
  favicon_url = extract_from_html(response.body, resolved) || default_path(resolved)
  verify_favicon_url(favicon_url)
end
request(url, limit = 10) click to toggle source

rubocop:disable Metrics/AbcSize,MethodLength

# File lib/flavicon/finder.rb, line 43
def request(url, limit = 10)
  raise TooManyRedirects if limit.negative?

  uri = URI.parse(url)
  http = Net::HTTP.new(uri.host, uri.port)
  request = Net::HTTP::Get.new(uri.request_uri)

  if uri.scheme == 'https'
    http.use_ssl = true
    http.verify_mode = OpenSSL::SSL::VERIFY_NONE
  end

  response = http.request(request)

  if response.is_a? Net::HTTPRedirection
    request(extract_location(response, url), limit - 1)
  else
    [response, url]
  end
end
verify_favicon_url(url) click to toggle source
# File lib/flavicon/finder.rb, line 23
def verify_favicon_url(url)
  response, resolved = request(url)
  return unless response.is_a?(Net::HTTPSuccess) && response.body.to_s != '' && response.content_type =~ /image/i

  resolved
end