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.

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