Enigma2 plugin to to play various online streams (mostly Latvian).

Downloader.py 2.1KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. from boxbranding import getMachineBrand, getMachineName
  2. from twisted.web import client
  3. from twisted.internet import reactor, defer, ssl
  4. class HTTPProgressDownloader(client.HTTPDownloader):
  5. def __init__(self, url, outfile, headers=None):
  6. client.HTTPDownloader.__init__(self, url, outfile, headers=headers, agent="Enigma2 HbbTV/1.1.1 (+PVR+RTSP+DL;OpenATV;;;)")
  7. self.status = None
  8. self.progress_callback = None
  9. self.deferred = defer.Deferred()
  10. def noPage(self, reason):
  11. if self.status == "304":
  12. print reason.getErrorMessage()
  13. client.HTTPDownloader.page(self, "")
  14. else:
  15. client.HTTPDownloader.noPage(self, reason)
  16. def gotHeaders(self, headers):
  17. if self.status == "200":
  18. if headers.has_key("content-length"):
  19. self.totalbytes = int(headers["content-length"][0])
  20. else:
  21. self.totalbytes = 0
  22. self.currentbytes = 0.0
  23. return client.HTTPDownloader.gotHeaders(self, headers)
  24. def pagePart(self, packet):
  25. if self.status == "200":
  26. self.currentbytes += len(packet)
  27. if self.totalbytes and self.progress_callback:
  28. self.progress_callback(self.currentbytes, self.totalbytes)
  29. return client.HTTPDownloader.pagePart(self, packet)
  30. def pageEnd(self):
  31. return client.HTTPDownloader.pageEnd(self)
  32. class downloadWithProgress:
  33. def __init__(self, url, outputfile, contextFactory=None, *args, **kwargs):
  34. if hasattr(client, '_parse'):
  35. scheme, host, port, path = client._parse(url)
  36. else:
  37. from twisted.web.client import _URI
  38. uri = _URI.fromBytes(url)
  39. scheme = uri.scheme
  40. host = uri.host
  41. port = uri.port
  42. path = uri.path
  43. self.factory = HTTPProgressDownloader(url, outputfile, *args, **kwargs)
  44. if scheme == "https":
  45. self.connection = reactor.connectSSL(host, port, self.factory, ssl.ClientContextFactory())
  46. else:
  47. self.connection = reactor.connectTCP(host, port, self.factory)
  48. def start(self):
  49. return self.factory.deferred
  50. def stop(self):
  51. if self.connection:
  52. print "[stop]"
  53. self.connection.disconnect()
  54. def addProgress(self, progress_callback):
  55. print "[addProgress]"
  56. self.factory.progress_callback = progress_callback