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