__init__.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import os
  2. import xml.etree.ElementTree as etree
  3. from .compat_utils import passthrough_module
  4. passthrough_module(__name__, '._deprecated')
  5. del passthrough_module
  6. # HTMLParseError has been deprecated in Python 3.3 and removed in
  7. # Python 3.5. Introducing dummy exception for Python >3.5 for compatible
  8. # and uniform cross-version exception handling
  9. class compat_HTMLParseError(ValueError):
  10. pass
  11. class _TreeBuilder(etree.TreeBuilder):
  12. def doctype(self, name, pubid, system):
  13. pass
  14. def compat_etree_fromstring(text):
  15. return etree.XML(text, parser=etree.XMLParser(target=_TreeBuilder()))
  16. def compat_ord(c):
  17. return c if isinstance(c, int) else ord(c)
  18. # Python 3.8+ does not honor %HOME% on windows, but this breaks compatibility with youtube-dl
  19. # See https://github.com/yt-dlp/yt-dlp/issues/792
  20. # https://docs.python.org/3/library/os.path.html#os.path.expanduser
  21. if os.name in ('nt', 'ce'):
  22. def compat_expanduser(path):
  23. HOME = os.environ.get('HOME')
  24. if not HOME:
  25. return os.path.expanduser(path)
  26. elif not path.startswith('~'):
  27. return path
  28. i = path.replace('\\', '/', 1).find('/') # ~user
  29. if i < 0:
  30. i = len(path)
  31. userhome = os.path.join(os.path.dirname(HOME), path[1:i]) if i > 1 else HOME
  32. return userhome + path[i:]
  33. else:
  34. compat_expanduser = os.path.expanduser
  35. def urllib_req_to_req(urllib_request):
  36. """Convert urllib Request to a networking Request"""
  37. from ..networking import Request
  38. from ..utils.networking import HTTPHeaderDict
  39. return Request(
  40. urllib_request.get_full_url(), data=urllib_request.data, method=urllib_request.get_method(),
  41. headers=HTTPHeaderDict(urllib_request.headers, urllib_request.unredirected_hdrs),
  42. extensions={'timeout': urllib_request.timeout} if hasattr(urllib_request, 'timeout') else None)