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.

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