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