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