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.

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