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.

649 lines
21 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 compat_shlex_quote
  296. except ImportError: # Python < 3.3
  297. def compat_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. if sys.version_info < (3, 0) and sys.platform == 'win32':
  400. def compat_getpass(prompt, *args, **kwargs):
  401. if isinstance(prompt, compat_str):
  402. from .utils import preferredencoding
  403. prompt = prompt.encode(preferredencoding())
  404. return getpass.getpass(prompt, *args, **kwargs)
  405. else:
  406. compat_getpass = getpass.getpass
  407. # Python < 2.6.5 require kwargs to be bytes
  408. try:
  409. def _testfunc(x):
  410. pass
  411. _testfunc(**{'x': 0})
  412. except TypeError:
  413. def compat_kwargs(kwargs):
  414. return dict((bytes(k), v) for k, v in kwargs.items())
  415. else:
  416. compat_kwargs = lambda kwargs: kwargs
  417. if sys.version_info < (2, 7):
  418. def compat_socket_create_connection(address, timeout, source_address=None):
  419. host, port = address
  420. err = None
  421. for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
  422. af, socktype, proto, canonname, sa = res
  423. sock = None
  424. try:
  425. sock = socket.socket(af, socktype, proto)
  426. sock.settimeout(timeout)
  427. if source_address:
  428. sock.bind(source_address)
  429. sock.connect(sa)
  430. return sock
  431. except socket.error as _:
  432. err = _
  433. if sock is not None:
  434. sock.close()
  435. if err is not None:
  436. raise err
  437. else:
  438. raise socket.error('getaddrinfo returns an empty list')
  439. else:
  440. compat_socket_create_connection = socket.create_connection
  441. # Fix https://github.com/rg3/youtube-dl/issues/4223
  442. # See http://bugs.python.org/issue9161 for what is broken
  443. def workaround_optparse_bug9161():
  444. op = optparse.OptionParser()
  445. og = optparse.OptionGroup(op, 'foo')
  446. try:
  447. og.add_option('-t')
  448. except TypeError:
  449. real_add_option = optparse.OptionGroup.add_option
  450. def _compat_add_option(self, *args, **kwargs):
  451. enc = lambda v: (
  452. v.encode('ascii', 'replace') if isinstance(v, compat_str)
  453. else v)
  454. bargs = [enc(a) for a in args]
  455. bkwargs = dict(
  456. (k, enc(v)) for k, v in kwargs.items())
  457. return real_add_option(self, *bargs, **bkwargs)
  458. optparse.OptionGroup.add_option = _compat_add_option
  459. if hasattr(shutil, 'get_terminal_size'): # Python >= 3.3
  460. compat_get_terminal_size = shutil.get_terminal_size
  461. else:
  462. _terminal_size = collections.namedtuple('terminal_size', ['columns', 'lines'])
  463. def compat_get_terminal_size(fallback=(80, 24)):
  464. columns = compat_getenv('COLUMNS')
  465. if columns:
  466. columns = int(columns)
  467. else:
  468. columns = None
  469. lines = compat_getenv('LINES')
  470. if lines:
  471. lines = int(lines)
  472. else:
  473. lines = None
  474. if columns is None or lines is None or columns <= 0 or lines <= 0:
  475. try:
  476. sp = subprocess.Popen(
  477. ['stty', 'size'],
  478. stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  479. out, err = sp.communicate()
  480. _lines, _columns = map(int, out.split())
  481. except Exception:
  482. _columns, _lines = _terminal_size(*fallback)
  483. if columns is None or columns <= 0:
  484. columns = _columns
  485. if lines is None or lines <= 0:
  486. lines = _lines
  487. return _terminal_size(columns, lines)
  488. try:
  489. itertools.count(start=0, step=1)
  490. compat_itertools_count = itertools.count
  491. except TypeError: # Python 2.6
  492. def compat_itertools_count(start=0, step=1):
  493. n = start
  494. while True:
  495. yield n
  496. n += step
  497. if sys.version_info >= (3, 0):
  498. from tokenize import tokenize as compat_tokenize_tokenize
  499. else:
  500. from tokenize import generate_tokens as compat_tokenize_tokenize
  501. try:
  502. struct.pack('!I', 0)
  503. except TypeError:
  504. # In Python 2.6 and 2.7.x < 2.7.7, struct requires a bytes argument
  505. # See https://bugs.python.org/issue19099
  506. def compat_struct_pack(spec, *args):
  507. if isinstance(spec, compat_str):
  508. spec = spec.encode('ascii')
  509. return struct.pack(spec, *args)
  510. def compat_struct_unpack(spec, *args):
  511. if isinstance(spec, compat_str):
  512. spec = spec.encode('ascii')
  513. return struct.unpack(spec, *args)
  514. else:
  515. compat_struct_pack = struct.pack
  516. compat_struct_unpack = struct.unpack
  517. __all__ = [
  518. 'compat_HTMLParser',
  519. 'compat_HTTPError',
  520. 'compat_basestring',
  521. 'compat_chr',
  522. 'compat_cookiejar',
  523. 'compat_cookies',
  524. 'compat_etree_fromstring',
  525. 'compat_expanduser',
  526. 'compat_get_terminal_size',
  527. 'compat_getenv',
  528. 'compat_getpass',
  529. 'compat_html_entities',
  530. 'compat_http_client',
  531. 'compat_http_server',
  532. 'compat_itertools_count',
  533. 'compat_kwargs',
  534. 'compat_ord',
  535. 'compat_os_name',
  536. 'compat_parse_qs',
  537. 'compat_print',
  538. 'compat_setenv',
  539. 'compat_shlex_quote',
  540. 'compat_shlex_split',
  541. 'compat_socket_create_connection',
  542. 'compat_str',
  543. 'compat_struct_pack',
  544. 'compat_struct_unpack',
  545. 'compat_subprocess_get_DEVNULL',
  546. 'compat_tokenize_tokenize',
  547. 'compat_urllib_error',
  548. 'compat_urllib_parse',
  549. 'compat_urllib_parse_unquote',
  550. 'compat_urllib_parse_unquote_plus',
  551. 'compat_urllib_parse_unquote_to_bytes',
  552. 'compat_urllib_parse_urlencode',
  553. 'compat_urllib_parse_urlparse',
  554. 'compat_urllib_request',
  555. 'compat_urllib_request_DataHandler',
  556. 'compat_urllib_response',
  557. 'compat_urlparse',
  558. 'compat_urlretrieve',
  559. 'compat_xml_parse_error',
  560. 'compat_xpath',
  561. 'workaround_optparse_bug9161',
  562. ]