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.

466 lines
15 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 collections
  3. import getpass
  4. import optparse
  5. import os
  6. import re
  7. import shutil
  8. import socket
  9. import subprocess
  10. import sys
  11. import itertools
  12. try:
  13. import urllib.request as compat_urllib_request
  14. except ImportError: # Python 2
  15. import urllib2 as compat_urllib_request
  16. try:
  17. import urllib.error as compat_urllib_error
  18. except ImportError: # Python 2
  19. import urllib2 as compat_urllib_error
  20. try:
  21. import urllib.parse as compat_urllib_parse
  22. except ImportError: # Python 2
  23. import urllib as compat_urllib_parse
  24. try:
  25. from urllib.parse import urlparse as compat_urllib_parse_urlparse
  26. except ImportError: # Python 2
  27. from urlparse import urlparse as compat_urllib_parse_urlparse
  28. try:
  29. import urllib.parse as compat_urlparse
  30. except ImportError: # Python 2
  31. import urlparse as compat_urlparse
  32. try:
  33. import http.cookiejar as compat_cookiejar
  34. except ImportError: # Python 2
  35. import cookielib as compat_cookiejar
  36. try:
  37. import html.entities as compat_html_entities
  38. except ImportError: # Python 2
  39. import htmlentitydefs as compat_html_entities
  40. try:
  41. import http.client as compat_http_client
  42. except ImportError: # Python 2
  43. import httplib as compat_http_client
  44. try:
  45. from urllib.error import HTTPError as compat_HTTPError
  46. except ImportError: # Python 2
  47. from urllib2 import HTTPError as compat_HTTPError
  48. try:
  49. from urllib.request import urlretrieve as compat_urlretrieve
  50. except ImportError: # Python 2
  51. from urllib import urlretrieve as compat_urlretrieve
  52. try:
  53. from subprocess import DEVNULL
  54. compat_subprocess_get_DEVNULL = lambda: DEVNULL
  55. except ImportError:
  56. compat_subprocess_get_DEVNULL = lambda: open(os.path.devnull, 'w')
  57. try:
  58. import http.server as compat_http_server
  59. except ImportError:
  60. import BaseHTTPServer as compat_http_server
  61. try:
  62. from urllib.parse import unquote_to_bytes as compat_urllib_parse_unquote_to_bytes
  63. from urllib.parse import unquote as compat_urllib_parse_unquote
  64. from urllib.parse import unquote_plus as compat_urllib_parse_unquote_plus
  65. except ImportError: # Python 2
  66. _asciire = re.compile('([\x00-\x7f]+)') if sys.version_info < (2, 7) else compat_urllib_parse._asciire
  67. # HACK: The following are the correct unquote_to_bytes, unquote and unquote_plus
  68. # implementations from cpython 3.4.3's stdlib. Python 2's version
  69. # is apparently broken (see https://github.com/rg3/youtube-dl/pull/6244)
  70. def compat_urllib_parse_unquote_to_bytes(string):
  71. """unquote_to_bytes('abc%20def') -> b'abc def'."""
  72. # Note: strings are encoded as UTF-8. This is only an issue if it contains
  73. # unescaped non-ASCII characters, which URIs should not.
  74. if not string:
  75. # Is it a string-like object?
  76. string.split
  77. return b''
  78. if isinstance(string, unicode):
  79. string = string.encode('utf-8')
  80. bits = string.split(b'%')
  81. if len(bits) == 1:
  82. return string
  83. res = [bits[0]]
  84. append = res.append
  85. for item in bits[1:]:
  86. try:
  87. append(compat_urllib_parse._hextochr[item[:2]])
  88. append(item[2:])
  89. except KeyError:
  90. append(b'%')
  91. append(item)
  92. return b''.join(res)
  93. def compat_urllib_parse_unquote(string, encoding='utf-8', errors='replace'):
  94. """Replace %xx escapes by their single-character equivalent. The optional
  95. encoding and errors parameters specify how to decode percent-encoded
  96. sequences into Unicode characters, as accepted by the bytes.decode()
  97. method.
  98. By default, percent-encoded sequences are decoded with UTF-8, and invalid
  99. sequences are replaced by a placeholder character.
  100. unquote('abc%20def') -> 'abc def'.
  101. """
  102. if '%' not in string:
  103. string.split
  104. return string
  105. if encoding is None:
  106. encoding = 'utf-8'
  107. if errors is None:
  108. errors = 'replace'
  109. bits = _asciire.split(string)
  110. res = [bits[0]]
  111. append = res.append
  112. for i in range(1, len(bits), 2):
  113. append(compat_urllib_parse_unquote_to_bytes(bits[i]).decode(encoding, errors))
  114. append(bits[i + 1])
  115. return ''.join(res)
  116. def compat_urllib_parse_unquote_plus(string, encoding='utf-8', errors='replace'):
  117. """Like unquote(), but also replace plus signs by spaces, as required for
  118. unquoting HTML form values.
  119. unquote_plus('%7e/abc+def') -> '~/abc def'
  120. """
  121. string = string.replace('+', ' ')
  122. return compat_urllib_parse_unquote(string, encoding, errors)
  123. try:
  124. compat_str = unicode # Python 2
  125. except NameError:
  126. compat_str = str
  127. try:
  128. compat_basestring = basestring # Python 2
  129. except NameError:
  130. compat_basestring = str
  131. try:
  132. compat_chr = unichr # Python 2
  133. except NameError:
  134. compat_chr = chr
  135. try:
  136. from xml.etree.ElementTree import ParseError as compat_xml_parse_error
  137. except ImportError: # Python 2.6
  138. from xml.parsers.expat import ExpatError as compat_xml_parse_error
  139. try:
  140. from urllib.parse import parse_qs as compat_parse_qs
  141. except ImportError: # Python 2
  142. # HACK: The following is the correct parse_qs implementation from cpython 3's stdlib.
  143. # Python 2's version is apparently totally broken
  144. def _parse_qsl(qs, keep_blank_values=False, strict_parsing=False,
  145. encoding='utf-8', errors='replace'):
  146. qs, _coerce_result = qs, compat_str
  147. pairs = [s2 for s1 in qs.split('&') for s2 in s1.split(';')]
  148. r = []
  149. for name_value in pairs:
  150. if not name_value and not strict_parsing:
  151. continue
  152. nv = name_value.split('=', 1)
  153. if len(nv) != 2:
  154. if strict_parsing:
  155. raise ValueError("bad query field: %r" % (name_value,))
  156. # Handle case of a control-name with no equal sign
  157. if keep_blank_values:
  158. nv.append('')
  159. else:
  160. continue
  161. if len(nv[1]) or keep_blank_values:
  162. name = nv[0].replace('+', ' ')
  163. name = compat_urllib_parse_unquote(
  164. name, encoding=encoding, errors=errors)
  165. name = _coerce_result(name)
  166. value = nv[1].replace('+', ' ')
  167. value = compat_urllib_parse_unquote(
  168. value, encoding=encoding, errors=errors)
  169. value = _coerce_result(value)
  170. r.append((name, value))
  171. return r
  172. def compat_parse_qs(qs, keep_blank_values=False, strict_parsing=False,
  173. encoding='utf-8', errors='replace'):
  174. parsed_result = {}
  175. pairs = _parse_qsl(qs, keep_blank_values, strict_parsing,
  176. encoding=encoding, errors=errors)
  177. for name, value in pairs:
  178. if name in parsed_result:
  179. parsed_result[name].append(value)
  180. else:
  181. parsed_result[name] = [value]
  182. return parsed_result
  183. try:
  184. from shlex import quote as shlex_quote
  185. except ImportError: # Python < 3.3
  186. def shlex_quote(s):
  187. if re.match(r'^[-_\w./]+$', s):
  188. return s
  189. else:
  190. return "'" + s.replace("'", "'\"'\"'") + "'"
  191. def compat_ord(c):
  192. if type(c) is int:
  193. return c
  194. else:
  195. return ord(c)
  196. if sys.version_info >= (3, 0):
  197. compat_getenv = os.getenv
  198. compat_expanduser = os.path.expanduser
  199. else:
  200. # Environment variables should be decoded with filesystem encoding.
  201. # Otherwise it will fail if any non-ASCII characters present (see #3854 #3217 #2918)
  202. def compat_getenv(key, default=None):
  203. from .utils import get_filesystem_encoding
  204. env = os.getenv(key, default)
  205. if env:
  206. env = env.decode(get_filesystem_encoding())
  207. return env
  208. # HACK: The default implementations of os.path.expanduser from cpython do not decode
  209. # environment variables with filesystem encoding. We will work around this by
  210. # providing adjusted implementations.
  211. # The following are os.path.expanduser implementations from cpython 2.7.8 stdlib
  212. # for different platforms with correct environment variables decoding.
  213. if os.name == 'posix':
  214. def compat_expanduser(path):
  215. """Expand ~ and ~user constructions. If user or $HOME is unknown,
  216. do nothing."""
  217. if not path.startswith('~'):
  218. return path
  219. i = path.find('/', 1)
  220. if i < 0:
  221. i = len(path)
  222. if i == 1:
  223. if 'HOME' not in os.environ:
  224. import pwd
  225. userhome = pwd.getpwuid(os.getuid()).pw_dir
  226. else:
  227. userhome = compat_getenv('HOME')
  228. else:
  229. import pwd
  230. try:
  231. pwent = pwd.getpwnam(path[1:i])
  232. except KeyError:
  233. return path
  234. userhome = pwent.pw_dir
  235. userhome = userhome.rstrip('/')
  236. return (userhome + path[i:]) or '/'
  237. elif os.name == 'nt' or os.name == 'ce':
  238. def compat_expanduser(path):
  239. """Expand ~ and ~user constructs.
  240. If user or $HOME is unknown, do nothing."""
  241. if path[:1] != '~':
  242. return path
  243. i, n = 1, len(path)
  244. while i < n and path[i] not in '/\\':
  245. i = i + 1
  246. if 'HOME' in os.environ:
  247. userhome = compat_getenv('HOME')
  248. elif 'USERPROFILE' in os.environ:
  249. userhome = compat_getenv('USERPROFILE')
  250. elif 'HOMEPATH' not in os.environ:
  251. return path
  252. else:
  253. try:
  254. drive = compat_getenv('HOMEDRIVE')
  255. except KeyError:
  256. drive = ''
  257. userhome = os.path.join(drive, compat_getenv('HOMEPATH'))
  258. if i != 1: # ~user
  259. userhome = os.path.join(os.path.dirname(userhome), path[1:i])
  260. return userhome + path[i:]
  261. else:
  262. compat_expanduser = os.path.expanduser
  263. if sys.version_info < (3, 0):
  264. def compat_print(s):
  265. from .utils import preferredencoding
  266. print(s.encode(preferredencoding(), 'xmlcharrefreplace'))
  267. else:
  268. def compat_print(s):
  269. assert isinstance(s, compat_str)
  270. print(s)
  271. try:
  272. subprocess_check_output = subprocess.check_output
  273. except AttributeError:
  274. def subprocess_check_output(*args, **kwargs):
  275. assert 'input' not in kwargs
  276. p = subprocess.Popen(*args, stdout=subprocess.PIPE, **kwargs)
  277. output, _ = p.communicate()
  278. ret = p.poll()
  279. if ret:
  280. raise subprocess.CalledProcessError(ret, p.args, output=output)
  281. return output
  282. if sys.version_info < (3, 0) and sys.platform == 'win32':
  283. def compat_getpass(prompt, *args, **kwargs):
  284. if isinstance(prompt, compat_str):
  285. from .utils import preferredencoding
  286. prompt = prompt.encode(preferredencoding())
  287. return getpass.getpass(prompt, *args, **kwargs)
  288. else:
  289. compat_getpass = getpass.getpass
  290. # Old 2.6 and 2.7 releases require kwargs to be bytes
  291. try:
  292. def _testfunc(x):
  293. pass
  294. _testfunc(**{'x': 0})
  295. except TypeError:
  296. def compat_kwargs(kwargs):
  297. return dict((bytes(k), v) for k, v in kwargs.items())
  298. else:
  299. compat_kwargs = lambda kwargs: kwargs
  300. if sys.version_info < (2, 7):
  301. def compat_socket_create_connection(address, timeout, source_address=None):
  302. host, port = address
  303. err = None
  304. for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
  305. af, socktype, proto, canonname, sa = res
  306. sock = None
  307. try:
  308. sock = socket.socket(af, socktype, proto)
  309. sock.settimeout(timeout)
  310. if source_address:
  311. sock.bind(source_address)
  312. sock.connect(sa)
  313. return sock
  314. except socket.error as _:
  315. err = _
  316. if sock is not None:
  317. sock.close()
  318. if err is not None:
  319. raise err
  320. else:
  321. raise socket.error("getaddrinfo returns an empty list")
  322. else:
  323. compat_socket_create_connection = socket.create_connection
  324. # Fix https://github.com/rg3/youtube-dl/issues/4223
  325. # See http://bugs.python.org/issue9161 for what is broken
  326. def workaround_optparse_bug9161():
  327. op = optparse.OptionParser()
  328. og = optparse.OptionGroup(op, 'foo')
  329. try:
  330. og.add_option('-t')
  331. except TypeError:
  332. real_add_option = optparse.OptionGroup.add_option
  333. def _compat_add_option(self, *args, **kwargs):
  334. enc = lambda v: (
  335. v.encode('ascii', 'replace') if isinstance(v, compat_str)
  336. else v)
  337. bargs = [enc(a) for a in args]
  338. bkwargs = dict(
  339. (k, enc(v)) for k, v in kwargs.items())
  340. return real_add_option(self, *bargs, **bkwargs)
  341. optparse.OptionGroup.add_option = _compat_add_option
  342. if hasattr(shutil, 'get_terminal_size'): # Python >= 3.3
  343. compat_get_terminal_size = shutil.get_terminal_size
  344. else:
  345. _terminal_size = collections.namedtuple('terminal_size', ['columns', 'lines'])
  346. def compat_get_terminal_size():
  347. columns = compat_getenv('COLUMNS', None)
  348. if columns:
  349. columns = int(columns)
  350. else:
  351. columns = None
  352. lines = compat_getenv('LINES', None)
  353. if lines:
  354. lines = int(lines)
  355. else:
  356. lines = None
  357. try:
  358. sp = subprocess.Popen(
  359. ['stty', 'size'],
  360. stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  361. out, err = sp.communicate()
  362. lines, columns = map(int, out.split())
  363. except Exception:
  364. pass
  365. return _terminal_size(columns, lines)
  366. try:
  367. itertools.count(start=0, step=1)
  368. compat_itertools_count = itertools.count
  369. except TypeError: # Python 2.6
  370. def compat_itertools_count(start=0, step=1):
  371. n = start
  372. while True:
  373. yield n
  374. n += step
  375. __all__ = [
  376. 'compat_HTTPError',
  377. 'compat_basestring',
  378. 'compat_chr',
  379. 'compat_cookiejar',
  380. 'compat_expanduser',
  381. 'compat_get_terminal_size',
  382. 'compat_getenv',
  383. 'compat_getpass',
  384. 'compat_html_entities',
  385. 'compat_http_client',
  386. 'compat_http_server',
  387. 'compat_itertools_count',
  388. 'compat_kwargs',
  389. 'compat_ord',
  390. 'compat_parse_qs',
  391. 'compat_print',
  392. 'compat_socket_create_connection',
  393. 'compat_str',
  394. 'compat_subprocess_get_DEVNULL',
  395. 'compat_urllib_error',
  396. 'compat_urllib_parse',
  397. 'compat_urllib_parse_unquote',
  398. 'compat_urllib_parse_unquote_plus',
  399. 'compat_urllib_parse_unquote_to_bytes',
  400. 'compat_urllib_parse_urlparse',
  401. 'compat_urllib_request',
  402. 'compat_urlparse',
  403. 'compat_urlretrieve',
  404. 'compat_xml_parse_error',
  405. 'shlex_quote',
  406. 'subprocess_check_output',
  407. 'workaround_optparse_bug9161',
  408. ]