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