[utils] Add extract_attributes for extracting html tag attributes
[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 try:
260     from urllib.parse import parse_qs as compat_parse_qs
261 except ImportError:  # Python 2
262     # HACK: The following is the correct parse_qs implementation from cpython 3's stdlib.
263     # Python 2's version is apparently totally broken
264
265     def _parse_qsl(qs, keep_blank_values=False, strict_parsing=False,
266                    encoding='utf-8', errors='replace'):
267         qs, _coerce_result = qs, compat_str
268         pairs = [s2 for s1 in qs.split('&') for s2 in s1.split(';')]
269         r = []
270         for name_value in pairs:
271             if not name_value and not strict_parsing:
272                 continue
273             nv = name_value.split('=', 1)
274             if len(nv) != 2:
275                 if strict_parsing:
276                     raise ValueError('bad query field: %r' % (name_value,))
277                 # Handle case of a control-name with no equal sign
278                 if keep_blank_values:
279                     nv.append('')
280                 else:
281                     continue
282             if len(nv[1]) or keep_blank_values:
283                 name = nv[0].replace('+', ' ')
284                 name = compat_urllib_parse_unquote(
285                     name, encoding=encoding, errors=errors)
286                 name = _coerce_result(name)
287                 value = nv[1].replace('+', ' ')
288                 value = compat_urllib_parse_unquote(
289                     value, encoding=encoding, errors=errors)
290                 value = _coerce_result(value)
291                 r.append((name, value))
292         return r
293
294     def compat_parse_qs(qs, keep_blank_values=False, strict_parsing=False,
295                         encoding='utf-8', errors='replace'):
296         parsed_result = {}
297         pairs = _parse_qsl(qs, keep_blank_values, strict_parsing,
298                            encoding=encoding, errors=errors)
299         for name, value in pairs:
300             if name in parsed_result:
301                 parsed_result[name].append(value)
302             else:
303                 parsed_result[name] = [value]
304         return parsed_result
305
306 try:
307     from shlex import quote as shlex_quote
308 except ImportError:  # Python < 3.3
309     def shlex_quote(s):
310         if re.match(r'^[-_\w./]+$', s):
311             return s
312         else:
313             return "'" + s.replace("'", "'\"'\"'") + "'"
314
315
316 if sys.version_info >= (2, 7, 3):
317     compat_shlex_split = shlex.split
318 else:
319     # Working around shlex issue with unicode strings on some python 2
320     # versions (see http://bugs.python.org/issue1548891)
321     def compat_shlex_split(s, comments=False, posix=True):
322         if isinstance(s, compat_str):
323             s = s.encode('utf-8')
324         return shlex.split(s, comments, posix)
325
326
327 def compat_ord(c):
328     if type(c) is int:
329         return c
330     else:
331         return ord(c)
332
333
334 if sys.version_info >= (3, 0):
335     compat_getenv = os.getenv
336     compat_expanduser = os.path.expanduser
337 else:
338     # Environment variables should be decoded with filesystem encoding.
339     # Otherwise it will fail if any non-ASCII characters present (see #3854 #3217 #2918)
340
341     def compat_getenv(key, default=None):
342         from .utils import get_filesystem_encoding
343         env = os.getenv(key, default)
344         if env:
345             env = env.decode(get_filesystem_encoding())
346         return env
347
348     # HACK: The default implementations of os.path.expanduser from cpython do not decode
349     # environment variables with filesystem encoding. We will work around this by
350     # providing adjusted implementations.
351     # The following are os.path.expanduser implementations from cpython 2.7.8 stdlib
352     # for different platforms with correct environment variables decoding.
353
354     if os.name == 'posix':
355         def compat_expanduser(path):
356             """Expand ~ and ~user constructions.  If user or $HOME is unknown,
357             do nothing."""
358             if not path.startswith('~'):
359                 return path
360             i = path.find('/', 1)
361             if i < 0:
362                 i = len(path)
363             if i == 1:
364                 if 'HOME' not in os.environ:
365                     import pwd
366                     userhome = pwd.getpwuid(os.getuid()).pw_dir
367                 else:
368                     userhome = compat_getenv('HOME')
369             else:
370                 import pwd
371                 try:
372                     pwent = pwd.getpwnam(path[1:i])
373                 except KeyError:
374                     return path
375                 userhome = pwent.pw_dir
376             userhome = userhome.rstrip('/')
377             return (userhome + path[i:]) or '/'
378     elif os.name == 'nt' or os.name == 'ce':
379         def compat_expanduser(path):
380             """Expand ~ and ~user constructs.
381
382             If user or $HOME is unknown, do nothing."""
383             if path[:1] != '~':
384                 return path
385             i, n = 1, len(path)
386             while i < n and path[i] not in '/\\':
387                 i = i + 1
388
389             if 'HOME' in os.environ:
390                 userhome = compat_getenv('HOME')
391             elif 'USERPROFILE' in os.environ:
392                 userhome = compat_getenv('USERPROFILE')
393             elif 'HOMEPATH' not in os.environ:
394                 return path
395             else:
396                 try:
397                     drive = compat_getenv('HOMEDRIVE')
398                 except KeyError:
399                     drive = ''
400                 userhome = os.path.join(drive, compat_getenv('HOMEPATH'))
401
402             if i != 1:  # ~user
403                 userhome = os.path.join(os.path.dirname(userhome), path[1:i])
404
405             return userhome + path[i:]
406     else:
407         compat_expanduser = os.path.expanduser
408
409
410 if sys.version_info < (3, 0):
411     def compat_print(s):
412         from .utils import preferredencoding
413         print(s.encode(preferredencoding(), 'xmlcharrefreplace'))
414 else:
415     def compat_print(s):
416         assert isinstance(s, compat_str)
417         print(s)
418
419
420 try:
421     subprocess_check_output = subprocess.check_output
422 except AttributeError:
423     def subprocess_check_output(*args, **kwargs):
424         assert 'input' not in kwargs
425         p = subprocess.Popen(*args, stdout=subprocess.PIPE, **kwargs)
426         output, _ = p.communicate()
427         ret = p.poll()
428         if ret:
429             raise subprocess.CalledProcessError(ret, p.args, output=output)
430         return output
431
432 if sys.version_info < (3, 0) and sys.platform == 'win32':
433     def compat_getpass(prompt, *args, **kwargs):
434         if isinstance(prompt, compat_str):
435             from .utils import preferredencoding
436             prompt = prompt.encode(preferredencoding())
437         return getpass.getpass(prompt, *args, **kwargs)
438 else:
439     compat_getpass = getpass.getpass
440
441 # Python < 2.6.5 require kwargs to be bytes
442 try:
443     def _testfunc(x):
444         pass
445     _testfunc(**{'x': 0})
446 except TypeError:
447     def compat_kwargs(kwargs):
448         return dict((bytes(k), v) for k, v in kwargs.items())
449 else:
450     compat_kwargs = lambda kwargs: kwargs
451
452
453 if sys.version_info < (2, 7):
454     def compat_socket_create_connection(address, timeout, source_address=None):
455         host, port = address
456         err = None
457         for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
458             af, socktype, proto, canonname, sa = res
459             sock = None
460             try:
461                 sock = socket.socket(af, socktype, proto)
462                 sock.settimeout(timeout)
463                 if source_address:
464                     sock.bind(source_address)
465                 sock.connect(sa)
466                 return sock
467             except socket.error as _:
468                 err = _
469                 if sock is not None:
470                     sock.close()
471         if err is not None:
472             raise err
473         else:
474             raise socket.error('getaddrinfo returns an empty list')
475 else:
476     compat_socket_create_connection = socket.create_connection
477
478
479 # Fix https://github.com/rg3/youtube-dl/issues/4223
480 # See http://bugs.python.org/issue9161 for what is broken
481 def workaround_optparse_bug9161():
482     op = optparse.OptionParser()
483     og = optparse.OptionGroup(op, 'foo')
484     try:
485         og.add_option('-t')
486     except TypeError:
487         real_add_option = optparse.OptionGroup.add_option
488
489         def _compat_add_option(self, *args, **kwargs):
490             enc = lambda v: (
491                 v.encode('ascii', 'replace') if isinstance(v, compat_str)
492                 else v)
493             bargs = [enc(a) for a in args]
494             bkwargs = dict(
495                 (k, enc(v)) for k, v in kwargs.items())
496             return real_add_option(self, *bargs, **bkwargs)
497         optparse.OptionGroup.add_option = _compat_add_option
498
499 if hasattr(shutil, 'get_terminal_size'):  # Python >= 3.3
500     compat_get_terminal_size = shutil.get_terminal_size
501 else:
502     _terminal_size = collections.namedtuple('terminal_size', ['columns', 'lines'])
503
504     def compat_get_terminal_size(fallback=(80, 24)):
505         columns = compat_getenv('COLUMNS')
506         if columns:
507             columns = int(columns)
508         else:
509             columns = None
510         lines = compat_getenv('LINES')
511         if lines:
512             lines = int(lines)
513         else:
514             lines = None
515
516         if columns is None or lines is None or columns <= 0 or lines <= 0:
517             try:
518                 sp = subprocess.Popen(
519                     ['stty', 'size'],
520                     stdout=subprocess.PIPE, stderr=subprocess.PIPE)
521                 out, err = sp.communicate()
522                 _lines, _columns = map(int, out.split())
523             except Exception:
524                 _columns, _lines = _terminal_size(*fallback)
525
526             if columns is None or columns <= 0:
527                 columns = _columns
528             if lines is None or lines <= 0:
529                 lines = _lines
530         return _terminal_size(columns, lines)
531
532 try:
533     itertools.count(start=0, step=1)
534     compat_itertools_count = itertools.count
535 except TypeError:  # Python 2.6
536     def compat_itertools_count(start=0, step=1):
537         n = start
538         while True:
539             yield n
540             n += step
541
542 if sys.version_info >= (3, 0):
543     from tokenize import tokenize as compat_tokenize_tokenize
544 else:
545     from tokenize import generate_tokens as compat_tokenize_tokenize
546
547 __all__ = [
548     'compat_HTMLParser',
549     'compat_HTTPError',
550     'compat_basestring',
551     'compat_chr',
552     'compat_cookiejar',
553     'compat_cookies',
554     'compat_etree_fromstring',
555     'compat_expanduser',
556     'compat_get_terminal_size',
557     'compat_getenv',
558     'compat_getpass',
559     'compat_html_entities',
560     'compat_http_client',
561     'compat_http_server',
562     'compat_itertools_count',
563     'compat_kwargs',
564     'compat_ord',
565     'compat_parse_qs',
566     'compat_print',
567     'compat_shlex_split',
568     'compat_socket_create_connection',
569     'compat_str',
570     'compat_subprocess_get_DEVNULL',
571     'compat_tokenize_tokenize',
572     'compat_urllib_error',
573     'compat_urllib_parse',
574     'compat_urllib_parse_unquote',
575     'compat_urllib_parse_unquote_plus',
576     'compat_urllib_parse_unquote_to_bytes',
577     'compat_urllib_parse_urlparse',
578     'compat_urllib_request',
579     'compat_urllib_request_DataHandler',
580     'compat_urllib_response',
581     'compat_urlparse',
582     'compat_urlretrieve',
583     'compat_xml_parse_error',
584     'shlex_quote',
585     'subprocess_check_output',
586     'workaround_optparse_bug9161',
587 ]