[utils] Do not fail on unknown date formats in unified_strdate
[youtube-dl] / youtube_dl / utils.py
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3
4 from __future__ import unicode_literals
5
6 import base64
7 import binascii
8 import calendar
9 import codecs
10 import contextlib
11 import ctypes
12 import datetime
13 import email.utils
14 import errno
15 import functools
16 import gzip
17 import io
18 import itertools
19 import json
20 import locale
21 import math
22 import operator
23 import os
24 import pipes
25 import platform
26 import re
27 import socket
28 import ssl
29 import subprocess
30 import sys
31 import tempfile
32 import traceback
33 import xml.etree.ElementTree
34 import zlib
35
36 from .compat import (
37     compat_HTMLParser,
38     compat_basestring,
39     compat_chr,
40     compat_etree_fromstring,
41     compat_html_entities,
42     compat_http_client,
43     compat_kwargs,
44     compat_parse_qs,
45     compat_shlex_quote,
46     compat_socket_create_connection,
47     compat_str,
48     compat_struct_pack,
49     compat_urllib_error,
50     compat_urllib_parse,
51     compat_urllib_parse_urlencode,
52     compat_urllib_parse_urlparse,
53     compat_urllib_parse_unquote_plus,
54     compat_urllib_request,
55     compat_urlparse,
56     compat_xpath,
57 )
58
59 from .socks import (
60     ProxyType,
61     sockssocket,
62 )
63
64
65 def register_socks_protocols():
66     # "Register" SOCKS protocols
67     # In Python < 2.6.5, urlsplit() suffers from bug https://bugs.python.org/issue7904
68     # URLs with protocols not in urlparse.uses_netloc are not handled correctly
69     for scheme in ('socks', 'socks4', 'socks4a', 'socks5'):
70         if scheme not in compat_urlparse.uses_netloc:
71             compat_urlparse.uses_netloc.append(scheme)
72
73
74 # This is not clearly defined otherwise
75 compiled_regex_type = type(re.compile(''))
76
77 std_headers = {
78     'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:10.0) Gecko/20150101 Firefox/44.0 (Chrome)',
79     'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
80     'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
81     'Accept-Encoding': 'gzip, deflate',
82     'Accept-Language': 'en-us,en;q=0.5',
83 }
84
85
86 NO_DEFAULT = object()
87
88 ENGLISH_MONTH_NAMES = [
89     'January', 'February', 'March', 'April', 'May', 'June',
90     'July', 'August', 'September', 'October', 'November', 'December']
91
92 KNOWN_EXTENSIONS = (
93     'mp4', 'm4a', 'm4p', 'm4b', 'm4r', 'm4v', 'aac',
94     'flv', 'f4v', 'f4a', 'f4b',
95     'webm', 'ogg', 'ogv', 'oga', 'ogx', 'spx', 'opus',
96     'mkv', 'mka', 'mk3d',
97     'avi', 'divx',
98     'mov',
99     'asf', 'wmv', 'wma',
100     '3gp', '3g2',
101     'mp3',
102     'flac',
103     'ape',
104     'wav',
105     'f4f', 'f4m', 'm3u8', 'smil')
106
107 # needed for sanitizing filenames in restricted mode
108 ACCENT_CHARS = dict(zip('ÂÃÄÀÁÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØŒÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõöøœùúûüýþÿ',
109                         itertools.chain('AAAAAA', ['AE'], 'CEEEEIIIIDNOOOOOO', ['OE'], 'UUUUYP', ['ss'],
110                                         'aaaaaa', ['ae'], 'ceeeeiiiionoooooo', ['oe'], 'uuuuypy')))
111
112
113 def preferredencoding():
114     """Get preferred encoding.
115
116     Returns the best encoding scheme for the system, based on
117     locale.getpreferredencoding() and some further tweaks.
118     """
119     try:
120         pref = locale.getpreferredencoding()
121         'TEST'.encode(pref)
122     except Exception:
123         pref = 'UTF-8'
124
125     return pref
126
127
128 def write_json_file(obj, fn):
129     """ Encode obj as JSON and write it to fn, atomically if possible """
130
131     fn = encodeFilename(fn)
132     if sys.version_info < (3, 0) and sys.platform != 'win32':
133         encoding = get_filesystem_encoding()
134         # os.path.basename returns a bytes object, but NamedTemporaryFile
135         # will fail if the filename contains non ascii characters unless we
136         # use a unicode object
137         path_basename = lambda f: os.path.basename(fn).decode(encoding)
138         # the same for os.path.dirname
139         path_dirname = lambda f: os.path.dirname(fn).decode(encoding)
140     else:
141         path_basename = os.path.basename
142         path_dirname = os.path.dirname
143
144     args = {
145         'suffix': '.tmp',
146         'prefix': path_basename(fn) + '.',
147         'dir': path_dirname(fn),
148         'delete': False,
149     }
150
151     # In Python 2.x, json.dump expects a bytestream.
152     # In Python 3.x, it writes to a character stream
153     if sys.version_info < (3, 0):
154         args['mode'] = 'wb'
155     else:
156         args.update({
157             'mode': 'w',
158             'encoding': 'utf-8',
159         })
160
161     tf = tempfile.NamedTemporaryFile(**compat_kwargs(args))
162
163     try:
164         with tf:
165             json.dump(obj, tf)
166         if sys.platform == 'win32':
167             # Need to remove existing file on Windows, else os.rename raises
168             # WindowsError or FileExistsError.
169             try:
170                 os.unlink(fn)
171             except OSError:
172                 pass
173         os.rename(tf.name, fn)
174     except Exception:
175         try:
176             os.remove(tf.name)
177         except OSError:
178             pass
179         raise
180
181
182 if sys.version_info >= (2, 7):
183     def find_xpath_attr(node, xpath, key, val=None):
184         """ Find the xpath xpath[@key=val] """
185         assert re.match(r'^[a-zA-Z_-]+$', key)
186         expr = xpath + ('[@%s]' % key if val is None else "[@%s='%s']" % (key, val))
187         return node.find(expr)
188 else:
189     def find_xpath_attr(node, xpath, key, val=None):
190         for f in node.findall(compat_xpath(xpath)):
191             if key not in f.attrib:
192                 continue
193             if val is None or f.attrib.get(key) == val:
194                 return f
195         return None
196
197 # On python2.6 the xml.etree.ElementTree.Element methods don't support
198 # the namespace parameter
199
200
201 def xpath_with_ns(path, ns_map):
202     components = [c.split(':') for c in path.split('/')]
203     replaced = []
204     for c in components:
205         if len(c) == 1:
206             replaced.append(c[0])
207         else:
208             ns, tag = c
209             replaced.append('{%s}%s' % (ns_map[ns], tag))
210     return '/'.join(replaced)
211
212
213 def xpath_element(node, xpath, name=None, fatal=False, default=NO_DEFAULT):
214     def _find_xpath(xpath):
215         return node.find(compat_xpath(xpath))
216
217     if isinstance(xpath, (str, compat_str)):
218         n = _find_xpath(xpath)
219     else:
220         for xp in xpath:
221             n = _find_xpath(xp)
222             if n is not None:
223                 break
224
225     if n is None:
226         if default is not NO_DEFAULT:
227             return default
228         elif fatal:
229             name = xpath if name is None else name
230             raise ExtractorError('Could not find XML element %s' % name)
231         else:
232             return None
233     return n
234
235
236 def xpath_text(node, xpath, name=None, fatal=False, default=NO_DEFAULT):
237     n = xpath_element(node, xpath, name, fatal=fatal, default=default)
238     if n is None or n == default:
239         return n
240     if n.text is None:
241         if default is not NO_DEFAULT:
242             return default
243         elif fatal:
244             name = xpath if name is None else name
245             raise ExtractorError('Could not find XML element\'s text %s' % name)
246         else:
247             return None
248     return n.text
249
250
251 def xpath_attr(node, xpath, key, name=None, fatal=False, default=NO_DEFAULT):
252     n = find_xpath_attr(node, xpath, key)
253     if n is None:
254         if default is not NO_DEFAULT:
255             return default
256         elif fatal:
257             name = '%s[@%s]' % (xpath, key) if name is None else name
258             raise ExtractorError('Could not find XML attribute %s' % name)
259         else:
260             return None
261     return n.attrib[key]
262
263
264 def get_element_by_id(id, html):
265     """Return the content of the tag with the specified ID in the passed HTML document"""
266     return get_element_by_attribute('id', id, html)
267
268
269 def get_element_by_attribute(attribute, value, html):
270     """Return the content of the tag with the specified attribute in the passed HTML document"""
271
272     m = re.search(r'''(?xs)
273         <([a-zA-Z0-9:._-]+)
274          (?:\s+[a-zA-Z0-9:._-]+(?:=[a-zA-Z0-9:._-]*|="[^"]*"|='[^']*'))*?
275          \s+%s=['"]?%s['"]?
276          (?:\s+[a-zA-Z0-9:._-]+(?:=[a-zA-Z0-9:._-]*|="[^"]*"|='[^']*'))*?
277         \s*>
278         (?P<content>.*?)
279         </\1>
280     ''' % (re.escape(attribute), re.escape(value)), html)
281
282     if not m:
283         return None
284     res = m.group('content')
285
286     if res.startswith('"') or res.startswith("'"):
287         res = res[1:-1]
288
289     return unescapeHTML(res)
290
291
292 class HTMLAttributeParser(compat_HTMLParser):
293     """Trivial HTML parser to gather the attributes for a single element"""
294     def __init__(self):
295         self.attrs = {}
296         compat_HTMLParser.__init__(self)
297
298     def handle_starttag(self, tag, attrs):
299         self.attrs = dict(attrs)
300
301
302 def extract_attributes(html_element):
303     """Given a string for an HTML element such as
304     <el
305          a="foo" B="bar" c="&98;az" d=boz
306          empty= noval entity="&amp;"
307          sq='"' dq="'"
308     >
309     Decode and return a dictionary of attributes.
310     {
311         'a': 'foo', 'b': 'bar', c: 'baz', d: 'boz',
312         'empty': '', 'noval': None, 'entity': '&',
313         'sq': '"', 'dq': '\''
314     }.
315     NB HTMLParser is stricter in Python 2.6 & 3.2 than in later versions,
316     but the cases in the unit test will work for all of 2.6, 2.7, 3.2-3.5.
317     """
318     parser = HTMLAttributeParser()
319     parser.feed(html_element)
320     parser.close()
321     return parser.attrs
322
323
324 def clean_html(html):
325     """Clean an HTML snippet into a readable string"""
326
327     if html is None:  # Convenience for sanitizing descriptions etc.
328         return html
329
330     # Newline vs <br />
331     html = html.replace('\n', ' ')
332     html = re.sub(r'\s*<\s*br\s*/?\s*>\s*', '\n', html)
333     html = re.sub(r'<\s*/\s*p\s*>\s*<\s*p[^>]*>', '\n', html)
334     # Strip html tags
335     html = re.sub('<.*?>', '', html)
336     # Replace html entities
337     html = unescapeHTML(html)
338     return html.strip()
339
340
341 def sanitize_open(filename, open_mode):
342     """Try to open the given filename, and slightly tweak it if this fails.
343
344     Attempts to open the given filename. If this fails, it tries to change
345     the filename slightly, step by step, until it's either able to open it
346     or it fails and raises a final exception, like the standard open()
347     function.
348
349     It returns the tuple (stream, definitive_file_name).
350     """
351     try:
352         if filename == '-':
353             if sys.platform == 'win32':
354                 import msvcrt
355                 msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
356             return (sys.stdout.buffer if hasattr(sys.stdout, 'buffer') else sys.stdout, filename)
357         stream = open(encodeFilename(filename), open_mode)
358         return (stream, filename)
359     except (IOError, OSError) as err:
360         if err.errno in (errno.EACCES,):
361             raise
362
363         # In case of error, try to remove win32 forbidden chars
364         alt_filename = sanitize_path(filename)
365         if alt_filename == filename:
366             raise
367         else:
368             # An exception here should be caught in the caller
369             stream = open(encodeFilename(alt_filename), open_mode)
370             return (stream, alt_filename)
371
372
373 def timeconvert(timestr):
374     """Convert RFC 2822 defined time string into system timestamp"""
375     timestamp = None
376     timetuple = email.utils.parsedate_tz(timestr)
377     if timetuple is not None:
378         timestamp = email.utils.mktime_tz(timetuple)
379     return timestamp
380
381
382 def sanitize_filename(s, restricted=False, is_id=False):
383     """Sanitizes a string so it could be used as part of a filename.
384     If restricted is set, use a stricter subset of allowed characters.
385     Set is_id if this is not an arbitrary string, but an ID that should be kept if possible
386     """
387     def replace_insane(char):
388         if restricted and char in ACCENT_CHARS:
389             return ACCENT_CHARS[char]
390         if char == '?' or ord(char) < 32 or ord(char) == 127:
391             return ''
392         elif char == '"':
393             return '' if restricted else '\''
394         elif char == ':':
395             return '_-' if restricted else ' -'
396         elif char in '\\/|*<>':
397             return '_'
398         if restricted and (char in '!&\'()[]{}$;`^,#' or char.isspace()):
399             return '_'
400         if restricted and ord(char) > 127:
401             return '_'
402         return char
403
404     # Handle timestamps
405     s = re.sub(r'[0-9]+(?::[0-9]+)+', lambda m: m.group(0).replace(':', '_'), s)
406     result = ''.join(map(replace_insane, s))
407     if not is_id:
408         while '__' in result:
409             result = result.replace('__', '_')
410         result = result.strip('_')
411         # Common case of "Foreign band name - English song title"
412         if restricted and result.startswith('-_'):
413             result = result[2:]
414         if result.startswith('-'):
415             result = '_' + result[len('-'):]
416         result = result.lstrip('.')
417         if not result:
418             result = '_'
419     return result
420
421
422 def sanitize_path(s):
423     """Sanitizes and normalizes path on Windows"""
424     if sys.platform != 'win32':
425         return s
426     drive_or_unc, _ = os.path.splitdrive(s)
427     if sys.version_info < (2, 7) and not drive_or_unc:
428         drive_or_unc, _ = os.path.splitunc(s)
429     norm_path = os.path.normpath(remove_start(s, drive_or_unc)).split(os.path.sep)
430     if drive_or_unc:
431         norm_path.pop(0)
432     sanitized_path = [
433         path_part if path_part in ['.', '..'] else re.sub('(?:[/<>:"\\|\\\\?\\*]|[\s.]$)', '#', path_part)
434         for path_part in norm_path]
435     if drive_or_unc:
436         sanitized_path.insert(0, drive_or_unc + os.path.sep)
437     return os.path.join(*sanitized_path)
438
439
440 # Prepend protocol-less URLs with `http:` scheme in order to mitigate the number of
441 # unwanted failures due to missing protocol
442 def sanitize_url(url):
443     return 'http:%s' % url if url.startswith('//') else url
444
445
446 def sanitized_Request(url, *args, **kwargs):
447     return compat_urllib_request.Request(sanitize_url(url), *args, **kwargs)
448
449
450 def orderedSet(iterable):
451     """ Remove all duplicates from the input iterable """
452     res = []
453     for el in iterable:
454         if el not in res:
455             res.append(el)
456     return res
457
458
459 def _htmlentity_transform(entity):
460     """Transforms an HTML entity to a character."""
461     # Known non-numeric HTML entity
462     if entity in compat_html_entities.name2codepoint:
463         return compat_chr(compat_html_entities.name2codepoint[entity])
464
465     mobj = re.match(r'#(x[0-9a-fA-F]+|[0-9]+)', entity)
466     if mobj is not None:
467         numstr = mobj.group(1)
468         if numstr.startswith('x'):
469             base = 16
470             numstr = '0%s' % numstr
471         else:
472             base = 10
473         # See https://github.com/rg3/youtube-dl/issues/7518
474         try:
475             return compat_chr(int(numstr, base))
476         except ValueError:
477             pass
478
479     # Unknown entity in name, return its literal representation
480     return '&%s;' % entity
481
482
483 def unescapeHTML(s):
484     if s is None:
485         return None
486     assert type(s) == compat_str
487
488     return re.sub(
489         r'&([^;]+);', lambda m: _htmlentity_transform(m.group(1)), s)
490
491
492 def get_subprocess_encoding():
493     if sys.platform == 'win32' and sys.getwindowsversion()[0] >= 5:
494         # For subprocess calls, encode with locale encoding
495         # Refer to http://stackoverflow.com/a/9951851/35070
496         encoding = preferredencoding()
497     else:
498         encoding = sys.getfilesystemencoding()
499     if encoding is None:
500         encoding = 'utf-8'
501     return encoding
502
503
504 def encodeFilename(s, for_subprocess=False):
505     """
506     @param s The name of the file
507     """
508
509     assert type(s) == compat_str
510
511     # Python 3 has a Unicode API
512     if sys.version_info >= (3, 0):
513         return s
514
515     # Pass '' directly to use Unicode APIs on Windows 2000 and up
516     # (Detecting Windows NT 4 is tricky because 'major >= 4' would
517     # match Windows 9x series as well. Besides, NT 4 is obsolete.)
518     if not for_subprocess and sys.platform == 'win32' and sys.getwindowsversion()[0] >= 5:
519         return s
520
521     # Jython assumes filenames are Unicode strings though reported as Python 2.x compatible
522     if sys.platform.startswith('java'):
523         return s
524
525     return s.encode(get_subprocess_encoding(), 'ignore')
526
527
528 def decodeFilename(b, for_subprocess=False):
529
530     if sys.version_info >= (3, 0):
531         return b
532
533     if not isinstance(b, bytes):
534         return b
535
536     return b.decode(get_subprocess_encoding(), 'ignore')
537
538
539 def encodeArgument(s):
540     if not isinstance(s, compat_str):
541         # Legacy code that uses byte strings
542         # Uncomment the following line after fixing all post processors
543         # assert False, 'Internal error: %r should be of type %r, is %r' % (s, compat_str, type(s))
544         s = s.decode('ascii')
545     return encodeFilename(s, True)
546
547
548 def decodeArgument(b):
549     return decodeFilename(b, True)
550
551
552 def decodeOption(optval):
553     if optval is None:
554         return optval
555     if isinstance(optval, bytes):
556         optval = optval.decode(preferredencoding())
557
558     assert isinstance(optval, compat_str)
559     return optval
560
561
562 def formatSeconds(secs):
563     if secs > 3600:
564         return '%d:%02d:%02d' % (secs // 3600, (secs % 3600) // 60, secs % 60)
565     elif secs > 60:
566         return '%d:%02d' % (secs // 60, secs % 60)
567     else:
568         return '%d' % secs
569
570
571 def make_HTTPS_handler(params, **kwargs):
572     opts_no_check_certificate = params.get('nocheckcertificate', False)
573     if hasattr(ssl, 'create_default_context'):  # Python >= 3.4 or 2.7.9
574         context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
575         if opts_no_check_certificate:
576             context.check_hostname = False
577             context.verify_mode = ssl.CERT_NONE
578         try:
579             return YoutubeDLHTTPSHandler(params, context=context, **kwargs)
580         except TypeError:
581             # Python 2.7.8
582             # (create_default_context present but HTTPSHandler has no context=)
583             pass
584
585     if sys.version_info < (3, 2):
586         return YoutubeDLHTTPSHandler(params, **kwargs)
587     else:  # Python < 3.4
588         context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
589         context.verify_mode = (ssl.CERT_NONE
590                                if opts_no_check_certificate
591                                else ssl.CERT_REQUIRED)
592         context.set_default_verify_paths()
593         return YoutubeDLHTTPSHandler(params, context=context, **kwargs)
594
595
596 def bug_reports_message():
597     if ytdl_is_updateable():
598         update_cmd = 'type  youtube-dl -U  to update'
599     else:
600         update_cmd = 'see  https://yt-dl.org/update  on how to update'
601     msg = '; please report this issue on https://yt-dl.org/bug .'
602     msg += ' Make sure you are using the latest version; %s.' % update_cmd
603     msg += ' Be sure to call youtube-dl with the --verbose flag and include its complete output.'
604     return msg
605
606
607 class ExtractorError(Exception):
608     """Error during info extraction."""
609
610     def __init__(self, msg, tb=None, expected=False, cause=None, video_id=None):
611         """ tb, if given, is the original traceback (so that it can be printed out).
612         If expected is set, this is a normal error message and most likely not a bug in youtube-dl.
613         """
614
615         if sys.exc_info()[0] in (compat_urllib_error.URLError, socket.timeout, UnavailableVideoError):
616             expected = True
617         if video_id is not None:
618             msg = video_id + ': ' + msg
619         if cause:
620             msg += ' (caused by %r)' % cause
621         if not expected:
622             msg += bug_reports_message()
623         super(ExtractorError, self).__init__(msg)
624
625         self.traceback = tb
626         self.exc_info = sys.exc_info()  # preserve original exception
627         self.cause = cause
628         self.video_id = video_id
629
630     def format_traceback(self):
631         if self.traceback is None:
632             return None
633         return ''.join(traceback.format_tb(self.traceback))
634
635
636 class UnsupportedError(ExtractorError):
637     def __init__(self, url):
638         super(UnsupportedError, self).__init__(
639             'Unsupported URL: %s' % url, expected=True)
640         self.url = url
641
642
643 class RegexNotFoundError(ExtractorError):
644     """Error when a regex didn't match"""
645     pass
646
647
648 class DownloadError(Exception):
649     """Download Error exception.
650
651     This exception may be thrown by FileDownloader objects if they are not
652     configured to continue on errors. They will contain the appropriate
653     error message.
654     """
655
656     def __init__(self, msg, exc_info=None):
657         """ exc_info, if given, is the original exception that caused the trouble (as returned by sys.exc_info()). """
658         super(DownloadError, self).__init__(msg)
659         self.exc_info = exc_info
660
661
662 class SameFileError(Exception):
663     """Same File exception.
664
665     This exception will be thrown by FileDownloader objects if they detect
666     multiple files would have to be downloaded to the same file on disk.
667     """
668     pass
669
670
671 class PostProcessingError(Exception):
672     """Post Processing exception.
673
674     This exception may be raised by PostProcessor's .run() method to
675     indicate an error in the postprocessing task.
676     """
677
678     def __init__(self, msg):
679         self.msg = msg
680
681
682 class MaxDownloadsReached(Exception):
683     """ --max-downloads limit has been reached. """
684     pass
685
686
687 class UnavailableVideoError(Exception):
688     """Unavailable Format exception.
689
690     This exception will be thrown when a video is requested
691     in a format that is not available for that video.
692     """
693     pass
694
695
696 class ContentTooShortError(Exception):
697     """Content Too Short exception.
698
699     This exception may be raised by FileDownloader objects when a file they
700     download is too small for what the server announced first, indicating
701     the connection was probably interrupted.
702     """
703
704     def __init__(self, downloaded, expected):
705         # Both in bytes
706         self.downloaded = downloaded
707         self.expected = expected
708
709
710 def _create_http_connection(ydl_handler, http_class, is_https, *args, **kwargs):
711     # Working around python 2 bug (see http://bugs.python.org/issue17849) by limiting
712     # expected HTTP responses to meet HTTP/1.0 or later (see also
713     # https://github.com/rg3/youtube-dl/issues/6727)
714     if sys.version_info < (3, 0):
715         kwargs[b'strict'] = True
716     hc = http_class(*args, **kwargs)
717     source_address = ydl_handler._params.get('source_address')
718     if source_address is not None:
719         sa = (source_address, 0)
720         if hasattr(hc, 'source_address'):  # Python 2.7+
721             hc.source_address = sa
722         else:  # Python 2.6
723             def _hc_connect(self, *args, **kwargs):
724                 sock = compat_socket_create_connection(
725                     (self.host, self.port), self.timeout, sa)
726                 if is_https:
727                     self.sock = ssl.wrap_socket(
728                         sock, self.key_file, self.cert_file,
729                         ssl_version=ssl.PROTOCOL_TLSv1)
730                 else:
731                     self.sock = sock
732             hc.connect = functools.partial(_hc_connect, hc)
733
734     return hc
735
736
737 def handle_youtubedl_headers(headers):
738     filtered_headers = headers
739
740     if 'Youtubedl-no-compression' in filtered_headers:
741         filtered_headers = dict((k, v) for k, v in filtered_headers.items() if k.lower() != 'accept-encoding')
742         del filtered_headers['Youtubedl-no-compression']
743
744     return filtered_headers
745
746
747 class YoutubeDLHandler(compat_urllib_request.HTTPHandler):
748     """Handler for HTTP requests and responses.
749
750     This class, when installed with an OpenerDirector, automatically adds
751     the standard headers to every HTTP request and handles gzipped and
752     deflated responses from web servers. If compression is to be avoided in
753     a particular request, the original request in the program code only has
754     to include the HTTP header "Youtubedl-no-compression", which will be
755     removed before making the real request.
756
757     Part of this code was copied from:
758
759     http://techknack.net/python-urllib2-handlers/
760
761     Andrew Rowls, the author of that code, agreed to release it to the
762     public domain.
763     """
764
765     def __init__(self, params, *args, **kwargs):
766         compat_urllib_request.HTTPHandler.__init__(self, *args, **kwargs)
767         self._params = params
768
769     def http_open(self, req):
770         conn_class = compat_http_client.HTTPConnection
771
772         socks_proxy = req.headers.get('Ytdl-socks-proxy')
773         if socks_proxy:
774             conn_class = make_socks_conn_class(conn_class, socks_proxy)
775             del req.headers['Ytdl-socks-proxy']
776
777         return self.do_open(functools.partial(
778             _create_http_connection, self, conn_class, False),
779             req)
780
781     @staticmethod
782     def deflate(data):
783         try:
784             return zlib.decompress(data, -zlib.MAX_WBITS)
785         except zlib.error:
786             return zlib.decompress(data)
787
788     @staticmethod
789     def addinfourl_wrapper(stream, headers, url, code):
790         if hasattr(compat_urllib_request.addinfourl, 'getcode'):
791             return compat_urllib_request.addinfourl(stream, headers, url, code)
792         ret = compat_urllib_request.addinfourl(stream, headers, url)
793         ret.code = code
794         return ret
795
796     def http_request(self, req):
797         # According to RFC 3986, URLs can not contain non-ASCII characters, however this is not
798         # always respected by websites, some tend to give out URLs with non percent-encoded
799         # non-ASCII characters (see telemb.py, ard.py [#3412])
800         # urllib chokes on URLs with non-ASCII characters (see http://bugs.python.org/issue3991)
801         # To work around aforementioned issue we will replace request's original URL with
802         # percent-encoded one
803         # Since redirects are also affected (e.g. http://www.southpark.de/alle-episoden/s18e09)
804         # the code of this workaround has been moved here from YoutubeDL.urlopen()
805         url = req.get_full_url()
806         url_escaped = escape_url(url)
807
808         # Substitute URL if any change after escaping
809         if url != url_escaped:
810             req = update_Request(req, url=url_escaped)
811
812         for h, v in std_headers.items():
813             # Capitalize is needed because of Python bug 2275: http://bugs.python.org/issue2275
814             # The dict keys are capitalized because of this bug by urllib
815             if h.capitalize() not in req.headers:
816                 req.add_header(h, v)
817
818         req.headers = handle_youtubedl_headers(req.headers)
819
820         if sys.version_info < (2, 7) and '#' in req.get_full_url():
821             # Python 2.6 is brain-dead when it comes to fragments
822             req._Request__original = req._Request__original.partition('#')[0]
823             req._Request__r_type = req._Request__r_type.partition('#')[0]
824
825         return req
826
827     def http_response(self, req, resp):
828         old_resp = resp
829         # gzip
830         if resp.headers.get('Content-encoding', '') == 'gzip':
831             content = resp.read()
832             gz = gzip.GzipFile(fileobj=io.BytesIO(content), mode='rb')
833             try:
834                 uncompressed = io.BytesIO(gz.read())
835             except IOError as original_ioerror:
836                 # There may be junk add the end of the file
837                 # See http://stackoverflow.com/q/4928560/35070 for details
838                 for i in range(1, 1024):
839                     try:
840                         gz = gzip.GzipFile(fileobj=io.BytesIO(content[:-i]), mode='rb')
841                         uncompressed = io.BytesIO(gz.read())
842                     except IOError:
843                         continue
844                     break
845                 else:
846                     raise original_ioerror
847             resp = self.addinfourl_wrapper(uncompressed, old_resp.headers, old_resp.url, old_resp.code)
848             resp.msg = old_resp.msg
849             del resp.headers['Content-encoding']
850         # deflate
851         if resp.headers.get('Content-encoding', '') == 'deflate':
852             gz = io.BytesIO(self.deflate(resp.read()))
853             resp = self.addinfourl_wrapper(gz, old_resp.headers, old_resp.url, old_resp.code)
854             resp.msg = old_resp.msg
855             del resp.headers['Content-encoding']
856         # Percent-encode redirect URL of Location HTTP header to satisfy RFC 3986 (see
857         # https://github.com/rg3/youtube-dl/issues/6457).
858         if 300 <= resp.code < 400:
859             location = resp.headers.get('Location')
860             if location:
861                 # As of RFC 2616 default charset is iso-8859-1 that is respected by python 3
862                 if sys.version_info >= (3, 0):
863                     location = location.encode('iso-8859-1').decode('utf-8')
864                 location_escaped = escape_url(location)
865                 if location != location_escaped:
866                     del resp.headers['Location']
867                     resp.headers['Location'] = location_escaped
868         return resp
869
870     https_request = http_request
871     https_response = http_response
872
873
874 def make_socks_conn_class(base_class, socks_proxy):
875     assert issubclass(base_class, (
876         compat_http_client.HTTPConnection, compat_http_client.HTTPSConnection))
877
878     url_components = compat_urlparse.urlparse(socks_proxy)
879     if url_components.scheme.lower() == 'socks5':
880         socks_type = ProxyType.SOCKS5
881     elif url_components.scheme.lower() in ('socks', 'socks4'):
882         socks_type = ProxyType.SOCKS4
883     elif url_components.scheme.lower() == 'socks4a':
884         socks_type = ProxyType.SOCKS4A
885
886     def unquote_if_non_empty(s):
887         if not s:
888             return s
889         return compat_urllib_parse_unquote_plus(s)
890
891     proxy_args = (
892         socks_type,
893         url_components.hostname, url_components.port or 1080,
894         True,  # Remote DNS
895         unquote_if_non_empty(url_components.username),
896         unquote_if_non_empty(url_components.password),
897     )
898
899     class SocksConnection(base_class):
900         def connect(self):
901             self.sock = sockssocket()
902             self.sock.setproxy(*proxy_args)
903             if type(self.timeout) in (int, float):
904                 self.sock.settimeout(self.timeout)
905             self.sock.connect((self.host, self.port))
906
907             if isinstance(self, compat_http_client.HTTPSConnection):
908                 if hasattr(self, '_context'):  # Python > 2.6
909                     self.sock = self._context.wrap_socket(
910                         self.sock, server_hostname=self.host)
911                 else:
912                     self.sock = ssl.wrap_socket(self.sock)
913
914     return SocksConnection
915
916
917 class YoutubeDLHTTPSHandler(compat_urllib_request.HTTPSHandler):
918     def __init__(self, params, https_conn_class=None, *args, **kwargs):
919         compat_urllib_request.HTTPSHandler.__init__(self, *args, **kwargs)
920         self._https_conn_class = https_conn_class or compat_http_client.HTTPSConnection
921         self._params = params
922
923     def https_open(self, req):
924         kwargs = {}
925         conn_class = self._https_conn_class
926
927         if hasattr(self, '_context'):  # python > 2.6
928             kwargs['context'] = self._context
929         if hasattr(self, '_check_hostname'):  # python 3.x
930             kwargs['check_hostname'] = self._check_hostname
931
932         socks_proxy = req.headers.get('Ytdl-socks-proxy')
933         if socks_proxy:
934             conn_class = make_socks_conn_class(conn_class, socks_proxy)
935             del req.headers['Ytdl-socks-proxy']
936
937         return self.do_open(functools.partial(
938             _create_http_connection, self, conn_class, True),
939             req, **kwargs)
940
941
942 class YoutubeDLCookieProcessor(compat_urllib_request.HTTPCookieProcessor):
943     def __init__(self, cookiejar=None):
944         compat_urllib_request.HTTPCookieProcessor.__init__(self, cookiejar)
945
946     def http_response(self, request, response):
947         # Python 2 will choke on next HTTP request in row if there are non-ASCII
948         # characters in Set-Cookie HTTP header of last response (see
949         # https://github.com/rg3/youtube-dl/issues/6769).
950         # In order to at least prevent crashing we will percent encode Set-Cookie
951         # header before HTTPCookieProcessor starts processing it.
952         # if sys.version_info < (3, 0) and response.headers:
953         #     for set_cookie_header in ('Set-Cookie', 'Set-Cookie2'):
954         #         set_cookie = response.headers.get(set_cookie_header)
955         #         if set_cookie:
956         #             set_cookie_escaped = compat_urllib_parse.quote(set_cookie, b"%/;:@&=+$,!~*'()?#[] ")
957         #             if set_cookie != set_cookie_escaped:
958         #                 del response.headers[set_cookie_header]
959         #                 response.headers[set_cookie_header] = set_cookie_escaped
960         return compat_urllib_request.HTTPCookieProcessor.http_response(self, request, response)
961
962     https_request = compat_urllib_request.HTTPCookieProcessor.http_request
963     https_response = http_response
964
965
966 def parse_iso8601(date_str, delimiter='T', timezone=None):
967     """ Return a UNIX timestamp from the given date """
968
969     if date_str is None:
970         return None
971
972     date_str = re.sub(r'\.[0-9]+', '', date_str)
973
974     if timezone is None:
975         m = re.search(
976             r'(?:Z$| ?(?P<sign>\+|-)(?P<hours>[0-9]{2}):?(?P<minutes>[0-9]{2})$)',
977             date_str)
978         if not m:
979             timezone = datetime.timedelta()
980         else:
981             date_str = date_str[:-len(m.group(0))]
982             if not m.group('sign'):
983                 timezone = datetime.timedelta()
984             else:
985                 sign = 1 if m.group('sign') == '+' else -1
986                 timezone = datetime.timedelta(
987                     hours=sign * int(m.group('hours')),
988                     minutes=sign * int(m.group('minutes')))
989     try:
990         date_format = '%Y-%m-%d{0}%H:%M:%S'.format(delimiter)
991         dt = datetime.datetime.strptime(date_str, date_format) - timezone
992         return calendar.timegm(dt.timetuple())
993     except ValueError:
994         pass
995
996
997 def unified_strdate(date_str, day_first=True):
998     """Return a string with the date in the format YYYYMMDD"""
999
1000     if date_str is None:
1001         return None
1002     upload_date = None
1003     # Replace commas
1004     date_str = date_str.replace(',', ' ')
1005     # %z (UTC offset) is only supported in python>=3.2
1006     if not re.match(r'^[0-9]{1,2}-[0-9]{1,2}-[0-9]{4}$', date_str):
1007         date_str = re.sub(r' ?(\+|-)[0-9]{2}:?[0-9]{2}$', '', date_str)
1008     # Remove AM/PM + timezone
1009     date_str = re.sub(r'(?i)\s*(?:AM|PM)(?:\s+[A-Z]+)?', '', date_str)
1010
1011     format_expressions = [
1012         '%d %B %Y',
1013         '%d %b %Y',
1014         '%B %d %Y',
1015         '%b %d %Y',
1016         '%b %dst %Y %I:%M',
1017         '%b %dnd %Y %I:%M',
1018         '%b %dth %Y %I:%M',
1019         '%Y %m %d',
1020         '%Y-%m-%d',
1021         '%Y/%m/%d',
1022         '%Y/%m/%d %H:%M:%S',
1023         '%Y-%m-%d %H:%M:%S',
1024         '%Y-%m-%d %H:%M:%S.%f',
1025         '%d.%m.%Y %H:%M',
1026         '%d.%m.%Y %H.%M',
1027         '%Y-%m-%dT%H:%M:%SZ',
1028         '%Y-%m-%dT%H:%M:%S.%fZ',
1029         '%Y-%m-%dT%H:%M:%S.%f0Z',
1030         '%Y-%m-%dT%H:%M:%S',
1031         '%Y-%m-%dT%H:%M:%S.%f',
1032         '%Y-%m-%dT%H:%M',
1033     ]
1034     if day_first:
1035         format_expressions.extend([
1036             '%d-%m-%Y',
1037             '%d.%m.%Y',
1038             '%d/%m/%Y',
1039             '%d/%m/%y',
1040             '%d/%m/%Y %H:%M:%S',
1041         ])
1042     else:
1043         format_expressions.extend([
1044             '%m-%d-%Y',
1045             '%m.%d.%Y',
1046             '%m/%d/%Y',
1047             '%m/%d/%y',
1048             '%m/%d/%Y %H:%M:%S',
1049         ])
1050     for expression in format_expressions:
1051         try:
1052             upload_date = datetime.datetime.strptime(date_str, expression).strftime('%Y%m%d')
1053         except ValueError:
1054             pass
1055     if upload_date is None:
1056         timetuple = email.utils.parsedate_tz(date_str)
1057         if timetuple:
1058             try:
1059                 upload_date = datetime.datetime(*timetuple[:6]).strftime('%Y%m%d')
1060             except ValueError:
1061                 pass
1062     if upload_date is not None:
1063         return compat_str(upload_date)
1064
1065
1066 def determine_ext(url, default_ext='unknown_video'):
1067     if url is None:
1068         return default_ext
1069     guess = url.partition('?')[0].rpartition('.')[2]
1070     if re.match(r'^[A-Za-z0-9]+$', guess):
1071         return guess
1072     # Try extract ext from URLs like http://example.com/foo/bar.mp4/?download
1073     elif guess.rstrip('/') in KNOWN_EXTENSIONS:
1074         return guess.rstrip('/')
1075     else:
1076         return default_ext
1077
1078
1079 def subtitles_filename(filename, sub_lang, sub_format):
1080     return filename.rsplit('.', 1)[0] + '.' + sub_lang + '.' + sub_format
1081
1082
1083 def date_from_str(date_str):
1084     """
1085     Return a datetime object from a string in the format YYYYMMDD or
1086     (now|today)[+-][0-9](day|week|month|year)(s)?"""
1087     today = datetime.date.today()
1088     if date_str in ('now', 'today'):
1089         return today
1090     if date_str == 'yesterday':
1091         return today - datetime.timedelta(days=1)
1092     match = re.match('(now|today)(?P<sign>[+-])(?P<time>\d+)(?P<unit>day|week|month|year)(s)?', date_str)
1093     if match is not None:
1094         sign = match.group('sign')
1095         time = int(match.group('time'))
1096         if sign == '-':
1097             time = -time
1098         unit = match.group('unit')
1099         # A bad approximation?
1100         if unit == 'month':
1101             unit = 'day'
1102             time *= 30
1103         elif unit == 'year':
1104             unit = 'day'
1105             time *= 365
1106         unit += 's'
1107         delta = datetime.timedelta(**{unit: time})
1108         return today + delta
1109     return datetime.datetime.strptime(date_str, '%Y%m%d').date()
1110
1111
1112 def hyphenate_date(date_str):
1113     """
1114     Convert a date in 'YYYYMMDD' format to 'YYYY-MM-DD' format"""
1115     match = re.match(r'^(\d\d\d\d)(\d\d)(\d\d)$', date_str)
1116     if match is not None:
1117         return '-'.join(match.groups())
1118     else:
1119         return date_str
1120
1121
1122 class DateRange(object):
1123     """Represents a time interval between two dates"""
1124
1125     def __init__(self, start=None, end=None):
1126         """start and end must be strings in the format accepted by date"""
1127         if start is not None:
1128             self.start = date_from_str(start)
1129         else:
1130             self.start = datetime.datetime.min.date()
1131         if end is not None:
1132             self.end = date_from_str(end)
1133         else:
1134             self.end = datetime.datetime.max.date()
1135         if self.start > self.end:
1136             raise ValueError('Date range: "%s" , the start date must be before the end date' % self)
1137
1138     @classmethod
1139     def day(cls, day):
1140         """Returns a range that only contains the given day"""
1141         return cls(day, day)
1142
1143     def __contains__(self, date):
1144         """Check if the date is in the range"""
1145         if not isinstance(date, datetime.date):
1146             date = date_from_str(date)
1147         return self.start <= date <= self.end
1148
1149     def __str__(self):
1150         return '%s - %s' % (self.start.isoformat(), self.end.isoformat())
1151
1152
1153 def platform_name():
1154     """ Returns the platform name as a compat_str """
1155     res = platform.platform()
1156     if isinstance(res, bytes):
1157         res = res.decode(preferredencoding())
1158
1159     assert isinstance(res, compat_str)
1160     return res
1161
1162
1163 def _windows_write_string(s, out):
1164     """ Returns True if the string was written using special methods,
1165     False if it has yet to be written out."""
1166     # Adapted from http://stackoverflow.com/a/3259271/35070
1167
1168     import ctypes
1169     import ctypes.wintypes
1170
1171     WIN_OUTPUT_IDS = {
1172         1: -11,
1173         2: -12,
1174     }
1175
1176     try:
1177         fileno = out.fileno()
1178     except AttributeError:
1179         # If the output stream doesn't have a fileno, it's virtual
1180         return False
1181     except io.UnsupportedOperation:
1182         # Some strange Windows pseudo files?
1183         return False
1184     if fileno not in WIN_OUTPUT_IDS:
1185         return False
1186
1187     GetStdHandle = ctypes.WINFUNCTYPE(
1188         ctypes.wintypes.HANDLE, ctypes.wintypes.DWORD)(
1189         (b'GetStdHandle', ctypes.windll.kernel32))
1190     h = GetStdHandle(WIN_OUTPUT_IDS[fileno])
1191
1192     WriteConsoleW = ctypes.WINFUNCTYPE(
1193         ctypes.wintypes.BOOL, ctypes.wintypes.HANDLE, ctypes.wintypes.LPWSTR,
1194         ctypes.wintypes.DWORD, ctypes.POINTER(ctypes.wintypes.DWORD),
1195         ctypes.wintypes.LPVOID)((b'WriteConsoleW', ctypes.windll.kernel32))
1196     written = ctypes.wintypes.DWORD(0)
1197
1198     GetFileType = ctypes.WINFUNCTYPE(ctypes.wintypes.DWORD, ctypes.wintypes.DWORD)((b'GetFileType', ctypes.windll.kernel32))
1199     FILE_TYPE_CHAR = 0x0002
1200     FILE_TYPE_REMOTE = 0x8000
1201     GetConsoleMode = ctypes.WINFUNCTYPE(
1202         ctypes.wintypes.BOOL, ctypes.wintypes.HANDLE,
1203         ctypes.POINTER(ctypes.wintypes.DWORD))(
1204         (b'GetConsoleMode', ctypes.windll.kernel32))
1205     INVALID_HANDLE_VALUE = ctypes.wintypes.DWORD(-1).value
1206
1207     def not_a_console(handle):
1208         if handle == INVALID_HANDLE_VALUE or handle is None:
1209             return True
1210         return ((GetFileType(handle) & ~FILE_TYPE_REMOTE) != FILE_TYPE_CHAR or
1211                 GetConsoleMode(handle, ctypes.byref(ctypes.wintypes.DWORD())) == 0)
1212
1213     if not_a_console(h):
1214         return False
1215
1216     def next_nonbmp_pos(s):
1217         try:
1218             return next(i for i, c in enumerate(s) if ord(c) > 0xffff)
1219         except StopIteration:
1220             return len(s)
1221
1222     while s:
1223         count = min(next_nonbmp_pos(s), 1024)
1224
1225         ret = WriteConsoleW(
1226             h, s, count if count else 2, ctypes.byref(written), None)
1227         if ret == 0:
1228             raise OSError('Failed to write string')
1229         if not count:  # We just wrote a non-BMP character
1230             assert written.value == 2
1231             s = s[1:]
1232         else:
1233             assert written.value > 0
1234             s = s[written.value:]
1235     return True
1236
1237
1238 def write_string(s, out=None, encoding=None):
1239     if out is None:
1240         out = sys.stderr
1241     assert type(s) == compat_str
1242
1243     if sys.platform == 'win32' and encoding is None and hasattr(out, 'fileno'):
1244         if _windows_write_string(s, out):
1245             return
1246
1247     if ('b' in getattr(out, 'mode', '') or
1248             sys.version_info[0] < 3):  # Python 2 lies about mode of sys.stderr
1249         byt = s.encode(encoding or preferredencoding(), 'ignore')
1250         out.write(byt)
1251     elif hasattr(out, 'buffer'):
1252         enc = encoding or getattr(out, 'encoding', None) or preferredencoding()
1253         byt = s.encode(enc, 'ignore')
1254         out.buffer.write(byt)
1255     else:
1256         out.write(s)
1257     out.flush()
1258
1259
1260 def bytes_to_intlist(bs):
1261     if not bs:
1262         return []
1263     if isinstance(bs[0], int):  # Python 3
1264         return list(bs)
1265     else:
1266         return [ord(c) for c in bs]
1267
1268
1269 def intlist_to_bytes(xs):
1270     if not xs:
1271         return b''
1272     return compat_struct_pack('%dB' % len(xs), *xs)
1273
1274
1275 # Cross-platform file locking
1276 if sys.platform == 'win32':
1277     import ctypes.wintypes
1278     import msvcrt
1279
1280     class OVERLAPPED(ctypes.Structure):
1281         _fields_ = [
1282             ('Internal', ctypes.wintypes.LPVOID),
1283             ('InternalHigh', ctypes.wintypes.LPVOID),
1284             ('Offset', ctypes.wintypes.DWORD),
1285             ('OffsetHigh', ctypes.wintypes.DWORD),
1286             ('hEvent', ctypes.wintypes.HANDLE),
1287         ]
1288
1289     kernel32 = ctypes.windll.kernel32
1290     LockFileEx = kernel32.LockFileEx
1291     LockFileEx.argtypes = [
1292         ctypes.wintypes.HANDLE,     # hFile
1293         ctypes.wintypes.DWORD,      # dwFlags
1294         ctypes.wintypes.DWORD,      # dwReserved
1295         ctypes.wintypes.DWORD,      # nNumberOfBytesToLockLow
1296         ctypes.wintypes.DWORD,      # nNumberOfBytesToLockHigh
1297         ctypes.POINTER(OVERLAPPED)  # Overlapped
1298     ]
1299     LockFileEx.restype = ctypes.wintypes.BOOL
1300     UnlockFileEx = kernel32.UnlockFileEx
1301     UnlockFileEx.argtypes = [
1302         ctypes.wintypes.HANDLE,     # hFile
1303         ctypes.wintypes.DWORD,      # dwReserved
1304         ctypes.wintypes.DWORD,      # nNumberOfBytesToLockLow
1305         ctypes.wintypes.DWORD,      # nNumberOfBytesToLockHigh
1306         ctypes.POINTER(OVERLAPPED)  # Overlapped
1307     ]
1308     UnlockFileEx.restype = ctypes.wintypes.BOOL
1309     whole_low = 0xffffffff
1310     whole_high = 0x7fffffff
1311
1312     def _lock_file(f, exclusive):
1313         overlapped = OVERLAPPED()
1314         overlapped.Offset = 0
1315         overlapped.OffsetHigh = 0
1316         overlapped.hEvent = 0
1317         f._lock_file_overlapped_p = ctypes.pointer(overlapped)
1318         handle = msvcrt.get_osfhandle(f.fileno())
1319         if not LockFileEx(handle, 0x2 if exclusive else 0x0, 0,
1320                           whole_low, whole_high, f._lock_file_overlapped_p):
1321             raise OSError('Locking file failed: %r' % ctypes.FormatError())
1322
1323     def _unlock_file(f):
1324         assert f._lock_file_overlapped_p
1325         handle = msvcrt.get_osfhandle(f.fileno())
1326         if not UnlockFileEx(handle, 0,
1327                             whole_low, whole_high, f._lock_file_overlapped_p):
1328             raise OSError('Unlocking file failed: %r' % ctypes.FormatError())
1329
1330 else:
1331     # Some platforms, such as Jython, is missing fcntl
1332     try:
1333         import fcntl
1334
1335         def _lock_file(f, exclusive):
1336             fcntl.flock(f, fcntl.LOCK_EX if exclusive else fcntl.LOCK_SH)
1337
1338         def _unlock_file(f):
1339             fcntl.flock(f, fcntl.LOCK_UN)
1340     except ImportError:
1341         UNSUPPORTED_MSG = 'file locking is not supported on this platform'
1342
1343         def _lock_file(f, exclusive):
1344             raise IOError(UNSUPPORTED_MSG)
1345
1346         def _unlock_file(f):
1347             raise IOError(UNSUPPORTED_MSG)
1348
1349
1350 class locked_file(object):
1351     def __init__(self, filename, mode, encoding=None):
1352         assert mode in ['r', 'a', 'w']
1353         self.f = io.open(filename, mode, encoding=encoding)
1354         self.mode = mode
1355
1356     def __enter__(self):
1357         exclusive = self.mode != 'r'
1358         try:
1359             _lock_file(self.f, exclusive)
1360         except IOError:
1361             self.f.close()
1362             raise
1363         return self
1364
1365     def __exit__(self, etype, value, traceback):
1366         try:
1367             _unlock_file(self.f)
1368         finally:
1369             self.f.close()
1370
1371     def __iter__(self):
1372         return iter(self.f)
1373
1374     def write(self, *args):
1375         return self.f.write(*args)
1376
1377     def read(self, *args):
1378         return self.f.read(*args)
1379
1380
1381 def get_filesystem_encoding():
1382     encoding = sys.getfilesystemencoding()
1383     return encoding if encoding is not None else 'utf-8'
1384
1385
1386 def shell_quote(args):
1387     quoted_args = []
1388     encoding = get_filesystem_encoding()
1389     for a in args:
1390         if isinstance(a, bytes):
1391             # We may get a filename encoded with 'encodeFilename'
1392             a = a.decode(encoding)
1393         quoted_args.append(pipes.quote(a))
1394     return ' '.join(quoted_args)
1395
1396
1397 def smuggle_url(url, data):
1398     """ Pass additional data in a URL for internal use. """
1399
1400     sdata = compat_urllib_parse_urlencode(
1401         {'__youtubedl_smuggle': json.dumps(data)})
1402     return url + '#' + sdata
1403
1404
1405 def unsmuggle_url(smug_url, default=None):
1406     if '#__youtubedl_smuggle' not in smug_url:
1407         return smug_url, default
1408     url, _, sdata = smug_url.rpartition('#')
1409     jsond = compat_parse_qs(sdata)['__youtubedl_smuggle'][0]
1410     data = json.loads(jsond)
1411     return url, data
1412
1413
1414 def format_bytes(bytes):
1415     if bytes is None:
1416         return 'N/A'
1417     if type(bytes) is str:
1418         bytes = float(bytes)
1419     if bytes == 0.0:
1420         exponent = 0
1421     else:
1422         exponent = int(math.log(bytes, 1024.0))
1423     suffix = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'][exponent]
1424     converted = float(bytes) / float(1024 ** exponent)
1425     return '%.2f%s' % (converted, suffix)
1426
1427
1428 def lookup_unit_table(unit_table, s):
1429     units_re = '|'.join(re.escape(u) for u in unit_table)
1430     m = re.match(
1431         r'(?P<num>[0-9]+(?:[,.][0-9]*)?)\s*(?P<unit>%s)\b' % units_re, s)
1432     if not m:
1433         return None
1434     num_str = m.group('num').replace(',', '.')
1435     mult = unit_table[m.group('unit')]
1436     return int(float(num_str) * mult)
1437
1438
1439 def parse_filesize(s):
1440     if s is None:
1441         return None
1442
1443     # The lower-case forms are of course incorrect and unofficial,
1444     # but we support those too
1445     _UNIT_TABLE = {
1446         'B': 1,
1447         'b': 1,
1448         'KiB': 1024,
1449         'KB': 1000,
1450         'kB': 1024,
1451         'Kb': 1000,
1452         'MiB': 1024 ** 2,
1453         'MB': 1000 ** 2,
1454         'mB': 1024 ** 2,
1455         'Mb': 1000 ** 2,
1456         'GiB': 1024 ** 3,
1457         'GB': 1000 ** 3,
1458         'gB': 1024 ** 3,
1459         'Gb': 1000 ** 3,
1460         'TiB': 1024 ** 4,
1461         'TB': 1000 ** 4,
1462         'tB': 1024 ** 4,
1463         'Tb': 1000 ** 4,
1464         'PiB': 1024 ** 5,
1465         'PB': 1000 ** 5,
1466         'pB': 1024 ** 5,
1467         'Pb': 1000 ** 5,
1468         'EiB': 1024 ** 6,
1469         'EB': 1000 ** 6,
1470         'eB': 1024 ** 6,
1471         'Eb': 1000 ** 6,
1472         'ZiB': 1024 ** 7,
1473         'ZB': 1000 ** 7,
1474         'zB': 1024 ** 7,
1475         'Zb': 1000 ** 7,
1476         'YiB': 1024 ** 8,
1477         'YB': 1000 ** 8,
1478         'yB': 1024 ** 8,
1479         'Yb': 1000 ** 8,
1480     }
1481
1482     return lookup_unit_table(_UNIT_TABLE, s)
1483
1484
1485 def parse_count(s):
1486     if s is None:
1487         return None
1488
1489     s = s.strip()
1490
1491     if re.match(r'^[\d,.]+$', s):
1492         return str_to_int(s)
1493
1494     _UNIT_TABLE = {
1495         'k': 1000,
1496         'K': 1000,
1497         'm': 1000 ** 2,
1498         'M': 1000 ** 2,
1499         'kk': 1000 ** 2,
1500         'KK': 1000 ** 2,
1501     }
1502
1503     return lookup_unit_table(_UNIT_TABLE, s)
1504
1505
1506 def month_by_name(name):
1507     """ Return the number of a month by (locale-independently) English name """
1508
1509     try:
1510         return ENGLISH_MONTH_NAMES.index(name) + 1
1511     except ValueError:
1512         return None
1513
1514
1515 def month_by_abbreviation(abbrev):
1516     """ Return the number of a month by (locale-independently) English
1517         abbreviations """
1518
1519     try:
1520         return [s[:3] for s in ENGLISH_MONTH_NAMES].index(abbrev) + 1
1521     except ValueError:
1522         return None
1523
1524
1525 def fix_xml_ampersands(xml_str):
1526     """Replace all the '&' by '&amp;' in XML"""
1527     return re.sub(
1528         r'&(?!amp;|lt;|gt;|apos;|quot;|#x[0-9a-fA-F]{,4};|#[0-9]{,4};)',
1529         '&amp;',
1530         xml_str)
1531
1532
1533 def setproctitle(title):
1534     assert isinstance(title, compat_str)
1535
1536     # ctypes in Jython is not complete
1537     # http://bugs.jython.org/issue2148
1538     if sys.platform.startswith('java'):
1539         return
1540
1541     try:
1542         libc = ctypes.cdll.LoadLibrary('libc.so.6')
1543     except OSError:
1544         return
1545     title_bytes = title.encode('utf-8')
1546     buf = ctypes.create_string_buffer(len(title_bytes))
1547     buf.value = title_bytes
1548     try:
1549         libc.prctl(15, buf, 0, 0, 0)
1550     except AttributeError:
1551         return  # Strange libc, just skip this
1552
1553
1554 def remove_start(s, start):
1555     return s[len(start):] if s is not None and s.startswith(start) else s
1556
1557
1558 def remove_end(s, end):
1559     return s[:-len(end)] if s is not None and s.endswith(end) else s
1560
1561
1562 def remove_quotes(s):
1563     if s is None or len(s) < 2:
1564         return s
1565     for quote in ('"', "'", ):
1566         if s[0] == quote and s[-1] == quote:
1567             return s[1:-1]
1568     return s
1569
1570
1571 def url_basename(url):
1572     path = compat_urlparse.urlparse(url).path
1573     return path.strip('/').split('/')[-1]
1574
1575
1576 class HEADRequest(compat_urllib_request.Request):
1577     def get_method(self):
1578         return 'HEAD'
1579
1580
1581 def int_or_none(v, scale=1, default=None, get_attr=None, invscale=1):
1582     if get_attr:
1583         if v is not None:
1584             v = getattr(v, get_attr, None)
1585     if v == '':
1586         v = None
1587     if v is None:
1588         return default
1589     try:
1590         return int(v) * invscale // scale
1591     except ValueError:
1592         return default
1593
1594
1595 def str_or_none(v, default=None):
1596     return default if v is None else compat_str(v)
1597
1598
1599 def str_to_int(int_str):
1600     """ A more relaxed version of int_or_none """
1601     if int_str is None:
1602         return None
1603     int_str = re.sub(r'[,\.\+]', '', int_str)
1604     return int(int_str)
1605
1606
1607 def float_or_none(v, scale=1, invscale=1, default=None):
1608     if v is None:
1609         return default
1610     try:
1611         return float(v) * invscale / scale
1612     except ValueError:
1613         return default
1614
1615
1616 def parse_duration(s):
1617     if not isinstance(s, compat_basestring):
1618         return None
1619
1620     s = s.strip()
1621
1622     days, hours, mins, secs, ms = [None] * 5
1623     m = re.match(r'(?:(?:(?:(?P<days>[0-9]+):)?(?P<hours>[0-9]+):)?(?P<mins>[0-9]+):)?(?P<secs>[0-9]+)(?P<ms>\.[0-9]+)?$', s)
1624     if m:
1625         days, hours, mins, secs, ms = m.groups()
1626     else:
1627         m = re.match(
1628             r'''(?ix)(?:P?T)?
1629                 (?:
1630                     (?P<days>[0-9]+)\s*d(?:ays?)?\s*
1631                 )?
1632                 (?:
1633                     (?P<hours>[0-9]+)\s*h(?:ours?)?\s*
1634                 )?
1635                 (?:
1636                     (?P<mins>[0-9]+)\s*m(?:in(?:ute)?s?)?\s*
1637                 )?
1638                 (?:
1639                     (?P<secs>[0-9]+)(?P<ms>\.[0-9]+)?\s*s(?:ec(?:ond)?s?)?\s*
1640                 )?$''', s)
1641         if m:
1642             days, hours, mins, secs, ms = m.groups()
1643         else:
1644             m = re.match(r'(?i)(?:(?P<hours>[0-9.]+)\s*(?:hours?)|(?P<mins>[0-9.]+)\s*(?:mins?\.?|minutes?)\s*)$', s)
1645             if m:
1646                 hours, mins = m.groups()
1647             else:
1648                 return None
1649
1650     duration = 0
1651     if secs:
1652         duration += float(secs)
1653     if mins:
1654         duration += float(mins) * 60
1655     if hours:
1656         duration += float(hours) * 60 * 60
1657     if days:
1658         duration += float(days) * 24 * 60 * 60
1659     if ms:
1660         duration += float(ms)
1661     return duration
1662
1663
1664 def prepend_extension(filename, ext, expected_real_ext=None):
1665     name, real_ext = os.path.splitext(filename)
1666     return (
1667         '{0}.{1}{2}'.format(name, ext, real_ext)
1668         if not expected_real_ext or real_ext[1:] == expected_real_ext
1669         else '{0}.{1}'.format(filename, ext))
1670
1671
1672 def replace_extension(filename, ext, expected_real_ext=None):
1673     name, real_ext = os.path.splitext(filename)
1674     return '{0}.{1}'.format(
1675         name if not expected_real_ext or real_ext[1:] == expected_real_ext else filename,
1676         ext)
1677
1678
1679 def check_executable(exe, args=[]):
1680     """ Checks if the given binary is installed somewhere in PATH, and returns its name.
1681     args can be a list of arguments for a short output (like -version) """
1682     try:
1683         subprocess.Popen([exe] + args, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
1684     except OSError:
1685         return False
1686     return exe
1687
1688
1689 def get_exe_version(exe, args=['--version'],
1690                     version_re=None, unrecognized='present'):
1691     """ Returns the version of the specified executable,
1692     or False if the executable is not present """
1693     try:
1694         out, _ = subprocess.Popen(
1695             [encodeArgument(exe)] + args,
1696             stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()
1697     except OSError:
1698         return False
1699     if isinstance(out, bytes):  # Python 2.x
1700         out = out.decode('ascii', 'ignore')
1701     return detect_exe_version(out, version_re, unrecognized)
1702
1703
1704 def detect_exe_version(output, version_re=None, unrecognized='present'):
1705     assert isinstance(output, compat_str)
1706     if version_re is None:
1707         version_re = r'version\s+([-0-9._a-zA-Z]+)'
1708     m = re.search(version_re, output)
1709     if m:
1710         return m.group(1)
1711     else:
1712         return unrecognized
1713
1714
1715 class PagedList(object):
1716     def __len__(self):
1717         # This is only useful for tests
1718         return len(self.getslice())
1719
1720
1721 class OnDemandPagedList(PagedList):
1722     def __init__(self, pagefunc, pagesize, use_cache=False):
1723         self._pagefunc = pagefunc
1724         self._pagesize = pagesize
1725         self._use_cache = use_cache
1726         if use_cache:
1727             self._cache = {}
1728
1729     def getslice(self, start=0, end=None):
1730         res = []
1731         for pagenum in itertools.count(start // self._pagesize):
1732             firstid = pagenum * self._pagesize
1733             nextfirstid = pagenum * self._pagesize + self._pagesize
1734             if start >= nextfirstid:
1735                 continue
1736
1737             page_results = None
1738             if self._use_cache:
1739                 page_results = self._cache.get(pagenum)
1740             if page_results is None:
1741                 page_results = list(self._pagefunc(pagenum))
1742             if self._use_cache:
1743                 self._cache[pagenum] = page_results
1744
1745             startv = (
1746                 start % self._pagesize
1747                 if firstid <= start < nextfirstid
1748                 else 0)
1749
1750             endv = (
1751                 ((end - 1) % self._pagesize) + 1
1752                 if (end is not None and firstid <= end <= nextfirstid)
1753                 else None)
1754
1755             if startv != 0 or endv is not None:
1756                 page_results = page_results[startv:endv]
1757             res.extend(page_results)
1758
1759             # A little optimization - if current page is not "full", ie. does
1760             # not contain page_size videos then we can assume that this page
1761             # is the last one - there are no more ids on further pages -
1762             # i.e. no need to query again.
1763             if len(page_results) + startv < self._pagesize:
1764                 break
1765
1766             # If we got the whole page, but the next page is not interesting,
1767             # break out early as well
1768             if end == nextfirstid:
1769                 break
1770         return res
1771
1772
1773 class InAdvancePagedList(PagedList):
1774     def __init__(self, pagefunc, pagecount, pagesize):
1775         self._pagefunc = pagefunc
1776         self._pagecount = pagecount
1777         self._pagesize = pagesize
1778
1779     def getslice(self, start=0, end=None):
1780         res = []
1781         start_page = start // self._pagesize
1782         end_page = (
1783             self._pagecount if end is None else (end // self._pagesize + 1))
1784         skip_elems = start - start_page * self._pagesize
1785         only_more = None if end is None else end - start
1786         for pagenum in range(start_page, end_page):
1787             page = list(self._pagefunc(pagenum))
1788             if skip_elems:
1789                 page = page[skip_elems:]
1790                 skip_elems = None
1791             if only_more is not None:
1792                 if len(page) < only_more:
1793                     only_more -= len(page)
1794                 else:
1795                     page = page[:only_more]
1796                     res.extend(page)
1797                     break
1798             res.extend(page)
1799         return res
1800
1801
1802 def uppercase_escape(s):
1803     unicode_escape = codecs.getdecoder('unicode_escape')
1804     return re.sub(
1805         r'\\U[0-9a-fA-F]{8}',
1806         lambda m: unicode_escape(m.group(0))[0],
1807         s)
1808
1809
1810 def lowercase_escape(s):
1811     unicode_escape = codecs.getdecoder('unicode_escape')
1812     return re.sub(
1813         r'\\u[0-9a-fA-F]{4}',
1814         lambda m: unicode_escape(m.group(0))[0],
1815         s)
1816
1817
1818 def escape_rfc3986(s):
1819     """Escape non-ASCII characters as suggested by RFC 3986"""
1820     if sys.version_info < (3, 0) and isinstance(s, compat_str):
1821         s = s.encode('utf-8')
1822     return compat_urllib_parse.quote(s, b"%/;:@&=+$,!~*'()?#[]")
1823
1824
1825 def escape_url(url):
1826     """Escape URL as suggested by RFC 3986"""
1827     url_parsed = compat_urllib_parse_urlparse(url)
1828     return url_parsed._replace(
1829         netloc=url_parsed.netloc.encode('idna').decode('ascii'),
1830         path=escape_rfc3986(url_parsed.path),
1831         params=escape_rfc3986(url_parsed.params),
1832         query=escape_rfc3986(url_parsed.query),
1833         fragment=escape_rfc3986(url_parsed.fragment)
1834     ).geturl()
1835
1836
1837 def read_batch_urls(batch_fd):
1838     def fixup(url):
1839         if not isinstance(url, compat_str):
1840             url = url.decode('utf-8', 'replace')
1841         BOM_UTF8 = '\xef\xbb\xbf'
1842         if url.startswith(BOM_UTF8):
1843             url = url[len(BOM_UTF8):]
1844         url = url.strip()
1845         if url.startswith(('#', ';', ']')):
1846             return False
1847         return url
1848
1849     with contextlib.closing(batch_fd) as fd:
1850         return [url for url in map(fixup, fd) if url]
1851
1852
1853 def urlencode_postdata(*args, **kargs):
1854     return compat_urllib_parse_urlencode(*args, **kargs).encode('ascii')
1855
1856
1857 def update_url_query(url, query):
1858     if not query:
1859         return url
1860     parsed_url = compat_urlparse.urlparse(url)
1861     qs = compat_parse_qs(parsed_url.query)
1862     qs.update(query)
1863     return compat_urlparse.urlunparse(parsed_url._replace(
1864         query=compat_urllib_parse_urlencode(qs, True)))
1865
1866
1867 def update_Request(req, url=None, data=None, headers={}, query={}):
1868     req_headers = req.headers.copy()
1869     req_headers.update(headers)
1870     req_data = data or req.data
1871     req_url = update_url_query(url or req.get_full_url(), query)
1872     req_type = HEADRequest if req.get_method() == 'HEAD' else compat_urllib_request.Request
1873     new_req = req_type(
1874         req_url, data=req_data, headers=req_headers,
1875         origin_req_host=req.origin_req_host, unverifiable=req.unverifiable)
1876     if hasattr(req, 'timeout'):
1877         new_req.timeout = req.timeout
1878     return new_req
1879
1880
1881 def dict_get(d, key_or_keys, default=None, skip_false_values=True):
1882     if isinstance(key_or_keys, (list, tuple)):
1883         for key in key_or_keys:
1884             if key not in d or d[key] is None or skip_false_values and not d[key]:
1885                 continue
1886             return d[key]
1887         return default
1888     return d.get(key_or_keys, default)
1889
1890
1891 def encode_compat_str(string, encoding=preferredencoding(), errors='strict'):
1892     return string if isinstance(string, compat_str) else compat_str(string, encoding, errors)
1893
1894
1895 US_RATINGS = {
1896     'G': 0,
1897     'PG': 10,
1898     'PG-13': 13,
1899     'R': 16,
1900     'NC': 18,
1901 }
1902
1903
1904 def parse_age_limit(s):
1905     if s is None:
1906         return None
1907     m = re.match(r'^(?P<age>\d{1,2})\+?$', s)
1908     return int(m.group('age')) if m else US_RATINGS.get(s)
1909
1910
1911 def strip_jsonp(code):
1912     return re.sub(
1913         r'(?s)^[a-zA-Z0-9_.]+\s*\(\s*(.*)\);?\s*?(?://[^\n]*)*$', r'\1', code)
1914
1915
1916 def js_to_json(code):
1917     def fix_kv(m):
1918         v = m.group(0)
1919         if v in ('true', 'false', 'null'):
1920             return v
1921         elif v.startswith('/*') or v == ',':
1922             return ""
1923
1924         if v[0] in ("'", '"'):
1925             v = re.sub(r'(?s)\\.|"', lambda m: {
1926                 '"': '\\"',
1927                 "\\'": "'",
1928                 '\\\n': '',
1929                 '\\x': '\\u00',
1930             }.get(m.group(0), m.group(0)), v[1:-1])
1931
1932         INTEGER_TABLE = (
1933             (r'^0[xX][0-9a-fA-F]+', 16),
1934             (r'^0+[0-7]+', 8),
1935         )
1936
1937         for regex, base in INTEGER_TABLE:
1938             im = re.match(regex, v)
1939             if im:
1940                 i = int(im.group(0), base)
1941                 return '"%d":' % i if v.endswith(':') else '%d' % i
1942
1943         return '"%s"' % v
1944
1945     return re.sub(r'''(?sx)
1946         "(?:[^"\\]*(?:\\\\|\\['"nurtbfx/\n]))*[^"\\]*"|
1947         '(?:[^'\\]*(?:\\\\|\\['"nurtbfx/\n]))*[^'\\]*'|
1948         /\*.*?\*/|,(?=\s*[\]}])|
1949         [a-zA-Z_][.a-zA-Z_0-9]*|
1950         (?:0[xX][0-9a-fA-F]+|0+[0-7]+)(?:\s*:)?|
1951         [0-9]+(?=\s*:)
1952         ''', fix_kv, code)
1953
1954
1955 def qualities(quality_ids):
1956     """ Get a numeric quality value out of a list of possible values """
1957     def q(qid):
1958         try:
1959             return quality_ids.index(qid)
1960         except ValueError:
1961             return -1
1962     return q
1963
1964
1965 DEFAULT_OUTTMPL = '%(title)s-%(id)s.%(ext)s'
1966
1967
1968 def limit_length(s, length):
1969     """ Add ellipses to overly long strings """
1970     if s is None:
1971         return None
1972     ELLIPSES = '...'
1973     if len(s) > length:
1974         return s[:length - len(ELLIPSES)] + ELLIPSES
1975     return s
1976
1977
1978 def version_tuple(v):
1979     return tuple(int(e) for e in re.split(r'[-.]', v))
1980
1981
1982 def is_outdated_version(version, limit, assume_new=True):
1983     if not version:
1984         return not assume_new
1985     try:
1986         return version_tuple(version) < version_tuple(limit)
1987     except ValueError:
1988         return not assume_new
1989
1990
1991 def ytdl_is_updateable():
1992     """ Returns if youtube-dl can be updated with -U """
1993     from zipimport import zipimporter
1994
1995     return isinstance(globals().get('__loader__'), zipimporter) or hasattr(sys, 'frozen')
1996
1997
1998 def args_to_str(args):
1999     # Get a short string representation for a subprocess command
2000     return ' '.join(compat_shlex_quote(a) for a in args)
2001
2002
2003 def error_to_compat_str(err):
2004     err_str = str(err)
2005     # On python 2 error byte string must be decoded with proper
2006     # encoding rather than ascii
2007     if sys.version_info[0] < 3:
2008         err_str = err_str.decode(preferredencoding())
2009     return err_str
2010
2011
2012 def mimetype2ext(mt):
2013     if mt is None:
2014         return None
2015
2016     ext = {
2017         'audio/mp4': 'm4a',
2018     }.get(mt)
2019     if ext is not None:
2020         return ext
2021
2022     _, _, res = mt.rpartition('/')
2023
2024     return {
2025         '3gpp': '3gp',
2026         'smptett+xml': 'tt',
2027         'srt': 'srt',
2028         'ttaf+xml': 'dfxp',
2029         'ttml+xml': 'ttml',
2030         'vtt': 'vtt',
2031         'x-flv': 'flv',
2032         'x-mp4-fragmented': 'mp4',
2033         'x-ms-wmv': 'wmv',
2034     }.get(res, res)
2035
2036
2037 def urlhandle_detect_ext(url_handle):
2038     getheader = url_handle.headers.get
2039
2040     cd = getheader('Content-Disposition')
2041     if cd:
2042         m = re.match(r'attachment;\s*filename="(?P<filename>[^"]+)"', cd)
2043         if m:
2044             e = determine_ext(m.group('filename'), default_ext=None)
2045             if e:
2046                 return e
2047
2048     return mimetype2ext(getheader('Content-Type'))
2049
2050
2051 def encode_data_uri(data, mime_type):
2052     return 'data:%s;base64,%s' % (mime_type, base64.b64encode(data).decode('ascii'))
2053
2054
2055 def age_restricted(content_limit, age_limit):
2056     """ Returns True iff the content should be blocked """
2057
2058     if age_limit is None:  # No limit set
2059         return False
2060     if content_limit is None:
2061         return False  # Content available for everyone
2062     return age_limit < content_limit
2063
2064
2065 def is_html(first_bytes):
2066     """ Detect whether a file contains HTML by examining its first bytes. """
2067
2068     BOMS = [
2069         (b'\xef\xbb\xbf', 'utf-8'),
2070         (b'\x00\x00\xfe\xff', 'utf-32-be'),
2071         (b'\xff\xfe\x00\x00', 'utf-32-le'),
2072         (b'\xff\xfe', 'utf-16-le'),
2073         (b'\xfe\xff', 'utf-16-be'),
2074     ]
2075     for bom, enc in BOMS:
2076         if first_bytes.startswith(bom):
2077             s = first_bytes[len(bom):].decode(enc, 'replace')
2078             break
2079     else:
2080         s = first_bytes.decode('utf-8', 'replace')
2081
2082     return re.match(r'^\s*<', s)
2083
2084
2085 def determine_protocol(info_dict):
2086     protocol = info_dict.get('protocol')
2087     if protocol is not None:
2088         return protocol
2089
2090     url = info_dict['url']
2091     if url.startswith('rtmp'):
2092         return 'rtmp'
2093     elif url.startswith('mms'):
2094         return 'mms'
2095     elif url.startswith('rtsp'):
2096         return 'rtsp'
2097
2098     ext = determine_ext(url)
2099     if ext == 'm3u8':
2100         return 'm3u8'
2101     elif ext == 'f4m':
2102         return 'f4m'
2103
2104     return compat_urllib_parse_urlparse(url).scheme
2105
2106
2107 def render_table(header_row, data):
2108     """ Render a list of rows, each as a list of values """
2109     table = [header_row] + data
2110     max_lens = [max(len(compat_str(v)) for v in col) for col in zip(*table)]
2111     format_str = ' '.join('%-' + compat_str(ml + 1) + 's' for ml in max_lens[:-1]) + '%s'
2112     return '\n'.join(format_str % tuple(row) for row in table)
2113
2114
2115 def _match_one(filter_part, dct):
2116     COMPARISON_OPERATORS = {
2117         '<': operator.lt,
2118         '<=': operator.le,
2119         '>': operator.gt,
2120         '>=': operator.ge,
2121         '=': operator.eq,
2122         '!=': operator.ne,
2123     }
2124     operator_rex = re.compile(r'''(?x)\s*
2125         (?P<key>[a-z_]+)
2126         \s*(?P<op>%s)(?P<none_inclusive>\s*\?)?\s*
2127         (?:
2128             (?P<intval>[0-9.]+(?:[kKmMgGtTpPeEzZyY]i?[Bb]?)?)|
2129             (?P<strval>(?![0-9.])[a-z0-9A-Z]*)
2130         )
2131         \s*$
2132         ''' % '|'.join(map(re.escape, COMPARISON_OPERATORS.keys())))
2133     m = operator_rex.search(filter_part)
2134     if m:
2135         op = COMPARISON_OPERATORS[m.group('op')]
2136         if m.group('strval') is not None:
2137             if m.group('op') not in ('=', '!='):
2138                 raise ValueError(
2139                     'Operator %s does not support string values!' % m.group('op'))
2140             comparison_value = m.group('strval')
2141         else:
2142             try:
2143                 comparison_value = int(m.group('intval'))
2144             except ValueError:
2145                 comparison_value = parse_filesize(m.group('intval'))
2146                 if comparison_value is None:
2147                     comparison_value = parse_filesize(m.group('intval') + 'B')
2148                 if comparison_value is None:
2149                     raise ValueError(
2150                         'Invalid integer value %r in filter part %r' % (
2151                             m.group('intval'), filter_part))
2152         actual_value = dct.get(m.group('key'))
2153         if actual_value is None:
2154             return m.group('none_inclusive')
2155         return op(actual_value, comparison_value)
2156
2157     UNARY_OPERATORS = {
2158         '': lambda v: v is not None,
2159         '!': lambda v: v is None,
2160     }
2161     operator_rex = re.compile(r'''(?x)\s*
2162         (?P<op>%s)\s*(?P<key>[a-z_]+)
2163         \s*$
2164         ''' % '|'.join(map(re.escape, UNARY_OPERATORS.keys())))
2165     m = operator_rex.search(filter_part)
2166     if m:
2167         op = UNARY_OPERATORS[m.group('op')]
2168         actual_value = dct.get(m.group('key'))
2169         return op(actual_value)
2170
2171     raise ValueError('Invalid filter part %r' % filter_part)
2172
2173
2174 def match_str(filter_str, dct):
2175     """ Filter a dictionary with a simple string syntax. Returns True (=passes filter) or false """
2176
2177     return all(
2178         _match_one(filter_part, dct) for filter_part in filter_str.split('&'))
2179
2180
2181 def match_filter_func(filter_str):
2182     def _match_func(info_dict):
2183         if match_str(filter_str, info_dict):
2184             return None
2185         else:
2186             video_title = info_dict.get('title', info_dict.get('id', 'video'))
2187             return '%s does not pass filter %s, skipping ..' % (video_title, filter_str)
2188     return _match_func
2189
2190
2191 def parse_dfxp_time_expr(time_expr):
2192     if not time_expr:
2193         return
2194
2195     mobj = re.match(r'^(?P<time_offset>\d+(?:\.\d+)?)s?$', time_expr)
2196     if mobj:
2197         return float(mobj.group('time_offset'))
2198
2199     mobj = re.match(r'^(\d+):(\d\d):(\d\d(?:(?:\.|:)\d+)?)$', time_expr)
2200     if mobj:
2201         return 3600 * int(mobj.group(1)) + 60 * int(mobj.group(2)) + float(mobj.group(3).replace(':', '.'))
2202
2203
2204 def srt_subtitles_timecode(seconds):
2205     return '%02d:%02d:%02d,%03d' % (seconds / 3600, (seconds % 3600) / 60, seconds % 60, (seconds % 1) * 1000)
2206
2207
2208 def dfxp2srt(dfxp_data):
2209     _x = functools.partial(xpath_with_ns, ns_map={
2210         'ttml': 'http://www.w3.org/ns/ttml',
2211         'ttaf1': 'http://www.w3.org/2006/10/ttaf1',
2212         'ttaf1_0604': 'http://www.w3.org/2006/04/ttaf1',
2213     })
2214
2215     class TTMLPElementParser(object):
2216         out = ''
2217
2218         def start(self, tag, attrib):
2219             if tag in (_x('ttml:br'), _x('ttaf1:br'), 'br'):
2220                 self.out += '\n'
2221
2222         def end(self, tag):
2223             pass
2224
2225         def data(self, data):
2226             self.out += data
2227
2228         def close(self):
2229             return self.out.strip()
2230
2231     def parse_node(node):
2232         target = TTMLPElementParser()
2233         parser = xml.etree.ElementTree.XMLParser(target=target)
2234         parser.feed(xml.etree.ElementTree.tostring(node))
2235         return parser.close()
2236
2237     dfxp = compat_etree_fromstring(dfxp_data.encode('utf-8'))
2238     out = []
2239     paras = dfxp.findall(_x('.//ttml:p')) or dfxp.findall(_x('.//ttaf1:p')) or dfxp.findall(_x('.//ttaf1_0604:p')) or dfxp.findall('.//p')
2240
2241     if not paras:
2242         raise ValueError('Invalid dfxp/TTML subtitle')
2243
2244     for para, index in zip(paras, itertools.count(1)):
2245         begin_time = parse_dfxp_time_expr(para.attrib.get('begin'))
2246         end_time = parse_dfxp_time_expr(para.attrib.get('end'))
2247         dur = parse_dfxp_time_expr(para.attrib.get('dur'))
2248         if begin_time is None:
2249             continue
2250         if not end_time:
2251             if not dur:
2252                 continue
2253             end_time = begin_time + dur
2254         out.append('%d\n%s --> %s\n%s\n\n' % (
2255             index,
2256             srt_subtitles_timecode(begin_time),
2257             srt_subtitles_timecode(end_time),
2258             parse_node(para)))
2259
2260     return ''.join(out)
2261
2262
2263 def cli_option(params, command_option, param):
2264     param = params.get(param)
2265     return [command_option, param] if param is not None else []
2266
2267
2268 def cli_bool_option(params, command_option, param, true_value='true', false_value='false', separator=None):
2269     param = params.get(param)
2270     assert isinstance(param, bool)
2271     if separator:
2272         return [command_option + separator + (true_value if param else false_value)]
2273     return [command_option, true_value if param else false_value]
2274
2275
2276 def cli_valueless_option(params, command_option, param, expected_value=True):
2277     param = params.get(param)
2278     return [command_option] if param == expected_value else []
2279
2280
2281 def cli_configuration_args(params, param, default=[]):
2282     ex_args = params.get(param)
2283     if ex_args is None:
2284         return default
2285     assert isinstance(ex_args, list)
2286     return ex_args
2287
2288
2289 class ISO639Utils(object):
2290     # See http://www.loc.gov/standards/iso639-2/ISO-639-2_utf-8.txt
2291     _lang_map = {
2292         'aa': 'aar',
2293         'ab': 'abk',
2294         'ae': 'ave',
2295         'af': 'afr',
2296         'ak': 'aka',
2297         'am': 'amh',
2298         'an': 'arg',
2299         'ar': 'ara',
2300         'as': 'asm',
2301         'av': 'ava',
2302         'ay': 'aym',
2303         'az': 'aze',
2304         'ba': 'bak',
2305         'be': 'bel',
2306         'bg': 'bul',
2307         'bh': 'bih',
2308         'bi': 'bis',
2309         'bm': 'bam',
2310         'bn': 'ben',
2311         'bo': 'bod',
2312         'br': 'bre',
2313         'bs': 'bos',
2314         'ca': 'cat',
2315         'ce': 'che',
2316         'ch': 'cha',
2317         'co': 'cos',
2318         'cr': 'cre',
2319         'cs': 'ces',
2320         'cu': 'chu',
2321         'cv': 'chv',
2322         'cy': 'cym',
2323         'da': 'dan',
2324         'de': 'deu',
2325         'dv': 'div',
2326         'dz': 'dzo',
2327         'ee': 'ewe',
2328         'el': 'ell',
2329         'en': 'eng',
2330         'eo': 'epo',
2331         'es': 'spa',
2332         'et': 'est',
2333         'eu': 'eus',
2334         'fa': 'fas',
2335         'ff': 'ful',
2336         'fi': 'fin',
2337         'fj': 'fij',
2338         'fo': 'fao',
2339         'fr': 'fra',
2340         'fy': 'fry',
2341         'ga': 'gle',
2342         'gd': 'gla',
2343         'gl': 'glg',
2344         'gn': 'grn',
2345         'gu': 'guj',
2346         'gv': 'glv',
2347         'ha': 'hau',
2348         'he': 'heb',
2349         'hi': 'hin',
2350         'ho': 'hmo',
2351         'hr': 'hrv',
2352         'ht': 'hat',
2353         'hu': 'hun',
2354         'hy': 'hye',
2355         'hz': 'her',
2356         'ia': 'ina',
2357         'id': 'ind',
2358         'ie': 'ile',
2359         'ig': 'ibo',
2360         'ii': 'iii',
2361         'ik': 'ipk',
2362         'io': 'ido',
2363         'is': 'isl',
2364         'it': 'ita',
2365         'iu': 'iku',
2366         'ja': 'jpn',
2367         'jv': 'jav',
2368         'ka': 'kat',
2369         'kg': 'kon',
2370         'ki': 'kik',
2371         'kj': 'kua',
2372         'kk': 'kaz',
2373         'kl': 'kal',
2374         'km': 'khm',
2375         'kn': 'kan',
2376         'ko': 'kor',
2377         'kr': 'kau',
2378         'ks': 'kas',
2379         'ku': 'kur',
2380         'kv': 'kom',
2381         'kw': 'cor',
2382         'ky': 'kir',
2383         'la': 'lat',
2384         'lb': 'ltz',
2385         'lg': 'lug',
2386         'li': 'lim',
2387         'ln': 'lin',
2388         'lo': 'lao',
2389         'lt': 'lit',
2390         'lu': 'lub',
2391         'lv': 'lav',
2392         'mg': 'mlg',
2393         'mh': 'mah',
2394         'mi': 'mri',
2395         'mk': 'mkd',
2396         'ml': 'mal',
2397         'mn': 'mon',
2398         'mr': 'mar',
2399         'ms': 'msa',
2400         'mt': 'mlt',
2401         'my': 'mya',
2402         'na': 'nau',
2403         'nb': 'nob',
2404         'nd': 'nde',
2405         'ne': 'nep',
2406         'ng': 'ndo',
2407         'nl': 'nld',
2408         'nn': 'nno',
2409         'no': 'nor',
2410         'nr': 'nbl',
2411         'nv': 'nav',
2412         'ny': 'nya',
2413         'oc': 'oci',
2414         'oj': 'oji',
2415         'om': 'orm',
2416         'or': 'ori',
2417         'os': 'oss',
2418         'pa': 'pan',
2419         'pi': 'pli',
2420         'pl': 'pol',
2421         'ps': 'pus',
2422         'pt': 'por',
2423         'qu': 'que',
2424         'rm': 'roh',
2425         'rn': 'run',
2426         'ro': 'ron',
2427         'ru': 'rus',
2428         'rw': 'kin',
2429         'sa': 'san',
2430         'sc': 'srd',
2431         'sd': 'snd',
2432         'se': 'sme',
2433         'sg': 'sag',
2434         'si': 'sin',
2435         'sk': 'slk',
2436         'sl': 'slv',
2437         'sm': 'smo',
2438         'sn': 'sna',
2439         'so': 'som',
2440         'sq': 'sqi',
2441         'sr': 'srp',
2442         'ss': 'ssw',
2443         'st': 'sot',
2444         'su': 'sun',
2445         'sv': 'swe',
2446         'sw': 'swa',
2447         'ta': 'tam',
2448         'te': 'tel',
2449         'tg': 'tgk',
2450         'th': 'tha',
2451         'ti': 'tir',
2452         'tk': 'tuk',
2453         'tl': 'tgl',
2454         'tn': 'tsn',
2455         'to': 'ton',
2456         'tr': 'tur',
2457         'ts': 'tso',
2458         'tt': 'tat',
2459         'tw': 'twi',
2460         'ty': 'tah',
2461         'ug': 'uig',
2462         'uk': 'ukr',
2463         'ur': 'urd',
2464         'uz': 'uzb',
2465         've': 'ven',
2466         'vi': 'vie',
2467         'vo': 'vol',
2468         'wa': 'wln',
2469         'wo': 'wol',
2470         'xh': 'xho',
2471         'yi': 'yid',
2472         'yo': 'yor',
2473         'za': 'zha',
2474         'zh': 'zho',
2475         'zu': 'zul',
2476     }
2477
2478     @classmethod
2479     def short2long(cls, code):
2480         """Convert language code from ISO 639-1 to ISO 639-2/T"""
2481         return cls._lang_map.get(code[:2])
2482
2483     @classmethod
2484     def long2short(cls, code):
2485         """Convert language code from ISO 639-2/T to ISO 639-1"""
2486         for short_name, long_name in cls._lang_map.items():
2487             if long_name == code:
2488                 return short_name
2489
2490
2491 class ISO3166Utils(object):
2492     # From http://data.okfn.org/data/core/country-list
2493     _country_map = {
2494         'AF': 'Afghanistan',
2495         'AX': 'Åland Islands',
2496         'AL': 'Albania',
2497         'DZ': 'Algeria',
2498         'AS': 'American Samoa',
2499         'AD': 'Andorra',
2500         'AO': 'Angola',
2501         'AI': 'Anguilla',
2502         'AQ': 'Antarctica',
2503         'AG': 'Antigua and Barbuda',
2504         'AR': 'Argentina',
2505         'AM': 'Armenia',
2506         'AW': 'Aruba',
2507         'AU': 'Australia',
2508         'AT': 'Austria',
2509         'AZ': 'Azerbaijan',
2510         'BS': 'Bahamas',
2511         'BH': 'Bahrain',
2512         'BD': 'Bangladesh',
2513         'BB': 'Barbados',
2514         'BY': 'Belarus',
2515         'BE': 'Belgium',
2516         'BZ': 'Belize',
2517         'BJ': 'Benin',
2518         'BM': 'Bermuda',
2519         'BT': 'Bhutan',
2520         'BO': 'Bolivia, Plurinational State of',
2521         'BQ': 'Bonaire, Sint Eustatius and Saba',
2522         'BA': 'Bosnia and Herzegovina',
2523         'BW': 'Botswana',
2524         'BV': 'Bouvet Island',
2525         'BR': 'Brazil',
2526         'IO': 'British Indian Ocean Territory',
2527         'BN': 'Brunei Darussalam',
2528         'BG': 'Bulgaria',
2529         'BF': 'Burkina Faso',
2530         'BI': 'Burundi',
2531         'KH': 'Cambodia',
2532         'CM': 'Cameroon',
2533         'CA': 'Canada',
2534         'CV': 'Cape Verde',
2535         'KY': 'Cayman Islands',
2536         'CF': 'Central African Republic',
2537         'TD': 'Chad',
2538         'CL': 'Chile',
2539         'CN': 'China',
2540         'CX': 'Christmas Island',
2541         'CC': 'Cocos (Keeling) Islands',
2542         'CO': 'Colombia',
2543         'KM': 'Comoros',
2544         'CG': 'Congo',
2545         'CD': 'Congo, the Democratic Republic of the',
2546         'CK': 'Cook Islands',
2547         'CR': 'Costa Rica',
2548         'CI': 'Côte d\'Ivoire',
2549         'HR': 'Croatia',
2550         'CU': 'Cuba',
2551         'CW': 'Curaçao',
2552         'CY': 'Cyprus',
2553         'CZ': 'Czech Republic',
2554         'DK': 'Denmark',
2555         'DJ': 'Djibouti',
2556         'DM': 'Dominica',
2557         'DO': 'Dominican Republic',
2558         'EC': 'Ecuador',
2559         'EG': 'Egypt',
2560         'SV': 'El Salvador',
2561         'GQ': 'Equatorial Guinea',
2562         'ER': 'Eritrea',
2563         'EE': 'Estonia',
2564         'ET': 'Ethiopia',
2565         'FK': 'Falkland Islands (Malvinas)',
2566         'FO': 'Faroe Islands',
2567         'FJ': 'Fiji',
2568         'FI': 'Finland',
2569         'FR': 'France',
2570         'GF': 'French Guiana',
2571         'PF': 'French Polynesia',
2572         'TF': 'French Southern Territories',
2573         'GA': 'Gabon',
2574         'GM': 'Gambia',
2575         'GE': 'Georgia',
2576         'DE': 'Germany',
2577         'GH': 'Ghana',
2578         'GI': 'Gibraltar',
2579         'GR': 'Greece',
2580         'GL': 'Greenland',
2581         'GD': 'Grenada',
2582         'GP': 'Guadeloupe',
2583         'GU': 'Guam',
2584         'GT': 'Guatemala',
2585         'GG': 'Guernsey',
2586         'GN': 'Guinea',
2587         'GW': 'Guinea-Bissau',
2588         'GY': 'Guyana',
2589         'HT': 'Haiti',
2590         'HM': 'Heard Island and McDonald Islands',
2591         'VA': 'Holy See (Vatican City State)',
2592         'HN': 'Honduras',
2593         'HK': 'Hong Kong',
2594         'HU': 'Hungary',
2595         'IS': 'Iceland',
2596         'IN': 'India',
2597         'ID': 'Indonesia',
2598         'IR': 'Iran, Islamic Republic of',
2599         'IQ': 'Iraq',
2600         'IE': 'Ireland',
2601         'IM': 'Isle of Man',
2602         'IL': 'Israel',
2603         'IT': 'Italy',
2604         'JM': 'Jamaica',
2605         'JP': 'Japan',
2606         'JE': 'Jersey',
2607         'JO': 'Jordan',
2608         'KZ': 'Kazakhstan',
2609         'KE': 'Kenya',
2610         'KI': 'Kiribati',
2611         'KP': 'Korea, Democratic People\'s Republic of',
2612         'KR': 'Korea, Republic of',
2613         'KW': 'Kuwait',
2614         'KG': 'Kyrgyzstan',
2615         'LA': 'Lao People\'s Democratic Republic',
2616         'LV': 'Latvia',
2617         'LB': 'Lebanon',
2618         'LS': 'Lesotho',
2619         'LR': 'Liberia',
2620         'LY': 'Libya',
2621         'LI': 'Liechtenstein',
2622         'LT': 'Lithuania',
2623         'LU': 'Luxembourg',
2624         'MO': 'Macao',
2625         'MK': 'Macedonia, the Former Yugoslav Republic of',
2626         'MG': 'Madagascar',
2627         'MW': 'Malawi',
2628         'MY': 'Malaysia',
2629         'MV': 'Maldives',
2630         'ML': 'Mali',
2631         'MT': 'Malta',
2632         'MH': 'Marshall Islands',
2633         'MQ': 'Martinique',
2634         'MR': 'Mauritania',
2635         'MU': 'Mauritius',
2636         'YT': 'Mayotte',
2637         'MX': 'Mexico',
2638         'FM': 'Micronesia, Federated States of',
2639         'MD': 'Moldova, Republic of',
2640         'MC': 'Monaco',
2641         'MN': 'Mongolia',
2642         'ME': 'Montenegro',
2643         'MS': 'Montserrat',
2644         'MA': 'Morocco',
2645         'MZ': 'Mozambique',
2646         'MM': 'Myanmar',
2647         'NA': 'Namibia',
2648         'NR': 'Nauru',
2649         'NP': 'Nepal',
2650         'NL': 'Netherlands',
2651         'NC': 'New Caledonia',
2652         'NZ': 'New Zealand',
2653         'NI': 'Nicaragua',
2654         'NE': 'Niger',
2655         'NG': 'Nigeria',
2656         'NU': 'Niue',
2657         'NF': 'Norfolk Island',
2658         'MP': 'Northern Mariana Islands',
2659         'NO': 'Norway',
2660         'OM': 'Oman',
2661         'PK': 'Pakistan',
2662         'PW': 'Palau',
2663         'PS': 'Palestine, State of',
2664         'PA': 'Panama',
2665         'PG': 'Papua New Guinea',
2666         'PY': 'Paraguay',
2667         'PE': 'Peru',
2668         'PH': 'Philippines',
2669         'PN': 'Pitcairn',
2670         'PL': 'Poland',
2671         'PT': 'Portugal',
2672         'PR': 'Puerto Rico',
2673         'QA': 'Qatar',
2674         'RE': 'Réunion',
2675         'RO': 'Romania',
2676         'RU': 'Russian Federation',
2677         'RW': 'Rwanda',
2678         'BL': 'Saint Barthélemy',
2679         'SH': 'Saint Helena, Ascension and Tristan da Cunha',
2680         'KN': 'Saint Kitts and Nevis',
2681         'LC': 'Saint Lucia',
2682         'MF': 'Saint Martin (French part)',
2683         'PM': 'Saint Pierre and Miquelon',
2684         'VC': 'Saint Vincent and the Grenadines',
2685         'WS': 'Samoa',
2686         'SM': 'San Marino',
2687         'ST': 'Sao Tome and Principe',
2688         'SA': 'Saudi Arabia',
2689         'SN': 'Senegal',
2690         'RS': 'Serbia',
2691         'SC': 'Seychelles',
2692         'SL': 'Sierra Leone',
2693         'SG': 'Singapore',
2694         'SX': 'Sint Maarten (Dutch part)',
2695         'SK': 'Slovakia',
2696         'SI': 'Slovenia',
2697         'SB': 'Solomon Islands',
2698         'SO': 'Somalia',
2699         'ZA': 'South Africa',
2700         'GS': 'South Georgia and the South Sandwich Islands',
2701         'SS': 'South Sudan',
2702         'ES': 'Spain',
2703         'LK': 'Sri Lanka',
2704         'SD': 'Sudan',
2705         'SR': 'Suriname',
2706         'SJ': 'Svalbard and Jan Mayen',
2707         'SZ': 'Swaziland',
2708         'SE': 'Sweden',
2709         'CH': 'Switzerland',
2710         'SY': 'Syrian Arab Republic',
2711         'TW': 'Taiwan, Province of China',
2712         'TJ': 'Tajikistan',
2713         'TZ': 'Tanzania, United Republic of',
2714         'TH': 'Thailand',
2715         'TL': 'Timor-Leste',
2716         'TG': 'Togo',
2717         'TK': 'Tokelau',
2718         'TO': 'Tonga',
2719         'TT': 'Trinidad and Tobago',
2720         'TN': 'Tunisia',
2721         'TR': 'Turkey',
2722         'TM': 'Turkmenistan',
2723         'TC': 'Turks and Caicos Islands',
2724         'TV': 'Tuvalu',
2725         'UG': 'Uganda',
2726         'UA': 'Ukraine',
2727         'AE': 'United Arab Emirates',
2728         'GB': 'United Kingdom',
2729         'US': 'United States',
2730         'UM': 'United States Minor Outlying Islands',
2731         'UY': 'Uruguay',
2732         'UZ': 'Uzbekistan',
2733         'VU': 'Vanuatu',
2734         'VE': 'Venezuela, Bolivarian Republic of',
2735         'VN': 'Viet Nam',
2736         'VG': 'Virgin Islands, British',
2737         'VI': 'Virgin Islands, U.S.',
2738         'WF': 'Wallis and Futuna',
2739         'EH': 'Western Sahara',
2740         'YE': 'Yemen',
2741         'ZM': 'Zambia',
2742         'ZW': 'Zimbabwe',
2743     }
2744
2745     @classmethod
2746     def short2full(cls, code):
2747         """Convert an ISO 3166-2 country code to the corresponding full name"""
2748         return cls._country_map.get(code.upper())
2749
2750
2751 class PerRequestProxyHandler(compat_urllib_request.ProxyHandler):
2752     def __init__(self, proxies=None):
2753         # Set default handlers
2754         for type in ('http', 'https'):
2755             setattr(self, '%s_open' % type,
2756                     lambda r, proxy='__noproxy__', type=type, meth=self.proxy_open:
2757                         meth(r, proxy, type))
2758         return compat_urllib_request.ProxyHandler.__init__(self, proxies)
2759
2760     def proxy_open(self, req, proxy, type):
2761         req_proxy = req.headers.get('Ytdl-request-proxy')
2762         if req_proxy is not None:
2763             proxy = req_proxy
2764             del req.headers['Ytdl-request-proxy']
2765
2766         if proxy == '__noproxy__':
2767             return None  # No Proxy
2768         if compat_urlparse.urlparse(proxy).scheme.lower() in ('socks', 'socks4', 'socks4a', 'socks5'):
2769             req.add_header('Ytdl-socks-proxy', proxy)
2770             # youtube-dl's http/https handlers do wrapping the socket with socks
2771             return None
2772         return compat_urllib_request.ProxyHandler.proxy_open(
2773             self, req, proxy, type)
2774
2775
2776 def ohdave_rsa_encrypt(data, exponent, modulus):
2777     '''
2778     Implement OHDave's RSA algorithm. See http://www.ohdave.com/rsa/
2779
2780     Input:
2781         data: data to encrypt, bytes-like object
2782         exponent, modulus: parameter e and N of RSA algorithm, both integer
2783     Output: hex string of encrypted data
2784
2785     Limitation: supports one block encryption only
2786     '''
2787
2788     payload = int(binascii.hexlify(data[::-1]), 16)
2789     encrypted = pow(payload, exponent, modulus)
2790     return '%x' % encrypted
2791
2792
2793 def encode_base_n(num, n, table=None):
2794     FULL_TABLE = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
2795     if not table:
2796         table = FULL_TABLE[:n]
2797
2798     if n > len(table):
2799         raise ValueError('base %d exceeds table length %d' % (n, len(table)))
2800
2801     if num == 0:
2802         return table[0]
2803
2804     ret = ''
2805     while num:
2806         ret = table[num % n] + ret
2807         num = num // n
2808     return ret
2809
2810
2811 def decode_packed_codes(code):
2812     mobj = re.search(
2813         r"}\('(.+)',(\d+),(\d+),'([^']+)'\.split\('\|'\)",
2814         code)
2815     obfucasted_code, base, count, symbols = mobj.groups()
2816     base = int(base)
2817     count = int(count)
2818     symbols = symbols.split('|')
2819     symbol_table = {}
2820
2821     while count:
2822         count -= 1
2823         base_n_count = encode_base_n(count, base)
2824         symbol_table[base_n_count] = symbols[count] or base_n_count
2825
2826     return re.sub(
2827         r'\b(\w+)\b', lambda mobj: symbol_table[mobj.group(0)],
2828         obfucasted_code)