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.

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