enigma2 (20120327 rel32 -> 20120430 master)
[enigma2.git] / usr / lib / enigma2 / python / Tools / Downloader.py
1 from twisted.web import client
2 from twisted.internet import reactor, defer
3
4 class HTTPProgressDownloader(client.HTTPDownloader):
5         def __init__(self, url, outfile, headers=None):
6                 client.HTTPDownloader.__init__(self, url, outfile, headers=headers, agent="Dreambox HTTP Downloader")
7                 self.status = None
8                 self.progress_callback = None
9                 self.deferred = defer.Deferred()
10
11         def noPage(self, reason):
12                 if self.status == "304":
13                         print reason.getErrorMessage()
14                         client.HTTPDownloader.page(self, "")
15                 else:
16                         client.HTTPDownloader.noPage(self, reason)
17
18         def gotHeaders(self, headers):
19                 if self.status == "200":
20                         if headers.has_key("content-length"):
21                                 self.totalbytes = int(headers["content-length"][0])
22                         else:
23                                 self.totalbytes = 0
24                         self.currentbytes = 0.0
25                 return client.HTTPDownloader.gotHeaders(self, headers)
26
27         def pagePart(self, packet):
28                 if self.status == "200":
29                         self.currentbytes += len(packet)
30                 if self.totalbytes and self.progress_callback:
31                         self.progress_callback(self.currentbytes, self.totalbytes)
32                 return client.HTTPDownloader.pagePart(self, packet)
33
34         def pageEnd(self):
35                 return client.HTTPDownloader.pageEnd(self)
36
37 class downloadWithProgress:
38         def __init__(self, url, outputfile, contextFactory=None, *args, **kwargs):
39                 scheme, host, port, path = client._parse(url)
40                 self.factory = HTTPProgressDownloader(url, outputfile, *args, **kwargs)
41                 self.connection = reactor.connectTCP(host, port, self.factory)
42
43         def start(self):
44                 return self.factory.deferred
45
46         def stop(self):
47                 print "[stop]"
48                 self.connection.disconnect()
49
50         def addProgress(self, progress_callback):
51                 print "[addProgress]"
52                 self.factory.progress_callback = progress_callback