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