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