You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

602 lines
20 KiB

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