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.

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