Class: Firebrew::Downloader

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

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(uri, out, progress_options = {}) ⇒ Downloader

Returns a new instance of Downloader.



34
35
36
37
38
# File 'lib/firebrew/downloader.rb', line 34

def initialize(uri, out, progress_options={})
  @uri = self.class.normalize_uri(uri)
  @out = out
  @progress_options = progress_options
end

Class Method Details

.normalize_uri(uri) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/firebrew/downloader.rb', line 7

def self.normalize_uri(uri)
  begin
    uri = URI.parse(uri)
  rescue URI::InvalidURIError
    uri = URI.parse(URI.encode uri)
  end
  
  uri.normalize!
  
  case uri.scheme
  when 'http','https','file' then
    # do nothing
  when nil then
    uri.scheme = 'file'
    path = File.expand_path(uri.path)
    path = "/#{path}" if path =~ /^[a-zA-Z]:/
    uri.path = path
  when /^[a-zA-Z]$/ then
    uri.path = "/#{uri.scheme.upcase}:#{uri.path}"
    uri.scheme = 'file'
  else
    raise Firebrew::NetworkError, "Don't support the scheme: #{uri.scheme}"
  end
  
  uri
end

Instance Method Details

#execObject



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/firebrew/downloader.rb', line 40

def exec
  case @uri.scheme
  when 'http','https' then
    @size = loop do
      response = self.http_connection do |http, path|
        http.head(path)
      end
      if response.code.to_i == 302 then
        @uri = self.class.normalize_uri(response['Location'])
        next
      end
      break response['Content-Length'].to_i
    end
    
    progress_bar = self.create_progress_bar
    
    self.http_connection do |http, path|
      http.get(path) do |chunk|
        progress_bar.progress += chunk.size
        @out.write chunk
      end
    end
    
  when 'file' then
    @size = self.file_connection do |file|
      file.size
    end
    
    progress_bar = self.create_progress_bar
    
    self.file_connection do |file|
      loop do
        chunk = file.read(1000)
        break if chunk.nil?
        progress_bar.progress += chunk.size
        @out.write chunk
      end
    end
  end
end