Downloader: replace import of urlparser
[openblackhole/openblackhole-enigma2.git] / lib / python / Tools / Downloader.py
1 from twisted.web import client
2 from twisted.internet import reactor, defer
3 from twisted.python import failure
4 from urlparse import urlparse
5
6 class HTTPProgressDownloader(client.HTTPDownloader):
7         def __init__(self, url, outfile, headers=None):
8                 client.HTTPDownloader.__init__(self, url, outfile, headers=headers, agent="STB HTTP Downloader")
9                 self.status = None
10                 self.progress_callback = None
11                 self.deferred = defer.Deferred()
12
13         def noPage(self, reason):
14                 if self.status == "304":
15                         print reason.getErrorMessage()
16                         client.HTTPDownloader.page(self, "")
17                 else:
18                         client.HTTPDownloader.noPage(self, reason)
19
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])
24                         else:
25                                 self.totalbytes = 0
26                         self.currentbytes = 0.0
27                 return client.HTTPDownloader.gotHeaders(self, headers)
28
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)
35
36         def pageEnd(self):
37                 return client.HTTPDownloader.pageEnd(self)
38
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)
46                 self.connection = reactor.connectTCP(host, port, self.factory)
47
48         def start(self):
49                 return self.factory.deferred
50
51         def stop(self):
52                 print "[stop]"
53                 self.connection.disconnect()
54
55         def addProgress(self, progress_callback):
56                 print "[addProgress]"
57                 self.factory.progress_callback = progress_callback