#!/usr/bin/python
# -*- coding: utf-8 -*-

import urllib2, os

class ConnectError(urllib2.URLError):
	'''A user-defined exception class.'''
	def __init__(self, reason):
		self.args = reason,
		self.reason = reason
	
	def __str__(self):
		return 'reason : ' % self.reason

def strreplaces(string, old, new):
	if len(old) != len(new):
		raise ValueError("Erreur, les deux listes doivent avoir la même longueur.")
	else:
		for i in range(len(old)-1):
			string = string.replace(old[i], new[i])
	return string

def url2file(url):
	return strreplaces(url, ["http://","\\","/","|",":","*","?","\"","<",">"], ["","","-","-","-","-","-","-","-","-"])

def proxydef(host, port, user, passw):
	if user != "":
		proxy_info = { 'host' : host,
					'port' : port,
					'user' : user,
					'pass' : passw }
		proxy_support = urllib2.ProxyHandler({"http" : "http://%(user)s:%(pass)s@%(host)s:%(port)d" % proxy_info})
	else:
		proxy_info = { 'host' : host,
					'port' : port }
		proxy_support = urllib2.ProxyHandler({"http" : "http://%(host)s:%(port)d" % proxy_info})
	opener = urllib2.build_opener(proxy_support)
	urllib2.install_opener(opener)

def proxydel():
	urllib2.install_opener(urllib2.build_opener(urllib2.ProxyHandler({})))

def urlopen(url):
	
	try:
		lien = urllib2.urlopen(url, None, 3)
	except urllib2.URLError, exc:
		raise ConnectError(exc)
	else:
		return lien

def httpDownload(url, filename, reporthook=None, postData=None):
	reqObj = urllib2.Request(url, postData)
	fp = urllib2.urlopen(reqObj)
	headers = fp.info()
	##    This function returns a file-like object with two additional methods:
	##
	##    * geturl() -- return the URL of the resource retrieved
	##    * info() -- return the meta-information of the page, as a dictionary-like object
	##
	##Raises URLError on errors.
	##
	##Note that None may be returned if no handler handles the request (though the default installed global OpenerDirector uses UnknownHandler to ensure this never happens).

	#read & write fileObj to filename
	tfp = open(filename, 'wb')
	result = filename, headers
	bs = 1024*8
	size = -1
	read = 0
	blocknum = 0

	if reporthook:
		if "content-length" in headers:
			size = int(headers["Content-Length"])
		reporthook(blocknum, bs, size)

	while 1:
		block = fp.read(bs)
		if block == "":
			break
		read += len(block)
		tfp.write(block)
		blocknum += 1
		if reporthook:
			reporthook(blocknum, bs, size)

	fp.close()
	tfp.close()
	del fp
	del tfp

	# raise exception if actual size does not match content-length header
	if size >= 0 and read < size:
		raise ContentTooShortError("retrieval incomplete: got only %i out "
									"of %i bytes" % (read, size), result)

	return result

"""

url = 'http://files.framakey.org/testing/main/packages/FK2.0/FramakeyInstaller_2.0.1.0-RC4-fr.exe'
headers = {
'User-Agent' : 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)',
'Accept' :
'text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5',
'Accept-Language' : 'fr-fr,en-us;q=0.7,en;q=0.3',
'Accept-Charset' : 'ISO-8859-1,utf-8;q=0.7,*;q=0.7'
}


#test it
httpDownload(url, 'dl.exe', headers, reportDownloadProgress)

"""
