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