]>
Commit | Line | Data |
---|---|---|
451948b2 PH |
1 | from __future__ import unicode_literals |
2 | ||
8c25f81b | 3 | import getpass |
e07e9313 | 4 | import optparse |
8c25f81b | 5 | import os |
7d4111ed | 6 | import re |
be4a824d | 7 | import socket |
8c25f81b PH |
8 | import subprocess |
9 | import sys | |
10 | ||
11 | ||
12 | try: | |
13 | import urllib.request as compat_urllib_request | |
5f6a1245 | 14 | except ImportError: # Python 2 |
8c25f81b PH |
15 | import urllib2 as compat_urllib_request |
16 | ||
17 | try: | |
18 | import urllib.error as compat_urllib_error | |
5f6a1245 | 19 | except ImportError: # Python 2 |
8c25f81b PH |
20 | import urllib2 as compat_urllib_error |
21 | ||
22 | try: | |
23 | import urllib.parse as compat_urllib_parse | |
5f6a1245 | 24 | except ImportError: # Python 2 |
8c25f81b PH |
25 | import urllib as compat_urllib_parse |
26 | ||
27 | try: | |
28 | from urllib.parse import urlparse as compat_urllib_parse_urlparse | |
5f6a1245 | 29 | except ImportError: # Python 2 |
8c25f81b PH |
30 | from urlparse import urlparse as compat_urllib_parse_urlparse |
31 | ||
32 | try: | |
33 | import urllib.parse as compat_urlparse | |
5f6a1245 | 34 | except ImportError: # Python 2 |
8c25f81b PH |
35 | import urlparse as compat_urlparse |
36 | ||
37 | try: | |
38 | import http.cookiejar as compat_cookiejar | |
5f6a1245 | 39 | except ImportError: # Python 2 |
8c25f81b PH |
40 | import cookielib as compat_cookiejar |
41 | ||
42 | try: | |
43 | import html.entities as compat_html_entities | |
5f6a1245 | 44 | except ImportError: # Python 2 |
8c25f81b PH |
45 | import htmlentitydefs as compat_html_entities |
46 | ||
47 | try: | |
48 | import html.parser as compat_html_parser | |
5f6a1245 | 49 | except ImportError: # Python 2 |
8c25f81b PH |
50 | import HTMLParser as compat_html_parser |
51 | ||
52 | try: | |
53 | import http.client as compat_http_client | |
5f6a1245 | 54 | except ImportError: # Python 2 |
8c25f81b PH |
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 | |
5f6a1245 | 115 | except ImportError: # Python 2 |
8c25f81b PH |
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, | |
9e1a5b84 | 120 | encoding='utf-8', errors='replace'): |
8c25f81b PH |
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, | |
9e1a5b84 | 149 | encoding='utf-8', errors='replace'): |
8c25f81b PH |
150 | parsed_result = {} |
151 | pairs = _parse_qsl(qs, keep_blank_values, strict_parsing, | |
9e1a5b84 | 152 | encoding=encoding, errors=errors) |
8c25f81b PH |
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: | |
5f6a1245 | 161 | compat_str = unicode # Python 2 |
8c25f81b PH |
162 | except NameError: |
163 | compat_str = str | |
164 | ||
165 | try: | |
5f6a1245 | 166 | compat_chr = unichr # Python 2 |
8c25f81b PH |
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): | |
7d4111ed PH |
179 | if re.match(r'^[-_\w./]+$', s): |
180 | return s | |
181 | else: | |
182 | return "'" + s.replace("'", "'\"'\"'") + "'" | |
8c25f81b PH |
183 | |
184 | ||
185 | def compat_ord(c): | |
5f6a1245 JW |
186 | if type(c) is int: |
187 | return c | |
188 | else: | |
189 | return ord(c) | |
8c25f81b PH |
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') | |
83e865a3 | 251 | elif 'HOMEPATH' not in os.environ: |
8c25f81b PH |
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 | ||
5f6a1245 | 260 | if i != 1: # ~user |
8c25f81b PH |
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): | |
b061ea6e | 274 | assert isinstance(s, compat_str) |
8c25f81b PH |
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): | |
baa70803 | 293 | from .utils import preferredencoding |
8c25f81b PH |
294 | prompt = prompt.encode(preferredencoding()) |
295 | return getpass.getpass(prompt, *args, **kwargs) | |
296 | else: | |
297 | compat_getpass = getpass.getpass | |
298 | ||
c7b0add8 PH |
299 | # Old 2.6 and 2.7 releases require kwargs to be bytes |
300 | try: | |
c6973bd4 PH |
301 | def _testfunc(x): |
302 | pass | |
303 | _testfunc(**{'x': 0}) | |
c7b0add8 PH |
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 | |
8c25f81b | 309 | |
e07e9313 | 310 | |
be4a824d PH |
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 error("getaddrinfo returns an empty list") | |
333 | else: | |
334 | compat_socket_create_connection = socket.create_connection | |
335 | ||
336 | ||
e07e9313 PH |
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(): | |
07e378fa PH |
340 | op = optparse.OptionParser() |
341 | og = optparse.OptionGroup(op, 'foo') | |
e07e9313 | 342 | try: |
07e378fa | 343 | og.add_option('-t') |
b244b5c3 | 344 | except TypeError: |
e07e9313 PH |
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 | ||
8c25f81b PH |
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', | |
c7b0add8 | 368 | 'compat_kwargs', |
8c25f81b PH |
369 | 'compat_ord', |
370 | 'compat_parse_qs', | |
371 | 'compat_print', | |
372 | 'compat_str', | |
be4a824d | 373 | 'compat_socket_create_connection', |
8c25f81b PH |
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', | |
e07e9313 | 385 | 'workaround_optparse_bug9161', |
8c25f81b | 386 | ] |