Class: Csspin::HTTP::Downloader

Inherits:
Object
  • Object
show all
Defined in:
lib/csspin/http/downloader.rb

Constant Summary collapse

MAX_REDIRECTS =
5
DEFAULT_ALLOWED_CONTENT_TYPES =
["text/css", "text/plain"].freeze

Instance Method Summary collapse

Instance Method Details

#get(url, allowed_content_types: DEFAULT_ALLOWED_CONTENT_TYPES) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/csspin/http/downloader.rb', line 12

def get(url, allowed_content_types: DEFAULT_ALLOWED_CONTENT_TYPES)
  uri = URI.parse(url)
  redirects = 0

  loop do
    http = build_http(uri)
    response = http.start { |h| h.get(uri.request_uri) }

    if response.is_a?(Net::HTTPRedirection)
      redirects += 1
      return {ok: false, error: "Too many redirects", status: response.code.to_i} if redirects > MAX_REDIRECTS

      location = response["location"]
      uri = URI.join(uri, location)
      next
    end

    if response.is_a?(Net::HTTPSuccess)
      content_type = response["content-type"].to_s
      unless allowed_content_types.any? { |allowed_content_type| content_type.include?(allowed_content_type) }
        return {ok: false, error: "Not a CSS file (content-type: #{content_type})", status: response.code.to_i}
      end

      return {ok: true, body: response.body}
    end

    return {ok: false, error: "HTTP #{response.code}", status: response.code.to_i}
  end
rescue Net::OpenTimeout, Net::ReadTimeout, Errno::ECONNRESET, SocketError, URI::InvalidURIError => e
  {ok: false, error: e.message, status: nil}
end