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.

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