1 from twisted.web import client
2 from twisted.internet import reactor, defer
3 from twisted.python import failure
4 from urlparse import urlparse
6 class HTTPProgressDownloader(client.HTTPDownloader):
7 def __init__(self, url, outfile, headers=None):
8 client.HTTPDownloader.__init__(self, url, outfile, headers=headers, agent="Enigma2 HbbTV/1.1.1 (+PVR+RTSP+DL;OpenPLi;;;)")
10 self.progress_callback = None
11 self.deferred = defer.Deferred()
13 def noPage(self, reason):
14 if self.status == "304":
15 print reason.getErrorMessage()
16 client.HTTPDownloader.page(self, "")
18 client.HTTPDownloader.noPage(self, reason)
20 def gotHeaders(self, headers):
21 if self.status == "200":
22 if headers.has_key("content-length"):
23 self.totalbytes = int(headers["content-length"][0])
26 self.currentbytes = 0.0
27 return client.HTTPDownloader.gotHeaders(self, headers)
29 def pagePart(self, packet):
30 if self.status == "200":
31 self.currentbytes += len(packet)
32 if self.totalbytes and self.progress_callback:
33 self.progress_callback(self.currentbytes, self.totalbytes)
34 return client.HTTPDownloader.pagePart(self, packet)
37 return client.HTTPDownloader.pageEnd(self)
39 class downloadWithProgress:
40 def __init__(self, url, outputfile, contextFactory=None, *args, **kwargs):
41 parsed = urlparse(url)
42 scheme = parsed.scheme
43 host = parsed.hostname
44 port = parsed.port or (443 if scheme == 'https' else 80)
45 self.factory = HTTPProgressDownloader(url, outputfile, *args, **kwargs)
47 from twisted.internet import ssl
48 if contextFactory is None:
49 contextFactory = ssl.ClientContextFactory()
50 self.connection = reactor.connectSSL(host, port, self.factory, contextFactory)
52 self.connection = reactor.connectTCP(host, port, self.factory)
55 return self.factory.deferred
59 self.connection.disconnect()
61 def addProgress(self, progress_callback):
63 self.factory.progress_callback = progress_callback