class Download::Object

Constants

DOWNLOAD_CHUNK_SIZE

Public Instance Methods

delete(hash={}) click to toggle source
# 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_response() click to toggle source
# 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
os() click to toggle source
# File lib/bundler-download/ext/download.rb, line 28
def os
  options.to_h[:os]
end
start(hash={}) click to toggle source
# 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