# $Id: downloader.rb,v 1.2 2002/09/28 12:29:10 sdalu Exp $

#
# Copyrigth (C) 2002  Stephane D'Alu
# Code is under GPL v2 (see http://www.gnu.org/licenses/gpl.txt)
#
# WWW: http://www.sdalu.com/software/
#

require 'progress'

module Net
    class HTTP
	def download(path, headers, io, output = $stdout, display = 0)
	    request_get(path, headers) do |response|
		length = response['content-length'].to_i;
		db     = TTY::ProgressBar::new(output, 0.2, display)
		begin
		    db.start(length)
		    response.read_body do |data|
			db.processed(data.length)
			io.write(data)
		    end
		    db.done(io.path)
		ensure
		    db.finish
		end
	    end
	end
    end

    class FTP
	def download(remotefile, io, output = $stdout, display = 0)
	    length = size(remotefile)
	    db     = TTY::ProgressBar::new(output, 0.2, display)
	    begin
		db.start(length)
		retrbinary("RETR " + remotefile, 1024) do |data|
		    db.processed(data.length)
		    io.write(data)
		end
		db.done(io.path)
	    ensure
		db.finish
	    end
	end
    end
end
