Class: Download::Object

Inherits:
Object
  • Object
show all
Defined in:
lib/bundler-download/ext/download.rb

Constant Summary collapse

DOWNLOAD_CHUNK_SIZE =
1_048_576

Instance Method Summary collapse

Instance Method Details

#delete(hash = {}) ⇒ Object



32
33
34
35
36
# File 'lib/bundler-download/ext/download.rb', line 32

def delete(hash={})
  set_multi(hash)

  File.delete(file_path) if File.exist?(file_path)      
end

#final_uri_and_head_responseObject



38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/bundler-download/ext/download.rb', line 38

def final_uri_and_head_response
  location = url
  head_response = nil
  begin
    uri = URI(location)
    options = {}
    options.merge!(use_ssl: true) if location.start_with?('https:')
    head_response = Net::HTTP.start(uri.hostname, uri.port, options) do |http|
      http.head(uri)
    end
    location = head_response['location'] if head_response['location']
  end while head_response.is_a?(Net::HTTPRedirection)      
  [uri, head_response]
end

#osObject



28
29
30
# File 'lib/bundler-download/ext/download.rb', line 28

def os
  options.to_h[:os]
end

#start(hash = {}) ⇒ Object



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
80
81
82
# File 'lib/bundler-download/ext/download.rb', line 53

def start(hash={})
  set_multi(hash)
  return puts("Download already exists: '#{file_path}' (run `bundle download` to redownload)") if options.keys.include?('--keep_existing') && File.exist?(file_path)
  
  uri, head_response = final_uri_and_head_response
  content_length = head_response["content-length"]
  puts "Download URL: #{uri.to_s}"
  puts "Download size: #{content_length}"
  puts "Download path: #{file_path}"
  file_size = content_length.to_f
  progress_total = (file_size / DOWNLOAD_CHUNK_SIZE).ceil
  bar = TTY::ProgressBar.new("Downloading :percent ( :eta ) [:bar]", total: progress_total)
  starting_bytes = 0
  File.open(file_path, 'wb') do |file_obj|
    until starting_bytes >= file_size
      Net::HTTP.start(uri.host, uri.port, :use_ssl => true) do |http|
        ending_bytes = [starting_bytes + DOWNLOAD_CHUNK_SIZE, file_size].min
        ending_bytes = nil if ending_bytes == file_size # this makes the request return remaining bytes only
        request = Net::HTTP::Get.new uri, 'Range' => "bytes=#{starting_bytes}-#{ending_bytes}"
        res = http.request request # Net::HTTPResponse object
        file_obj << res.body
        starting_bytes += DOWNLOAD_CHUNK_SIZE + 1
        bar.advance(1)
      end
    end
  end

  return file_path

end