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