[compat] Add compat_urllib_request_Request
[youtube-dl] / youtube_dl / compat.py
1 from __future__ import unicode_literals
2
3 import binascii
4 import collections
5 import email
6 import getpass
7 import io
8 import optparse
9 import os
10 import re
11 import shlex
12 import shutil
13 import socket
14 import subprocess
15 import sys
16 import itertools
17 import xml.etree.ElementTree
18
19
20 try:
21     import urllib.request as compat_urllib_request
22 except ImportError:  # Python 2
23     import urllib2 as compat_urllib_request
24
25 try:
26     import urllib.error as compat_urllib_error
27 except ImportError:  # Python 2
28     import urllib2 as compat_urllib_error
29
30 try:
31     import urllib.parse as compat_urllib_parse
32 except ImportError:  # Python 2
33     import urllib as compat_urllib_parse
34
35 try:
36     from urllib.parse import urlparse as compat_urllib_parse_urlparse
37 except ImportError:  # Python 2
38     from urlparse import urlparse as compat_urllib_parse_urlparse
39
40 try:
41     import urllib.parse as compat_urlparse
42 except ImportError:  # Python 2
43     import urlparse as compat_urlparse
44
45 try:
46     import urllib.response as compat_urllib_response
47 except ImportError:  # Python 2
48     import urllib as compat_urllib_response
49
50 try:
51     import http.cookiejar as compat_cookiejar
52 except ImportError:  # Python 2
53     import cookielib as compat_cookiejar
54
55 try:
56     import http.cookies as compat_cookies
57 except ImportError:  # Python 2
58     import Cookie as compat_cookies
59
60 try:
61     import html.entities as compat_html_entities
62 except ImportError:  # Python 2
63     import htmlentitydefs as compat_html_entities
64
65 try:
66     import http.client as compat_http_client
67 except ImportError:  # Python 2
68     import httplib as compat_http_client
69
70 try:
71     from urllib.error import HTTPError as compat_HTTPError
72 except ImportError:  # Python 2
73     from urllib2 import HTTPError as compat_HTTPError
74
75 try:
76     from urllib.request import urlretrieve as compat_urlretrieve
77 except ImportError:  # Python 2
78     from urllib import urlretrieve as compat_urlretrieve
79
80
81 try:
82     from subprocess import DEVNULL
83     compat_subprocess_get_DEVNULL = lambda: DEVNULL
84 except ImportError:
85     compat_subprocess_get_DEVNULL = lambda: open(os.path.devnull, 'w')
86
87 try:
88     import http.server as compat_http_server
89 except ImportError:
90     import BaseHTTPServer as compat_http_server
91
92 try:
93     compat_str = unicode  # Python 2
94 except NameError:
95     compat_str = str
96
97 try:
98     from urllib.parse import unquote_to_bytes as compat_urllib_parse_unquote_to_bytes
99     from urllib.parse import unquote as compat_urllib_parse_unquote
100     from urllib.parse import unquote_plus as compat_urllib_parse_unquote_plus
101 except ImportError:  # Python 2
102     _asciire = (compat_urllib_parse._asciire if hasattr(compat_urllib_parse, '_asciire')
103                 else re.compile('([\x00-\x7f]+)'))
104
105     # HACK: The following are the correct unquote_to_bytes, unquote and unquote_plus
106     # implementations from cpython 3.4.3's stdlib. Python 2's version
107     # is apparently broken (see https://github.com/rg3/youtube-dl/pull/6244)
108
109     def compat_urllib_parse_unquote_to_bytes(string):
110         """unquote_to_bytes('abc%20def') -> b'abc def'."""
111         # Note: strings are encoded as UTF-8. This is only an issue if it contains
112         # unescaped non-ASCII characters, which URIs should not.
113         if not string:
114             # Is it a string-like object?
115             string.split
116             return b''
117         if isinstance(string, compat_str):
118             string = string.encode('utf-8')
119         bits = string.split(b'%')
120         if len(bits) == 1:
121             return string
122         res = [bits[0]]
123         append = res.append
124         for item in bits[1:]:
125             try:
126                 append(compat_urllib_parse._hextochr[item[:2]])
127                 append(item[2:])
128             except KeyError:
129                 append(b'%')
130                 append(item)
131         return b''.join(res)
132
133     def compat_urllib_parse_unquote(string, encoding='utf-8', errors='replace'):
134         """Replace %xx escapes by their single-character equivalent. The optional
135         encoding and errors parameters specify how to decode percent-encoded
136         sequences into Unicode characters, as accepted by the bytes.decode()
137         method.
138         By default, percent-encoded sequences are decoded with UTF-8, and invalid
139         sequences are replaced by a placeholder character.
140
141         unquote('abc%20def') -> 'abc def'.
142         """
143         if '%' not in string:
144             string.split
145             return string
146         if encoding is None:
147             encoding = 'utf-8'
148         if errors is None:
149             errors = 'replace'
150         bits = _asciire.split(string)
151         res = [bits[0]]
152         append = res.append
153         for i in range(1, len(bits), 2):
154             append(compat_urllib_parse_unquote_to_bytes(bits[i]).decode(encoding, errors))
155             append(bits[i + 1])
156         return ''.join(res)
157
158     def compat_urllib_parse_unquote_plus(string, encoding='utf-8', errors='replace'):
159         """Like unquote(), but also replace plus signs by spaces, as required for
160         unquoting HTML form values.
161
162         unquote_plus('%7e/abc+def') -> '~/abc def'
163         """
164         string = string.replace('+', ' ')
165         return compat_urllib_parse_unquote(string, encoding, errors)
166
167 try:
168     from urllib.request import DataHandler as compat_urllib_request_DataHandler
169 except ImportError:  # Python < 3.4
170     # Ported from CPython 98774:1733b3bd46db, Lib/urllib/request.py
171     class compat_urllib_request_DataHandler(compat_urllib_request.BaseHandler):
172         def data_open(self, req):
173             # data URLs as specified in RFC 2397.
174             #
175             # ignores POSTed data
176             #
177             # syntax:
178             # dataurl   := "data:" [ mediatype ] [ ";base64" ] "," data
179             # mediatype := [ type "/" subtype ] *( ";" parameter )
180             # data      := *urlchar
181             # parameter := attribute "=" value
182             url = req.get_full_url()
183
184             scheme, data = url.split(":", 1)
185             mediatype, data = data.split(",", 1)
186
187             # even base64 encoded data URLs might be quoted so unquote in any case:
188             data = compat_urllib_parse_unquote_to_bytes(data)
189             if mediatype.endswith(";base64"):
190                 data = binascii.a2b_base64(data)
191                 mediatype = mediatype[:-7]
192
193             if not mediatype:
194                 mediatype = "text/plain;charset=US-ASCII"
195
196             headers = email.message_from_string(
197                 "Content-type: %s\nContent-length: %d\n" % (mediatype, len(data)))
198
199             return compat_urllib_response.addinfourl(io.BytesIO(data), headers, url)
200
201
202 # Prepend protocol-less URLs with `http:` scheme in order to mitigate the number of
203 # unwanted failures due to missing protocol
204 def compat_urllib_request_Request(url, *args, **kwargs):
205     return compat_urllib_request.Request(
206         'http:%s' % url if url.startswith('//') else url, *args, **kwargs)
207
208
209 try:
210     compat_basestring = basestring  # Python 2
211 except NameError:
212     compat_basestring = str
213
214 try:
215     compat_chr = unichr  # Python 2
216 except NameError:
217     compat_chr = chr
218
219 try:
220     from xml.etree.ElementTree import ParseError as compat_xml_parse_error
221 except ImportError:  # Python 2.6
222     from xml.parsers.expat import ExpatError as compat_xml_parse_error
223
224 if sys.version_info[0] >= 3:
225     compat_etree_fromstring = xml.etree.ElementTree.fromstring
226 else:
227     # python 2.x tries to encode unicode strings with ascii (see the
228     # XMLParser._fixtext method)
229     etree = xml.etree.ElementTree
230
231     try:
232         _etree_iter = etree.Element.iter
233     except AttributeError:  # Python <=2.6
234         def _etree_iter(root):
235             for el in root.findall('*'):
236                 yield el
237                 for sub in _etree_iter(el):
238                     yield sub
239
240     # on 2.6 XML doesn't have a parser argument, function copied from CPython
241     # 2.7 source
242     def _XML(text, parser=None):
243         if not parser:
244             parser = etree.XMLParser(target=etree.TreeBuilder())
245         parser.feed(text)
246         return parser.close()
247
248     def _element_factory(*args, **kwargs):
249         el = etree.Element(*args, **kwargs)
250         for k, v in el.items():
251             if isinstance(v, bytes):
252                 el.set(k, v.decode('utf-8'))
253         return el
254
255     def compat_etree_fromstring(text):
256         doc = _XML(text, parser=etree.XMLParser(target=etree.TreeBuilder(element_factory=_element_factory)))
257         for el in _etree_iter(doc):
258             if el.text is not None and isinstance(el.text, bytes):
259                 el.text = el.text.decode('utf-8')
260         return doc
261
262 try:
263     from urllib.parse import parse_qs as compat_parse_qs
264 except ImportError:  # Python 2
265     # HACK: The following is the correct parse_qs implementation from cpython 3's stdlib.
266     # Python 2's version is apparently totally broken
267
268     def _parse_qsl(qs, keep_blank_values=False, strict_parsing=False,
269                    encoding='utf-8', errors='replace'):
270         qs, _coerce_result = qs, compat_str
271         pairs = [s2 for s1 in qs.split('&') for s2 in s1.split(';')]
272         r = []
273         for name_value in pairs:
274             if not name_value and not strict_parsing:
275                 continue
276             nv = name_value.split('=', 1)
277             if len(nv) != 2:
278                 if strict_parsing:
279                     raise ValueError("bad query field: %r" % (name_value,))
280                 # Handle case of a control-name with no equal sign
281                 if keep_blank_values:
282                     nv.append('')
283                 else:
284                     continue
285             if len(nv[1]) or keep_blank_values:
286                 name = nv[0].replace('+', ' ')
287                 name = compat_urllib_parse_unquote(
288                     name, encoding=encoding, errors=errors)
289                 name = _coerce_result(name)
290                 value = nv[1].replace('+', ' ')
291                 value = compat_urllib_parse_unquote(
292                     value, encoding=encoding, errors=errors)
293                 value = _coerce_result(value)
294                 r.append((name, value))
295         return r
296
297     def compat_parse_qs(qs, keep_blank_values=False, strict_parsing=False,
298                         encoding='utf-8', errors='replace'):
299         parsed_result = {}
300         pairs = _parse_qsl(qs, keep_blank_values, strict_parsing,
301                            encoding=encoding, errors=errors)
302         for name, value in pairs:
303             if name in parsed_result:
304                 parsed_result[name].append(value)
305             else:
306                 parsed_result[name] = [value]
307         return parsed_result
308
309 try:
310     from shlex import quote as shlex_quote
311 except ImportError:  # Python < 3.3
312     def shlex_quote(s):
313         if re.match(r'^[-_\w./]+$', s):
314             return s
315         else:
316             return "'" + s.replace("'", "'\"'\"'") + "'"
317
318
319 if sys.version_info >= (2, 7, 3):
320     compat_shlex_split = shlex.split
321 else:
322     # Working around shlex issue with unicode strings on some python 2
323     # versions (see http://bugs.python.org/issue1548891)
324     def compat_shlex_split(s, comments=False, posix=True):
325         if isinstance(s, compat_str):
326             s = s.encode('utf-8')
327         return shlex.split(s, comments, posix)
328
329
330 def compat_ord(c):
331     if type(c) is int:
332         return c
333     else:
334         return ord(c)
335
336
337 if sys.version_info >= (3, 0):
338     compat_getenv = os.getenv
339     compat_expanduser = os.path.expanduser
340 else:
341     # Environment variables should be decoded with filesystem encoding.
342     # Otherwise it will fail if any non-ASCII characters present (see #3854 #3217 #2918)
343
344     def compat_getenv(key, default=None):
345         from .utils import get_filesystem_encoding
346         env = os.getenv(key, default)
347         if env:
348             env = env.decode(get_filesystem_encoding())
349         return env
350
351     # HACK: The default implementations of os.path.expanduser from cpython do not decode
352     # environment variables with filesystem encoding. We will work around this by
353     # providing adjusted implementations.
354     # The following are os.path.expanduser implementations from cpython 2.7.8 stdlib
355     # for different platforms with correct environment variables decoding.
356
357     if os.name == 'posix':
358         def compat_expanduser(path):
359             """Expand ~ and ~user constructions.  If user or $HOME is unknown,
360             do nothing."""
361             if not path.startswith('~'):
362                 return path
363             i = path.find('/', 1)
364             if i < 0:
365                 i = len(path)
366             if i == 1:
367                 if 'HOME' not in os.environ:
368                     import pwd
369                     userhome = pwd.getpwuid(os.getuid()).pw_dir
370                 else:
371                     userhome = compat_getenv('HOME')
372             else:
373                 import pwd
374                 try:
375                     pwent = pwd.getpwnam(path[1:i])
376                 except KeyError:
377                     return path
378                 userhome = pwent.pw_dir
379             userhome = userhome.rstrip('/')
380             return (userhome + path[i:]) or '/'
381     elif os.name == 'nt' or os.name == 'ce':
382         def compat_expanduser(path):
383             """Expand ~ and ~user constructs.
384
385             If user or $HOME is unknown, do nothing."""
386             if path[:1] != '~':
387                 return path
388             i, n = 1, len(path)
389             while i < n and path[i] not in '/\\':
390                 i = i + 1
391
392             if 'HOME' in os.environ:
393                 userhome = compat_getenv('HOME')
394             elif 'USERPROFILE' in os.environ:
395                 userhome = compat_getenv('USERPROFILE')
396             elif 'HOMEPATH' not in os.environ:
397                 return path
398             else:
399                 try:
400                     drive = compat_getenv('HOMEDRIVE')
401                 except KeyError:
402                     drive = ''
403                 userhome = os.path.join(drive, compat_getenv('HOMEPATH'))
404
405             if i != 1:  # ~user
406                 userhome = os.path.join(os.path.dirname(userhome), path[1:i])
407
408             return userhome + path[i:]
409     else:
410         compat_expanduser = os.path.expanduser
411
412
413 if sys.version_info < (3, 0):
414     def compat_print(s):
415         from .utils import preferredencoding
416         print(s.encode(preferredencoding(), 'xmlcharrefreplace'))
417 else:
418     def compat_print(s):
419         assert isinstance(s, compat_str)
420         print(s)
421
422
423 try:
424     subprocess_check_output = subprocess.check_output
425 except AttributeError:
426     def subprocess_check_output(*args, **kwargs):
427         assert 'input' not in kwargs
428         p = subprocess.Popen(*args, stdout=subprocess.PIPE, **kwargs)
429         output, _ = p.communicate()
430         ret = p.poll()
431         if ret:
432             raise subprocess.CalledProcessError(ret, p.args, output=output)
433         return output
434
435 if sys.version_info < (3, 0) and sys.platform == 'win32':
436     def compat_getpass(prompt, *args, **kwargs):
437         if isinstance(prompt, compat_str):
438             from .utils import preferredencoding
439             prompt = prompt.encode(preferredencoding())
440         return getpass.getpass(prompt, *args, **kwargs)
441 else:
442     compat_getpass = getpass.getpass
443
444 # Old 2.6 and 2.7 releases require kwargs to be bytes
445 try:
446     def _testfunc(x):
447         pass
448     _testfunc(**{'x': 0})
449 except TypeError:
450     def compat_kwargs(kwargs):
451         return dict((bytes(k), v) for k, v in kwargs.items())
452 else:
453     compat_kwargs = lambda kwargs: kwargs
454
455
456 if sys.version_info < (2, 7):
457     def compat_socket_create_connection(address, timeout, source_address=None):
458         host, port = address
459         err = None
460         for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
461             af, socktype, proto, canonname, sa = res
462             sock = None
463             try:
464                 sock = socket.socket(af, socktype, proto)
465                 sock.settimeout(timeout)
466                 if source_address:
467                     sock.bind(source_address)
468                 sock.connect(sa)
469                 return sock
470             except socket.error as _:
471                 err = _
472                 if sock is not None:
473                     sock.close()
474         if err is not None:
475             raise err
476         else:
477             raise socket.error("getaddrinfo returns an empty list")
478 else:
479     compat_socket_create_connection = socket.create_connection
480
481
482 # Fix https://github.com/rg3/youtube-dl/issues/4223
483 # See http://bugs.python.org/issue9161 for what is broken
484 def workaround_optparse_bug9161():
485     op = optparse.OptionParser()
486     og = optparse.OptionGroup(op, 'foo')
487     try:
488         og.add_option('-t')
489     except TypeError:
490         real_add_option = optparse.OptionGroup.add_option
491
492         def _compat_add_option(self, *args, **kwargs):
493             enc = lambda v: (
494                 v.encode('ascii', 'replace') if isinstance(v, compat_str)
495                 else v)
496             bargs = [enc(a) for a in args]
497             bkwargs = dict(
498                 (k, enc(v)) for k, v in kwargs.items())
499             return real_add_option(self, *bargs, **bkwargs)
500         optparse.OptionGroup.add_option = _compat_add_option
501
502 if hasattr(shutil, 'get_terminal_size'):  # Python >= 3.3
503     compat_get_terminal_size = shutil.get_terminal_size
504 else:
505     _terminal_size = collections.namedtuple('terminal_size', ['columns', 'lines'])
506
507     def compat_get_terminal_size(fallback=(80, 24)):
508         columns = compat_getenv('COLUMNS')
509         if columns:
510             columns = int(columns)
511         else:
512             columns = None
513         lines = compat_getenv('LINES')
514         if lines:
515             lines = int(lines)
516         else:
517             lines = None
518
519         if columns is None or lines is None or columns <= 0 or lines <= 0:
520             try:
521                 sp = subprocess.Popen(
522                     ['stty', 'size'],
523                     stdout=subprocess.PIPE, stderr=subprocess.PIPE)
524                 out, err = sp.communicate()
525                 _lines, _columns = map(int, out.split())
526             except Exception:
527                 _columns, _lines = _terminal_size(*fallback)
528
529             if columns is None or columns <= 0:
530                 columns = _columns
531             if lines is None or lines <= 0:
532                 lines = _lines
533         return _terminal_size(columns, lines)
534
535 try:
536     itertools.count(start=0, step=1)
537     compat_itertools_count = itertools.count
538 except TypeError:  # Python 2.6
539     def compat_itertools_count(start=0, step=1):
540         n = start
541         while True:
542             yield n
543             n += step
544
545 if sys.version_info >= (3, 0):
546     from tokenize import tokenize as compat_tokenize_tokenize
547 else:
548     from tokenize import generate_tokens as compat_tokenize_tokenize
549
550 __all__ = [
551     'compat_HTTPError',
552     'compat_basestring',
553     'compat_chr',
554     'compat_cookiejar',
555     'compat_cookies',
556     'compat_etree_fromstring',
557     'compat_expanduser',
558     'compat_get_terminal_size',
559     'compat_getenv',
560     'compat_getpass',
561     'compat_html_entities',
562     'compat_http_client',
563     'compat_http_server',
564     'compat_itertools_count',
565     'compat_kwargs',
566     'compat_ord',
567     'compat_parse_qs',
568     'compat_print',
569     'compat_shlex_split',
570     'compat_socket_create_connection',
571     'compat_str',
572     'compat_subprocess_get_DEVNULL',
573     'compat_tokenize_tokenize',
574     'compat_urllib_error',
575     'compat_urllib_parse',
576     'compat_urllib_parse_unquote',
577     'compat_urllib_parse_unquote_plus',
578     'compat_urllib_parse_unquote_to_bytes',
579     'compat_urllib_parse_urlparse',
580     'compat_urllib_request',
581     'compat_urllib_request_DataHandler',
582     'compat_urllib_response',
583     'compat_urlparse',
584     'compat_urlretrieve',
585     'compat_xml_parse_error',
586     'shlex_quote',
587     'subprocess_check_output',
588     'workaround_optparse_bug9161',
589 ]