compat.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589
  1. from __future__ import unicode_literals
  2. import binascii
  3. import collections
  4. import email
  5. import getpass
  6. import io
  7. import optparse
  8. import os
  9. import re
  10. import shlex
  11. import shutil
  12. import socket
  13. import subprocess
  14. import sys
  15. import itertools
  16. import xml.etree.ElementTree
  17. try:
  18. import urllib.request as compat_urllib_request
  19. except ImportError: # Python 2
  20. import urllib2 as compat_urllib_request
  21. try:
  22. import urllib.error as compat_urllib_error
  23. except ImportError: # Python 2
  24. import urllib2 as compat_urllib_error
  25. try:
  26. import urllib.parse as compat_urllib_parse
  27. except ImportError: # Python 2
  28. import urllib as compat_urllib_parse
  29. try:
  30. from urllib.parse import urlparse as compat_urllib_parse_urlparse
  31. except ImportError: # Python 2
  32. from urlparse import urlparse as compat_urllib_parse_urlparse
  33. try:
  34. import urllib.parse as compat_urlparse
  35. except ImportError: # Python 2
  36. import urlparse as compat_urlparse
  37. try:
  38. import urllib.response as compat_urllib_response
  39. except ImportError: # Python 2
  40. import urllib as compat_urllib_response
  41. try:
  42. import http.cookiejar as compat_cookiejar
  43. except ImportError: # Python 2
  44. import cookielib as compat_cookiejar
  45. try:
  46. import http.cookies as compat_cookies
  47. except ImportError: # Python 2
  48. import Cookie as compat_cookies
  49. try:
  50. import html.entities as compat_html_entities
  51. except ImportError: # Python 2
  52. import htmlentitydefs as compat_html_entities
  53. try:
  54. import http.client as compat_http_client
  55. except ImportError: # Python 2
  56. import httplib as compat_http_client
  57. try:
  58. from urllib.error import HTTPError as compat_HTTPError
  59. except ImportError: # Python 2
  60. from urllib2 import HTTPError as compat_HTTPError
  61. try:
  62. from urllib.request import urlretrieve as compat_urlretrieve
  63. except ImportError: # Python 2
  64. from urllib import urlretrieve as compat_urlretrieve
  65. try:
  66. from subprocess import DEVNULL
  67. compat_subprocess_get_DEVNULL = lambda: DEVNULL
  68. except ImportError:
  69. compat_subprocess_get_DEVNULL = lambda: open(os.path.devnull, 'w')
  70. try:
  71. import http.server as compat_http_server
  72. except ImportError:
  73. import BaseHTTPServer as compat_http_server
  74. try:
  75. compat_str = unicode # Python 2
  76. except NameError:
  77. compat_str = str
  78. try:
  79. from urllib.parse import unquote_to_bytes as compat_urllib_parse_unquote_to_bytes
  80. from urllib.parse import unquote as compat_urllib_parse_unquote
  81. from urllib.parse import unquote_plus as compat_urllib_parse_unquote_plus
  82. except ImportError: # Python 2
  83. _asciire = (compat_urllib_parse._asciire if hasattr(compat_urllib_parse, '_asciire')
  84. else re.compile('([\x00-\x7f]+)'))
  85. # HACK: The following are the correct unquote_to_bytes, unquote and unquote_plus
  86. # implementations from cpython 3.4.3's stdlib. Python 2's version
  87. # is apparently broken (see https://github.com/rg3/youtube-dl/pull/6244)
  88. def compat_urllib_parse_unquote_to_bytes(string):
  89. """unquote_to_bytes('abc%20def') -> b'abc def'."""
  90. # Note: strings are encoded as UTF-8. This is only an issue if it contains
  91. # unescaped non-ASCII characters, which URIs should not.
  92. if not string:
  93. # Is it a string-like object?
  94. string.split
  95. return b''
  96. if isinstance(string, compat_str):
  97. string = string.encode('utf-8')
  98. bits = string.split(b'%')
  99. if len(bits) == 1:
  100. return string
  101. res = [bits[0]]
  102. append = res.append
  103. for item in bits[1:]:
  104. try:
  105. append(compat_urllib_parse._hextochr[item[:2]])
  106. append(item[2:])
  107. except KeyError:
  108. append(b'%')
  109. append(item)
  110. return b''.join(res)
  111. def compat_urllib_parse_unquote(string, encoding='utf-8', errors='replace'):
  112. """Replace %xx escapes by their single-character equivalent. The optional
  113. encoding and errors parameters specify how to decode percent-encoded
  114. sequences into Unicode characters, as accepted by the bytes.decode()
  115. method.
  116. By default, percent-encoded sequences are decoded with UTF-8, and invalid
  117. sequences are replaced by a placeholder character.
  118. unquote('abc%20def') -> 'abc def'.
  119. """
  120. if '%' not in string:
  121. string.split
  122. return string
  123. if encoding is None:
  124. encoding = 'utf-8'
  125. if errors is None:
  126. errors = 'replace'
  127. bits = _asciire.split(string)
  128. res = [bits[0]]
  129. append = res.append
  130. for i in range(1, len(bits), 2):
  131. append(compat_urllib_parse_unquote_to_bytes(bits[i]).decode(encoding, errors))
  132. append(bits[i + 1])
  133. return ''.join(res)
  134. def compat_urllib_parse_unquote_plus(string, encoding='utf-8', errors='replace'):
  135. """Like unquote(), but also replace plus signs by spaces, as required for
  136. unquoting HTML form values.
  137. unquote_plus('%7e/abc+def') -> '~/abc def'
  138. """
  139. string = string.replace('+', ' ')
  140. return compat_urllib_parse_unquote(string, encoding, errors)
  141. try:
  142. from urllib.request import DataHandler as compat_urllib_request_DataHandler
  143. except ImportError: # Python < 3.4
  144. # Ported from CPython 98774:1733b3bd46db, Lib/urllib/request.py
  145. class compat_urllib_request_DataHandler(compat_urllib_request.BaseHandler):
  146. def data_open(self, req):
  147. # data URLs as specified in RFC 2397.
  148. #
  149. # ignores POSTed data
  150. #
  151. # syntax:
  152. # dataurl := "data:" [ mediatype ] [ ";base64" ] "," data
  153. # mediatype := [ type "/" subtype ] *( ";" parameter )
  154. # data := *urlchar
  155. # parameter := attribute "=" value
  156. url = req.get_full_url()
  157. scheme, data = url.split(":", 1)
  158. mediatype, data = data.split(",", 1)
  159. # even base64 encoded data URLs might be quoted so unquote in any case:
  160. data = compat_urllib_parse_unquote_to_bytes(data)
  161. if mediatype.endswith(";base64"):
  162. data = binascii.a2b_base64(data)
  163. mediatype = mediatype[:-7]
  164. if not mediatype:
  165. mediatype = "text/plain;charset=US-ASCII"
  166. headers = email.message_from_string(
  167. "Content-type: %s\nContent-length: %d\n" % (mediatype, len(data)))
  168. return compat_urllib_response.addinfourl(io.BytesIO(data), headers, url)
  169. # Prepend protocol-less URLs with `http:` scheme in order to mitigate the number of
  170. # unwanted failures due to missing protocol
  171. def compat_urllib_request_Request(url, *args, **kwargs):
  172. return compat_urllib_request.Request(
  173. 'http:%s' % url if url.startswith('//') else url, *args, **kwargs)
  174. try:
  175. compat_basestring = basestring # Python 2
  176. except NameError:
  177. compat_basestring = str
  178. try:
  179. compat_chr = unichr # Python 2
  180. except NameError:
  181. compat_chr = chr
  182. try:
  183. from xml.etree.ElementTree import ParseError as compat_xml_parse_error
  184. except ImportError: # Python 2.6
  185. from xml.parsers.expat import ExpatError as compat_xml_parse_error
  186. if sys.version_info[0] >= 3:
  187. compat_etree_fromstring = xml.etree.ElementTree.fromstring
  188. else:
  189. # python 2.x tries to encode unicode strings with ascii (see the
  190. # XMLParser._fixtext method)
  191. etree = xml.etree.ElementTree
  192. try:
  193. _etree_iter = etree.Element.iter
  194. except AttributeError: # Python <=2.6
  195. def _etree_iter(root):
  196. for el in root.findall('*'):
  197. yield el
  198. for sub in _etree_iter(el):
  199. yield sub
  200. # on 2.6 XML doesn't have a parser argument, function copied from CPython
  201. # 2.7 source
  202. def _XML(text, parser=None):
  203. if not parser:
  204. parser = etree.XMLParser(target=etree.TreeBuilder())
  205. parser.feed(text)
  206. return parser.close()
  207. def _element_factory(*args, **kwargs):
  208. el = etree.Element(*args, **kwargs)
  209. for k, v in el.items():
  210. if isinstance(v, bytes):
  211. el.set(k, v.decode('utf-8'))
  212. return el
  213. def compat_etree_fromstring(text):
  214. doc = _XML(text, parser=etree.XMLParser(target=etree.TreeBuilder(element_factory=_element_factory)))
  215. for el in _etree_iter(doc):
  216. if el.text is not None and isinstance(el.text, bytes):
  217. el.text = el.text.decode('utf-8')
  218. return doc
  219. try:
  220. from urllib.parse import parse_qs as compat_parse_qs
  221. except ImportError: # Python 2
  222. # HACK: The following is the correct parse_qs implementation from cpython 3's stdlib.
  223. # Python 2's version is apparently totally broken
  224. def _parse_qsl(qs, keep_blank_values=False, strict_parsing=False,
  225. encoding='utf-8', errors='replace'):
  226. qs, _coerce_result = qs, compat_str
  227. pairs = [s2 for s1 in qs.split('&') for s2 in s1.split(';')]
  228. r = []
  229. for name_value in pairs:
  230. if not name_value and not strict_parsing:
  231. continue
  232. nv = name_value.split('=', 1)
  233. if len(nv) != 2:
  234. if strict_parsing:
  235. raise ValueError("bad query field: %r" % (name_value,))
  236. # Handle case of a control-name with no equal sign
  237. if keep_blank_values:
  238. nv.append('')
  239. else:
  240. continue
  241. if len(nv[1]) or keep_blank_values:
  242. name = nv[0].replace('+', ' ')
  243. name = compat_urllib_parse_unquote(
  244. name, encoding=encoding, errors=errors)
  245. name = _coerce_result(name)
  246. value = nv[1].replace('+', ' ')
  247. value = compat_urllib_parse_unquote(
  248. value, encoding=encoding, errors=errors)
  249. value = _coerce_result(value)
  250. r.append((name, value))
  251. return r
  252. def compat_parse_qs(qs, keep_blank_values=False, strict_parsing=False,
  253. encoding='utf-8', errors='replace'):
  254. parsed_result = {}
  255. pairs = _parse_qsl(qs, keep_blank_values, strict_parsing,
  256. encoding=encoding, errors=errors)
  257. for name, value in pairs:
  258. if name in parsed_result:
  259. parsed_result[name].append(value)
  260. else:
  261. parsed_result[name] = [value]
  262. return parsed_result
  263. try:
  264. from shlex import quote as shlex_quote
  265. except ImportError: # Python < 3.3
  266. def shlex_quote(s):
  267. if re.match(r'^[-_\w./]+$', s):
  268. return s
  269. else:
  270. return "'" + s.replace("'", "'\"'\"'") + "'"
  271. if sys.version_info >= (2, 7, 3):
  272. compat_shlex_split = shlex.split
  273. else:
  274. # Working around shlex issue with unicode strings on some python 2
  275. # versions (see http://bugs.python.org/issue1548891)
  276. def compat_shlex_split(s, comments=False, posix=True):
  277. if isinstance(s, compat_str):
  278. s = s.encode('utf-8')
  279. return shlex.split(s, comments, posix)
  280. def compat_ord(c):
  281. if type(c) is int:
  282. return c
  283. else:
  284. return ord(c)
  285. if sys.version_info >= (3, 0):
  286. compat_getenv = os.getenv
  287. compat_expanduser = os.path.expanduser
  288. else:
  289. # Environment variables should be decoded with filesystem encoding.
  290. # Otherwise it will fail if any non-ASCII characters present (see #3854 #3217 #2918)
  291. def compat_getenv(key, default=None):
  292. from .utils import get_filesystem_encoding
  293. env = os.getenv(key, default)
  294. if env:
  295. env = env.decode(get_filesystem_encoding())
  296. return env
  297. # HACK: The default implementations of os.path.expanduser from cpython do not decode
  298. # environment variables with filesystem encoding. We will work around this by
  299. # providing adjusted implementations.
  300. # The following are os.path.expanduser implementations from cpython 2.7.8 stdlib
  301. # for different platforms with correct environment variables decoding.
  302. if os.name == 'posix':
  303. def compat_expanduser(path):
  304. """Expand ~ and ~user constructions. If user or $HOME is unknown,
  305. do nothing."""
  306. if not path.startswith('~'):
  307. return path
  308. i = path.find('/', 1)
  309. if i < 0:
  310. i = len(path)
  311. if i == 1:
  312. if 'HOME' not in os.environ:
  313. import pwd
  314. userhome = pwd.getpwuid(os.getuid()).pw_dir
  315. else:
  316. userhome = compat_getenv('HOME')
  317. else:
  318. import pwd
  319. try:
  320. pwent = pwd.getpwnam(path[1:i])
  321. except KeyError:
  322. return path
  323. userhome = pwent.pw_dir
  324. userhome = userhome.rstrip('/')
  325. return (userhome + path[i:]) or '/'
  326. elif os.name == 'nt' or os.name == 'ce':
  327. def compat_expanduser(path):
  328. """Expand ~ and ~user constructs.
  329. If user or $HOME is unknown, do nothing."""
  330. if path[:1] != '~':
  331. return path
  332. i, n = 1, len(path)
  333. while i < n and path[i] not in '/\\':
  334. i = i + 1
  335. if 'HOME' in os.environ:
  336. userhome = compat_getenv('HOME')
  337. elif 'USERPROFILE' in os.environ:
  338. userhome = compat_getenv('USERPROFILE')
  339. elif 'HOMEPATH' not in os.environ:
  340. return path
  341. else:
  342. try:
  343. drive = compat_getenv('HOMEDRIVE')
  344. except KeyError:
  345. drive = ''
  346. userhome = os.path.join(drive, compat_getenv('HOMEPATH'))
  347. if i != 1: # ~user
  348. userhome = os.path.join(os.path.dirname(userhome), path[1:i])
  349. return userhome + path[i:]
  350. else:
  351. compat_expanduser = os.path.expanduser
  352. if sys.version_info < (3, 0):
  353. def compat_print(s):
  354. from .utils import preferredencoding
  355. print(s.encode(preferredencoding(), 'xmlcharrefreplace'))
  356. else:
  357. def compat_print(s):
  358. assert isinstance(s, compat_str)
  359. print(s)
  360. try:
  361. subprocess_check_output = subprocess.check_output
  362. except AttributeError:
  363. def subprocess_check_output(*args, **kwargs):
  364. assert 'input' not in kwargs
  365. p = subprocess.Popen(*args, stdout=subprocess.PIPE, **kwargs)
  366. output, _ = p.communicate()
  367. ret = p.poll()
  368. if ret:
  369. raise subprocess.CalledProcessError(ret, p.args, output=output)
  370. return output
  371. if sys.version_info < (3, 0) and sys.platform == 'win32':
  372. def compat_getpass(prompt, *args, **kwargs):
  373. if isinstance(prompt, compat_str):
  374. from .utils import preferredencoding
  375. prompt = prompt.encode(preferredencoding())
  376. return getpass.getpass(prompt, *args, **kwargs)
  377. else:
  378. compat_getpass = getpass.getpass
  379. # Old 2.6 and 2.7 releases require kwargs to be bytes
  380. try:
  381. def _testfunc(x):
  382. pass
  383. _testfunc(**{'x': 0})
  384. except TypeError:
  385. def compat_kwargs(kwargs):
  386. return dict((bytes(k), v) for k, v in kwargs.items())
  387. else:
  388. compat_kwargs = lambda kwargs: kwargs
  389. if sys.version_info < (2, 7):
  390. def compat_socket_create_connection(address, timeout, source_address=None):
  391. host, port = address
  392. err = None
  393. for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
  394. af, socktype, proto, canonname, sa = res
  395. sock = None
  396. try:
  397. sock = socket.socket(af, socktype, proto)
  398. sock.settimeout(timeout)
  399. if source_address:
  400. sock.bind(source_address)
  401. sock.connect(sa)
  402. return sock
  403. except socket.error as _:
  404. err = _
  405. if sock is not None:
  406. sock.close()
  407. if err is not None:
  408. raise err
  409. else:
  410. raise socket.error("getaddrinfo returns an empty list")
  411. else:
  412. compat_socket_create_connection = socket.create_connection
  413. # Fix https://github.com/rg3/youtube-dl/issues/4223
  414. # See http://bugs.python.org/issue9161 for what is broken
  415. def workaround_optparse_bug9161():
  416. op = optparse.OptionParser()
  417. og = optparse.OptionGroup(op, 'foo')
  418. try:
  419. og.add_option('-t')
  420. except TypeError:
  421. real_add_option = optparse.OptionGroup.add_option
  422. def _compat_add_option(self, *args, **kwargs):
  423. enc = lambda v: (
  424. v.encode('ascii', 'replace') if isinstance(v, compat_str)
  425. else v)
  426. bargs = [enc(a) for a in args]
  427. bkwargs = dict(
  428. (k, enc(v)) for k, v in kwargs.items())
  429. return real_add_option(self, *bargs, **bkwargs)
  430. optparse.OptionGroup.add_option = _compat_add_option
  431. if hasattr(shutil, 'get_terminal_size'): # Python >= 3.3
  432. compat_get_terminal_size = shutil.get_terminal_size
  433. else:
  434. _terminal_size = collections.namedtuple('terminal_size', ['columns', 'lines'])
  435. def compat_get_terminal_size(fallback=(80, 24)):
  436. columns = compat_getenv('COLUMNS')
  437. if columns:
  438. columns = int(columns)
  439. else:
  440. columns = None
  441. lines = compat_getenv('LINES')
  442. if lines:
  443. lines = int(lines)
  444. else:
  445. lines = None
  446. if columns is None or lines is None or columns <= 0 or lines <= 0:
  447. try:
  448. sp = subprocess.Popen(
  449. ['stty', 'size'],
  450. stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  451. out, err = sp.communicate()
  452. _lines, _columns = map(int, out.split())
  453. except Exception:
  454. _columns, _lines = _terminal_size(*fallback)
  455. if columns is None or columns <= 0:
  456. columns = _columns
  457. if lines is None or lines <= 0:
  458. lines = _lines
  459. return _terminal_size(columns, lines)
  460. try:
  461. itertools.count(start=0, step=1)
  462. compat_itertools_count = itertools.count
  463. except TypeError: # Python 2.6
  464. def compat_itertools_count(start=0, step=1):
  465. n = start
  466. while True:
  467. yield n
  468. n += step
  469. if sys.version_info >= (3, 0):
  470. from tokenize import tokenize as compat_tokenize_tokenize
  471. else:
  472. from tokenize import generate_tokens as compat_tokenize_tokenize
  473. __all__ = [
  474. 'compat_HTTPError',
  475. 'compat_basestring',
  476. 'compat_chr',
  477. 'compat_cookiejar',
  478. 'compat_cookies',
  479. 'compat_etree_fromstring',
  480. 'compat_expanduser',
  481. 'compat_get_terminal_size',
  482. 'compat_getenv',
  483. 'compat_getpass',
  484. 'compat_html_entities',
  485. 'compat_http_client',
  486. 'compat_http_server',
  487. 'compat_itertools_count',
  488. 'compat_kwargs',
  489. 'compat_ord',
  490. 'compat_parse_qs',
  491. 'compat_print',
  492. 'compat_shlex_split',
  493. 'compat_socket_create_connection',
  494. 'compat_str',
  495. 'compat_subprocess_get_DEVNULL',
  496. 'compat_tokenize_tokenize',
  497. 'compat_urllib_error',
  498. 'compat_urllib_parse',
  499. 'compat_urllib_parse_unquote',
  500. 'compat_urllib_parse_unquote_plus',
  501. 'compat_urllib_parse_unquote_to_bytes',
  502. 'compat_urllib_parse_urlparse',
  503. 'compat_urllib_request',
  504. 'compat_urllib_request_DataHandler',
  505. 'compat_urllib_response',
  506. 'compat_urlparse',
  507. 'compat_urlretrieve',
  508. 'compat_xml_parse_error',
  509. 'shlex_quote',
  510. 'subprocess_check_output',
  511. 'workaround_optparse_bug9161',
  512. ]