1 from __future__ import unicode_literals
16 import urllib.request as compat_urllib_request
17 except ImportError: # Python 2
18 import urllib2 as compat_urllib_request
21 import urllib.error as compat_urllib_error
22 except ImportError: # Python 2
23 import urllib2 as compat_urllib_error
26 import urllib.parse as compat_urllib_parse
27 except ImportError: # Python 2
28 import urllib as compat_urllib_parse
31 from urllib.parse import urlparse as compat_urllib_parse_urlparse
32 except ImportError: # Python 2
33 from urlparse import urlparse as compat_urllib_parse_urlparse
36 import urllib.parse as compat_urlparse
37 except ImportError: # Python 2
38 import urlparse as compat_urlparse
41 import http.cookiejar as compat_cookiejar
42 except ImportError: # Python 2
43 import cookielib as compat_cookiejar
46 import html.entities as compat_html_entities
47 except ImportError: # Python 2
48 import htmlentitydefs as compat_html_entities
51 import http.client as compat_http_client
52 except ImportError: # Python 2
53 import httplib as compat_http_client
56 from urllib.error import HTTPError as compat_HTTPError
57 except ImportError: # Python 2
58 from urllib2 import HTTPError as compat_HTTPError
61 from urllib.request import urlretrieve as compat_urlretrieve
62 except ImportError: # Python 2
63 from urllib import urlretrieve as compat_urlretrieve
67 from subprocess import DEVNULL
68 compat_subprocess_get_DEVNULL = lambda: DEVNULL
70 compat_subprocess_get_DEVNULL = lambda: open(os.path.devnull, 'w')
73 import http.server as compat_http_server
75 import BaseHTTPServer as compat_http_server
78 from urllib.parse import unquote_to_bytes as compat_urllib_parse_unquote_to_bytes
79 from urllib.parse import unquote as compat_urllib_parse_unquote
80 from urllib.parse import unquote_plus as compat_urllib_parse_unquote_plus
81 except ImportError: # Python 2
82 # HACK: The following are the correct unquote_to_bytes and unquote
83 # implementations from cpython 3.4.3's stdlib. Python 2's version
84 # is apparently broken (see https://github.com/rg3/youtube-dl/pull/6244)
86 def compat_urllib_parse_unquote_to_bytes(string):
87 """unquote_to_bytes('abc%20def') -> b'abc def'."""
88 # Note: strings are encoded as UTF-8. This is only an issue if it contains
89 # unescaped non-ASCII characters, which URIs should not.
91 # Is it a string-like object?
94 if isinstance(string, unicode):
95 string = string.encode('utf-8')
96 bits = string.split(b'%')
101 for item in bits[1:]:
103 append(compat_urllib_parse._hextochr[item[:2]])
110 def compat_urllib_parse_unquote(string, encoding='utf-8', errors='replace'):
111 """Replace %xx escapes by their single-character equivalent. The optional
112 encoding and errors parameters specify how to decode percent-encoded
113 sequences into Unicode characters, as accepted by the bytes.decode()
115 By default, percent-encoded sequences are decoded with UTF-8, and invalid
116 sequences are replaced by a placeholder character.
118 unquote('abc%20def') -> 'abc def'.
120 if '%' not in string:
127 bits = compat_urllib_parse._asciire.split(string)
130 for i in range(1, len(bits), 2):
131 append(compat_urllib_parse_unquote_to_bytes(bits[i]).decode(encoding, errors))
135 def compat_urllib_parse_unquote_plus(string, encoding='utf-8', errors='replace'):
136 """Like unquote(), but also replace plus signs by spaces, as required for
137 unquoting HTML form values.
139 unquote_plus('%7e/abc+def') -> '~/abc def'
141 string = string.replace('+', ' ')
142 return compat_urllib_parse_unquote(string, encoding, errors)
145 compat_str = unicode # Python 2
150 compat_basestring = basestring # Python 2
152 compat_basestring = str
155 compat_chr = unichr # Python 2
160 from xml.etree.ElementTree import ParseError as compat_xml_parse_error
161 except ImportError: # Python 2.6
162 from xml.parsers.expat import ExpatError as compat_xml_parse_error
166 from urllib.parse import parse_qs as compat_parse_qs
167 except ImportError: # Python 2
168 # HACK: The following is the correct parse_qs implementation from cpython 3's stdlib.
169 # Python 2's version is apparently totally broken
171 def _parse_qsl(qs, keep_blank_values=False, strict_parsing=False,
172 encoding='utf-8', errors='replace'):
173 qs, _coerce_result = qs, compat_str
174 pairs = [s2 for s1 in qs.split('&') for s2 in s1.split(';')]
176 for name_value in pairs:
177 if not name_value and not strict_parsing:
179 nv = name_value.split('=', 1)
182 raise ValueError("bad query field: %r" % (name_value,))
183 # Handle case of a control-name with no equal sign
184 if keep_blank_values:
188 if len(nv[1]) or keep_blank_values:
189 name = nv[0].replace('+', ' ')
190 name = compat_urllib_parse_unquote(
191 name, encoding=encoding, errors=errors)
192 name = _coerce_result(name)
193 value = nv[1].replace('+', ' ')
194 value = compat_urllib_parse_unquote(
195 value, encoding=encoding, errors=errors)
196 value = _coerce_result(value)
197 r.append((name, value))
200 def compat_parse_qs(qs, keep_blank_values=False, strict_parsing=False,
201 encoding='utf-8', errors='replace'):
203 pairs = _parse_qsl(qs, keep_blank_values, strict_parsing,
204 encoding=encoding, errors=errors)
205 for name, value in pairs:
206 if name in parsed_result:
207 parsed_result[name].append(value)
209 parsed_result[name] = [value]
213 from shlex import quote as shlex_quote
214 except ImportError: # Python < 3.3
216 if re.match(r'^[-_\w./]+$', s):
219 return "'" + s.replace("'", "'\"'\"'") + "'"
229 if sys.version_info >= (3, 0):
230 compat_getenv = os.getenv
231 compat_expanduser = os.path.expanduser
233 # Environment variables should be decoded with filesystem encoding.
234 # Otherwise it will fail if any non-ASCII characters present (see #3854 #3217 #2918)
236 def compat_getenv(key, default=None):
237 from .utils import get_filesystem_encoding
238 env = os.getenv(key, default)
240 env = env.decode(get_filesystem_encoding())
243 # HACK: The default implementations of os.path.expanduser from cpython do not decode
244 # environment variables with filesystem encoding. We will work around this by
245 # providing adjusted implementations.
246 # The following are os.path.expanduser implementations from cpython 2.7.8 stdlib
247 # for different platforms with correct environment variables decoding.
249 if os.name == 'posix':
250 def compat_expanduser(path):
251 """Expand ~ and ~user constructions. If user or $HOME is unknown,
253 if not path.startswith('~'):
255 i = path.find('/', 1)
259 if 'HOME' not in os.environ:
261 userhome = pwd.getpwuid(os.getuid()).pw_dir
263 userhome = compat_getenv('HOME')
267 pwent = pwd.getpwnam(path[1:i])
270 userhome = pwent.pw_dir
271 userhome = userhome.rstrip('/')
272 return (userhome + path[i:]) or '/'
273 elif os.name == 'nt' or os.name == 'ce':
274 def compat_expanduser(path):
275 """Expand ~ and ~user constructs.
277 If user or $HOME is unknown, do nothing."""
281 while i < n and path[i] not in '/\\':
284 if 'HOME' in os.environ:
285 userhome = compat_getenv('HOME')
286 elif 'USERPROFILE' in os.environ:
287 userhome = compat_getenv('USERPROFILE')
288 elif 'HOMEPATH' not in os.environ:
292 drive = compat_getenv('HOMEDRIVE')
295 userhome = os.path.join(drive, compat_getenv('HOMEPATH'))
298 userhome = os.path.join(os.path.dirname(userhome), path[1:i])
300 return userhome + path[i:]
302 compat_expanduser = os.path.expanduser
305 if sys.version_info < (3, 0):
307 from .utils import preferredencoding
308 print(s.encode(preferredencoding(), 'xmlcharrefreplace'))
311 assert isinstance(s, compat_str)
316 subprocess_check_output = subprocess.check_output
317 except AttributeError:
318 def subprocess_check_output(*args, **kwargs):
319 assert 'input' not in kwargs
320 p = subprocess.Popen(*args, stdout=subprocess.PIPE, **kwargs)
321 output, _ = p.communicate()
324 raise subprocess.CalledProcessError(ret, p.args, output=output)
327 if sys.version_info < (3, 0) and sys.platform == 'win32':
328 def compat_getpass(prompt, *args, **kwargs):
329 if isinstance(prompt, compat_str):
330 from .utils import preferredencoding
331 prompt = prompt.encode(preferredencoding())
332 return getpass.getpass(prompt, *args, **kwargs)
334 compat_getpass = getpass.getpass
336 # Old 2.6 and 2.7 releases require kwargs to be bytes
340 _testfunc(**{'x': 0})
342 def compat_kwargs(kwargs):
343 return dict((bytes(k), v) for k, v in kwargs.items())
345 compat_kwargs = lambda kwargs: kwargs
348 if sys.version_info < (2, 7):
349 def compat_socket_create_connection(address, timeout, source_address=None):
352 for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
353 af, socktype, proto, canonname, sa = res
356 sock = socket.socket(af, socktype, proto)
357 sock.settimeout(timeout)
359 sock.bind(source_address)
362 except socket.error as _:
369 raise socket.error("getaddrinfo returns an empty list")
371 compat_socket_create_connection = socket.create_connection
374 # Fix https://github.com/rg3/youtube-dl/issues/4223
375 # See http://bugs.python.org/issue9161 for what is broken
376 def workaround_optparse_bug9161():
377 op = optparse.OptionParser()
378 og = optparse.OptionGroup(op, 'foo')
382 real_add_option = optparse.OptionGroup.add_option
384 def _compat_add_option(self, *args, **kwargs):
386 v.encode('ascii', 'replace') if isinstance(v, compat_str)
388 bargs = [enc(a) for a in args]
390 (k, enc(v)) for k, v in kwargs.items())
391 return real_add_option(self, *bargs, **bkwargs)
392 optparse.OptionGroup.add_option = _compat_add_option
394 if hasattr(shutil, 'get_terminal_size'): # Python >= 3.3
395 compat_get_terminal_size = shutil.get_terminal_size
397 _terminal_size = collections.namedtuple('terminal_size', ['columns', 'lines'])
399 def compat_get_terminal_size():
400 columns = compat_getenv('COLUMNS', None)
402 columns = int(columns)
405 lines = compat_getenv('LINES', None)
412 sp = subprocess.Popen(
414 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
415 out, err = sp.communicate()
416 lines, columns = map(int, out.split())
419 return _terminal_size(columns, lines)
422 itertools.count(start=0, step=1)
423 compat_itertools_count = itertools.count
424 except TypeError: # Python 2.6
425 def compat_itertools_count(start=0, step=1):
437 'compat_get_terminal_size',
440 'compat_html_entities',
441 'compat_http_client',
442 'compat_http_server',
443 'compat_itertools_count',
448 'compat_socket_create_connection',
450 'compat_subprocess_get_DEVNULL',
451 'compat_urllib_error',
452 'compat_urllib_parse',
453 'compat_urllib_parse_unquote',
454 'compat_urllib_parse_unquote_plus',
455 'compat_urllib_parse_unquote_to_bytes',
456 'compat_urllib_parse_urlparse',
457 'compat_urllib_request',
459 'compat_urlretrieve',
460 'compat_xml_parse_error',
462 'subprocess_check_output',
463 'workaround_optparse_bug9161',