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

__init__.py 2.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. # coding: utf-8
  2. # Copyright 2014 Globo.com Player authors. All rights reserved.
  3. # Use of this source code is governed by a MIT License
  4. # license that can be found in the LICENSE file.
  5. import sys
  6. PYTHON_MAJOR_VERSION = sys.version_info
  7. import os
  8. import posixpath
  9. try:
  10. import urlparse as url_parser
  11. import urllib2
  12. urlopen = urllib2.urlopen
  13. except ImportError:
  14. import urllib.parse as url_parser
  15. from urllib.request import urlopen as url_opener
  16. urlopen = url_opener
  17. from m3u8.model import M3U8, Playlist, IFramePlaylist, Media, Segment
  18. from m3u8.parser import parse, is_url
  19. __all__ = ('M3U8', 'Playlist', 'IFramePlaylist', 'Media',
  20. 'Segment', 'loads', 'load', 'parse')
  21. def loads(content):
  22. '''
  23. Given a string with a m3u8 content, returns a M3U8 object.
  24. Raises ValueError if invalid content
  25. '''
  26. return M3U8(content)
  27. def load(uri):
  28. '''
  29. Retrieves the content from a given URI and returns a M3U8 object.
  30. Raises ValueError if invalid content or IOError if request fails.
  31. '''
  32. if is_url(uri):
  33. return _load_from_uri(uri)
  34. else:
  35. return _load_from_file(uri)
  36. # Support for python3 inspired by https://github.com/szemtiv/m3u8/
  37. def _load_from_uri(uri):
  38. resource = urlopen(uri)
  39. base_uri = _parsed_url(_url_for(uri))
  40. if PYTHON_MAJOR_VERSION < (3,):
  41. content = _read_python2x(resource)
  42. else:
  43. content = _read_python3x(resource)
  44. return M3U8(content, base_uri=base_uri)
  45. def _url_for(uri):
  46. return urlopen(uri).geturl()
  47. def _parsed_url(url):
  48. parsed_url = url_parser.urlparse(url)
  49. prefix = parsed_url.scheme + '://' + parsed_url.netloc
  50. base_path = posixpath.normpath(parsed_url.path + '/..')
  51. return url_parser.urljoin(prefix, base_path)
  52. def _read_python2x(resource):
  53. return resource.read().strip()
  54. def _read_python3x(resource):
  55. return resource.read().decode(resource.headers.get_content_charset(failobj="utf-8"))
  56. def _load_from_file(uri):
  57. with open(uri) as fileobj:
  58. raw_content = fileobj.read().strip()
  59. base_uri = os.path.dirname(uri)
  60. return M3U8(raw_content, base_uri=base_uri)