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