]> jfr.im git - yt-dlp.git/blame - yt_dlp/utils.py
Use certificates from `certifi` if installed (#3115)
[yt-dlp.git] / yt_dlp / utils.py
CommitLineData
cc52de43 1#!/usr/bin/env python3
dcdb292f 2# coding: utf-8
d77c3dfd 3
ecc0c5ee
PH
4from __future__ import unicode_literals
5
da42679b 6import asyncio
15dfb392 7import atexit
1e399778 8import base64
5bc880b9 9import binascii
912b38b4 10import calendar
676eb3f2 11import codecs
c380cc28 12import collections
62e609ab 13import contextlib
e3946f98 14import ctypes
c496ca96
PH
15import datetime
16import email.utils
0c265486 17import email.header
f45c185f 18import errno
be4a824d 19import functools
d77c3dfd 20import gzip
49fa4d9a
N
21import hashlib
22import hmac
019a94f7 23import importlib.util
03f9daab 24import io
79a2e94e 25import itertools
f4bfd65f 26import json
d77c3dfd 27import locale
02dbf93f 28import math
347de493 29import operator
d77c3dfd 30import os
c496ca96 31import platform
773f291d 32import random
d77c3dfd 33import re
c496ca96 34import socket
79a2e94e 35import ssl
1c088fa8 36import subprocess
d77c3dfd 37import sys
181c8655 38import tempfile
c380cc28 39import time
01951dda 40import traceback
bcf89ce6 41import xml.etree.ElementTree
d77c3dfd 42import zlib
2814f12b 43import mimetypes
d77c3dfd 44
8c25f81b 45from .compat import (
b4a3d461 46 compat_HTMLParseError,
8bb56eee 47 compat_HTMLParser,
201c1459 48 compat_HTTPError,
8f9312c3 49 compat_basestring,
4390d5ec 50 compat_brotli,
8c25f81b 51 compat_chr,
1bab3437 52 compat_cookiejar,
d7cd9a9e 53 compat_ctypes_WINFUNCTYPE,
36e6f62c 54 compat_etree_fromstring,
51098426 55 compat_expanduser,
8c25f81b 56 compat_html_entities,
55b2f099 57 compat_html_entities_html5,
be4a824d 58 compat_http_client,
42db58ec 59 compat_integer_types,
e29663c6 60 compat_numeric_types,
c86b6142 61 compat_kwargs,
efa97bdc 62 compat_os_name,
8c25f81b 63 compat_parse_qs,
06e57990 64 compat_shlex_split,
702ccf2d 65 compat_shlex_quote,
8c25f81b 66 compat_str,
edaa23f8 67 compat_struct_pack,
d3f8e038 68 compat_struct_unpack,
8c25f81b
PH
69 compat_urllib_error,
70 compat_urllib_parse,
15707c7e 71 compat_urllib_parse_urlencode,
8c25f81b 72 compat_urllib_parse_urlparse,
732044af 73 compat_urllib_parse_urlunparse,
74 compat_urllib_parse_quote,
75 compat_urllib_parse_quote_plus,
7581bfc9 76 compat_urllib_parse_unquote_plus,
8c25f81b
PH
77 compat_urllib_request,
78 compat_urlparse,
da42679b 79 compat_websockets,
810c10ba 80 compat_xpath,
8c25f81b 81)
4644ac55 82
71aff188
YCH
83from .socks import (
84 ProxyType,
85 sockssocket,
86)
87
d5820461 88try:
89 import certifi
90 has_certifi = True
91except ImportError:
92 has_certifi = False
93
4644ac55 94
51fb4995
YCH
95def register_socks_protocols():
96 # "Register" SOCKS protocols
d5ae6bb5
YCH
97 # In Python < 2.6.5, urlsplit() suffers from bug https://bugs.python.org/issue7904
98 # URLs with protocols not in urlparse.uses_netloc are not handled correctly
51fb4995
YCH
99 for scheme in ('socks', 'socks4', 'socks4a', 'socks5'):
100 if scheme not in compat_urlparse.uses_netloc:
101 compat_urlparse.uses_netloc.append(scheme)
102
103
468e2e92
FV
104# This is not clearly defined otherwise
105compiled_regex_type = type(re.compile(''))
106
f7a147e3
S
107
108def random_user_agent():
109 _USER_AGENT_TPL = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Safari/537.36'
110 _CHROME_VERSIONS = (
19b4c74d 111 '90.0.4430.212',
112 '90.0.4430.24',
113 '90.0.4430.70',
114 '90.0.4430.72',
115 '90.0.4430.85',
116 '90.0.4430.93',
117 '91.0.4472.101',
118 '91.0.4472.106',
119 '91.0.4472.114',
120 '91.0.4472.124',
121 '91.0.4472.164',
122 '91.0.4472.19',
123 '91.0.4472.77',
124 '92.0.4515.107',
125 '92.0.4515.115',
126 '92.0.4515.131',
127 '92.0.4515.159',
128 '92.0.4515.43',
129 '93.0.4556.0',
130 '93.0.4577.15',
131 '93.0.4577.63',
132 '93.0.4577.82',
133 '94.0.4606.41',
134 '94.0.4606.54',
135 '94.0.4606.61',
136 '94.0.4606.71',
137 '94.0.4606.81',
138 '94.0.4606.85',
139 '95.0.4638.17',
140 '95.0.4638.50',
141 '95.0.4638.54',
142 '95.0.4638.69',
143 '95.0.4638.74',
144 '96.0.4664.18',
145 '96.0.4664.45',
146 '96.0.4664.55',
147 '96.0.4664.93',
148 '97.0.4692.20',
f7a147e3
S
149 )
150 return _USER_AGENT_TPL % random.choice(_CHROME_VERSIONS)
151
152
4390d5ec 153SUPPORTED_ENCODINGS = [
154 'gzip', 'deflate'
155]
156if compat_brotli:
157 SUPPORTED_ENCODINGS.append('br')
158
3e669f36 159std_headers = {
f7a147e3 160 'User-Agent': random_user_agent(),
59ae15a5 161 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
4390d5ec 162 'Accept-Encoding': ', '.join(SUPPORTED_ENCODINGS),
59ae15a5 163 'Accept-Language': 'en-us,en;q=0.5',
b1156c1e 164 'Sec-Fetch-Mode': 'navigate',
3e669f36 165}
f427df17 166
5f6a1245 167
fb37eb25
S
168USER_AGENTS = {
169 'Safari': 'Mozilla/5.0 (X11; Linux x86_64; rv:10.0) AppleWebKit/533.20.25 (KHTML, like Gecko) Version/5.0.4 Safari/533.20.27',
170}
171
172
bf42a990
S
173NO_DEFAULT = object()
174
7105440c
YCH
175ENGLISH_MONTH_NAMES = [
176 'January', 'February', 'March', 'April', 'May', 'June',
177 'July', 'August', 'September', 'October', 'November', 'December']
178
f6717dec
S
179MONTH_NAMES = {
180 'en': ENGLISH_MONTH_NAMES,
181 'fr': [
3e4185c3
S
182 'janvier', 'février', 'mars', 'avril', 'mai', 'juin',
183 'juillet', 'août', 'septembre', 'octobre', 'novembre', 'décembre'],
f6717dec 184}
a942d6cb 185
a7aaa398
S
186KNOWN_EXTENSIONS = (
187 'mp4', 'm4a', 'm4p', 'm4b', 'm4r', 'm4v', 'aac',
188 'flv', 'f4v', 'f4a', 'f4b',
189 'webm', 'ogg', 'ogv', 'oga', 'ogx', 'spx', 'opus',
190 'mkv', 'mka', 'mk3d',
191 'avi', 'divx',
192 'mov',
193 'asf', 'wmv', 'wma',
194 '3gp', '3g2',
195 'mp3',
196 'flac',
197 'ape',
198 'wav',
199 'f4f', 'f4m', 'm3u8', 'smil')
200
c587cbb7 201# needed for sanitizing filenames in restricted mode
c8827027 202ACCENT_CHARS = dict(zip('ÂÃÄÀÁÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖŐØŒÙÚÛÜŰÝÞßàáâãäåæçèéêëìíîïðñòóôõöőøœùúûüűýþÿ',
fd35d8cd
JW
203 itertools.chain('AAAAAA', ['AE'], 'CEEEEIIIIDNOOOOOOO', ['OE'], 'UUUUUY', ['TH', 'ss'],
204 'aaaaaa', ['ae'], 'ceeeeiiiionooooooo', ['oe'], 'uuuuuy', ['th'], 'y')))
c587cbb7 205
46f59e89
S
206DATE_FORMATS = (
207 '%d %B %Y',
208 '%d %b %Y',
209 '%B %d %Y',
cb655f34
S
210 '%B %dst %Y',
211 '%B %dnd %Y',
9d30c213 212 '%B %drd %Y',
cb655f34 213 '%B %dth %Y',
46f59e89 214 '%b %d %Y',
cb655f34
S
215 '%b %dst %Y',
216 '%b %dnd %Y',
9d30c213 217 '%b %drd %Y',
cb655f34 218 '%b %dth %Y',
46f59e89
S
219 '%b %dst %Y %I:%M',
220 '%b %dnd %Y %I:%M',
9d30c213 221 '%b %drd %Y %I:%M',
46f59e89
S
222 '%b %dth %Y %I:%M',
223 '%Y %m %d',
224 '%Y-%m-%d',
bccdbd22 225 '%Y.%m.%d.',
46f59e89 226 '%Y/%m/%d',
81c13222 227 '%Y/%m/%d %H:%M',
46f59e89 228 '%Y/%m/%d %H:%M:%S',
1931a55e
THD
229 '%Y%m%d%H%M',
230 '%Y%m%d%H%M%S',
4f3fa23e 231 '%Y%m%d',
0c1c6f4b 232 '%Y-%m-%d %H:%M',
46f59e89
S
233 '%Y-%m-%d %H:%M:%S',
234 '%Y-%m-%d %H:%M:%S.%f',
5014558a 235 '%Y-%m-%d %H:%M:%S:%f',
46f59e89
S
236 '%d.%m.%Y %H:%M',
237 '%d.%m.%Y %H.%M',
238 '%Y-%m-%dT%H:%M:%SZ',
239 '%Y-%m-%dT%H:%M:%S.%fZ',
240 '%Y-%m-%dT%H:%M:%S.%f0Z',
241 '%Y-%m-%dT%H:%M:%S',
242 '%Y-%m-%dT%H:%M:%S.%f',
243 '%Y-%m-%dT%H:%M',
c6eed6b8
S
244 '%b %d %Y at %H:%M',
245 '%b %d %Y at %H:%M:%S',
b555ae9b
S
246 '%B %d %Y at %H:%M',
247 '%B %d %Y at %H:%M:%S',
a63d9bd0 248 '%H:%M %d-%b-%Y',
46f59e89
S
249)
250
251DATE_FORMATS_DAY_FIRST = list(DATE_FORMATS)
252DATE_FORMATS_DAY_FIRST.extend([
253 '%d-%m-%Y',
254 '%d.%m.%Y',
255 '%d.%m.%y',
256 '%d/%m/%Y',
257 '%d/%m/%y',
258 '%d/%m/%Y %H:%M:%S',
259])
260
261DATE_FORMATS_MONTH_FIRST = list(DATE_FORMATS)
262DATE_FORMATS_MONTH_FIRST.extend([
263 '%m-%d-%Y',
264 '%m.%d.%Y',
265 '%m/%d/%Y',
266 '%m/%d/%y',
267 '%m/%d/%Y %H:%M:%S',
268])
269
06b3fe29 270PACKED_CODES_RE = r"}\('(.+)',(\d+),(\d+),'([^']+)'\.split\('\|'\)"
22f5f5c6 271JSON_LD_RE = r'(?is)<script[^>]+type=(["\']?)application/ld\+json\1[^>]*>(?P<json_ld>.+?)</script>'
06b3fe29 272
7105440c 273
d77c3dfd 274def preferredencoding():
59ae15a5 275 """Get preferred encoding.
d77c3dfd 276
59ae15a5
PH
277 Returns the best encoding scheme for the system, based on
278 locale.getpreferredencoding() and some further tweaks.
279 """
280 try:
281 pref = locale.getpreferredencoding()
28e614de 282 'TEST'.encode(pref)
70a1165b 283 except Exception:
59ae15a5 284 pref = 'UTF-8'
bae611f2 285
59ae15a5 286 return pref
d77c3dfd 287
f4bfd65f 288
181c8655 289def write_json_file(obj, fn):
1394646a 290 """ Encode obj as JSON and write it to fn, atomically if possible """
181c8655 291
92120217 292 fn = encodeFilename(fn)
61ee5aeb 293 if sys.version_info < (3, 0) and sys.platform != 'win32':
ec5f6016
JMF
294 encoding = get_filesystem_encoding()
295 # os.path.basename returns a bytes object, but NamedTemporaryFile
296 # will fail if the filename contains non ascii characters unless we
297 # use a unicode object
298 path_basename = lambda f: os.path.basename(fn).decode(encoding)
299 # the same for os.path.dirname
300 path_dirname = lambda f: os.path.dirname(fn).decode(encoding)
301 else:
302 path_basename = os.path.basename
303 path_dirname = os.path.dirname
304
73159f99
S
305 args = {
306 'suffix': '.tmp',
ec5f6016
JMF
307 'prefix': path_basename(fn) + '.',
308 'dir': path_dirname(fn),
73159f99
S
309 'delete': False,
310 }
311
181c8655
PH
312 # In Python 2.x, json.dump expects a bytestream.
313 # In Python 3.x, it writes to a character stream
314 if sys.version_info < (3, 0):
73159f99 315 args['mode'] = 'wb'
181c8655 316 else:
73159f99
S
317 args.update({
318 'mode': 'w',
319 'encoding': 'utf-8',
320 })
321
c86b6142 322 tf = tempfile.NamedTemporaryFile(**compat_kwargs(args))
181c8655
PH
323
324 try:
325 with tf:
45d86abe 326 json.dump(obj, tf, ensure_ascii=False)
1394646a
IK
327 if sys.platform == 'win32':
328 # Need to remove existing file on Windows, else os.rename raises
329 # WindowsError or FileExistsError.
330 try:
331 os.unlink(fn)
332 except OSError:
333 pass
9cd5f54e
R
334 try:
335 mask = os.umask(0)
336 os.umask(mask)
337 os.chmod(tf.name, 0o666 & ~mask)
338 except OSError:
339 pass
181c8655 340 os.rename(tf.name, fn)
70a1165b 341 except Exception:
181c8655
PH
342 try:
343 os.remove(tf.name)
344 except OSError:
345 pass
346 raise
347
348
349if sys.version_info >= (2, 7):
ee114368 350 def find_xpath_attr(node, xpath, key, val=None):
59ae56fa 351 """ Find the xpath xpath[@key=val] """
5d2354f1 352 assert re.match(r'^[a-zA-Z_-]+$', key)
ee114368 353 expr = xpath + ('[@%s]' % key if val is None else "[@%s='%s']" % (key, val))
59ae56fa
PH
354 return node.find(expr)
355else:
ee114368 356 def find_xpath_attr(node, xpath, key, val=None):
810c10ba 357 for f in node.findall(compat_xpath(xpath)):
ee114368
S
358 if key not in f.attrib:
359 continue
360 if val is None or f.attrib.get(key) == val:
59ae56fa
PH
361 return f
362 return None
363
d7e66d39
JMF
364# On python2.6 the xml.etree.ElementTree.Element methods don't support
365# the namespace parameter
5f6a1245
JW
366
367
d7e66d39
JMF
368def xpath_with_ns(path, ns_map):
369 components = [c.split(':') for c in path.split('/')]
370 replaced = []
371 for c in components:
372 if len(c) == 1:
373 replaced.append(c[0])
374 else:
375 ns, tag = c
376 replaced.append('{%s}%s' % (ns_map[ns], tag))
377 return '/'.join(replaced)
378
d77c3dfd 379
a41fb80c 380def xpath_element(node, xpath, name=None, fatal=False, default=NO_DEFAULT):
578c0745 381 def _find_xpath(xpath):
810c10ba 382 return node.find(compat_xpath(xpath))
578c0745
S
383
384 if isinstance(xpath, (str, compat_str)):
385 n = _find_xpath(xpath)
386 else:
387 for xp in xpath:
388 n = _find_xpath(xp)
389 if n is not None:
390 break
d74bebd5 391
8e636da4 392 if n is None:
bf42a990
S
393 if default is not NO_DEFAULT:
394 return default
395 elif fatal:
bf0ff932
PH
396 name = xpath if name is None else name
397 raise ExtractorError('Could not find XML element %s' % name)
398 else:
399 return None
a41fb80c
S
400 return n
401
402
403def xpath_text(node, xpath, name=None, fatal=False, default=NO_DEFAULT):
8e636da4
S
404 n = xpath_element(node, xpath, name, fatal=fatal, default=default)
405 if n is None or n == default:
406 return n
407 if n.text is None:
408 if default is not NO_DEFAULT:
409 return default
410 elif fatal:
411 name = xpath if name is None else name
412 raise ExtractorError('Could not find XML element\'s text %s' % name)
413 else:
414 return None
415 return n.text
a41fb80c
S
416
417
418def xpath_attr(node, xpath, key, name=None, fatal=False, default=NO_DEFAULT):
419 n = find_xpath_attr(node, xpath, key)
420 if n is None:
421 if default is not NO_DEFAULT:
422 return default
423 elif fatal:
424 name = '%s[@%s]' % (xpath, key) if name is None else name
425 raise ExtractorError('Could not find XML attribute %s' % name)
426 else:
427 return None
428 return n.attrib[key]
bf0ff932
PH
429
430
9e6dd238 431def get_element_by_id(id, html):
43e8fafd 432 """Return the content of the tag with the specified ID in the passed HTML document"""
611c1dd9 433 return get_element_by_attribute('id', id, html)
43e8fafd 434
12ea2f30 435
6f32a0b5
ZM
436def get_element_html_by_id(id, html):
437 """Return the html of the tag with the specified ID in the passed HTML document"""
438 return get_element_html_by_attribute('id', id, html)
439
440
84c237fb 441def get_element_by_class(class_name, html):
2af12ad9
TC
442 """Return the content of the first tag with the specified class in the passed HTML document"""
443 retval = get_elements_by_class(class_name, html)
444 return retval[0] if retval else None
445
446
6f32a0b5
ZM
447def get_element_html_by_class(class_name, html):
448 """Return the html of the first tag with the specified class in the passed HTML document"""
449 retval = get_elements_html_by_class(class_name, html)
450 return retval[0] if retval else None
451
452
2af12ad9
TC
453def get_element_by_attribute(attribute, value, html, escape_value=True):
454 retval = get_elements_by_attribute(attribute, value, html, escape_value)
455 return retval[0] if retval else None
456
457
6f32a0b5
ZM
458def get_element_html_by_attribute(attribute, value, html, escape_value=True):
459 retval = get_elements_html_by_attribute(attribute, value, html, escape_value)
460 return retval[0] if retval else None
461
462
2af12ad9
TC
463def get_elements_by_class(class_name, html):
464 """Return the content of all tags with the specified class in the passed HTML document as a list"""
465 return get_elements_by_attribute(
84c237fb
YCH
466 'class', r'[^\'"]*\b%s\b[^\'"]*' % re.escape(class_name),
467 html, escape_value=False)
468
469
6f32a0b5
ZM
470def get_elements_html_by_class(class_name, html):
471 """Return the html of all tags with the specified class in the passed HTML document as a list"""
472 return get_elements_html_by_attribute(
473 'class', r'[^\'"]*\b%s\b[^\'"]*' % re.escape(class_name),
474 html, escape_value=False)
475
476
477def get_elements_by_attribute(*args, **kwargs):
43e8fafd 478 """Return the content of the tag with the specified attribute in the passed HTML document"""
6f32a0b5
ZM
479 return [content for content, _ in get_elements_text_and_html_by_attribute(*args, **kwargs)]
480
481
482def get_elements_html_by_attribute(*args, **kwargs):
483 """Return the html of the tag with the specified attribute in the passed HTML document"""
484 return [whole for _, whole in get_elements_text_and_html_by_attribute(*args, **kwargs)]
485
486
487def get_elements_text_and_html_by_attribute(attribute, value, html, escape_value=True):
488 """
489 Return the text (content) and the html (whole) of the tag with the specified
490 attribute in the passed HTML document
491 """
9e6dd238 492
0254f162
ZM
493 value_quote_optional = '' if re.match(r'''[\s"'`=<>]''', value) else '?'
494
84c237fb
YCH
495 value = re.escape(value) if escape_value else value
496
0254f162 497 partial_element_re = r'''(?x)
6f32a0b5 498 <(?P<tag>[a-zA-Z0-9:._-]+)
0254f162
ZM
499 (?:\s(?:[^>"']|"[^"]*"|'[^']*')*)?
500 \s%(attribute)s\s*=\s*(?P<_q>['"]%(vqo)s)(?-x:%(value)s)(?P=_q)
501 ''' % {'attribute': re.escape(attribute), 'value': value, 'vqo': value_quote_optional}
38285056 502
0254f162
ZM
503 for m in re.finditer(partial_element_re, html):
504 content, whole = get_element_text_and_html_by_tag(m.group('tag'), html[m.start():])
a921f407 505
0254f162
ZM
506 yield (
507 unescapeHTML(re.sub(r'^(?P<q>["\'])(?P<content>.*)(?P=q)$', r'\g<content>', content, flags=re.DOTALL)),
508 whole
509 )
a921f407 510
c5229f39 511
6f32a0b5
ZM
512class HTMLBreakOnClosingTagParser(compat_HTMLParser):
513 """
514 HTML parser which raises HTMLBreakOnClosingTagException upon reaching the
515 closing tag for the first opening tag it has encountered, and can be used
516 as a context manager
517 """
518
519 class HTMLBreakOnClosingTagException(Exception):
520 pass
521
522 def __init__(self):
523 self.tagstack = collections.deque()
524 compat_HTMLParser.__init__(self)
525
526 def __enter__(self):
527 return self
528
529 def __exit__(self, *_):
530 self.close()
531
532 def close(self):
533 # handle_endtag does not return upon raising HTMLBreakOnClosingTagException,
534 # so data remains buffered; we no longer have any interest in it, thus
535 # override this method to discard it
536 pass
537
538 def handle_starttag(self, tag, _):
539 self.tagstack.append(tag)
540
541 def handle_endtag(self, tag):
542 if not self.tagstack:
543 raise compat_HTMLParseError('no tags in the stack')
544 while self.tagstack:
545 inner_tag = self.tagstack.pop()
546 if inner_tag == tag:
547 break
548 else:
549 raise compat_HTMLParseError(f'matching opening tag for closing {tag} tag not found')
550 if not self.tagstack:
551 raise self.HTMLBreakOnClosingTagException()
552
553
554def get_element_text_and_html_by_tag(tag, html):
555 """
556 For the first element with the specified tag in the passed HTML document
557 return its' content (text) and the whole element (html)
558 """
559 def find_or_raise(haystack, needle, exc):
560 try:
561 return haystack.index(needle)
562 except ValueError:
563 raise exc
564 closing_tag = f'</{tag}>'
565 whole_start = find_or_raise(
566 html, f'<{tag}', compat_HTMLParseError(f'opening {tag} tag not found'))
567 content_start = find_or_raise(
568 html[whole_start:], '>', compat_HTMLParseError(f'malformed opening {tag} tag'))
569 content_start += whole_start + 1
570 with HTMLBreakOnClosingTagParser() as parser:
571 parser.feed(html[whole_start:content_start])
572 if not parser.tagstack or parser.tagstack[0] != tag:
573 raise compat_HTMLParseError(f'parser did not match opening {tag} tag')
574 offset = content_start
575 while offset < len(html):
576 next_closing_tag_start = find_or_raise(
577 html[offset:], closing_tag,
578 compat_HTMLParseError(f'closing {tag} tag not found'))
579 next_closing_tag_end = next_closing_tag_start + len(closing_tag)
580 try:
581 parser.feed(html[offset:offset + next_closing_tag_end])
582 offset += next_closing_tag_end
583 except HTMLBreakOnClosingTagParser.HTMLBreakOnClosingTagException:
584 return html[content_start:offset + next_closing_tag_start], \
585 html[whole_start:offset + next_closing_tag_end]
586 raise compat_HTMLParseError('unexpected end of html')
587
588
8bb56eee
BF
589class HTMLAttributeParser(compat_HTMLParser):
590 """Trivial HTML parser to gather the attributes for a single element"""
b6e0c7d2 591
8bb56eee 592 def __init__(self):
c5229f39 593 self.attrs = {}
8bb56eee
BF
594 compat_HTMLParser.__init__(self)
595
596 def handle_starttag(self, tag, attrs):
597 self.attrs = dict(attrs)
598
c5229f39 599
73673ccf
FF
600class HTMLListAttrsParser(compat_HTMLParser):
601 """HTML parser to gather the attributes for the elements of a list"""
602
603 def __init__(self):
604 compat_HTMLParser.__init__(self)
605 self.items = []
606 self._level = 0
607
608 def handle_starttag(self, tag, attrs):
609 if tag == 'li' and self._level == 0:
610 self.items.append(dict(attrs))
611 self._level += 1
612
613 def handle_endtag(self, tag):
614 self._level -= 1
615
616
8bb56eee
BF
617def extract_attributes(html_element):
618 """Given a string for an HTML element such as
619 <el
620 a="foo" B="bar" c="&98;az" d=boz
621 empty= noval entity="&amp;"
622 sq='"' dq="'"
623 >
624 Decode and return a dictionary of attributes.
625 {
626 'a': 'foo', 'b': 'bar', c: 'baz', d: 'boz',
627 'empty': '', 'noval': None, 'entity': '&',
628 'sq': '"', 'dq': '\''
629 }.
630 NB HTMLParser is stricter in Python 2.6 & 3.2 than in later versions,
631 but the cases in the unit test will work for all of 2.6, 2.7, 3.2-3.5.
632 """
633 parser = HTMLAttributeParser()
b4a3d461
S
634 try:
635 parser.feed(html_element)
636 parser.close()
637 # Older Python may throw HTMLParseError in case of malformed HTML
638 except compat_HTMLParseError:
639 pass
8bb56eee 640 return parser.attrs
9e6dd238 641
c5229f39 642
73673ccf
FF
643def parse_list(webpage):
644 """Given a string for an series of HTML <li> elements,
645 return a dictionary of their attributes"""
646 parser = HTMLListAttrsParser()
647 parser.feed(webpage)
648 parser.close()
649 return parser.items
650
651
9e6dd238 652def clean_html(html):
59ae15a5 653 """Clean an HTML snippet into a readable string"""
dd622d7c
PH
654
655 if html is None: # Convenience for sanitizing descriptions etc.
656 return html
657
49185227 658 html = re.sub(r'\s+', ' ', html)
659 html = re.sub(r'(?u)\s?<\s?br\s?/?\s?>\s?', '\n', html)
660 html = re.sub(r'(?u)<\s?/\s?p\s?>\s?<\s?p[^>]*>', '\n', html)
59ae15a5
PH
661 # Strip html tags
662 html = re.sub('<.*?>', '', html)
663 # Replace html entities
664 html = unescapeHTML(html)
7decf895 665 return html.strip()
9e6dd238
FV
666
667
d77c3dfd 668def sanitize_open(filename, open_mode):
59ae15a5
PH
669 """Try to open the given filename, and slightly tweak it if this fails.
670
671 Attempts to open the given filename. If this fails, it tries to change
672 the filename slightly, step by step, until it's either able to open it
673 or it fails and raises a final exception, like the standard open()
674 function.
675
676 It returns the tuple (stream, definitive_file_name).
677 """
678 try:
28e614de 679 if filename == '-':
59ae15a5
PH
680 if sys.platform == 'win32':
681 import msvcrt
682 msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
898280a0 683 return (sys.stdout.buffer if hasattr(sys.stdout, 'buffer') else sys.stdout, filename)
a3125791 684 stream = locked_file(filename, open_mode, block=False).open()
59ae15a5
PH
685 return (stream, filename)
686 except (IOError, OSError) as err:
f45c185f
PH
687 if err.errno in (errno.EACCES,):
688 raise
59ae15a5 689
f45c185f 690 # In case of error, try to remove win32 forbidden chars
d55de57b 691 alt_filename = sanitize_path(filename)
f45c185f
PH
692 if alt_filename == filename:
693 raise
694 else:
695 # An exception here should be caught in the caller
a3125791 696 stream = locked_file(filename, open_mode, block=False).open()
f45c185f 697 return (stream, alt_filename)
d77c3dfd
FV
698
699
700def timeconvert(timestr):
59ae15a5
PH
701 """Convert RFC 2822 defined time string into system timestamp"""
702 timestamp = None
703 timetuple = email.utils.parsedate_tz(timestr)
704 if timetuple is not None:
705 timestamp = email.utils.mktime_tz(timetuple)
706 return timestamp
1c469a94 707
5f6a1245 708
796173d0 709def sanitize_filename(s, restricted=False, is_id=False):
59ae15a5
PH
710 """Sanitizes a string so it could be used as part of a filename.
711 If restricted is set, use a stricter subset of allowed characters.
158af524
S
712 Set is_id if this is not an arbitrary string, but an ID that should be kept
713 if possible.
59ae15a5
PH
714 """
715 def replace_insane(char):
c587cbb7
AT
716 if restricted and char in ACCENT_CHARS:
717 return ACCENT_CHARS[char]
91dd88b9 718 elif not restricted and char == '\n':
719 return ' '
720 elif char == '?' or ord(char) < 32 or ord(char) == 127:
59ae15a5
PH
721 return ''
722 elif char == '"':
723 return '' if restricted else '\''
724 elif char == ':':
725 return '_-' if restricted else ' -'
726 elif char in '\\/|*<>':
727 return '_'
627dcfff 728 if restricted and (char in '!&\'()[]{}$;`^,#' or char.isspace()):
59ae15a5
PH
729 return '_'
730 if restricted and ord(char) > 127:
731 return '_'
732 return char
733
639f1cea 734 if s == '':
735 return ''
2aeb06d6
PH
736 # Handle timestamps
737 s = re.sub(r'[0-9]+(?::[0-9]+)+', lambda m: m.group(0).replace(':', '_'), s)
28e614de 738 result = ''.join(map(replace_insane, s))
796173d0
PH
739 if not is_id:
740 while '__' in result:
741 result = result.replace('__', '_')
742 result = result.strip('_')
743 # Common case of "Foreign band name - English song title"
744 if restricted and result.startswith('-_'):
745 result = result[2:]
5a42414b
PH
746 if result.startswith('-'):
747 result = '_' + result[len('-'):]
a7440261 748 result = result.lstrip('.')
796173d0
PH
749 if not result:
750 result = '_'
59ae15a5 751 return result
d77c3dfd 752
5f6a1245 753
c2934512 754def sanitize_path(s, force=False):
a2aaf4db 755 """Sanitizes and normalizes path on Windows"""
c2934512 756 if sys.platform == 'win32':
c4218ac3 757 force = False
c2934512 758 drive_or_unc, _ = os.path.splitdrive(s)
759 if sys.version_info < (2, 7) and not drive_or_unc:
760 drive_or_unc, _ = os.path.splitunc(s)
761 elif force:
762 drive_or_unc = ''
763 else:
a2aaf4db 764 return s
c2934512 765
be531ef1
S
766 norm_path = os.path.normpath(remove_start(s, drive_or_unc)).split(os.path.sep)
767 if drive_or_unc:
a2aaf4db
S
768 norm_path.pop(0)
769 sanitized_path = [
ec85ded8 770 path_part if path_part in ['.', '..'] else re.sub(r'(?:[/<>:"\|\\?\*]|[\s.]$)', '#', path_part)
a2aaf4db 771 for path_part in norm_path]
be531ef1
S
772 if drive_or_unc:
773 sanitized_path.insert(0, drive_or_unc + os.path.sep)
c4218ac3 774 elif force and s[0] == os.path.sep:
775 sanitized_path.insert(0, os.path.sep)
a2aaf4db
S
776 return os.path.join(*sanitized_path)
777
778
17bcc626 779def sanitize_url(url):
befa4708
S
780 # Prepend protocol-less URLs with `http:` scheme in order to mitigate
781 # the number of unwanted failures due to missing protocol
782 if url.startswith('//'):
783 return 'http:%s' % url
784 # Fix some common typos seen so far
785 COMMON_TYPOS = (
067aa17e 786 # https://github.com/ytdl-org/youtube-dl/issues/15649
befa4708
S
787 (r'^httpss://', r'https://'),
788 # https://bx1.be/lives/direct-tv/
789 (r'^rmtp([es]?)://', r'rtmp\1://'),
790 )
791 for mistake, fixup in COMMON_TYPOS:
792 if re.match(mistake, url):
793 return re.sub(mistake, fixup, url)
bc6b9bcd 794 return url
17bcc626
S
795
796
5435dcf9
HH
797def extract_basic_auth(url):
798 parts = compat_urlparse.urlsplit(url)
799 if parts.username is None:
800 return url, None
801 url = compat_urlparse.urlunsplit(parts._replace(netloc=(
802 parts.hostname if parts.port is None
803 else '%s:%d' % (parts.hostname, parts.port))))
804 auth_payload = base64.b64encode(
805 ('%s:%s' % (parts.username, parts.password or '')).encode('utf-8'))
806 return url, 'Basic ' + auth_payload.decode('utf-8')
807
808
67dda517 809def sanitized_Request(url, *args, **kwargs):
bc6b9bcd 810 url, auth_header = extract_basic_auth(escape_url(sanitize_url(url)))
5435dcf9
HH
811 if auth_header is not None:
812 headers = args[1] if len(args) >= 2 else kwargs.setdefault('headers', {})
813 headers['Authorization'] = auth_header
814 return compat_urllib_request.Request(url, *args, **kwargs)
67dda517
S
815
816
51098426
S
817def expand_path(s):
818 """Expand shell variables and ~"""
819 return os.path.expandvars(compat_expanduser(s))
820
821
d77c3dfd 822def orderedSet(iterable):
59ae15a5
PH
823 """ Remove all duplicates from the input iterable """
824 res = []
825 for el in iterable:
826 if el not in res:
827 res.append(el)
828 return res
d77c3dfd 829
912b38b4 830
55b2f099 831def _htmlentity_transform(entity_with_semicolon):
4e408e47 832 """Transforms an HTML entity to a character."""
55b2f099
YCH
833 entity = entity_with_semicolon[:-1]
834
4e408e47
PH
835 # Known non-numeric HTML entity
836 if entity in compat_html_entities.name2codepoint:
837 return compat_chr(compat_html_entities.name2codepoint[entity])
838
55b2f099
YCH
839 # TODO: HTML5 allows entities without a semicolon. For example,
840 # '&Eacuteric' should be decoded as 'Éric'.
841 if entity_with_semicolon in compat_html_entities_html5:
842 return compat_html_entities_html5[entity_with_semicolon]
843
91757b0f 844 mobj = re.match(r'#(x[0-9a-fA-F]+|[0-9]+)', entity)
4e408e47
PH
845 if mobj is not None:
846 numstr = mobj.group(1)
28e614de 847 if numstr.startswith('x'):
4e408e47 848 base = 16
28e614de 849 numstr = '0%s' % numstr
4e408e47
PH
850 else:
851 base = 10
067aa17e 852 # See https://github.com/ytdl-org/youtube-dl/issues/7518
7aefc49c
S
853 try:
854 return compat_chr(int(numstr, base))
855 except ValueError:
856 pass
4e408e47
PH
857
858 # Unknown entity in name, return its literal representation
7a3f0c00 859 return '&%s;' % entity
4e408e47
PH
860
861
d77c3dfd 862def unescapeHTML(s):
912b38b4
PH
863 if s is None:
864 return None
865 assert type(s) == compat_str
d77c3dfd 866
4e408e47 867 return re.sub(
95f3f7c2 868 r'&([^&;]+;)', lambda m: _htmlentity_transform(m.group(1)), s)
d77c3dfd 869
8bf48f23 870
cdb19aa4 871def escapeHTML(text):
872 return (
873 text
874 .replace('&', '&amp;')
875 .replace('<', '&lt;')
876 .replace('>', '&gt;')
877 .replace('"', '&quot;')
878 .replace("'", '&#39;')
879 )
880
881
f5b1bca9 882def process_communicate_or_kill(p, *args, **kwargs):
883 try:
884 return p.communicate(*args, **kwargs)
885 except BaseException: # Including KeyboardInterrupt
886 p.kill()
887 p.wait()
888 raise
889
890
d3c93ec2 891class Popen(subprocess.Popen):
892 if sys.platform == 'win32':
893 _startupinfo = subprocess.STARTUPINFO()
894 _startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
895 else:
896 _startupinfo = None
897
898 def __init__(self, *args, **kwargs):
899 super(Popen, self).__init__(*args, **kwargs, startupinfo=self._startupinfo)
900
901 def communicate_or_kill(self, *args, **kwargs):
902 return process_communicate_or_kill(self, *args, **kwargs)
903
904
aa49acd1
S
905def get_subprocess_encoding():
906 if sys.platform == 'win32' and sys.getwindowsversion()[0] >= 5:
907 # For subprocess calls, encode with locale encoding
908 # Refer to http://stackoverflow.com/a/9951851/35070
909 encoding = preferredencoding()
910 else:
911 encoding = sys.getfilesystemencoding()
912 if encoding is None:
913 encoding = 'utf-8'
914 return encoding
915
916
8bf48f23 917def encodeFilename(s, for_subprocess=False):
59ae15a5
PH
918 """
919 @param s The name of the file
920 """
d77c3dfd 921
8bf48f23 922 assert type(s) == compat_str
d77c3dfd 923
59ae15a5
PH
924 # Python 3 has a Unicode API
925 if sys.version_info >= (3, 0):
926 return s
0f00efed 927
aa49acd1
S
928 # Pass '' directly to use Unicode APIs on Windows 2000 and up
929 # (Detecting Windows NT 4 is tricky because 'major >= 4' would
930 # match Windows 9x series as well. Besides, NT 4 is obsolete.)
931 if not for_subprocess and sys.platform == 'win32' and sys.getwindowsversion()[0] >= 5:
932 return s
933
8ee239e9
YCH
934 # Jython assumes filenames are Unicode strings though reported as Python 2.x compatible
935 if sys.platform.startswith('java'):
936 return s
937
aa49acd1
S
938 return s.encode(get_subprocess_encoding(), 'ignore')
939
940
941def decodeFilename(b, for_subprocess=False):
942
943 if sys.version_info >= (3, 0):
944 return b
945
946 if not isinstance(b, bytes):
947 return b
948
949 return b.decode(get_subprocess_encoding(), 'ignore')
8bf48f23 950
f07b74fc
PH
951
952def encodeArgument(s):
953 if not isinstance(s, compat_str):
954 # Legacy code that uses byte strings
955 # Uncomment the following line after fixing all post processors
7af808a5 956 # assert False, 'Internal error: %r should be of type %r, is %r' % (s, compat_str, type(s))
f07b74fc
PH
957 s = s.decode('ascii')
958 return encodeFilename(s, True)
959
960
aa49acd1
S
961def decodeArgument(b):
962 return decodeFilename(b, True)
963
964
8271226a
PH
965def decodeOption(optval):
966 if optval is None:
967 return optval
968 if isinstance(optval, bytes):
969 optval = optval.decode(preferredencoding())
970
971 assert isinstance(optval, compat_str)
972 return optval
1c256f70 973
5f6a1245 974
aa7785f8 975_timetuple = collections.namedtuple('Time', ('hours', 'minutes', 'seconds', 'milliseconds'))
976
977
978def timetuple_from_msec(msec):
979 secs, msec = divmod(msec, 1000)
980 mins, secs = divmod(secs, 60)
981 hrs, mins = divmod(mins, 60)
982 return _timetuple(hrs, mins, secs, msec)
983
984
cdb19aa4 985def formatSeconds(secs, delim=':', msec=False):
aa7785f8 986 time = timetuple_from_msec(secs * 1000)
987 if time.hours:
988 ret = '%d%s%02d%s%02d' % (time.hours, delim, time.minutes, delim, time.seconds)
989 elif time.minutes:
990 ret = '%d%s%02d' % (time.minutes, delim, time.seconds)
4539dd30 991 else:
aa7785f8 992 ret = '%d' % time.seconds
993 return '%s.%03d' % (ret, time.milliseconds) if msec else ret
4539dd30 994
a0ddb8a2 995
77562778 996def _ssl_load_windows_store_certs(ssl_context, storename):
997 # Code adapted from _load_windows_store_certs in https://github.com/python/cpython/blob/main/Lib/ssl.py
998 try:
999 certs = [cert for cert, encoding, trust in ssl.enum_certificates(storename)
1000 if encoding == 'x509_asn' and (
1001 trust is True or ssl.Purpose.SERVER_AUTH.oid in trust)]
1002 except PermissionError:
1003 return
1004 for cert in certs:
a2366922 1005 try:
77562778 1006 ssl_context.load_verify_locations(cadata=cert)
1007 except ssl.SSLError:
a2366922
PH
1008 pass
1009
77562778 1010
1011def make_HTTPS_handler(params, **kwargs):
1012 opts_check_certificate = not params.get('nocheckcertificate')
1013 context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
1014 context.check_hostname = opts_check_certificate
f81c62a6 1015 if params.get('legacyserverconnect'):
1016 context.options |= 4 # SSL_OP_LEGACY_SERVER_CONNECT
77562778 1017 context.verify_mode = ssl.CERT_REQUIRED if opts_check_certificate else ssl.CERT_NONE
1018 if opts_check_certificate:
d5820461 1019 if has_certifi and 'no-certifi' not in params.get('compat_opts', []):
1020 context.load_verify_locations(cafile=certifi.where())
1021 else:
1022 try:
1023 context.load_default_certs()
1024 # Work around the issue in load_default_certs when there are bad certificates. See:
1025 # https://github.com/yt-dlp/yt-dlp/issues/1060,
1026 # https://bugs.python.org/issue35665, https://bugs.python.org/issue45312
1027 except ssl.SSLError:
1028 # enum_certificates is not present in mingw python. See https://github.com/yt-dlp/yt-dlp/issues/1151
1029 if sys.platform == 'win32' and hasattr(ssl, 'enum_certificates'):
1030 # Create a new context to discard any certificates that were already loaded
1031 context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
1032 context.check_hostname, context.verify_mode = True, ssl.CERT_REQUIRED
1033 for storename in ('CA', 'ROOT'):
1034 _ssl_load_windows_store_certs(context, storename)
1035 context.set_default_verify_paths()
77562778 1036 return YoutubeDLHTTPSHandler(params, context=context, **kwargs)
ea6d901e 1037
732ea2f0 1038
5873d4cc 1039def bug_reports_message(before=';'):
455a15e2 1040 msg = ('please report this issue on https://github.com/yt-dlp/yt-dlp , '
592b7485 1041 'filling out the appropriate issue template. '
08d30158 1042 'Confirm you are on the latest version using yt-dlp -U')
5873d4cc
F
1043
1044 before = before.rstrip()
1045 if not before or before.endswith(('.', '!', '?')):
1046 msg = msg[0].title() + msg[1:]
1047
1048 return (before + ' ' if before else '') + msg
08f2a92c
JMF
1049
1050
bf5b9d85
PM
1051class YoutubeDLError(Exception):
1052 """Base exception for YoutubeDL errors."""
aa9369a2 1053 msg = None
1054
1055 def __init__(self, msg=None):
1056 if msg is not None:
1057 self.msg = msg
1058 elif self.msg is None:
1059 self.msg = type(self).__name__
1060 super().__init__(self.msg)
bf5b9d85
PM
1061
1062
3158150c 1063network_exceptions = [compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error]
1064if hasattr(ssl, 'CertificateError'):
1065 network_exceptions.append(ssl.CertificateError)
1066network_exceptions = tuple(network_exceptions)
1067
1068
bf5b9d85 1069class ExtractorError(YoutubeDLError):
1c256f70 1070 """Error during info extraction."""
5f6a1245 1071
1151c407 1072 def __init__(self, msg, tb=None, expected=False, cause=None, video_id=None, ie=None):
9a82b238 1073 """ tb, if given, is the original traceback (so that it can be printed out).
7a5c1cfe 1074 If expected is set, this is a normal error message and most likely not a bug in yt-dlp.
9a82b238 1075 """
3158150c 1076 if sys.exc_info()[0] in network_exceptions:
9a82b238 1077 expected = True
d5979c5d 1078
7265a219 1079 self.orig_msg = str(msg)
1c256f70 1080 self.traceback = tb
1151c407 1081 self.expected = expected
2eabb802 1082 self.cause = cause
d11271dd 1083 self.video_id = video_id
1151c407 1084 self.ie = ie
1085 self.exc_info = sys.exc_info() # preserve original exception
1086
1087 super(ExtractorError, self).__init__(''.join((
1088 format_field(ie, template='[%s] '),
1089 format_field(video_id, template='%s: '),
7265a219 1090 msg,
1151c407 1091 format_field(cause, template=' (caused by %r)'),
1092 '' if expected else bug_reports_message())))
1c256f70 1093
01951dda 1094 def format_traceback(self):
497d2fab 1095 return join_nonempty(
1096 self.traceback and ''.join(traceback.format_tb(self.traceback)),
e491d06d 1097 self.cause and ''.join(traceback.format_exception(None, self.cause, self.cause.__traceback__)[1:]),
497d2fab 1098 delim='\n') or None
01951dda 1099
1c256f70 1100
416c7fcb
PH
1101class UnsupportedError(ExtractorError):
1102 def __init__(self, url):
1103 super(UnsupportedError, self).__init__(
1104 'Unsupported URL: %s' % url, expected=True)
1105 self.url = url
1106
1107
55b3e45b
JMF
1108class RegexNotFoundError(ExtractorError):
1109 """Error when a regex didn't match"""
1110 pass
1111
1112
773f291d
S
1113class GeoRestrictedError(ExtractorError):
1114 """Geographic restriction Error exception.
1115
1116 This exception may be thrown when a video is not available from your
1117 geographic location due to geographic restrictions imposed by a website.
1118 """
b6e0c7d2 1119
0db3bae8 1120 def __init__(self, msg, countries=None, **kwargs):
1121 kwargs['expected'] = True
1122 super(GeoRestrictedError, self).__init__(msg, **kwargs)
773f291d
S
1123 self.countries = countries
1124
1125
bf5b9d85 1126class DownloadError(YoutubeDLError):
59ae15a5 1127 """Download Error exception.
d77c3dfd 1128
59ae15a5
PH
1129 This exception may be thrown by FileDownloader objects if they are not
1130 configured to continue on errors. They will contain the appropriate
1131 error message.
1132 """
5f6a1245 1133
8cc83b8d
FV
1134 def __init__(self, msg, exc_info=None):
1135 """ exc_info, if given, is the original exception that caused the trouble (as returned by sys.exc_info()). """
1136 super(DownloadError, self).__init__(msg)
1137 self.exc_info = exc_info
d77c3dfd
FV
1138
1139
498f5606 1140class EntryNotInPlaylist(YoutubeDLError):
1141 """Entry not in playlist exception.
1142
1143 This exception will be thrown by YoutubeDL when a requested entry
1144 is not found in the playlist info_dict
1145 """
aa9369a2 1146 msg = 'Entry not found in info'
498f5606 1147
1148
bf5b9d85 1149class SameFileError(YoutubeDLError):
59ae15a5 1150 """Same File exception.
d77c3dfd 1151
59ae15a5
PH
1152 This exception will be thrown by FileDownloader objects if they detect
1153 multiple files would have to be downloaded to the same file on disk.
1154 """
aa9369a2 1155 msg = 'Fixed output name but more than one file to download'
1156
1157 def __init__(self, filename=None):
1158 if filename is not None:
1159 self.msg += f': {filename}'
1160 super().__init__(self.msg)
d77c3dfd
FV
1161
1162
bf5b9d85 1163class PostProcessingError(YoutubeDLError):
59ae15a5 1164 """Post Processing exception.
d77c3dfd 1165
59ae15a5
PH
1166 This exception may be raised by PostProcessor's .run() method to
1167 indicate an error in the postprocessing task.
1168 """
5f6a1245 1169
5f6a1245 1170
48f79687 1171class DownloadCancelled(YoutubeDLError):
1172 """ Exception raised when the download queue should be interrupted """
1173 msg = 'The download was cancelled'
8b0d7497 1174
8b0d7497 1175
48f79687 1176class ExistingVideoReached(DownloadCancelled):
1177 """ --break-on-existing triggered """
1178 msg = 'Encountered a video that is already in the archive, stopping due to --break-on-existing'
8b0d7497 1179
48f79687 1180
1181class RejectedVideoReached(DownloadCancelled):
1182 """ --break-on-reject triggered """
1183 msg = 'Encountered a video that did not match filter, stopping due to --break-on-reject'
51d9739f 1184
1185
48f79687 1186class MaxDownloadsReached(DownloadCancelled):
59ae15a5 1187 """ --max-downloads limit has been reached. """
48f79687 1188 msg = 'Maximum number of downloads reached, stopping due to --max-downloads'
1189
1190
f2ebc5c7 1191class ReExtractInfo(YoutubeDLError):
1192 """ Video info needs to be re-extracted. """
1193
1194 def __init__(self, msg, expected=False):
1195 super().__init__(msg)
1196 self.expected = expected
1197
1198
1199class ThrottledDownload(ReExtractInfo):
48f79687 1200 """ Download speed below --throttled-rate. """
aa9369a2 1201 msg = 'The download speed is below throttle limit'
d77c3dfd 1202
43b22906 1203 def __init__(self):
1204 super().__init__(self.msg, expected=False)
f2ebc5c7 1205
d77c3dfd 1206
bf5b9d85 1207class UnavailableVideoError(YoutubeDLError):
59ae15a5 1208 """Unavailable Format exception.
d77c3dfd 1209
59ae15a5
PH
1210 This exception will be thrown when a video is requested
1211 in a format that is not available for that video.
1212 """
aa9369a2 1213 msg = 'Unable to download video'
1214
1215 def __init__(self, err=None):
1216 if err is not None:
1217 self.msg += f': {err}'
1218 super().__init__(self.msg)
d77c3dfd
FV
1219
1220
bf5b9d85 1221class ContentTooShortError(YoutubeDLError):
59ae15a5 1222 """Content Too Short exception.
d77c3dfd 1223
59ae15a5
PH
1224 This exception may be raised by FileDownloader objects when a file they
1225 download is too small for what the server announced first, indicating
1226 the connection was probably interrupted.
1227 """
d77c3dfd 1228
59ae15a5 1229 def __init__(self, downloaded, expected):
bf5b9d85
PM
1230 super(ContentTooShortError, self).__init__(
1231 'Downloaded {0} bytes, expected {1} bytes'.format(downloaded, expected)
1232 )
2c7ed247 1233 # Both in bytes
59ae15a5
PH
1234 self.downloaded = downloaded
1235 self.expected = expected
d77c3dfd 1236
5f6a1245 1237
bf5b9d85 1238class XAttrMetadataError(YoutubeDLError):
efa97bdc
YCH
1239 def __init__(self, code=None, msg='Unknown error'):
1240 super(XAttrMetadataError, self).__init__(msg)
1241 self.code = code
bd264412 1242 self.msg = msg
efa97bdc
YCH
1243
1244 # Parsing code and msg
3089bc74 1245 if (self.code in (errno.ENOSPC, errno.EDQUOT)
a0566bbf 1246 or 'No space left' in self.msg or 'Disk quota exceeded' in self.msg):
efa97bdc
YCH
1247 self.reason = 'NO_SPACE'
1248 elif self.code == errno.E2BIG or 'Argument list too long' in self.msg:
1249 self.reason = 'VALUE_TOO_LONG'
1250 else:
1251 self.reason = 'NOT_SUPPORTED'
1252
1253
bf5b9d85 1254class XAttrUnavailableError(YoutubeDLError):
efa97bdc
YCH
1255 pass
1256
1257
c5a59d93 1258def _create_http_connection(ydl_handler, http_class, is_https, *args, **kwargs):
e5e78797
S
1259 # Working around python 2 bug (see http://bugs.python.org/issue17849) by limiting
1260 # expected HTTP responses to meet HTTP/1.0 or later (see also
067aa17e 1261 # https://github.com/ytdl-org/youtube-dl/issues/6727)
e5e78797 1262 if sys.version_info < (3, 0):
65220c3b
S
1263 kwargs['strict'] = True
1264 hc = http_class(*args, **compat_kwargs(kwargs))
be4a824d 1265 source_address = ydl_handler._params.get('source_address')
8959018a 1266
be4a824d 1267 if source_address is not None:
8959018a
AU
1268 # This is to workaround _create_connection() from socket where it will try all
1269 # address data from getaddrinfo() including IPv6. This filters the result from
1270 # getaddrinfo() based on the source_address value.
1271 # This is based on the cpython socket.create_connection() function.
1272 # https://github.com/python/cpython/blob/master/Lib/socket.py#L691
1273 def _create_connection(address, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, source_address=None):
1274 host, port = address
1275 err = None
1276 addrs = socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM)
9e21e6d9
S
1277 af = socket.AF_INET if '.' in source_address[0] else socket.AF_INET6
1278 ip_addrs = [addr for addr in addrs if addr[0] == af]
1279 if addrs and not ip_addrs:
1280 ip_version = 'v4' if af == socket.AF_INET else 'v6'
1281 raise socket.error(
1282 "No remote IP%s addresses available for connect, can't use '%s' as source address"
1283 % (ip_version, source_address[0]))
8959018a
AU
1284 for res in ip_addrs:
1285 af, socktype, proto, canonname, sa = res
1286 sock = None
1287 try:
1288 sock = socket.socket(af, socktype, proto)
1289 if timeout is not socket._GLOBAL_DEFAULT_TIMEOUT:
1290 sock.settimeout(timeout)
1291 sock.bind(source_address)
1292 sock.connect(sa)
1293 err = None # Explicitly break reference cycle
1294 return sock
1295 except socket.error as _:
1296 err = _
1297 if sock is not None:
1298 sock.close()
1299 if err is not None:
1300 raise err
1301 else:
9e21e6d9
S
1302 raise socket.error('getaddrinfo returns an empty list')
1303 if hasattr(hc, '_create_connection'):
1304 hc._create_connection = _create_connection
be4a824d
PH
1305 sa = (source_address, 0)
1306 if hasattr(hc, 'source_address'): # Python 2.7+
1307 hc.source_address = sa
1308 else: # Python 2.6
1309 def _hc_connect(self, *args, **kwargs):
9e21e6d9 1310 sock = _create_connection(
be4a824d
PH
1311 (self.host, self.port), self.timeout, sa)
1312 if is_https:
d7932313
PH
1313 self.sock = ssl.wrap_socket(
1314 sock, self.key_file, self.cert_file,
1315 ssl_version=ssl.PROTOCOL_TLSv1)
be4a824d
PH
1316 else:
1317 self.sock = sock
1318 hc.connect = functools.partial(_hc_connect, hc)
1319
1320 return hc
1321
1322
87f0e62d 1323def handle_youtubedl_headers(headers):
992fc9d6
YCH
1324 filtered_headers = headers
1325
1326 if 'Youtubedl-no-compression' in filtered_headers:
1327 filtered_headers = dict((k, v) for k, v in filtered_headers.items() if k.lower() != 'accept-encoding')
87f0e62d 1328 del filtered_headers['Youtubedl-no-compression']
87f0e62d 1329
992fc9d6 1330 return filtered_headers
87f0e62d
YCH
1331
1332
acebc9cd 1333class YoutubeDLHandler(compat_urllib_request.HTTPHandler):
59ae15a5
PH
1334 """Handler for HTTP requests and responses.
1335
1336 This class, when installed with an OpenerDirector, automatically adds
1337 the standard headers to every HTTP request and handles gzipped and
1338 deflated responses from web servers. If compression is to be avoided in
1339 a particular request, the original request in the program code only has
0424ec30 1340 to include the HTTP header "Youtubedl-no-compression", which will be
59ae15a5
PH
1341 removed before making the real request.
1342
1343 Part of this code was copied from:
1344
1345 http://techknack.net/python-urllib2-handlers/
1346
1347 Andrew Rowls, the author of that code, agreed to release it to the
1348 public domain.
1349 """
1350
be4a824d
PH
1351 def __init__(self, params, *args, **kwargs):
1352 compat_urllib_request.HTTPHandler.__init__(self, *args, **kwargs)
1353 self._params = params
1354
1355 def http_open(self, req):
71aff188
YCH
1356 conn_class = compat_http_client.HTTPConnection
1357
1358 socks_proxy = req.headers.get('Ytdl-socks-proxy')
1359 if socks_proxy:
1360 conn_class = make_socks_conn_class(conn_class, socks_proxy)
1361 del req.headers['Ytdl-socks-proxy']
1362
be4a824d 1363 return self.do_open(functools.partial(
71aff188 1364 _create_http_connection, self, conn_class, False),
be4a824d
PH
1365 req)
1366
59ae15a5
PH
1367 @staticmethod
1368 def deflate(data):
fc2119f2 1369 if not data:
1370 return data
59ae15a5
PH
1371 try:
1372 return zlib.decompress(data, -zlib.MAX_WBITS)
1373 except zlib.error:
1374 return zlib.decompress(data)
1375
4390d5ec 1376 @staticmethod
1377 def brotli(data):
1378 if not data:
1379 return data
1380 return compat_brotli.decompress(data)
1381
acebc9cd 1382 def http_request(self, req):
51f267d9
S
1383 # According to RFC 3986, URLs can not contain non-ASCII characters, however this is not
1384 # always respected by websites, some tend to give out URLs with non percent-encoded
1385 # non-ASCII characters (see telemb.py, ard.py [#3412])
1386 # urllib chokes on URLs with non-ASCII characters (see http://bugs.python.org/issue3991)
1387 # To work around aforementioned issue we will replace request's original URL with
1388 # percent-encoded one
1389 # Since redirects are also affected (e.g. http://www.southpark.de/alle-episoden/s18e09)
1390 # the code of this workaround has been moved here from YoutubeDL.urlopen()
1391 url = req.get_full_url()
1392 url_escaped = escape_url(url)
1393
1394 # Substitute URL if any change after escaping
1395 if url != url_escaped:
15d260eb 1396 req = update_Request(req, url=url_escaped)
51f267d9 1397
8b7539d2 1398 for h, v in self._params.get('http_headers', std_headers).items():
3d5f7a39
JK
1399 # Capitalize is needed because of Python bug 2275: http://bugs.python.org/issue2275
1400 # The dict keys are capitalized because of this bug by urllib
1401 if h.capitalize() not in req.headers:
33ac271b 1402 req.add_header(h, v)
87f0e62d
YCH
1403
1404 req.headers = handle_youtubedl_headers(req.headers)
989b4b2b
PH
1405
1406 if sys.version_info < (2, 7) and '#' in req.get_full_url():
1407 # Python 2.6 is brain-dead when it comes to fragments
1408 req._Request__original = req._Request__original.partition('#')[0]
1409 req._Request__r_type = req._Request__r_type.partition('#')[0]
1410
59ae15a5
PH
1411 return req
1412
acebc9cd 1413 def http_response(self, req, resp):
59ae15a5
PH
1414 old_resp = resp
1415 # gzip
1416 if resp.headers.get('Content-encoding', '') == 'gzip':
aa3e9507
PH
1417 content = resp.read()
1418 gz = gzip.GzipFile(fileobj=io.BytesIO(content), mode='rb')
1419 try:
1420 uncompressed = io.BytesIO(gz.read())
1421 except IOError as original_ioerror:
1422 # There may be junk add the end of the file
1423 # See http://stackoverflow.com/q/4928560/35070 for details
1424 for i in range(1, 1024):
1425 try:
1426 gz = gzip.GzipFile(fileobj=io.BytesIO(content[:-i]), mode='rb')
1427 uncompressed = io.BytesIO(gz.read())
1428 except IOError:
1429 continue
1430 break
1431 else:
1432 raise original_ioerror
b407d853 1433 resp = compat_urllib_request.addinfourl(uncompressed, old_resp.headers, old_resp.url, old_resp.code)
59ae15a5 1434 resp.msg = old_resp.msg
c047270c 1435 del resp.headers['Content-encoding']
59ae15a5
PH
1436 # deflate
1437 if resp.headers.get('Content-encoding', '') == 'deflate':
1438 gz = io.BytesIO(self.deflate(resp.read()))
b407d853 1439 resp = compat_urllib_request.addinfourl(gz, old_resp.headers, old_resp.url, old_resp.code)
59ae15a5 1440 resp.msg = old_resp.msg
c047270c 1441 del resp.headers['Content-encoding']
4390d5ec 1442 # brotli
1443 if resp.headers.get('Content-encoding', '') == 'br':
1444 resp = compat_urllib_request.addinfourl(
1445 io.BytesIO(self.brotli(resp.read())), old_resp.headers, old_resp.url, old_resp.code)
1446 resp.msg = old_resp.msg
1447 del resp.headers['Content-encoding']
ad729172 1448 # Percent-encode redirect URL of Location HTTP header to satisfy RFC 3986 (see
067aa17e 1449 # https://github.com/ytdl-org/youtube-dl/issues/6457).
5a4d9ddb
S
1450 if 300 <= resp.code < 400:
1451 location = resp.headers.get('Location')
1452 if location:
1453 # As of RFC 2616 default charset is iso-8859-1 that is respected by python 3
1454 if sys.version_info >= (3, 0):
1455 location = location.encode('iso-8859-1').decode('utf-8')
0ea59007
YCH
1456 else:
1457 location = location.decode('utf-8')
5a4d9ddb
S
1458 location_escaped = escape_url(location)
1459 if location != location_escaped:
1460 del resp.headers['Location']
9a4aec8b
YCH
1461 if sys.version_info < (3, 0):
1462 location_escaped = location_escaped.encode('utf-8')
5a4d9ddb 1463 resp.headers['Location'] = location_escaped
59ae15a5 1464 return resp
0f8d03f8 1465
acebc9cd
PH
1466 https_request = http_request
1467 https_response = http_response
bf50b038 1468
5de90176 1469
71aff188
YCH
1470def make_socks_conn_class(base_class, socks_proxy):
1471 assert issubclass(base_class, (
1472 compat_http_client.HTTPConnection, compat_http_client.HTTPSConnection))
1473
1474 url_components = compat_urlparse.urlparse(socks_proxy)
1475 if url_components.scheme.lower() == 'socks5':
1476 socks_type = ProxyType.SOCKS5
1477 elif url_components.scheme.lower() in ('socks', 'socks4'):
1478 socks_type = ProxyType.SOCKS4
51fb4995
YCH
1479 elif url_components.scheme.lower() == 'socks4a':
1480 socks_type = ProxyType.SOCKS4A
71aff188 1481
cdd94c2e
YCH
1482 def unquote_if_non_empty(s):
1483 if not s:
1484 return s
1485 return compat_urllib_parse_unquote_plus(s)
1486
71aff188
YCH
1487 proxy_args = (
1488 socks_type,
1489 url_components.hostname, url_components.port or 1080,
1490 True, # Remote DNS
cdd94c2e
YCH
1491 unquote_if_non_empty(url_components.username),
1492 unquote_if_non_empty(url_components.password),
71aff188
YCH
1493 )
1494
1495 class SocksConnection(base_class):
1496 def connect(self):
1497 self.sock = sockssocket()
1498 self.sock.setproxy(*proxy_args)
1499 if type(self.timeout) in (int, float):
1500 self.sock.settimeout(self.timeout)
1501 self.sock.connect((self.host, self.port))
1502
1503 if isinstance(self, compat_http_client.HTTPSConnection):
1504 if hasattr(self, '_context'): # Python > 2.6
1505 self.sock = self._context.wrap_socket(
1506 self.sock, server_hostname=self.host)
1507 else:
1508 self.sock = ssl.wrap_socket(self.sock)
1509
1510 return SocksConnection
1511
1512
be4a824d
PH
1513class YoutubeDLHTTPSHandler(compat_urllib_request.HTTPSHandler):
1514 def __init__(self, params, https_conn_class=None, *args, **kwargs):
1515 compat_urllib_request.HTTPSHandler.__init__(self, *args, **kwargs)
1516 self._https_conn_class = https_conn_class or compat_http_client.HTTPSConnection
1517 self._params = params
1518
1519 def https_open(self, req):
4f264c02 1520 kwargs = {}
71aff188
YCH
1521 conn_class = self._https_conn_class
1522
4f264c02
JMF
1523 if hasattr(self, '_context'): # python > 2.6
1524 kwargs['context'] = self._context
1525 if hasattr(self, '_check_hostname'): # python 3.x
1526 kwargs['check_hostname'] = self._check_hostname
71aff188
YCH
1527
1528 socks_proxy = req.headers.get('Ytdl-socks-proxy')
1529 if socks_proxy:
1530 conn_class = make_socks_conn_class(conn_class, socks_proxy)
1531 del req.headers['Ytdl-socks-proxy']
1532
be4a824d 1533 return self.do_open(functools.partial(
71aff188 1534 _create_http_connection, self, conn_class, True),
4f264c02 1535 req, **kwargs)
be4a824d
PH
1536
1537
1bab3437 1538class YoutubeDLCookieJar(compat_cookiejar.MozillaCookieJar):
f1a8511f
S
1539 """
1540 See [1] for cookie file format.
1541
1542 1. https://curl.haxx.se/docs/http-cookies.html
1543 """
e7e62441 1544 _HTTPONLY_PREFIX = '#HttpOnly_'
c380cc28
S
1545 _ENTRY_LEN = 7
1546 _HEADER = '''# Netscape HTTP Cookie File
7a5c1cfe 1547# This file is generated by yt-dlp. Do not edit.
c380cc28
S
1548
1549'''
1550 _CookieFileEntry = collections.namedtuple(
1551 'CookieFileEntry',
1552 ('domain_name', 'include_subdomains', 'path', 'https_only', 'expires_at', 'name', 'value'))
e7e62441 1553
1bab3437 1554 def save(self, filename=None, ignore_discard=False, ignore_expires=False):
c380cc28
S
1555 """
1556 Save cookies to a file.
1557
1558 Most of the code is taken from CPython 3.8 and slightly adapted
1559 to support cookie files with UTF-8 in both python 2 and 3.
1560 """
1561 if filename is None:
1562 if self.filename is not None:
1563 filename = self.filename
1564 else:
1565 raise ValueError(compat_cookiejar.MISSING_FILENAME_TEXT)
1566
1bab3437
S
1567 # Store session cookies with `expires` set to 0 instead of an empty
1568 # string
1569 for cookie in self:
1570 if cookie.expires is None:
1571 cookie.expires = 0
c380cc28
S
1572
1573 with io.open(filename, 'w', encoding='utf-8') as f:
1574 f.write(self._HEADER)
1575 now = time.time()
1576 for cookie in self:
1577 if not ignore_discard and cookie.discard:
1578 continue
1579 if not ignore_expires and cookie.is_expired(now):
1580 continue
1581 if cookie.secure:
1582 secure = 'TRUE'
1583 else:
1584 secure = 'FALSE'
1585 if cookie.domain.startswith('.'):
1586 initial_dot = 'TRUE'
1587 else:
1588 initial_dot = 'FALSE'
1589 if cookie.expires is not None:
1590 expires = compat_str(cookie.expires)
1591 else:
1592 expires = ''
1593 if cookie.value is None:
1594 # cookies.txt regards 'Set-Cookie: foo' as a cookie
1595 # with no name, whereas http.cookiejar regards it as a
1596 # cookie with no value.
1597 name = ''
1598 value = cookie.name
1599 else:
1600 name = cookie.name
1601 value = cookie.value
1602 f.write(
1603 '\t'.join([cookie.domain, initial_dot, cookie.path,
1604 secure, expires, name, value]) + '\n')
1bab3437
S
1605
1606 def load(self, filename=None, ignore_discard=False, ignore_expires=False):
e7e62441 1607 """Load cookies from a file."""
1608 if filename is None:
1609 if self.filename is not None:
1610 filename = self.filename
1611 else:
1612 raise ValueError(compat_cookiejar.MISSING_FILENAME_TEXT)
1613
c380cc28
S
1614 def prepare_line(line):
1615 if line.startswith(self._HTTPONLY_PREFIX):
1616 line = line[len(self._HTTPONLY_PREFIX):]
1617 # comments and empty lines are fine
1618 if line.startswith('#') or not line.strip():
1619 return line
1620 cookie_list = line.split('\t')
1621 if len(cookie_list) != self._ENTRY_LEN:
1622 raise compat_cookiejar.LoadError('invalid length %d' % len(cookie_list))
1623 cookie = self._CookieFileEntry(*cookie_list)
1624 if cookie.expires_at and not cookie.expires_at.isdigit():
1625 raise compat_cookiejar.LoadError('invalid expires at %s' % cookie.expires_at)
1626 return line
1627
e7e62441 1628 cf = io.StringIO()
c380cc28 1629 with io.open(filename, encoding='utf-8') as f:
e7e62441 1630 for line in f:
c380cc28
S
1631 try:
1632 cf.write(prepare_line(line))
1633 except compat_cookiejar.LoadError as e:
1634 write_string(
1635 'WARNING: skipping cookie file entry due to %s: %r\n'
1636 % (e, line), sys.stderr)
1637 continue
e7e62441 1638 cf.seek(0)
1639 self._really_load(cf, filename, ignore_discard, ignore_expires)
1bab3437
S
1640 # Session cookies are denoted by either `expires` field set to
1641 # an empty string or 0. MozillaCookieJar only recognizes the former
1642 # (see [1]). So we need force the latter to be recognized as session
1643 # cookies on our own.
1644 # Session cookies may be important for cookies-based authentication,
1645 # e.g. usually, when user does not check 'Remember me' check box while
1646 # logging in on a site, some important cookies are stored as session
1647 # cookies so that not recognizing them will result in failed login.
1648 # 1. https://bugs.python.org/issue17164
1649 for cookie in self:
1650 # Treat `expires=0` cookies as session cookies
1651 if cookie.expires == 0:
1652 cookie.expires = None
1653 cookie.discard = True
1654
1655
a6420bf5
S
1656class YoutubeDLCookieProcessor(compat_urllib_request.HTTPCookieProcessor):
1657 def __init__(self, cookiejar=None):
1658 compat_urllib_request.HTTPCookieProcessor.__init__(self, cookiejar)
1659
1660 def http_response(self, request, response):
1661 # Python 2 will choke on next HTTP request in row if there are non-ASCII
1662 # characters in Set-Cookie HTTP header of last response (see
067aa17e 1663 # https://github.com/ytdl-org/youtube-dl/issues/6769).
a6420bf5
S
1664 # In order to at least prevent crashing we will percent encode Set-Cookie
1665 # header before HTTPCookieProcessor starts processing it.
e28034c5
S
1666 # if sys.version_info < (3, 0) and response.headers:
1667 # for set_cookie_header in ('Set-Cookie', 'Set-Cookie2'):
1668 # set_cookie = response.headers.get(set_cookie_header)
1669 # if set_cookie:
1670 # set_cookie_escaped = compat_urllib_parse.quote(set_cookie, b"%/;:@&=+$,!~*'()?#[] ")
1671 # if set_cookie != set_cookie_escaped:
1672 # del response.headers[set_cookie_header]
1673 # response.headers[set_cookie_header] = set_cookie_escaped
a6420bf5
S
1674 return compat_urllib_request.HTTPCookieProcessor.http_response(self, request, response)
1675
f5fa042c 1676 https_request = compat_urllib_request.HTTPCookieProcessor.http_request
a6420bf5
S
1677 https_response = http_response
1678
1679
fca6dba8 1680class YoutubeDLRedirectHandler(compat_urllib_request.HTTPRedirectHandler):
201c1459 1681 """YoutubeDL redirect handler
1682
1683 The code is based on HTTPRedirectHandler implementation from CPython [1].
1684
1685 This redirect handler solves two issues:
1686 - ensures redirect URL is always unicode under python 2
1687 - introduces support for experimental HTTP response status code
1688 308 Permanent Redirect [2] used by some sites [3]
1689
1690 1. https://github.com/python/cpython/blob/master/Lib/urllib/request.py
1691 2. https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/308
1692 3. https://github.com/ytdl-org/youtube-dl/issues/28768
1693 """
1694
1695 http_error_301 = http_error_303 = http_error_307 = http_error_308 = compat_urllib_request.HTTPRedirectHandler.http_error_302
1696
1697 def redirect_request(self, req, fp, code, msg, headers, newurl):
1698 """Return a Request or None in response to a redirect.
1699
1700 This is called by the http_error_30x methods when a
1701 redirection response is received. If a redirection should
1702 take place, return a new Request to allow http_error_30x to
1703 perform the redirect. Otherwise, raise HTTPError if no-one
1704 else should try to handle this url. Return None if you can't
1705 but another Handler might.
1706 """
1707 m = req.get_method()
1708 if (not (code in (301, 302, 303, 307, 308) and m in ("GET", "HEAD")
1709 or code in (301, 302, 303) and m == "POST")):
1710 raise compat_HTTPError(req.full_url, code, msg, headers, fp)
1711 # Strictly (according to RFC 2616), 301 or 302 in response to
1712 # a POST MUST NOT cause a redirection without confirmation
1713 # from the user (of urllib.request, in this case). In practice,
1714 # essentially all clients do redirect in this case, so we do
1715 # the same.
1716
1717 # On python 2 urlh.geturl() may sometimes return redirect URL
1718 # as byte string instead of unicode. This workaround allows
1719 # to force it always return unicode.
1720 if sys.version_info[0] < 3:
1721 newurl = compat_str(newurl)
1722
1723 # Be conciliant with URIs containing a space. This is mainly
1724 # redundant with the more complete encoding done in http_error_302(),
1725 # but it is kept for compatibility with other callers.
1726 newurl = newurl.replace(' ', '%20')
1727
1728 CONTENT_HEADERS = ("content-length", "content-type")
1729 # NB: don't use dict comprehension for python 2.6 compatibility
1730 newheaders = dict((k, v) for k, v in req.headers.items()
1731 if k.lower() not in CONTENT_HEADERS)
1732 return compat_urllib_request.Request(
1733 newurl, headers=newheaders, origin_req_host=req.origin_req_host,
1734 unverifiable=True)
fca6dba8
S
1735
1736
46f59e89
S
1737def extract_timezone(date_str):
1738 m = re.search(
f137e4c2 1739 r'''(?x)
1740 ^.{8,}? # >=8 char non-TZ prefix, if present
1741 (?P<tz>Z| # just the UTC Z, or
1742 (?:(?<=.\b\d{4}|\b\d{2}:\d\d)| # preceded by 4 digits or hh:mm or
1743 (?<!.\b[a-zA-Z]{3}|[a-zA-Z]{4}|..\b\d\d)) # not preceded by 3 alpha word or >= 4 alpha or 2 digits
1744 [ ]? # optional space
1745 (?P<sign>\+|-) # +/-
1746 (?P<hours>[0-9]{2}):?(?P<minutes>[0-9]{2}) # hh[:]mm
1747 $)
1748 ''', date_str)
46f59e89
S
1749 if not m:
1750 timezone = datetime.timedelta()
1751 else:
1752 date_str = date_str[:-len(m.group('tz'))]
1753 if not m.group('sign'):
1754 timezone = datetime.timedelta()
1755 else:
1756 sign = 1 if m.group('sign') == '+' else -1
1757 timezone = datetime.timedelta(
1758 hours=sign * int(m.group('hours')),
1759 minutes=sign * int(m.group('minutes')))
1760 return timezone, date_str
1761
1762
08b38d54 1763def parse_iso8601(date_str, delimiter='T', timezone=None):
912b38b4
PH
1764 """ Return a UNIX timestamp from the given date """
1765
1766 if date_str is None:
1767 return None
1768
52c3a6e4
S
1769 date_str = re.sub(r'\.[0-9]+', '', date_str)
1770
08b38d54 1771 if timezone is None:
46f59e89
S
1772 timezone, date_str = extract_timezone(date_str)
1773
52c3a6e4
S
1774 try:
1775 date_format = '%Y-%m-%d{0}%H:%M:%S'.format(delimiter)
1776 dt = datetime.datetime.strptime(date_str, date_format) - timezone
1777 return calendar.timegm(dt.timetuple())
1778 except ValueError:
1779 pass
912b38b4
PH
1780
1781
46f59e89
S
1782def date_formats(day_first=True):
1783 return DATE_FORMATS_DAY_FIRST if day_first else DATE_FORMATS_MONTH_FIRST
1784
1785
42bdd9d0 1786def unified_strdate(date_str, day_first=True):
bf50b038 1787 """Return a string with the date in the format YYYYMMDD"""
64e7ad60
PH
1788
1789 if date_str is None:
1790 return None
bf50b038 1791 upload_date = None
5f6a1245 1792 # Replace commas
026fcc04 1793 date_str = date_str.replace(',', ' ')
42bdd9d0 1794 # Remove AM/PM + timezone
9bb8e0a3 1795 date_str = re.sub(r'(?i)\s*(?:AM|PM)(?:\s+[A-Z]+)?', '', date_str)
46f59e89 1796 _, date_str = extract_timezone(date_str)
42bdd9d0 1797
46f59e89 1798 for expression in date_formats(day_first):
bf50b038
JMF
1799 try:
1800 upload_date = datetime.datetime.strptime(date_str, expression).strftime('%Y%m%d')
5de90176 1801 except ValueError:
bf50b038 1802 pass
42393ce2
PH
1803 if upload_date is None:
1804 timetuple = email.utils.parsedate_tz(date_str)
1805 if timetuple:
c6b9cf05
S
1806 try:
1807 upload_date = datetime.datetime(*timetuple[:6]).strftime('%Y%m%d')
1808 except ValueError:
1809 pass
6a750402
JMF
1810 if upload_date is not None:
1811 return compat_str(upload_date)
bf50b038 1812
5f6a1245 1813
46f59e89
S
1814def unified_timestamp(date_str, day_first=True):
1815 if date_str is None:
1816 return None
1817
2ae2ffda 1818 date_str = re.sub(r'[,|]', '', date_str)
46f59e89 1819
7dc2a74e 1820 pm_delta = 12 if re.search(r'(?i)PM', date_str) else 0
46f59e89
S
1821 timezone, date_str = extract_timezone(date_str)
1822
1823 # Remove AM/PM + timezone
1824 date_str = re.sub(r'(?i)\s*(?:AM|PM)(?:\s+[A-Z]+)?', '', date_str)
1825
deef3195
S
1826 # Remove unrecognized timezones from ISO 8601 alike timestamps
1827 m = re.search(r'\d{1,2}:\d{1,2}(?:\.\d+)?(?P<tz>\s*[A-Z]+)$', date_str)
1828 if m:
1829 date_str = date_str[:-len(m.group('tz'))]
1830
f226880c
PH
1831 # Python only supports microseconds, so remove nanoseconds
1832 m = re.search(r'^([0-9]{4,}-[0-9]{1,2}-[0-9]{1,2}T[0-9]{1,2}:[0-9]{1,2}:[0-9]{1,2}\.[0-9]{6})[0-9]+$', date_str)
1833 if m:
1834 date_str = m.group(1)
1835
46f59e89
S
1836 for expression in date_formats(day_first):
1837 try:
7dc2a74e 1838 dt = datetime.datetime.strptime(date_str, expression) - timezone + datetime.timedelta(hours=pm_delta)
46f59e89
S
1839 return calendar.timegm(dt.timetuple())
1840 except ValueError:
1841 pass
1842 timetuple = email.utils.parsedate_tz(date_str)
1843 if timetuple:
7dc2a74e 1844 return calendar.timegm(timetuple) + pm_delta * 3600
46f59e89
S
1845
1846
28e614de 1847def determine_ext(url, default_ext='unknown_video'):
85750f89 1848 if url is None or '.' not in url:
f4776371 1849 return default_ext
9cb9a5df 1850 guess = url.partition('?')[0].rpartition('.')[2]
73e79f2a
PH
1851 if re.match(r'^[A-Za-z0-9]+$', guess):
1852 return guess
a7aaa398
S
1853 # Try extract ext from URLs like http://example.com/foo/bar.mp4/?download
1854 elif guess.rstrip('/') in KNOWN_EXTENSIONS:
9cb9a5df 1855 return guess.rstrip('/')
73e79f2a 1856 else:
cbdbb766 1857 return default_ext
73e79f2a 1858
5f6a1245 1859
824fa511
S
1860def subtitles_filename(filename, sub_lang, sub_format, expected_real_ext=None):
1861 return replace_extension(filename, sub_lang + '.' + sub_format, expected_real_ext)
d4051a8e 1862
5f6a1245 1863
9e62f283 1864def datetime_from_str(date_str, precision='auto', format='%Y%m%d'):
37254abc
JMF
1865 """
1866 Return a datetime object from a string in the format YYYYMMDD or
d49f8db3 1867 (now|today|yesterday|date)[+-][0-9](microsecond|second|minute|hour|day|week|month|year)(s)?
9e62f283 1868
1869 format: string date format used to return datetime object from
1870 precision: round the time portion of a datetime object.
1871 auto|microsecond|second|minute|hour|day.
1872 auto: round to the unit provided in date_str (if applicable).
1873 """
1874 auto_precision = False
1875 if precision == 'auto':
1876 auto_precision = True
1877 precision = 'microsecond'
396a76f7 1878 today = datetime_round(datetime.datetime.utcnow(), precision)
f8795e10 1879 if date_str in ('now', 'today'):
37254abc 1880 return today
f8795e10
PH
1881 if date_str == 'yesterday':
1882 return today - datetime.timedelta(days=1)
9e62f283 1883 match = re.match(
1884 r'(?P<start>.+)(?P<sign>[+-])(?P<time>\d+)(?P<unit>microsecond|second|minute|hour|day|week|month|year)(s)?',
1885 date_str)
37254abc 1886 if match is not None:
9e62f283 1887 start_time = datetime_from_str(match.group('start'), precision, format)
1888 time = int(match.group('time')) * (-1 if match.group('sign') == '-' else 1)
37254abc 1889 unit = match.group('unit')
9e62f283 1890 if unit == 'month' or unit == 'year':
1891 new_date = datetime_add_months(start_time, time * 12 if unit == 'year' else time)
37254abc 1892 unit = 'day'
9e62f283 1893 else:
1894 if unit == 'week':
1895 unit = 'day'
1896 time *= 7
1897 delta = datetime.timedelta(**{unit + 's': time})
1898 new_date = start_time + delta
1899 if auto_precision:
1900 return datetime_round(new_date, unit)
1901 return new_date
1902
1903 return datetime_round(datetime.datetime.strptime(date_str, format), precision)
1904
1905
d49f8db3 1906def date_from_str(date_str, format='%Y%m%d', strict=False):
9e62f283 1907 """
1908 Return a datetime object from a string in the format YYYYMMDD or
d49f8db3 1909 (now|today|yesterday|date)[+-][0-9](microsecond|second|minute|hour|day|week|month|year)(s)?
1910
1911 If "strict", only (now|today)[+-][0-9](day|week|month|year)(s)? is allowed
9e62f283 1912
1913 format: string date format used to return datetime object from
1914 """
d49f8db3 1915 if strict and not re.fullmatch(r'\d{8}|(now|today)[+-]\d+(day|week|month|year)(s)?', date_str):
1916 raise ValueError(f'Invalid date format {date_str}')
9e62f283 1917 return datetime_from_str(date_str, precision='microsecond', format=format).date()
1918
1919
1920def datetime_add_months(dt, months):
1921 """Increment/Decrement a datetime object by months."""
1922 month = dt.month + months - 1
1923 year = dt.year + month // 12
1924 month = month % 12 + 1
1925 day = min(dt.day, calendar.monthrange(year, month)[1])
1926 return dt.replace(year, month, day)
1927
1928
1929def datetime_round(dt, precision='day'):
1930 """
1931 Round a datetime object's time to a specific precision
1932 """
1933 if precision == 'microsecond':
1934 return dt
1935
1936 unit_seconds = {
1937 'day': 86400,
1938 'hour': 3600,
1939 'minute': 60,
1940 'second': 1,
1941 }
1942 roundto = lambda x, n: ((x + n / 2) // n) * n
1943 timestamp = calendar.timegm(dt.timetuple())
1944 return datetime.datetime.utcfromtimestamp(roundto(timestamp, unit_seconds[precision]))
5f6a1245
JW
1945
1946
e63fc1be 1947def hyphenate_date(date_str):
1948 """
1949 Convert a date in 'YYYYMMDD' format to 'YYYY-MM-DD' format"""
1950 match = re.match(r'^(\d\d\d\d)(\d\d)(\d\d)$', date_str)
1951 if match is not None:
1952 return '-'.join(match.groups())
1953 else:
1954 return date_str
1955
5f6a1245 1956
bd558525
JMF
1957class DateRange(object):
1958 """Represents a time interval between two dates"""
5f6a1245 1959
bd558525
JMF
1960 def __init__(self, start=None, end=None):
1961 """start and end must be strings in the format accepted by date"""
1962 if start is not None:
d49f8db3 1963 self.start = date_from_str(start, strict=True)
bd558525
JMF
1964 else:
1965 self.start = datetime.datetime.min.date()
1966 if end is not None:
d49f8db3 1967 self.end = date_from_str(end, strict=True)
bd558525
JMF
1968 else:
1969 self.end = datetime.datetime.max.date()
37254abc 1970 if self.start > self.end:
bd558525 1971 raise ValueError('Date range: "%s" , the start date must be before the end date' % self)
5f6a1245 1972
bd558525
JMF
1973 @classmethod
1974 def day(cls, day):
1975 """Returns a range that only contains the given day"""
5f6a1245
JW
1976 return cls(day, day)
1977
bd558525
JMF
1978 def __contains__(self, date):
1979 """Check if the date is in the range"""
37254abc
JMF
1980 if not isinstance(date, datetime.date):
1981 date = date_from_str(date)
1982 return self.start <= date <= self.end
5f6a1245 1983
bd558525 1984 def __str__(self):
5f6a1245 1985 return '%s - %s' % (self.start.isoformat(), self.end.isoformat())
c496ca96
PH
1986
1987
1988def platform_name():
1989 """ Returns the platform name as a compat_str """
1990 res = platform.platform()
1991 if isinstance(res, bytes):
1992 res = res.decode(preferredencoding())
1993
1994 assert isinstance(res, compat_str)
1995 return res
c257baff
PH
1996
1997
49fa4d9a
N
1998def get_windows_version():
1999 ''' Get Windows version. None if it's not running on Windows '''
2000 if compat_os_name == 'nt':
2001 return version_tuple(platform.win32_ver()[1])
2002 else:
2003 return None
2004
2005
b58ddb32
PH
2006def _windows_write_string(s, out):
2007 """ Returns True if the string was written using special methods,
2008 False if it has yet to be written out."""
2009 # Adapted from http://stackoverflow.com/a/3259271/35070
2010
b58ddb32
PH
2011 import ctypes.wintypes
2012
2013 WIN_OUTPUT_IDS = {
2014 1: -11,
2015 2: -12,
2016 }
2017
a383a98a
PH
2018 try:
2019 fileno = out.fileno()
2020 except AttributeError:
2021 # If the output stream doesn't have a fileno, it's virtual
2022 return False
aa42e873
PH
2023 except io.UnsupportedOperation:
2024 # Some strange Windows pseudo files?
2025 return False
b58ddb32
PH
2026 if fileno not in WIN_OUTPUT_IDS:
2027 return False
2028
d7cd9a9e 2029 GetStdHandle = compat_ctypes_WINFUNCTYPE(
b58ddb32 2030 ctypes.wintypes.HANDLE, ctypes.wintypes.DWORD)(
d7cd9a9e 2031 ('GetStdHandle', ctypes.windll.kernel32))
b58ddb32
PH
2032 h = GetStdHandle(WIN_OUTPUT_IDS[fileno])
2033
d7cd9a9e 2034 WriteConsoleW = compat_ctypes_WINFUNCTYPE(
b58ddb32
PH
2035 ctypes.wintypes.BOOL, ctypes.wintypes.HANDLE, ctypes.wintypes.LPWSTR,
2036 ctypes.wintypes.DWORD, ctypes.POINTER(ctypes.wintypes.DWORD),
d7cd9a9e 2037 ctypes.wintypes.LPVOID)(('WriteConsoleW', ctypes.windll.kernel32))
b58ddb32
PH
2038 written = ctypes.wintypes.DWORD(0)
2039
d7cd9a9e 2040 GetFileType = compat_ctypes_WINFUNCTYPE(ctypes.wintypes.DWORD, ctypes.wintypes.DWORD)(('GetFileType', ctypes.windll.kernel32))
b58ddb32
PH
2041 FILE_TYPE_CHAR = 0x0002
2042 FILE_TYPE_REMOTE = 0x8000
d7cd9a9e 2043 GetConsoleMode = compat_ctypes_WINFUNCTYPE(
b58ddb32
PH
2044 ctypes.wintypes.BOOL, ctypes.wintypes.HANDLE,
2045 ctypes.POINTER(ctypes.wintypes.DWORD))(
d7cd9a9e 2046 ('GetConsoleMode', ctypes.windll.kernel32))
b58ddb32
PH
2047 INVALID_HANDLE_VALUE = ctypes.wintypes.DWORD(-1).value
2048
2049 def not_a_console(handle):
2050 if handle == INVALID_HANDLE_VALUE or handle is None:
2051 return True
3089bc74
S
2052 return ((GetFileType(handle) & ~FILE_TYPE_REMOTE) != FILE_TYPE_CHAR
2053 or GetConsoleMode(handle, ctypes.byref(ctypes.wintypes.DWORD())) == 0)
b58ddb32
PH
2054
2055 if not_a_console(h):
2056 return False
2057
d1b9c912
PH
2058 def next_nonbmp_pos(s):
2059 try:
2060 return next(i for i, c in enumerate(s) if ord(c) > 0xffff)
2061 except StopIteration:
2062 return len(s)
2063
2064 while s:
2065 count = min(next_nonbmp_pos(s), 1024)
2066
b58ddb32 2067 ret = WriteConsoleW(
d1b9c912 2068 h, s, count if count else 2, ctypes.byref(written), None)
b58ddb32
PH
2069 if ret == 0:
2070 raise OSError('Failed to write string')
d1b9c912
PH
2071 if not count: # We just wrote a non-BMP character
2072 assert written.value == 2
2073 s = s[1:]
2074 else:
2075 assert written.value > 0
2076 s = s[written.value:]
b58ddb32
PH
2077 return True
2078
2079
734f90bb 2080def write_string(s, out=None, encoding=None):
7459e3a2
PH
2081 if out is None:
2082 out = sys.stderr
8bf48f23 2083 assert type(s) == compat_str
7459e3a2 2084
b58ddb32
PH
2085 if sys.platform == 'win32' and encoding is None and hasattr(out, 'fileno'):
2086 if _windows_write_string(s, out):
2087 return
2088
3089bc74
S
2089 if ('b' in getattr(out, 'mode', '')
2090 or sys.version_info[0] < 3): # Python 2 lies about mode of sys.stderr
104aa738
PH
2091 byt = s.encode(encoding or preferredencoding(), 'ignore')
2092 out.write(byt)
2093 elif hasattr(out, 'buffer'):
2094 enc = encoding or getattr(out, 'encoding', None) or preferredencoding()
2095 byt = s.encode(enc, 'ignore')
2096 out.buffer.write(byt)
2097 else:
8bf48f23 2098 out.write(s)
7459e3a2
PH
2099 out.flush()
2100
2101
48ea9cea
PH
2102def bytes_to_intlist(bs):
2103 if not bs:
2104 return []
2105 if isinstance(bs[0], int): # Python 3
2106 return list(bs)
2107 else:
2108 return [ord(c) for c in bs]
2109
c257baff 2110
cba892fa 2111def intlist_to_bytes(xs):
2112 if not xs:
2113 return b''
edaa23f8 2114 return compat_struct_pack('%dB' % len(xs), *xs)
c38b1e77
PH
2115
2116
c1c9a79c
PH
2117# Cross-platform file locking
2118if sys.platform == 'win32':
2119 import ctypes.wintypes
2120 import msvcrt
2121
2122 class OVERLAPPED(ctypes.Structure):
2123 _fields_ = [
2124 ('Internal', ctypes.wintypes.LPVOID),
2125 ('InternalHigh', ctypes.wintypes.LPVOID),
2126 ('Offset', ctypes.wintypes.DWORD),
2127 ('OffsetHigh', ctypes.wintypes.DWORD),
2128 ('hEvent', ctypes.wintypes.HANDLE),
2129 ]
2130
2131 kernel32 = ctypes.windll.kernel32
2132 LockFileEx = kernel32.LockFileEx
2133 LockFileEx.argtypes = [
2134 ctypes.wintypes.HANDLE, # hFile
2135 ctypes.wintypes.DWORD, # dwFlags
2136 ctypes.wintypes.DWORD, # dwReserved
2137 ctypes.wintypes.DWORD, # nNumberOfBytesToLockLow
2138 ctypes.wintypes.DWORD, # nNumberOfBytesToLockHigh
2139 ctypes.POINTER(OVERLAPPED) # Overlapped
2140 ]
2141 LockFileEx.restype = ctypes.wintypes.BOOL
2142 UnlockFileEx = kernel32.UnlockFileEx
2143 UnlockFileEx.argtypes = [
2144 ctypes.wintypes.HANDLE, # hFile
2145 ctypes.wintypes.DWORD, # dwReserved
2146 ctypes.wintypes.DWORD, # nNumberOfBytesToLockLow
2147 ctypes.wintypes.DWORD, # nNumberOfBytesToLockHigh
2148 ctypes.POINTER(OVERLAPPED) # Overlapped
2149 ]
2150 UnlockFileEx.restype = ctypes.wintypes.BOOL
2151 whole_low = 0xffffffff
2152 whole_high = 0x7fffffff
2153
747c0bd1 2154 def _lock_file(f, exclusive, block):
c1c9a79c
PH
2155 overlapped = OVERLAPPED()
2156 overlapped.Offset = 0
2157 overlapped.OffsetHigh = 0
2158 overlapped.hEvent = 0
2159 f._lock_file_overlapped_p = ctypes.pointer(overlapped)
747c0bd1 2160
2161 if not LockFileEx(msvcrt.get_osfhandle(f.fileno()),
2162 (0x2 if exclusive else 0x0) | (0x0 if block else 0x1),
2163 0, whole_low, whole_high, f._lock_file_overlapped_p):
2164 raise BlockingIOError('Locking file failed: %r' % ctypes.FormatError())
c1c9a79c
PH
2165
2166 def _unlock_file(f):
2167 assert f._lock_file_overlapped_p
2168 handle = msvcrt.get_osfhandle(f.fileno())
747c0bd1 2169 if not UnlockFileEx(handle, 0, whole_low, whole_high, f._lock_file_overlapped_p):
c1c9a79c
PH
2170 raise OSError('Unlocking file failed: %r' % ctypes.FormatError())
2171
2172else:
399a76e6
YCH
2173 try:
2174 import fcntl
c1c9a79c 2175
a3125791 2176 def _lock_file(f, exclusive, block):
acea8d7c
JK
2177 try:
2178 fcntl.flock(f,
2179 fcntl.LOCK_SH if not exclusive
2180 else fcntl.LOCK_EX if block
2181 else fcntl.LOCK_EX | fcntl.LOCK_NB)
2182 except BlockingIOError:
2183 raise
2184 except OSError: # AOSP does not have flock()
2185 fcntl.lockf(f,
2186 fcntl.LOCK_SH if not exclusive
2187 else fcntl.LOCK_EX if block
2188 else fcntl.LOCK_EX | fcntl.LOCK_NB)
c1c9a79c 2189
399a76e6 2190 def _unlock_file(f):
acea8d7c
JK
2191 try:
2192 fcntl.flock(f, fcntl.LOCK_UN)
2193 except OSError:
2194 fcntl.lockf(f, fcntl.LOCK_UN)
a3125791 2195
399a76e6
YCH
2196 except ImportError:
2197 UNSUPPORTED_MSG = 'file locking is not supported on this platform'
2198
a3125791 2199 def _lock_file(f, exclusive, block):
399a76e6
YCH
2200 raise IOError(UNSUPPORTED_MSG)
2201
2202 def _unlock_file(f):
2203 raise IOError(UNSUPPORTED_MSG)
c1c9a79c
PH
2204
2205
2206class locked_file(object):
747c0bd1 2207 _closed = False
2208
a3125791
JK
2209 def __init__(self, filename, mode, block=True, encoding=None):
2210 assert mode in ['r', 'rb', 'a', 'ab', 'w', 'wb']
c1c9a79c
PH
2211 self.f = io.open(filename, mode, encoding=encoding)
2212 self.mode = mode
a3125791 2213 self.block = block
c1c9a79c
PH
2214
2215 def __enter__(self):
a3125791 2216 exclusive = 'r' not in self.mode
c1c9a79c 2217 try:
a3125791 2218 _lock_file(self.f, exclusive, self.block)
c1c9a79c
PH
2219 except IOError:
2220 self.f.close()
2221 raise
2222 return self
2223
2224 def __exit__(self, etype, value, traceback):
2225 try:
747c0bd1 2226 if not self._closed:
2227 _unlock_file(self.f)
c1c9a79c
PH
2228 finally:
2229 self.f.close()
747c0bd1 2230 self._closed = True
c1c9a79c
PH
2231
2232 def __iter__(self):
2233 return iter(self.f)
2234
2235 def write(self, *args):
2236 return self.f.write(*args)
2237
2238 def read(self, *args):
2239 return self.f.read(*args)
4eb7f1d1 2240
a3125791
JK
2241 def flush(self):
2242 self.f.flush()
2243
2244 def open(self):
2245 return self.__enter__()
2246
2247 def close(self, *args):
2248 self.__exit__(self, *args, value=False, traceback=False)
2249
4eb7f1d1 2250
4644ac55
S
2251def get_filesystem_encoding():
2252 encoding = sys.getfilesystemencoding()
2253 return encoding if encoding is not None else 'utf-8'
2254
2255
4eb7f1d1 2256def shell_quote(args):
a6a173c2 2257 quoted_args = []
4644ac55 2258 encoding = get_filesystem_encoding()
a6a173c2
JMF
2259 for a in args:
2260 if isinstance(a, bytes):
2261 # We may get a filename encoded with 'encodeFilename'
2262 a = a.decode(encoding)
aefce8e6 2263 quoted_args.append(compat_shlex_quote(a))
28e614de 2264 return ' '.join(quoted_args)
9d4660ca
PH
2265
2266
2267def smuggle_url(url, data):
2268 """ Pass additional data in a URL for internal use. """
2269
81953d1a
RA
2270 url, idata = unsmuggle_url(url, {})
2271 data.update(idata)
15707c7e 2272 sdata = compat_urllib_parse_urlencode(
28e614de
PH
2273 {'__youtubedl_smuggle': json.dumps(data)})
2274 return url + '#' + sdata
9d4660ca
PH
2275
2276
79f82953 2277def unsmuggle_url(smug_url, default=None):
83e865a3 2278 if '#__youtubedl_smuggle' not in smug_url:
79f82953 2279 return smug_url, default
28e614de
PH
2280 url, _, sdata = smug_url.rpartition('#')
2281 jsond = compat_parse_qs(sdata)['__youtubedl_smuggle'][0]
9d4660ca
PH
2282 data = json.loads(jsond)
2283 return url, data
02dbf93f
PH
2284
2285
e0fd9573 2286def format_decimal_suffix(num, fmt='%d%s', *, factor=1000):
2287 """ Formats numbers with decimal sufixes like K, M, etc """
2288 num, factor = float_or_none(num), float(factor)
4c3f8c3f 2289 if num is None or num < 0:
e0fd9573 2290 return None
eeb2a770 2291 POSSIBLE_SUFFIXES = 'kMGTPEZY'
2292 exponent = 0 if num == 0 else min(int(math.log(num, factor)), len(POSSIBLE_SUFFIXES))
2293 suffix = ['', *POSSIBLE_SUFFIXES][exponent]
abbeeebc 2294 if factor == 1024:
2295 suffix = {'k': 'Ki', '': ''}.get(suffix, f'{suffix}i')
e0fd9573 2296 converted = num / (factor ** exponent)
abbeeebc 2297 return fmt % (converted, suffix)
e0fd9573 2298
2299
02dbf93f 2300def format_bytes(bytes):
f02d24d8 2301 return format_decimal_suffix(bytes, '%.2f%sB', factor=1024) or 'N/A'
f53c966a 2302
1c088fa8 2303
fb47597b
S
2304def lookup_unit_table(unit_table, s):
2305 units_re = '|'.join(re.escape(u) for u in unit_table)
2306 m = re.match(
782b1b5b 2307 r'(?P<num>[0-9]+(?:[,.][0-9]*)?)\s*(?P<unit>%s)\b' % units_re, s)
fb47597b
S
2308 if not m:
2309 return None
2310 num_str = m.group('num').replace(',', '.')
2311 mult = unit_table[m.group('unit')]
2312 return int(float(num_str) * mult)
2313
2314
be64b5b0
PH
2315def parse_filesize(s):
2316 if s is None:
2317 return None
2318
dfb1b146 2319 # The lower-case forms are of course incorrect and unofficial,
be64b5b0
PH
2320 # but we support those too
2321 _UNIT_TABLE = {
2322 'B': 1,
2323 'b': 1,
70852b47 2324 'bytes': 1,
be64b5b0
PH
2325 'KiB': 1024,
2326 'KB': 1000,
2327 'kB': 1024,
2328 'Kb': 1000,
13585d76 2329 'kb': 1000,
70852b47
YCH
2330 'kilobytes': 1000,
2331 'kibibytes': 1024,
be64b5b0
PH
2332 'MiB': 1024 ** 2,
2333 'MB': 1000 ** 2,
2334 'mB': 1024 ** 2,
2335 'Mb': 1000 ** 2,
13585d76 2336 'mb': 1000 ** 2,
70852b47
YCH
2337 'megabytes': 1000 ** 2,
2338 'mebibytes': 1024 ** 2,
be64b5b0
PH
2339 'GiB': 1024 ** 3,
2340 'GB': 1000 ** 3,
2341 'gB': 1024 ** 3,
2342 'Gb': 1000 ** 3,
13585d76 2343 'gb': 1000 ** 3,
70852b47
YCH
2344 'gigabytes': 1000 ** 3,
2345 'gibibytes': 1024 ** 3,
be64b5b0
PH
2346 'TiB': 1024 ** 4,
2347 'TB': 1000 ** 4,
2348 'tB': 1024 ** 4,
2349 'Tb': 1000 ** 4,
13585d76 2350 'tb': 1000 ** 4,
70852b47
YCH
2351 'terabytes': 1000 ** 4,
2352 'tebibytes': 1024 ** 4,
be64b5b0
PH
2353 'PiB': 1024 ** 5,
2354 'PB': 1000 ** 5,
2355 'pB': 1024 ** 5,
2356 'Pb': 1000 ** 5,
13585d76 2357 'pb': 1000 ** 5,
70852b47
YCH
2358 'petabytes': 1000 ** 5,
2359 'pebibytes': 1024 ** 5,
be64b5b0
PH
2360 'EiB': 1024 ** 6,
2361 'EB': 1000 ** 6,
2362 'eB': 1024 ** 6,
2363 'Eb': 1000 ** 6,
13585d76 2364 'eb': 1000 ** 6,
70852b47
YCH
2365 'exabytes': 1000 ** 6,
2366 'exbibytes': 1024 ** 6,
be64b5b0
PH
2367 'ZiB': 1024 ** 7,
2368 'ZB': 1000 ** 7,
2369 'zB': 1024 ** 7,
2370 'Zb': 1000 ** 7,
13585d76 2371 'zb': 1000 ** 7,
70852b47
YCH
2372 'zettabytes': 1000 ** 7,
2373 'zebibytes': 1024 ** 7,
be64b5b0
PH
2374 'YiB': 1024 ** 8,
2375 'YB': 1000 ** 8,
2376 'yB': 1024 ** 8,
2377 'Yb': 1000 ** 8,
13585d76 2378 'yb': 1000 ** 8,
70852b47
YCH
2379 'yottabytes': 1000 ** 8,
2380 'yobibytes': 1024 ** 8,
be64b5b0
PH
2381 }
2382
fb47597b
S
2383 return lookup_unit_table(_UNIT_TABLE, s)
2384
2385
2386def parse_count(s):
2387 if s is None:
be64b5b0
PH
2388 return None
2389
352d5da8 2390 s = re.sub(r'^[^\d]+\s', '', s).strip()
fb47597b
S
2391
2392 if re.match(r'^[\d,.]+$', s):
2393 return str_to_int(s)
2394
2395 _UNIT_TABLE = {
2396 'k': 1000,
2397 'K': 1000,
2398 'm': 1000 ** 2,
2399 'M': 1000 ** 2,
2400 'kk': 1000 ** 2,
2401 'KK': 1000 ** 2,
352d5da8 2402 'b': 1000 ** 3,
2403 'B': 1000 ** 3,
fb47597b 2404 }
be64b5b0 2405
352d5da8 2406 ret = lookup_unit_table(_UNIT_TABLE, s)
2407 if ret is not None:
2408 return ret
2409
2410 mobj = re.match(r'([\d,.]+)(?:$|\s)', s)
2411 if mobj:
2412 return str_to_int(mobj.group(1))
be64b5b0 2413
2f7ae819 2414
b871d7e9
S
2415def parse_resolution(s):
2416 if s is None:
2417 return {}
2418
17ec8bcf 2419 mobj = re.search(r'(?<![a-zA-Z0-9])(?P<w>\d+)\s*[xX×,]\s*(?P<h>\d+)(?![a-zA-Z0-9])', s)
b871d7e9
S
2420 if mobj:
2421 return {
2422 'width': int(mobj.group('w')),
2423 'height': int(mobj.group('h')),
2424 }
2425
17ec8bcf 2426 mobj = re.search(r'(?<![a-zA-Z0-9])(\d+)[pPiI](?![a-zA-Z0-9])', s)
b871d7e9
S
2427 if mobj:
2428 return {'height': int(mobj.group(1))}
2429
2430 mobj = re.search(r'\b([48])[kK]\b', s)
2431 if mobj:
2432 return {'height': int(mobj.group(1)) * 540}
2433
2434 return {}
2435
2436
0dc41787
S
2437def parse_bitrate(s):
2438 if not isinstance(s, compat_str):
2439 return
2440 mobj = re.search(r'\b(\d+)\s*kbps', s)
2441 if mobj:
2442 return int(mobj.group(1))
2443
2444
a942d6cb 2445def month_by_name(name, lang='en'):
caefb1de
PH
2446 """ Return the number of a month by (locale-independently) English name """
2447
f6717dec 2448 month_names = MONTH_NAMES.get(lang, MONTH_NAMES['en'])
a942d6cb 2449
caefb1de 2450 try:
f6717dec 2451 return month_names.index(name) + 1
7105440c
YCH
2452 except ValueError:
2453 return None
2454
2455
2456def month_by_abbreviation(abbrev):
2457 """ Return the number of a month by (locale-independently) English
2458 abbreviations """
2459
2460 try:
2461 return [s[:3] for s in ENGLISH_MONTH_NAMES].index(abbrev) + 1
caefb1de
PH
2462 except ValueError:
2463 return None
18258362
JMF
2464
2465
5aafe895 2466def fix_xml_ampersands(xml_str):
18258362 2467 """Replace all the '&' by '&amp;' in XML"""
5aafe895
PH
2468 return re.sub(
2469 r'&(?!amp;|lt;|gt;|apos;|quot;|#x[0-9a-fA-F]{,4};|#[0-9]{,4};)',
28e614de 2470 '&amp;',
5aafe895 2471 xml_str)
e3946f98
PH
2472
2473
2474def setproctitle(title):
8bf48f23 2475 assert isinstance(title, compat_str)
c1c05c67
YCH
2476
2477 # ctypes in Jython is not complete
2478 # http://bugs.jython.org/issue2148
2479 if sys.platform.startswith('java'):
2480 return
2481
e3946f98 2482 try:
611c1dd9 2483 libc = ctypes.cdll.LoadLibrary('libc.so.6')
e3946f98
PH
2484 except OSError:
2485 return
2f49bcd6
RC
2486 except TypeError:
2487 # LoadLibrary in Windows Python 2.7.13 only expects
2488 # a bytestring, but since unicode_literals turns
2489 # every string into a unicode string, it fails.
2490 return
6eefe533
PH
2491 title_bytes = title.encode('utf-8')
2492 buf = ctypes.create_string_buffer(len(title_bytes))
2493 buf.value = title_bytes
e3946f98 2494 try:
6eefe533 2495 libc.prctl(15, buf, 0, 0, 0)
e3946f98
PH
2496 except AttributeError:
2497 return # Strange libc, just skip this
d7dda168
PH
2498
2499
2500def remove_start(s, start):
46bc9b7d 2501 return s[len(start):] if s is not None and s.startswith(start) else s
29eb5174
PH
2502
2503
2b9faf55 2504def remove_end(s, end):
46bc9b7d 2505 return s[:-len(end)] if s is not None and s.endswith(end) else s
2b9faf55
PH
2506
2507
31b2051e
S
2508def remove_quotes(s):
2509 if s is None or len(s) < 2:
2510 return s
2511 for quote in ('"', "'", ):
2512 if s[0] == quote and s[-1] == quote:
2513 return s[1:-1]
2514 return s
2515
2516
b6e0c7d2
U
2517def get_domain(url):
2518 domain = re.match(r'(?:https?:\/\/)?(?:www\.)?(?P<domain>[^\n\/]+\.[^\n\/]+)(?:\/(.*))?', url)
2519 return domain.group('domain') if domain else None
2520
2521
29eb5174 2522def url_basename(url):
9b8aaeed 2523 path = compat_urlparse.urlparse(url).path
28e614de 2524 return path.strip('/').split('/')[-1]
aa94a6d3
PH
2525
2526
02dc0a36
S
2527def base_url(url):
2528 return re.match(r'https?://[^?#&]+/', url).group()
2529
2530
e34c3361 2531def urljoin(base, path):
4b5de77b
S
2532 if isinstance(path, bytes):
2533 path = path.decode('utf-8')
e34c3361
S
2534 if not isinstance(path, compat_str) or not path:
2535 return None
fad4ceb5 2536 if re.match(r'^(?:[a-zA-Z][a-zA-Z0-9+-.]*:)?//', path):
e34c3361 2537 return path
4b5de77b
S
2538 if isinstance(base, bytes):
2539 base = base.decode('utf-8')
2540 if not isinstance(base, compat_str) or not re.match(
2541 r'^(?:https?:)?//', base):
e34c3361
S
2542 return None
2543 return compat_urlparse.urljoin(base, path)
2544
2545
aa94a6d3
PH
2546class HEADRequest(compat_urllib_request.Request):
2547 def get_method(self):
611c1dd9 2548 return 'HEAD'
7217e148
PH
2549
2550
95cf60e8
S
2551class PUTRequest(compat_urllib_request.Request):
2552 def get_method(self):
2553 return 'PUT'
2554
2555
9732d77e 2556def int_or_none(v, scale=1, default=None, get_attr=None, invscale=1):
9e907ebd 2557 if get_attr and v is not None:
2558 v = getattr(v, get_attr, None)
1812afb7
S
2559 try:
2560 return int(v) * invscale // scale
31c49255 2561 except (ValueError, TypeError, OverflowError):
af98f8ff 2562 return default
9732d77e 2563
9572013d 2564
40a90862
JMF
2565def str_or_none(v, default=None):
2566 return default if v is None else compat_str(v)
2567
9732d77e
PH
2568
2569def str_to_int(int_str):
48d4681e 2570 """ A more relaxed version of int_or_none """
42db58ec 2571 if isinstance(int_str, compat_integer_types):
348c6bf1 2572 return int_str
42db58ec
S
2573 elif isinstance(int_str, compat_str):
2574 int_str = re.sub(r'[,\.\+]', '', int_str)
2575 return int_or_none(int_str)
608d11f5
PH
2576
2577
9732d77e 2578def float_or_none(v, scale=1, invscale=1, default=None):
caf80631
S
2579 if v is None:
2580 return default
2581 try:
2582 return float(v) * invscale / scale
5e1271c5 2583 except (ValueError, TypeError):
caf80631 2584 return default
43f775e4
PH
2585
2586
c7e327c4
S
2587def bool_or_none(v, default=None):
2588 return v if isinstance(v, bool) else default
2589
2590
53cd37ba
S
2591def strip_or_none(v, default=None):
2592 return v.strip() if isinstance(v, compat_str) else default
b72b4431
S
2593
2594
af03000a
S
2595def url_or_none(url):
2596 if not url or not isinstance(url, compat_str):
2597 return None
2598 url = url.strip()
29f7c58a 2599 return url if re.match(r'^(?:(?:https?|rt(?:m(?:pt?[es]?|fp)|sp[su]?)|mms|ftps?):)?//', url) else None
af03000a
S
2600
2601
3e9b66d7
LNO
2602def request_to_url(req):
2603 if isinstance(req, compat_urllib_request.Request):
2604 return req.get_full_url()
2605 else:
2606 return req
2607
2608
e29663c6 2609def strftime_or_none(timestamp, date_format, default=None):
2610 datetime_object = None
2611 try:
2612 if isinstance(timestamp, compat_numeric_types): # unix timestamp
2613 datetime_object = datetime.datetime.utcfromtimestamp(timestamp)
2614 elif isinstance(timestamp, compat_str): # assume YYYYMMDD
2615 datetime_object = datetime.datetime.strptime(timestamp, '%Y%m%d')
2616 return datetime_object.strftime(date_format)
2617 except (ValueError, TypeError, AttributeError):
2618 return default
2619
2620
608d11f5 2621def parse_duration(s):
8f9312c3 2622 if not isinstance(s, compat_basestring):
608d11f5 2623 return None
ca7b3246 2624 s = s.strip()
38d79fd1 2625 if not s:
2626 return None
ca7b3246 2627
acaff495 2628 days, hours, mins, secs, ms = [None] * 5
8bd1c00b 2629 m = re.match(r'''(?x)
2630 (?P<before_secs>
2631 (?:(?:(?P<days>[0-9]+):)?(?P<hours>[0-9]+):)?(?P<mins>[0-9]+):)?
2632 (?P<secs>(?(before_secs)[0-9]{1,2}|[0-9]+))
2633 (?P<ms>[.:][0-9]+)?Z?$
2634 ''', s)
acaff495 2635 if m:
8bd1c00b 2636 days, hours, mins, secs, ms = m.group('days', 'hours', 'mins', 'secs', 'ms')
acaff495 2637 else:
2638 m = re.match(
056653bb
S
2639 r'''(?ix)(?:P?
2640 (?:
2641 [0-9]+\s*y(?:ears?)?\s*
2642 )?
2643 (?:
2644 [0-9]+\s*m(?:onths?)?\s*
2645 )?
2646 (?:
2647 [0-9]+\s*w(?:eeks?)?\s*
2648 )?
8f4b58d7 2649 (?:
acaff495 2650 (?P<days>[0-9]+)\s*d(?:ays?)?\s*
8f4b58d7 2651 )?
056653bb 2652 T)?
acaff495 2653 (?:
2654 (?P<hours>[0-9]+)\s*h(?:ours?)?\s*
2655 )?
2656 (?:
2657 (?P<mins>[0-9]+)\s*m(?:in(?:ute)?s?)?\s*
2658 )?
2659 (?:
2660 (?P<secs>[0-9]+)(?P<ms>\.[0-9]+)?\s*s(?:ec(?:ond)?s?)?\s*
15846398 2661 )?Z?$''', s)
acaff495 2662 if m:
2663 days, hours, mins, secs, ms = m.groups()
2664 else:
15846398 2665 m = re.match(r'(?i)(?:(?P<hours>[0-9.]+)\s*(?:hours?)|(?P<mins>[0-9.]+)\s*(?:mins?\.?|minutes?)\s*)Z?$', s)
acaff495 2666 if m:
2667 hours, mins = m.groups()
2668 else:
2669 return None
2670
2671 duration = 0
2672 if secs:
2673 duration += float(secs)
2674 if mins:
2675 duration += float(mins) * 60
2676 if hours:
2677 duration += float(hours) * 60 * 60
2678 if days:
2679 duration += float(days) * 24 * 60 * 60
2680 if ms:
8bd1c00b 2681 duration += float(ms.replace(':', '.'))
acaff495 2682 return duration
91d7d0b3
JMF
2683
2684
e65e4c88 2685def prepend_extension(filename, ext, expected_real_ext=None):
5f6a1245 2686 name, real_ext = os.path.splitext(filename)
e65e4c88
S
2687 return (
2688 '{0}.{1}{2}'.format(name, ext, real_ext)
2689 if not expected_real_ext or real_ext[1:] == expected_real_ext
2690 else '{0}.{1}'.format(filename, ext))
d70ad093
PH
2691
2692
b3ed15b7
S
2693def replace_extension(filename, ext, expected_real_ext=None):
2694 name, real_ext = os.path.splitext(filename)
2695 return '{0}.{1}'.format(
2696 name if not expected_real_ext or real_ext[1:] == expected_real_ext else filename,
2697 ext)
2698
2699
d70ad093
PH
2700def check_executable(exe, args=[]):
2701 """ Checks if the given binary is installed somewhere in PATH, and returns its name.
2702 args can be a list of arguments for a short output (like -version) """
2703 try:
d3c93ec2 2704 Popen([exe] + args, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate_or_kill()
d70ad093
PH
2705 except OSError:
2706 return False
2707 return exe
b7ab0590
PH
2708
2709
9af98e17 2710def _get_exe_version_output(exe, args):
95807118 2711 try:
b64d04c1 2712 # STDIN should be redirected too. On UNIX-like systems, ffmpeg triggers
7a5c1cfe 2713 # SIGTTOU if yt-dlp is run in the background.
067aa17e 2714 # See https://github.com/ytdl-org/youtube-dl/issues/955#issuecomment-209789656
d3c93ec2 2715 out, _ = Popen(
2716 [encodeArgument(exe)] + args, stdin=subprocess.PIPE,
2717 stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate_or_kill()
95807118
PH
2718 except OSError:
2719 return False
cae97f65
PH
2720 if isinstance(out, bytes): # Python 2.x
2721 out = out.decode('ascii', 'ignore')
9af98e17 2722 return out
cae97f65
PH
2723
2724
2725def detect_exe_version(output, version_re=None, unrecognized='present'):
2726 assert isinstance(output, compat_str)
2727 if version_re is None:
2728 version_re = r'version\s+([-0-9._a-zA-Z]+)'
2729 m = re.search(version_re, output)
95807118
PH
2730 if m:
2731 return m.group(1)
2732 else:
2733 return unrecognized
2734
2735
9af98e17 2736def get_exe_version(exe, args=['--version'],
2737 version_re=None, unrecognized='present'):
2738 """ Returns the version of the specified executable,
2739 or False if the executable is not present """
2740 out = _get_exe_version_output(exe, args)
2741 return detect_exe_version(out, version_re, unrecognized) if out else False
2742
2743
cb89cfc1 2744class LazyList(collections.abc.Sequence):
483336e7 2745 ''' Lazy immutable list from an iterable
2746 Note that slices of a LazyList are lists and not LazyList'''
2747
8e5fecc8 2748 class IndexError(IndexError):
2749 pass
2750
282f5709 2751 def __init__(self, iterable, *, reverse=False, _cache=None):
483336e7 2752 self.__iterable = iter(iterable)
282f5709 2753 self.__cache = [] if _cache is None else _cache
2754 self.__reversed = reverse
483336e7 2755
2756 def __iter__(self):
28419ca2 2757 if self.__reversed:
2758 # We need to consume the entire iterable to iterate in reverse
981052c9 2759 yield from self.exhaust()
28419ca2 2760 return
2761 yield from self.__cache
483336e7 2762 for item in self.__iterable:
2763 self.__cache.append(item)
2764 yield item
2765
981052c9 2766 def __exhaust(self):
483336e7 2767 self.__cache.extend(self.__iterable)
9f1a1c36 2768 # Discard the emptied iterable to make it pickle-able
2769 self.__iterable = []
28419ca2 2770 return self.__cache
2771
981052c9 2772 def exhaust(self):
2773 ''' Evaluate the entire iterable '''
2774 return self.__exhaust()[::-1 if self.__reversed else 1]
2775
28419ca2 2776 @staticmethod
981052c9 2777 def __reverse_index(x):
e0f2b4b4 2778 return None if x is None else -(x + 1)
483336e7 2779
2780 def __getitem__(self, idx):
2781 if isinstance(idx, slice):
28419ca2 2782 if self.__reversed:
e0f2b4b4 2783 idx = slice(self.__reverse_index(idx.start), self.__reverse_index(idx.stop), -(idx.step or 1))
2784 start, stop, step = idx.start, idx.stop, idx.step or 1
483336e7 2785 elif isinstance(idx, int):
28419ca2 2786 if self.__reversed:
981052c9 2787 idx = self.__reverse_index(idx)
e0f2b4b4 2788 start, stop, step = idx, idx, 0
483336e7 2789 else:
2790 raise TypeError('indices must be integers or slices')
e0f2b4b4 2791 if ((start or 0) < 0 or (stop or 0) < 0
2792 or (start is None and step < 0)
2793 or (stop is None and step > 0)):
483336e7 2794 # We need to consume the entire iterable to be able to slice from the end
2795 # Obviously, never use this with infinite iterables
8e5fecc8 2796 self.__exhaust()
2797 try:
2798 return self.__cache[idx]
2799 except IndexError as e:
2800 raise self.IndexError(e) from e
e0f2b4b4 2801 n = max(start or 0, stop or 0) - len(self.__cache) + 1
28419ca2 2802 if n > 0:
2803 self.__cache.extend(itertools.islice(self.__iterable, n))
8e5fecc8 2804 try:
2805 return self.__cache[idx]
2806 except IndexError as e:
2807 raise self.IndexError(e) from e
483336e7 2808
2809 def __bool__(self):
2810 try:
28419ca2 2811 self[-1] if self.__reversed else self[0]
8e5fecc8 2812 except self.IndexError:
483336e7 2813 return False
2814 return True
2815
2816 def __len__(self):
8e5fecc8 2817 self.__exhaust()
483336e7 2818 return len(self.__cache)
2819
282f5709 2820 def __reversed__(self):
2821 return type(self)(self.__iterable, reverse=not self.__reversed, _cache=self.__cache)
2822
2823 def __copy__(self):
2824 return type(self)(self.__iterable, reverse=self.__reversed, _cache=self.__cache)
2825
28419ca2 2826 def __repr__(self):
2827 # repr and str should mimic a list. So we exhaust the iterable
2828 return repr(self.exhaust())
2829
2830 def __str__(self):
2831 return repr(self.exhaust())
2832
483336e7 2833
7be9ccff 2834class PagedList:
c07a39ae 2835
2836 class IndexError(IndexError):
2837 pass
2838
dd26ced1
PH
2839 def __len__(self):
2840 # This is only useful for tests
2841 return len(self.getslice())
2842
7be9ccff 2843 def __init__(self, pagefunc, pagesize, use_cache=True):
2844 self._pagefunc = pagefunc
2845 self._pagesize = pagesize
f1d13090 2846 self._pagecount = float('inf')
7be9ccff 2847 self._use_cache = use_cache
2848 self._cache = {}
2849
2850 def getpage(self, pagenum):
d8cf8d97 2851 page_results = self._cache.get(pagenum)
2852 if page_results is None:
f1d13090 2853 page_results = [] if pagenum > self._pagecount else list(self._pagefunc(pagenum))
7be9ccff 2854 if self._use_cache:
2855 self._cache[pagenum] = page_results
2856 return page_results
2857
2858 def getslice(self, start=0, end=None):
2859 return list(self._getslice(start, end))
2860
2861 def _getslice(self, start, end):
55575225 2862 raise NotImplementedError('This method must be implemented by subclasses')
2863
2864 def __getitem__(self, idx):
f1d13090 2865 assert self._use_cache, 'Indexing PagedList requires cache'
55575225 2866 if not isinstance(idx, int) or idx < 0:
2867 raise TypeError('indices must be non-negative integers')
2868 entries = self.getslice(idx, idx + 1)
d8cf8d97 2869 if not entries:
c07a39ae 2870 raise self.IndexError()
d8cf8d97 2871 return entries[0]
55575225 2872
9c44d242
PH
2873
2874class OnDemandPagedList(PagedList):
7be9ccff 2875 def _getslice(self, start, end):
b7ab0590
PH
2876 for pagenum in itertools.count(start // self._pagesize):
2877 firstid = pagenum * self._pagesize
2878 nextfirstid = pagenum * self._pagesize + self._pagesize
2879 if start >= nextfirstid:
2880 continue
2881
b7ab0590
PH
2882 startv = (
2883 start % self._pagesize
2884 if firstid <= start < nextfirstid
2885 else 0)
b7ab0590
PH
2886 endv = (
2887 ((end - 1) % self._pagesize) + 1
2888 if (end is not None and firstid <= end <= nextfirstid)
2889 else None)
2890
f1d13090 2891 try:
2892 page_results = self.getpage(pagenum)
2893 except Exception:
2894 self._pagecount = pagenum - 1
2895 raise
b7ab0590
PH
2896 if startv != 0 or endv is not None:
2897 page_results = page_results[startv:endv]
7be9ccff 2898 yield from page_results
b7ab0590
PH
2899
2900 # A little optimization - if current page is not "full", ie. does
2901 # not contain page_size videos then we can assume that this page
2902 # is the last one - there are no more ids on further pages -
2903 # i.e. no need to query again.
2904 if len(page_results) + startv < self._pagesize:
2905 break
2906
2907 # If we got the whole page, but the next page is not interesting,
2908 # break out early as well
2909 if end == nextfirstid:
2910 break
81c2f20b
PH
2911
2912
9c44d242
PH
2913class InAdvancePagedList(PagedList):
2914 def __init__(self, pagefunc, pagecount, pagesize):
7be9ccff 2915 PagedList.__init__(self, pagefunc, pagesize, True)
f1d13090 2916 self._pagecount = pagecount
9c44d242 2917
7be9ccff 2918 def _getslice(self, start, end):
9c44d242 2919 start_page = start // self._pagesize
d37707bd 2920 end_page = self._pagecount if end is None else min(self._pagecount, end // self._pagesize + 1)
9c44d242
PH
2921 skip_elems = start - start_page * self._pagesize
2922 only_more = None if end is None else end - start
2923 for pagenum in range(start_page, end_page):
7be9ccff 2924 page_results = self.getpage(pagenum)
9c44d242 2925 if skip_elems:
7be9ccff 2926 page_results = page_results[skip_elems:]
9c44d242
PH
2927 skip_elems = None
2928 if only_more is not None:
7be9ccff 2929 if len(page_results) < only_more:
2930 only_more -= len(page_results)
9c44d242 2931 else:
7be9ccff 2932 yield from page_results[:only_more]
9c44d242 2933 break
7be9ccff 2934 yield from page_results
9c44d242
PH
2935
2936
81c2f20b 2937def uppercase_escape(s):
676eb3f2 2938 unicode_escape = codecs.getdecoder('unicode_escape')
81c2f20b 2939 return re.sub(
a612753d 2940 r'\\U[0-9a-fA-F]{8}',
676eb3f2
PH
2941 lambda m: unicode_escape(m.group(0))[0],
2942 s)
0fe2ff78
YCH
2943
2944
2945def lowercase_escape(s):
2946 unicode_escape = codecs.getdecoder('unicode_escape')
2947 return re.sub(
2948 r'\\u[0-9a-fA-F]{4}',
2949 lambda m: unicode_escape(m.group(0))[0],
2950 s)
b53466e1 2951
d05cfe06
S
2952
2953def escape_rfc3986(s):
2954 """Escape non-ASCII characters as suggested by RFC 3986"""
8f9312c3 2955 if sys.version_info < (3, 0) and isinstance(s, compat_str):
d05cfe06 2956 s = s.encode('utf-8')
ecc0c5ee 2957 return compat_urllib_parse.quote(s, b"%/;:@&=+$,!~*'()?#[]")
d05cfe06
S
2958
2959
2960def escape_url(url):
2961 """Escape URL as suggested by RFC 3986"""
2962 url_parsed = compat_urllib_parse_urlparse(url)
2963 return url_parsed._replace(
efbed08d 2964 netloc=url_parsed.netloc.encode('idna').decode('ascii'),
d05cfe06
S
2965 path=escape_rfc3986(url_parsed.path),
2966 params=escape_rfc3986(url_parsed.params),
2967 query=escape_rfc3986(url_parsed.query),
2968 fragment=escape_rfc3986(url_parsed.fragment)
2969 ).geturl()
2970
62e609ab 2971
4dfbf869 2972def parse_qs(url):
2973 return compat_parse_qs(compat_urllib_parse_urlparse(url).query)
2974
2975
62e609ab
PH
2976def read_batch_urls(batch_fd):
2977 def fixup(url):
2978 if not isinstance(url, compat_str):
2979 url = url.decode('utf-8', 'replace')
8c04f0be 2980 BOM_UTF8 = ('\xef\xbb\xbf', '\ufeff')
2981 for bom in BOM_UTF8:
2982 if url.startswith(bom):
2983 url = url[len(bom):]
2984 url = url.lstrip()
2985 if not url or url.startswith(('#', ';', ']')):
62e609ab 2986 return False
8c04f0be 2987 # "#" cannot be stripped out since it is part of the URI
2988 # However, it can be safely stipped out if follwing a whitespace
2989 return re.split(r'\s#', url, 1)[0].rstrip()
62e609ab
PH
2990
2991 with contextlib.closing(batch_fd) as fd:
2992 return [url for url in map(fixup, fd) if url]
b74fa8cd
JMF
2993
2994
2995def urlencode_postdata(*args, **kargs):
15707c7e 2996 return compat_urllib_parse_urlencode(*args, **kargs).encode('ascii')
bcf89ce6
PH
2997
2998
38f9ef31 2999def update_url_query(url, query):
cacd9966
YCH
3000 if not query:
3001 return url
38f9ef31 3002 parsed_url = compat_urlparse.urlparse(url)
3003 qs = compat_parse_qs(parsed_url.query)
3004 qs.update(query)
3005 return compat_urlparse.urlunparse(parsed_url._replace(
15707c7e 3006 query=compat_urllib_parse_urlencode(qs, True)))
16392824 3007
8e60dc75 3008
ed0291d1
S
3009def update_Request(req, url=None, data=None, headers={}, query={}):
3010 req_headers = req.headers.copy()
3011 req_headers.update(headers)
3012 req_data = data or req.data
3013 req_url = update_url_query(url or req.get_full_url(), query)
95cf60e8
S
3014 req_get_method = req.get_method()
3015 if req_get_method == 'HEAD':
3016 req_type = HEADRequest
3017 elif req_get_method == 'PUT':
3018 req_type = PUTRequest
3019 else:
3020 req_type = compat_urllib_request.Request
ed0291d1
S
3021 new_req = req_type(
3022 req_url, data=req_data, headers=req_headers,
3023 origin_req_host=req.origin_req_host, unverifiable=req.unverifiable)
3024 if hasattr(req, 'timeout'):
3025 new_req.timeout = req.timeout
3026 return new_req
3027
3028
10c87c15 3029def _multipart_encode_impl(data, boundary):
0c265486
YCH
3030 content_type = 'multipart/form-data; boundary=%s' % boundary
3031
3032 out = b''
3033 for k, v in data.items():
3034 out += b'--' + boundary.encode('ascii') + b'\r\n'
3035 if isinstance(k, compat_str):
3036 k = k.encode('utf-8')
3037 if isinstance(v, compat_str):
3038 v = v.encode('utf-8')
3039 # RFC 2047 requires non-ASCII field names to be encoded, while RFC 7578
3040 # suggests sending UTF-8 directly. Firefox sends UTF-8, too
b2ad479d 3041 content = b'Content-Disposition: form-data; name="' + k + b'"\r\n\r\n' + v + b'\r\n'
0c265486
YCH
3042 if boundary.encode('ascii') in content:
3043 raise ValueError('Boundary overlaps with data')
3044 out += content
3045
3046 out += b'--' + boundary.encode('ascii') + b'--\r\n'
3047
3048 return out, content_type
3049
3050
3051def multipart_encode(data, boundary=None):
3052 '''
3053 Encode a dict to RFC 7578-compliant form-data
3054
3055 data:
3056 A dict where keys and values can be either Unicode or bytes-like
3057 objects.
3058 boundary:
3059 If specified a Unicode object, it's used as the boundary. Otherwise
3060 a random boundary is generated.
3061
3062 Reference: https://tools.ietf.org/html/rfc7578
3063 '''
3064 has_specified_boundary = boundary is not None
3065
3066 while True:
3067 if boundary is None:
3068 boundary = '---------------' + str(random.randrange(0x0fffffff, 0xffffffff))
3069
3070 try:
10c87c15 3071 out, content_type = _multipart_encode_impl(data, boundary)
0c265486
YCH
3072 break
3073 except ValueError:
3074 if has_specified_boundary:
3075 raise
3076 boundary = None
3077
3078 return out, content_type
3079
3080
86296ad2 3081def dict_get(d, key_or_keys, default=None, skip_false_values=True):
cbecc9b9
S
3082 if isinstance(key_or_keys, (list, tuple)):
3083 for key in key_or_keys:
86296ad2
S
3084 if key not in d or d[key] is None or skip_false_values and not d[key]:
3085 continue
3086 return d[key]
cbecc9b9
S
3087 return default
3088 return d.get(key_or_keys, default)
3089
3090
329ca3be 3091def try_get(src, getter, expected_type=None):
6606817a 3092 for get in variadic(getter):
a32a9a7e
S
3093 try:
3094 v = get(src)
3095 except (AttributeError, KeyError, TypeError, IndexError):
3096 pass
3097 else:
3098 if expected_type is None or isinstance(v, expected_type):
3099 return v
329ca3be
S
3100
3101
6cc62232
S
3102def merge_dicts(*dicts):
3103 merged = {}
3104 for a_dict in dicts:
3105 for k, v in a_dict.items():
3106 if v is None:
3107 continue
3089bc74
S
3108 if (k not in merged
3109 or (isinstance(v, compat_str) and v
3110 and isinstance(merged[k], compat_str)
3111 and not merged[k])):
6cc62232
S
3112 merged[k] = v
3113 return merged
3114
3115
8e60dc75
S
3116def encode_compat_str(string, encoding=preferredencoding(), errors='strict'):
3117 return string if isinstance(string, compat_str) else compat_str(string, encoding, errors)
3118
16392824 3119
a1a530b0
PH
3120US_RATINGS = {
3121 'G': 0,
3122 'PG': 10,
3123 'PG-13': 13,
3124 'R': 16,
3125 'NC': 18,
3126}
fac55558
PH
3127
3128
a8795327 3129TV_PARENTAL_GUIDELINES = {
5a16c9d9
RA
3130 'TV-Y': 0,
3131 'TV-Y7': 7,
3132 'TV-G': 0,
3133 'TV-PG': 0,
3134 'TV-14': 14,
3135 'TV-MA': 17,
a8795327
S
3136}
3137
3138
146c80e2 3139def parse_age_limit(s):
a8795327
S
3140 if type(s) == int:
3141 return s if 0 <= s <= 21 else None
3142 if not isinstance(s, compat_basestring):
d838b1bd 3143 return None
146c80e2 3144 m = re.match(r'^(?P<age>\d{1,2})\+?$', s)
a8795327
S
3145 if m:
3146 return int(m.group('age'))
5c5fae6d 3147 s = s.upper()
a8795327
S
3148 if s in US_RATINGS:
3149 return US_RATINGS[s]
5a16c9d9 3150 m = re.match(r'^TV[_-]?(%s)$' % '|'.join(k[3:] for k in TV_PARENTAL_GUIDELINES), s)
b8361187 3151 if m:
5a16c9d9 3152 return TV_PARENTAL_GUIDELINES['TV-' + m.group(1)]
b8361187 3153 return None
146c80e2
S
3154
3155
fac55558 3156def strip_jsonp(code):
609a61e3 3157 return re.sub(
5552c9eb 3158 r'''(?sx)^
e9c671d5 3159 (?:window\.)?(?P<func_name>[a-zA-Z0-9_.$]*)
5552c9eb
YCH
3160 (?:\s*&&\s*(?P=func_name))?
3161 \s*\(\s*(?P<callback_data>.*)\);?
3162 \s*?(?://[^\n]*)*$''',
3163 r'\g<callback_data>', code)
478c2c61
PH
3164
3165
5c610515 3166def js_to_json(code, vars={}):
3167 # vars is a dict of var, val pairs to substitute
c843e685 3168 COMMENT_RE = r'/\*(?:(?!\*/).)*?\*/|//[^\n]*\n'
4195096e
S
3169 SKIP_RE = r'\s*(?:{comment})?\s*'.format(comment=COMMENT_RE)
3170 INTEGER_TABLE = (
3171 (r'(?s)^(0[xX][0-9a-fA-F]+){skip}:?$'.format(skip=SKIP_RE), 16),
3172 (r'(?s)^(0+[0-7]+){skip}:?$'.format(skip=SKIP_RE), 8),
3173 )
3174
e05f6939 3175 def fix_kv(m):
e7b6d122
PH
3176 v = m.group(0)
3177 if v in ('true', 'false', 'null'):
3178 return v
421ddcb8
C
3179 elif v in ('undefined', 'void 0'):
3180 return 'null'
8bdd16b4 3181 elif v.startswith('/*') or v.startswith('//') or v.startswith('!') or v == ',':
bd1e4844 3182 return ""
3183
3184 if v[0] in ("'", '"'):
3185 v = re.sub(r'(?s)\\.|"', lambda m: {
e7b6d122 3186 '"': '\\"',
bd1e4844 3187 "\\'": "'",
3188 '\\\n': '',
3189 '\\x': '\\u00',
3190 }.get(m.group(0), m.group(0)), v[1:-1])
8bdd16b4 3191 else:
3192 for regex, base in INTEGER_TABLE:
3193 im = re.match(regex, v)
3194 if im:
3195 i = int(im.group(1), base)
3196 return '"%d":' % i if v.endswith(':') else '%d' % i
89ac4a19 3197
5c610515 3198 if v in vars:
3199 return vars[v]
3200
e7b6d122 3201 return '"%s"' % v
e05f6939 3202
febff4c1
B
3203 code = re.sub(r'new Date\((".+")\)', r'\g<1>', code)
3204
bd1e4844 3205 return re.sub(r'''(?sx)
3206 "(?:[^"\\]*(?:\\\\|\\['"nurtbfx/\n]))*[^"\\]*"|
3207 '(?:[^'\\]*(?:\\\\|\\['"nurtbfx/\n]))*[^'\\]*'|
4195096e 3208 {comment}|,(?={skip}[\]}}])|
421ddcb8 3209 void\s0|(?:(?<![0-9])[eE]|[a-df-zA-DF-Z_$])[.a-zA-Z_$0-9]*|
4195096e 3210 \b(?:0[xX][0-9a-fA-F]+|0+[0-7]+)(?:{skip}:)?|
8bdd16b4 3211 [0-9]+(?={skip}:)|
3212 !+
4195096e 3213 '''.format(comment=COMMENT_RE, skip=SKIP_RE), fix_kv, code)
e05f6939
PH
3214
3215
478c2c61
PH
3216def qualities(quality_ids):
3217 """ Get a numeric quality value out of a list of possible values """
3218 def q(qid):
3219 try:
3220 return quality_ids.index(qid)
3221 except ValueError:
3222 return -1
3223 return q
3224
acd69589 3225
09b49e1f 3226POSTPROCESS_WHEN = {'pre_process', 'after_filter', 'before_dl', 'after_move', 'post_process', 'after_video', 'playlist'}
1e43a6f7 3227
3228
de6000d9 3229DEFAULT_OUTTMPL = {
3230 'default': '%(title)s [%(id)s].%(ext)s',
72755351 3231 'chapter': '%(title)s - %(section_number)03d %(section_title)s [%(id)s].%(ext)s',
de6000d9 3232}
3233OUTTMPL_TYPES = {
72755351 3234 'chapter': None,
de6000d9 3235 'subtitle': None,
3236 'thumbnail': None,
3237 'description': 'description',
3238 'annotation': 'annotations.xml',
3239 'infojson': 'info.json',
08438d2c 3240 'link': None,
3b603dbd 3241 'pl_video': None,
5112f26a 3242 'pl_thumbnail': None,
de6000d9 3243 'pl_description': 'description',
3244 'pl_infojson': 'info.json',
3245}
0a871f68 3246
143db31d 3247# As of [1] format syntax is:
3248# %[mapping_key][conversion_flags][minimum_width][.precision][length_modifier]type
3249# 1. https://docs.python.org/2/library/stdtypes.html#string-formatting
901130bb 3250STR_FORMAT_RE_TMPL = r'''(?x)
3251 (?<!%)(?P<prefix>(?:%%)*)
143db31d 3252 %
524e2e4f 3253 (?P<has_key>\((?P<key>{0})\))?
752cda38 3254 (?P<format>
524e2e4f 3255 (?P<conversion>[#0\-+ ]+)?
3256 (?P<min_width>\d+)?
3257 (?P<precision>\.\d+)?
3258 (?P<len_mod>[hlL])? # unused in python
901130bb 3259 {1} # conversion type
752cda38 3260 )
143db31d 3261'''
3262
7d1eb38a 3263
901130bb 3264STR_FORMAT_TYPES = 'diouxXeEfFgGcrs'
a020a0dc 3265
7d1eb38a 3266
a020a0dc
PH
3267def limit_length(s, length):
3268 """ Add ellipses to overly long strings """
3269 if s is None:
3270 return None
3271 ELLIPSES = '...'
3272 if len(s) > length:
3273 return s[:length - len(ELLIPSES)] + ELLIPSES
3274 return s
48844745
PH
3275
3276
3277def version_tuple(v):
5f9b8394 3278 return tuple(int(e) for e in re.split(r'[-.]', v))
48844745
PH
3279
3280
3281def is_outdated_version(version, limit, assume_new=True):
3282 if not version:
3283 return not assume_new
3284 try:
3285 return version_tuple(version) < version_tuple(limit)
3286 except ValueError:
3287 return not assume_new
732ea2f0
PH
3288
3289
3290def ytdl_is_updateable():
7a5c1cfe 3291 """ Returns if yt-dlp can be updated with -U """
735d865e 3292
5d535b4a 3293 from .update import is_non_updateable
732ea2f0 3294
5d535b4a 3295 return not is_non_updateable()
7d4111ed
PH
3296
3297
3298def args_to_str(args):
3299 # Get a short string representation for a subprocess command
702ccf2d 3300 return ' '.join(compat_shlex_quote(a) for a in args)
2ccd1b10
PH
3301
3302
9b9c5355 3303def error_to_compat_str(err):
fdae2358
S
3304 err_str = str(err)
3305 # On python 2 error byte string must be decoded with proper
3306 # encoding rather than ascii
3307 if sys.version_info[0] < 3:
3308 err_str = err_str.decode(preferredencoding())
3309 return err_str
3310
3311
c460bdd5 3312def mimetype2ext(mt):
eb9ee194
S
3313 if mt is None:
3314 return None
3315
9359f3d4
F
3316 mt, _, params = mt.partition(';')
3317 mt = mt.strip()
3318
3319 FULL_MAP = {
765ac263 3320 'audio/mp4': 'm4a',
6c33d24b
YCH
3321 # Per RFC 3003, audio/mpeg can be .mp1, .mp2 or .mp3. Here use .mp3 as
3322 # it's the most popular one
3323 'audio/mpeg': 'mp3',
ba39289d 3324 'audio/x-wav': 'wav',
9359f3d4
F
3325 'audio/wav': 'wav',
3326 'audio/wave': 'wav',
3327 }
3328
3329 ext = FULL_MAP.get(mt)
765ac263
JMF
3330 if ext is not None:
3331 return ext
3332
9359f3d4 3333 SUBTYPE_MAP = {
f6861ec9 3334 '3gpp': '3gp',
cafcf657 3335 'smptett+xml': 'tt',
cafcf657 3336 'ttaf+xml': 'dfxp',
a0d8d704 3337 'ttml+xml': 'ttml',
f6861ec9 3338 'x-flv': 'flv',
a0d8d704 3339 'x-mp4-fragmented': 'mp4',
d4f05d47 3340 'x-ms-sami': 'sami',
a0d8d704 3341 'x-ms-wmv': 'wmv',
b4173f15
RA
3342 'mpegurl': 'm3u8',
3343 'x-mpegurl': 'm3u8',
3344 'vnd.apple.mpegurl': 'm3u8',
3345 'dash+xml': 'mpd',
b4173f15 3346 'f4m+xml': 'f4m',
f164b971 3347 'hds+xml': 'f4m',
e910fe2f 3348 'vnd.ms-sstr+xml': 'ism',
c2b2c7e1 3349 'quicktime': 'mov',
98ce1a3f 3350 'mp2t': 'ts',
39e7107d 3351 'x-wav': 'wav',
9359f3d4
F
3352 'filmstrip+json': 'fs',
3353 'svg+xml': 'svg',
3354 }
3355
3356 _, _, subtype = mt.rpartition('/')
3357 ext = SUBTYPE_MAP.get(subtype.lower())
3358 if ext is not None:
3359 return ext
3360
3361 SUFFIX_MAP = {
3362 'json': 'json',
3363 'xml': 'xml',
3364 'zip': 'zip',
3365 'gzip': 'gz',
3366 }
3367
3368 _, _, suffix = subtype.partition('+')
3369 ext = SUFFIX_MAP.get(suffix)
3370 if ext is not None:
3371 return ext
3372
3373 return subtype.replace('+', '.')
c460bdd5
PH
3374
3375
2814f12b
THD
3376def ext2mimetype(ext_or_url):
3377 if not ext_or_url:
3378 return None
3379 if '.' not in ext_or_url:
3380 ext_or_url = f'file.{ext_or_url}'
3381 return mimetypes.guess_type(ext_or_url)[0]
3382
3383
4f3c5e06 3384def parse_codecs(codecs_str):
3385 # http://tools.ietf.org/html/rfc6381
3386 if not codecs_str:
3387 return {}
a0566bbf 3388 split_codecs = list(filter(None, map(
dbf5416a 3389 str.strip, codecs_str.strip().strip(',').split(','))))
4afa3ec4 3390 vcodec, acodec, tcodec, hdr = None, None, None, None
a0566bbf 3391 for full_codec in split_codecs:
9bd979ca 3392 parts = full_codec.split('.')
3393 codec = parts[0].replace('0', '')
3394 if codec in ('avc1', 'avc2', 'avc3', 'avc4', 'vp9', 'vp8', 'hev1', 'hev2',
3395 'h263', 'h264', 'mp4v', 'hvc1', 'av1', 'theora', 'dvh1', 'dvhe'):
4f3c5e06 3396 if not vcodec:
b69fd25c 3397 vcodec = '.'.join(parts[:4]) if codec in ('vp9', 'av1', 'hvc1') else full_codec
176f1866 3398 if codec in ('dvh1', 'dvhe'):
3399 hdr = 'DV'
9bd979ca 3400 elif codec == 'av1' and len(parts) > 3 and parts[3] == '10':
3401 hdr = 'HDR10'
3402 elif full_codec.replace('0', '').startswith('vp9.2'):
176f1866 3403 hdr = 'HDR10'
b69fd25c 3404 elif codec in ('flac', 'mp4a', 'opus', 'vorbis', 'mp3', 'aac', 'ac-3', 'ec-3', 'eac3', 'dtsc', 'dtse', 'dtsh', 'dtsl'):
4f3c5e06 3405 if not acodec:
3406 acodec = full_codec
4afa3ec4
F
3407 elif codec in ('stpp', 'wvtt',):
3408 if not tcodec:
3409 tcodec = full_codec
4f3c5e06 3410 else:
60f5c9fb 3411 write_string('WARNING: Unknown codec %s\n' % full_codec, sys.stderr)
4afa3ec4 3412 if vcodec or acodec or tcodec:
4f3c5e06 3413 return {
3414 'vcodec': vcodec or 'none',
3415 'acodec': acodec or 'none',
176f1866 3416 'dynamic_range': hdr,
4afa3ec4 3417 **({'tcodec': tcodec} if tcodec is not None else {}),
4f3c5e06 3418 }
b69fd25c 3419 elif len(split_codecs) == 2:
3420 return {
3421 'vcodec': split_codecs[0],
3422 'acodec': split_codecs[1],
3423 }
4f3c5e06 3424 return {}
3425
3426
2ccd1b10 3427def urlhandle_detect_ext(url_handle):
79298173 3428 getheader = url_handle.headers.get
2ccd1b10 3429
b55ee18f
PH
3430 cd = getheader('Content-Disposition')
3431 if cd:
3432 m = re.match(r'attachment;\s*filename="(?P<filename>[^"]+)"', cd)
3433 if m:
3434 e = determine_ext(m.group('filename'), default_ext=None)
3435 if e:
3436 return e
3437
c460bdd5 3438 return mimetype2ext(getheader('Content-Type'))
05900629
PH
3439
3440
1e399778
YCH
3441def encode_data_uri(data, mime_type):
3442 return 'data:%s;base64,%s' % (mime_type, base64.b64encode(data).decode('ascii'))
3443
3444
05900629 3445def age_restricted(content_limit, age_limit):
6ec6cb4e 3446 """ Returns True iff the content should be blocked """
05900629
PH
3447
3448 if age_limit is None: # No limit set
3449 return False
3450 if content_limit is None:
3451 return False # Content available for everyone
3452 return age_limit < content_limit
61ca9a80
PH
3453
3454
3455def is_html(first_bytes):
3456 """ Detect whether a file contains HTML by examining its first bytes. """
3457
3458 BOMS = [
3459 (b'\xef\xbb\xbf', 'utf-8'),
3460 (b'\x00\x00\xfe\xff', 'utf-32-be'),
3461 (b'\xff\xfe\x00\x00', 'utf-32-le'),
3462 (b'\xff\xfe', 'utf-16-le'),
3463 (b'\xfe\xff', 'utf-16-be'),
3464 ]
3465 for bom, enc in BOMS:
3466 if first_bytes.startswith(bom):
3467 s = first_bytes[len(bom):].decode(enc, 'replace')
3468 break
3469 else:
3470 s = first_bytes.decode('utf-8', 'replace')
3471
3472 return re.match(r'^\s*<', s)
a055469f
PH
3473
3474
3475def determine_protocol(info_dict):
3476 protocol = info_dict.get('protocol')
3477 if protocol is not None:
3478 return protocol
3479
7de837a5 3480 url = sanitize_url(info_dict['url'])
a055469f
PH
3481 if url.startswith('rtmp'):
3482 return 'rtmp'
3483 elif url.startswith('mms'):
3484 return 'mms'
3485 elif url.startswith('rtsp'):
3486 return 'rtsp'
3487
3488 ext = determine_ext(url)
3489 if ext == 'm3u8':
3490 return 'm3u8'
3491 elif ext == 'f4m':
3492 return 'f4m'
3493
3494 return compat_urllib_parse_urlparse(url).scheme
cfb56d1a
PH
3495
3496
c5e3f849 3497def render_table(header_row, data, delim=False, extra_gap=0, hide_empty=False):
3498 """ Render a list of rows, each as a list of values.
3499 Text after a \t will be right aligned """
ec11a9f4 3500 def width(string):
c5e3f849 3501 return len(remove_terminal_sequences(string).replace('\t', ''))
76d321f6 3502
3503 def get_max_lens(table):
ec11a9f4 3504 return [max(width(str(v)) for v in col) for col in zip(*table)]
76d321f6 3505
3506 def filter_using_list(row, filterArray):
d16df59d 3507 return [col for take, col in itertools.zip_longest(filterArray, row, fillvalue=True) if take]
76d321f6 3508
d16df59d 3509 max_lens = get_max_lens(data) if hide_empty else []
3510 header_row = filter_using_list(header_row, max_lens)
3511 data = [filter_using_list(row, max_lens) for row in data]
76d321f6 3512
cfb56d1a 3513 table = [header_row] + data
76d321f6 3514 max_lens = get_max_lens(table)
c5e3f849 3515 extra_gap += 1
76d321f6 3516 if delim:
c5e3f849 3517 table = [header_row, [delim * (ml + extra_gap) for ml in max_lens]] + data
1ed7953a 3518 table[1][-1] = table[1][-1][:-extra_gap * len(delim)] # Remove extra_gap from end of delimiter
ec11a9f4 3519 for row in table:
3520 for pos, text in enumerate(map(str, row)):
c5e3f849 3521 if '\t' in text:
3522 row[pos] = text.replace('\t', ' ' * (max_lens[pos] - width(text))) + ' ' * extra_gap
3523 else:
3524 row[pos] = text + ' ' * (max_lens[pos] - width(text) + extra_gap)
3525 ret = '\n'.join(''.join(row).rstrip() for row in table)
ec11a9f4 3526 return ret
347de493
PH
3527
3528
8f18aca8 3529def _match_one(filter_part, dct, incomplete):
77b87f05 3530 # TODO: Generalize code with YoutubeDL._build_format_filter
a047eeb6 3531 STRING_OPERATORS = {
3532 '*=': operator.contains,
3533 '^=': lambda attr, value: attr.startswith(value),
3534 '$=': lambda attr, value: attr.endswith(value),
3535 '~=': lambda attr, value: re.search(value, attr),
3536 }
347de493 3537 COMPARISON_OPERATORS = {
a047eeb6 3538 **STRING_OPERATORS,
3539 '<=': operator.le, # "<=" must be defined above "<"
347de493 3540 '<': operator.lt,
347de493 3541 '>=': operator.ge,
a047eeb6 3542 '>': operator.gt,
347de493 3543 '=': operator.eq,
347de493 3544 }
a047eeb6 3545
347de493
PH
3546 operator_rex = re.compile(r'''(?x)\s*
3547 (?P<key>[a-z_]+)
77b87f05 3548 \s*(?P<negation>!\s*)?(?P<op>%s)(?P<none_inclusive>\s*\?)?\s*
347de493 3549 (?:
a047eeb6 3550 (?P<quote>["\'])(?P<quotedstrval>.+?)(?P=quote)|
3551 (?P<strval>.+?)
347de493
PH
3552 )
3553 \s*$
3554 ''' % '|'.join(map(re.escape, COMPARISON_OPERATORS.keys())))
3555 m = operator_rex.search(filter_part)
3556 if m:
18f96d12 3557 m = m.groupdict()
3558 unnegated_op = COMPARISON_OPERATORS[m['op']]
3559 if m['negation']:
77b87f05
MT
3560 op = lambda attr, value: not unnegated_op(attr, value)
3561 else:
3562 op = unnegated_op
18f96d12 3563 comparison_value = m['quotedstrval'] or m['strval'] or m['intval']
3564 if m['quote']:
3565 comparison_value = comparison_value.replace(r'\%s' % m['quote'], m['quote'])
3566 actual_value = dct.get(m['key'])
3567 numeric_comparison = None
3568 if isinstance(actual_value, compat_numeric_types):
e5a088dc
S
3569 # If the original field is a string and matching comparisonvalue is
3570 # a number we should respect the origin of the original field
3571 # and process comparison value as a string (see
18f96d12 3572 # https://github.com/ytdl-org/youtube-dl/issues/11082)
347de493 3573 try:
18f96d12 3574 numeric_comparison = int(comparison_value)
347de493 3575 except ValueError:
18f96d12 3576 numeric_comparison = parse_filesize(comparison_value)
3577 if numeric_comparison is None:
3578 numeric_comparison = parse_filesize(f'{comparison_value}B')
3579 if numeric_comparison is None:
3580 numeric_comparison = parse_duration(comparison_value)
3581 if numeric_comparison is not None and m['op'] in STRING_OPERATORS:
3582 raise ValueError('Operator %s only supports string values!' % m['op'])
347de493 3583 if actual_value is None:
18f96d12 3584 return incomplete or m['none_inclusive']
3585 return op(actual_value, comparison_value if numeric_comparison is None else numeric_comparison)
347de493
PH
3586
3587 UNARY_OPERATORS = {
1cc47c66
S
3588 '': lambda v: (v is True) if isinstance(v, bool) else (v is not None),
3589 '!': lambda v: (v is False) if isinstance(v, bool) else (v is None),
347de493
PH
3590 }
3591 operator_rex = re.compile(r'''(?x)\s*
3592 (?P<op>%s)\s*(?P<key>[a-z_]+)
3593 \s*$
3594 ''' % '|'.join(map(re.escape, UNARY_OPERATORS.keys())))
3595 m = operator_rex.search(filter_part)
3596 if m:
3597 op = UNARY_OPERATORS[m.group('op')]
3598 actual_value = dct.get(m.group('key'))
8f18aca8 3599 if incomplete and actual_value is None:
3600 return True
347de493
PH
3601 return op(actual_value)
3602
3603 raise ValueError('Invalid filter part %r' % filter_part)
3604
3605
8f18aca8 3606def match_str(filter_str, dct, incomplete=False):
3607 """ Filter a dictionary with a simple string syntax. Returns True (=passes filter) or false
3608 When incomplete, all conditions passes on missing fields
3609 """
347de493 3610 return all(
8f18aca8 3611 _match_one(filter_part.replace(r'\&', '&'), dct, incomplete)
a047eeb6 3612 for filter_part in re.split(r'(?<!\\)&', filter_str))
347de493
PH
3613
3614
3615def match_filter_func(filter_str):
d1b5f70b 3616 if filter_str is None:
3617 return None
3618
8f18aca8 3619 def _match_func(info_dict, *args, **kwargs):
3620 if match_str(filter_str, info_dict, *args, **kwargs):
347de493
PH
3621 return None
3622 else:
3623 video_title = info_dict.get('title', info_dict.get('id', 'video'))
3624 return '%s does not pass filter %s, skipping ..' % (video_title, filter_str)
3625 return _match_func
91410c9b
PH
3626
3627
bf6427d2
YCH
3628def parse_dfxp_time_expr(time_expr):
3629 if not time_expr:
d631d5f9 3630 return
bf6427d2
YCH
3631
3632 mobj = re.match(r'^(?P<time_offset>\d+(?:\.\d+)?)s?$', time_expr)
3633 if mobj:
3634 return float(mobj.group('time_offset'))
3635
db2fe38b 3636 mobj = re.match(r'^(\d+):(\d\d):(\d\d(?:(?:\.|:)\d+)?)$', time_expr)
bf6427d2 3637 if mobj:
db2fe38b 3638 return 3600 * int(mobj.group(1)) + 60 * int(mobj.group(2)) + float(mobj.group(3).replace(':', '.'))
bf6427d2
YCH
3639
3640
c1c924ab 3641def srt_subtitles_timecode(seconds):
aa7785f8 3642 return '%02d:%02d:%02d,%03d' % timetuple_from_msec(seconds * 1000)
3643
3644
3645def ass_subtitles_timecode(seconds):
3646 time = timetuple_from_msec(seconds * 1000)
3647 return '%01d:%02d:%02d.%02d' % (*time[:-1], time.milliseconds / 10)
bf6427d2
YCH
3648
3649
3650def dfxp2srt(dfxp_data):
3869028f
YCH
3651 '''
3652 @param dfxp_data A bytes-like object containing DFXP data
3653 @returns A unicode object containing converted SRT data
3654 '''
5b995f71 3655 LEGACY_NAMESPACES = (
3869028f
YCH
3656 (b'http://www.w3.org/ns/ttml', [
3657 b'http://www.w3.org/2004/11/ttaf1',
3658 b'http://www.w3.org/2006/04/ttaf1',
3659 b'http://www.w3.org/2006/10/ttaf1',
5b995f71 3660 ]),
3869028f
YCH
3661 (b'http://www.w3.org/ns/ttml#styling', [
3662 b'http://www.w3.org/ns/ttml#style',
5b995f71
RA
3663 ]),
3664 )
3665
3666 SUPPORTED_STYLING = [
3667 'color',
3668 'fontFamily',
3669 'fontSize',
3670 'fontStyle',
3671 'fontWeight',
3672 'textDecoration'
3673 ]
3674
4e335771 3675 _x = functools.partial(xpath_with_ns, ns_map={
261f4730 3676 'xml': 'http://www.w3.org/XML/1998/namespace',
4e335771 3677 'ttml': 'http://www.w3.org/ns/ttml',
5b995f71 3678 'tts': 'http://www.w3.org/ns/ttml#styling',
4e335771 3679 })
bf6427d2 3680
5b995f71
RA
3681 styles = {}
3682 default_style = {}
3683
87de7069 3684 class TTMLPElementParser(object):
5b995f71
RA
3685 _out = ''
3686 _unclosed_elements = []
3687 _applied_styles = []
bf6427d2 3688
2b14cb56 3689 def start(self, tag, attrib):
5b995f71
RA
3690 if tag in (_x('ttml:br'), 'br'):
3691 self._out += '\n'
3692 else:
3693 unclosed_elements = []
3694 style = {}
3695 element_style_id = attrib.get('style')
3696 if default_style:
3697 style.update(default_style)
3698 if element_style_id:
3699 style.update(styles.get(element_style_id, {}))
3700 for prop in SUPPORTED_STYLING:
3701 prop_val = attrib.get(_x('tts:' + prop))
3702 if prop_val:
3703 style[prop] = prop_val
3704 if style:
3705 font = ''
3706 for k, v in sorted(style.items()):
3707 if self._applied_styles and self._applied_styles[-1].get(k) == v:
3708 continue
3709 if k == 'color':
3710 font += ' color="%s"' % v
3711 elif k == 'fontSize':
3712 font += ' size="%s"' % v
3713 elif k == 'fontFamily':
3714 font += ' face="%s"' % v
3715 elif k == 'fontWeight' and v == 'bold':
3716 self._out += '<b>'
3717 unclosed_elements.append('b')
3718 elif k == 'fontStyle' and v == 'italic':
3719 self._out += '<i>'
3720 unclosed_elements.append('i')
3721 elif k == 'textDecoration' and v == 'underline':
3722 self._out += '<u>'
3723 unclosed_elements.append('u')
3724 if font:
3725 self._out += '<font' + font + '>'
3726 unclosed_elements.append('font')
3727 applied_style = {}
3728 if self._applied_styles:
3729 applied_style.update(self._applied_styles[-1])
3730 applied_style.update(style)
3731 self._applied_styles.append(applied_style)
3732 self._unclosed_elements.append(unclosed_elements)
bf6427d2 3733
2b14cb56 3734 def end(self, tag):
5b995f71
RA
3735 if tag not in (_x('ttml:br'), 'br'):
3736 unclosed_elements = self._unclosed_elements.pop()
3737 for element in reversed(unclosed_elements):
3738 self._out += '</%s>' % element
3739 if unclosed_elements and self._applied_styles:
3740 self._applied_styles.pop()
bf6427d2 3741
2b14cb56 3742 def data(self, data):
5b995f71 3743 self._out += data
2b14cb56 3744
3745 def close(self):
5b995f71 3746 return self._out.strip()
2b14cb56 3747
3748 def parse_node(node):
3749 target = TTMLPElementParser()
3750 parser = xml.etree.ElementTree.XMLParser(target=target)
3751 parser.feed(xml.etree.ElementTree.tostring(node))
3752 return parser.close()
bf6427d2 3753
5b995f71
RA
3754 for k, v in LEGACY_NAMESPACES:
3755 for ns in v:
3756 dfxp_data = dfxp_data.replace(ns, k)
3757
3869028f 3758 dfxp = compat_etree_fromstring(dfxp_data)
bf6427d2 3759 out = []
5b995f71 3760 paras = dfxp.findall(_x('.//ttml:p')) or dfxp.findall('.//p')
1b0427e6
YCH
3761
3762 if not paras:
3763 raise ValueError('Invalid dfxp/TTML subtitle')
bf6427d2 3764
5b995f71
RA
3765 repeat = False
3766 while True:
3767 for style in dfxp.findall(_x('.//ttml:style')):
261f4730
RA
3768 style_id = style.get('id') or style.get(_x('xml:id'))
3769 if not style_id:
3770 continue
5b995f71
RA
3771 parent_style_id = style.get('style')
3772 if parent_style_id:
3773 if parent_style_id not in styles:
3774 repeat = True
3775 continue
3776 styles[style_id] = styles[parent_style_id].copy()
3777 for prop in SUPPORTED_STYLING:
3778 prop_val = style.get(_x('tts:' + prop))
3779 if prop_val:
3780 styles.setdefault(style_id, {})[prop] = prop_val
3781 if repeat:
3782 repeat = False
3783 else:
3784 break
3785
3786 for p in ('body', 'div'):
3787 ele = xpath_element(dfxp, [_x('.//ttml:' + p), './/' + p])
3788 if ele is None:
3789 continue
3790 style = styles.get(ele.get('style'))
3791 if not style:
3792 continue
3793 default_style.update(style)
3794
bf6427d2 3795 for para, index in zip(paras, itertools.count(1)):
d631d5f9 3796 begin_time = parse_dfxp_time_expr(para.attrib.get('begin'))
7dff0363 3797 end_time = parse_dfxp_time_expr(para.attrib.get('end'))
d631d5f9
YCH
3798 dur = parse_dfxp_time_expr(para.attrib.get('dur'))
3799 if begin_time is None:
3800 continue
7dff0363 3801 if not end_time:
d631d5f9
YCH
3802 if not dur:
3803 continue
3804 end_time = begin_time + dur
bf6427d2
YCH
3805 out.append('%d\n%s --> %s\n%s\n\n' % (
3806 index,
c1c924ab
YCH
3807 srt_subtitles_timecode(begin_time),
3808 srt_subtitles_timecode(end_time),
bf6427d2
YCH
3809 parse_node(para)))
3810
3811 return ''.join(out)
3812
3813
66e289ba
S
3814def cli_option(params, command_option, param):
3815 param = params.get(param)
98e698f1
RA
3816 if param:
3817 param = compat_str(param)
66e289ba
S
3818 return [command_option, param] if param is not None else []
3819
3820
3821def cli_bool_option(params, command_option, param, true_value='true', false_value='false', separator=None):
3822 param = params.get(param)
5b232f46
S
3823 if param is None:
3824 return []
66e289ba
S
3825 assert isinstance(param, bool)
3826 if separator:
3827 return [command_option + separator + (true_value if param else false_value)]
3828 return [command_option, true_value if param else false_value]
3829
3830
3831def cli_valueless_option(params, command_option, param, expected_value=True):
3832 param = params.get(param)
3833 return [command_option] if param == expected_value else []
3834
3835
e92caff5 3836def cli_configuration_args(argdict, keys, default=[], use_compat=True):
eab9b2bc 3837 if isinstance(argdict, (list, tuple)): # for backward compatibility
e92caff5 3838 if use_compat:
5b1ecbb3 3839 return argdict
3840 else:
3841 argdict = None
eab9b2bc 3842 if argdict is None:
5b1ecbb3 3843 return default
eab9b2bc 3844 assert isinstance(argdict, dict)
3845
e92caff5 3846 assert isinstance(keys, (list, tuple))
3847 for key_list in keys:
e92caff5 3848 arg_list = list(filter(
3849 lambda x: x is not None,
6606817a 3850 [argdict.get(key.lower()) for key in variadic(key_list)]))
e92caff5 3851 if arg_list:
3852 return [arg for args in arg_list for arg in args]
3853 return default
66e289ba 3854
6251555f 3855
330690a2 3856def _configuration_args(main_key, argdict, exe, keys=None, default=[], use_compat=True):
3857 main_key, exe = main_key.lower(), exe.lower()
3858 root_key = exe if main_key == exe else f'{main_key}+{exe}'
3859 keys = [f'{root_key}{k}' for k in (keys or [''])]
3860 if root_key in keys:
3861 if main_key != exe:
3862 keys.append((main_key, exe))
3863 keys.append('default')
3864 else:
3865 use_compat = False
3866 return cli_configuration_args(argdict, keys, default, use_compat)
3867
66e289ba 3868
39672624
YCH
3869class ISO639Utils(object):
3870 # See http://www.loc.gov/standards/iso639-2/ISO-639-2_utf-8.txt
3871 _lang_map = {
3872 'aa': 'aar',
3873 'ab': 'abk',
3874 'ae': 'ave',
3875 'af': 'afr',
3876 'ak': 'aka',
3877 'am': 'amh',
3878 'an': 'arg',
3879 'ar': 'ara',
3880 'as': 'asm',
3881 'av': 'ava',
3882 'ay': 'aym',
3883 'az': 'aze',
3884 'ba': 'bak',
3885 'be': 'bel',
3886 'bg': 'bul',
3887 'bh': 'bih',
3888 'bi': 'bis',
3889 'bm': 'bam',
3890 'bn': 'ben',
3891 'bo': 'bod',
3892 'br': 'bre',
3893 'bs': 'bos',
3894 'ca': 'cat',
3895 'ce': 'che',
3896 'ch': 'cha',
3897 'co': 'cos',
3898 'cr': 'cre',
3899 'cs': 'ces',
3900 'cu': 'chu',
3901 'cv': 'chv',
3902 'cy': 'cym',
3903 'da': 'dan',
3904 'de': 'deu',
3905 'dv': 'div',
3906 'dz': 'dzo',
3907 'ee': 'ewe',
3908 'el': 'ell',
3909 'en': 'eng',
3910 'eo': 'epo',
3911 'es': 'spa',
3912 'et': 'est',
3913 'eu': 'eus',
3914 'fa': 'fas',
3915 'ff': 'ful',
3916 'fi': 'fin',
3917 'fj': 'fij',
3918 'fo': 'fao',
3919 'fr': 'fra',
3920 'fy': 'fry',
3921 'ga': 'gle',
3922 'gd': 'gla',
3923 'gl': 'glg',
3924 'gn': 'grn',
3925 'gu': 'guj',
3926 'gv': 'glv',
3927 'ha': 'hau',
3928 'he': 'heb',
b7acc835 3929 'iw': 'heb', # Replaced by he in 1989 revision
39672624
YCH
3930 'hi': 'hin',
3931 'ho': 'hmo',
3932 'hr': 'hrv',
3933 'ht': 'hat',
3934 'hu': 'hun',
3935 'hy': 'hye',
3936 'hz': 'her',
3937 'ia': 'ina',
3938 'id': 'ind',
b7acc835 3939 'in': 'ind', # Replaced by id in 1989 revision
39672624
YCH
3940 'ie': 'ile',
3941 'ig': 'ibo',
3942 'ii': 'iii',
3943 'ik': 'ipk',
3944 'io': 'ido',
3945 'is': 'isl',
3946 'it': 'ita',
3947 'iu': 'iku',
3948 'ja': 'jpn',
3949 'jv': 'jav',
3950 'ka': 'kat',
3951 'kg': 'kon',
3952 'ki': 'kik',
3953 'kj': 'kua',
3954 'kk': 'kaz',
3955 'kl': 'kal',
3956 'km': 'khm',
3957 'kn': 'kan',
3958 'ko': 'kor',
3959 'kr': 'kau',
3960 'ks': 'kas',
3961 'ku': 'kur',
3962 'kv': 'kom',
3963 'kw': 'cor',
3964 'ky': 'kir',
3965 'la': 'lat',
3966 'lb': 'ltz',
3967 'lg': 'lug',
3968 'li': 'lim',
3969 'ln': 'lin',
3970 'lo': 'lao',
3971 'lt': 'lit',
3972 'lu': 'lub',
3973 'lv': 'lav',
3974 'mg': 'mlg',
3975 'mh': 'mah',
3976 'mi': 'mri',
3977 'mk': 'mkd',
3978 'ml': 'mal',
3979 'mn': 'mon',
3980 'mr': 'mar',
3981 'ms': 'msa',
3982 'mt': 'mlt',
3983 'my': 'mya',
3984 'na': 'nau',
3985 'nb': 'nob',
3986 'nd': 'nde',
3987 'ne': 'nep',
3988 'ng': 'ndo',
3989 'nl': 'nld',
3990 'nn': 'nno',
3991 'no': 'nor',
3992 'nr': 'nbl',
3993 'nv': 'nav',
3994 'ny': 'nya',
3995 'oc': 'oci',
3996 'oj': 'oji',
3997 'om': 'orm',
3998 'or': 'ori',
3999 'os': 'oss',
4000 'pa': 'pan',
4001 'pi': 'pli',
4002 'pl': 'pol',
4003 'ps': 'pus',
4004 'pt': 'por',
4005 'qu': 'que',
4006 'rm': 'roh',
4007 'rn': 'run',
4008 'ro': 'ron',
4009 'ru': 'rus',
4010 'rw': 'kin',
4011 'sa': 'san',
4012 'sc': 'srd',
4013 'sd': 'snd',
4014 'se': 'sme',
4015 'sg': 'sag',
4016 'si': 'sin',
4017 'sk': 'slk',
4018 'sl': 'slv',
4019 'sm': 'smo',
4020 'sn': 'sna',
4021 'so': 'som',
4022 'sq': 'sqi',
4023 'sr': 'srp',
4024 'ss': 'ssw',
4025 'st': 'sot',
4026 'su': 'sun',
4027 'sv': 'swe',
4028 'sw': 'swa',
4029 'ta': 'tam',
4030 'te': 'tel',
4031 'tg': 'tgk',
4032 'th': 'tha',
4033 'ti': 'tir',
4034 'tk': 'tuk',
4035 'tl': 'tgl',
4036 'tn': 'tsn',
4037 'to': 'ton',
4038 'tr': 'tur',
4039 'ts': 'tso',
4040 'tt': 'tat',
4041 'tw': 'twi',
4042 'ty': 'tah',
4043 'ug': 'uig',
4044 'uk': 'ukr',
4045 'ur': 'urd',
4046 'uz': 'uzb',
4047 've': 'ven',
4048 'vi': 'vie',
4049 'vo': 'vol',
4050 'wa': 'wln',
4051 'wo': 'wol',
4052 'xh': 'xho',
4053 'yi': 'yid',
e9a50fba 4054 'ji': 'yid', # Replaced by yi in 1989 revision
39672624
YCH
4055 'yo': 'yor',
4056 'za': 'zha',
4057 'zh': 'zho',
4058 'zu': 'zul',
4059 }
4060
4061 @classmethod
4062 def short2long(cls, code):
4063 """Convert language code from ISO 639-1 to ISO 639-2/T"""
4064 return cls._lang_map.get(code[:2])
4065
4066 @classmethod
4067 def long2short(cls, code):
4068 """Convert language code from ISO 639-2/T to ISO 639-1"""
4069 for short_name, long_name in cls._lang_map.items():
4070 if long_name == code:
4071 return short_name
4072
4073
4eb10f66
YCH
4074class ISO3166Utils(object):
4075 # From http://data.okfn.org/data/core/country-list
4076 _country_map = {
4077 'AF': 'Afghanistan',
4078 'AX': 'Åland Islands',
4079 'AL': 'Albania',
4080 'DZ': 'Algeria',
4081 'AS': 'American Samoa',
4082 'AD': 'Andorra',
4083 'AO': 'Angola',
4084 'AI': 'Anguilla',
4085 'AQ': 'Antarctica',
4086 'AG': 'Antigua and Barbuda',
4087 'AR': 'Argentina',
4088 'AM': 'Armenia',
4089 'AW': 'Aruba',
4090 'AU': 'Australia',
4091 'AT': 'Austria',
4092 'AZ': 'Azerbaijan',
4093 'BS': 'Bahamas',
4094 'BH': 'Bahrain',
4095 'BD': 'Bangladesh',
4096 'BB': 'Barbados',
4097 'BY': 'Belarus',
4098 'BE': 'Belgium',
4099 'BZ': 'Belize',
4100 'BJ': 'Benin',
4101 'BM': 'Bermuda',
4102 'BT': 'Bhutan',
4103 'BO': 'Bolivia, Plurinational State of',
4104 'BQ': 'Bonaire, Sint Eustatius and Saba',
4105 'BA': 'Bosnia and Herzegovina',
4106 'BW': 'Botswana',
4107 'BV': 'Bouvet Island',
4108 'BR': 'Brazil',
4109 'IO': 'British Indian Ocean Territory',
4110 'BN': 'Brunei Darussalam',
4111 'BG': 'Bulgaria',
4112 'BF': 'Burkina Faso',
4113 'BI': 'Burundi',
4114 'KH': 'Cambodia',
4115 'CM': 'Cameroon',
4116 'CA': 'Canada',
4117 'CV': 'Cape Verde',
4118 'KY': 'Cayman Islands',
4119 'CF': 'Central African Republic',
4120 'TD': 'Chad',
4121 'CL': 'Chile',
4122 'CN': 'China',
4123 'CX': 'Christmas Island',
4124 'CC': 'Cocos (Keeling) Islands',
4125 'CO': 'Colombia',
4126 'KM': 'Comoros',
4127 'CG': 'Congo',
4128 'CD': 'Congo, the Democratic Republic of the',
4129 'CK': 'Cook Islands',
4130 'CR': 'Costa Rica',
4131 'CI': 'Côte d\'Ivoire',
4132 'HR': 'Croatia',
4133 'CU': 'Cuba',
4134 'CW': 'Curaçao',
4135 'CY': 'Cyprus',
4136 'CZ': 'Czech Republic',
4137 'DK': 'Denmark',
4138 'DJ': 'Djibouti',
4139 'DM': 'Dominica',
4140 'DO': 'Dominican Republic',
4141 'EC': 'Ecuador',
4142 'EG': 'Egypt',
4143 'SV': 'El Salvador',
4144 'GQ': 'Equatorial Guinea',
4145 'ER': 'Eritrea',
4146 'EE': 'Estonia',
4147 'ET': 'Ethiopia',
4148 'FK': 'Falkland Islands (Malvinas)',
4149 'FO': 'Faroe Islands',
4150 'FJ': 'Fiji',
4151 'FI': 'Finland',
4152 'FR': 'France',
4153 'GF': 'French Guiana',
4154 'PF': 'French Polynesia',
4155 'TF': 'French Southern Territories',
4156 'GA': 'Gabon',
4157 'GM': 'Gambia',
4158 'GE': 'Georgia',
4159 'DE': 'Germany',
4160 'GH': 'Ghana',
4161 'GI': 'Gibraltar',
4162 'GR': 'Greece',
4163 'GL': 'Greenland',
4164 'GD': 'Grenada',
4165 'GP': 'Guadeloupe',
4166 'GU': 'Guam',
4167 'GT': 'Guatemala',
4168 'GG': 'Guernsey',
4169 'GN': 'Guinea',
4170 'GW': 'Guinea-Bissau',
4171 'GY': 'Guyana',
4172 'HT': 'Haiti',
4173 'HM': 'Heard Island and McDonald Islands',
4174 'VA': 'Holy See (Vatican City State)',
4175 'HN': 'Honduras',
4176 'HK': 'Hong Kong',
4177 'HU': 'Hungary',
4178 'IS': 'Iceland',
4179 'IN': 'India',
4180 'ID': 'Indonesia',
4181 'IR': 'Iran, Islamic Republic of',
4182 'IQ': 'Iraq',
4183 'IE': 'Ireland',
4184 'IM': 'Isle of Man',
4185 'IL': 'Israel',
4186 'IT': 'Italy',
4187 'JM': 'Jamaica',
4188 'JP': 'Japan',
4189 'JE': 'Jersey',
4190 'JO': 'Jordan',
4191 'KZ': 'Kazakhstan',
4192 'KE': 'Kenya',
4193 'KI': 'Kiribati',
4194 'KP': 'Korea, Democratic People\'s Republic of',
4195 'KR': 'Korea, Republic of',
4196 'KW': 'Kuwait',
4197 'KG': 'Kyrgyzstan',
4198 'LA': 'Lao People\'s Democratic Republic',
4199 'LV': 'Latvia',
4200 'LB': 'Lebanon',
4201 'LS': 'Lesotho',
4202 'LR': 'Liberia',
4203 'LY': 'Libya',
4204 'LI': 'Liechtenstein',
4205 'LT': 'Lithuania',
4206 'LU': 'Luxembourg',
4207 'MO': 'Macao',
4208 'MK': 'Macedonia, the Former Yugoslav Republic of',
4209 'MG': 'Madagascar',
4210 'MW': 'Malawi',
4211 'MY': 'Malaysia',
4212 'MV': 'Maldives',
4213 'ML': 'Mali',
4214 'MT': 'Malta',
4215 'MH': 'Marshall Islands',
4216 'MQ': 'Martinique',
4217 'MR': 'Mauritania',
4218 'MU': 'Mauritius',
4219 'YT': 'Mayotte',
4220 'MX': 'Mexico',
4221 'FM': 'Micronesia, Federated States of',
4222 'MD': 'Moldova, Republic of',
4223 'MC': 'Monaco',
4224 'MN': 'Mongolia',
4225 'ME': 'Montenegro',
4226 'MS': 'Montserrat',
4227 'MA': 'Morocco',
4228 'MZ': 'Mozambique',
4229 'MM': 'Myanmar',
4230 'NA': 'Namibia',
4231 'NR': 'Nauru',
4232 'NP': 'Nepal',
4233 'NL': 'Netherlands',
4234 'NC': 'New Caledonia',
4235 'NZ': 'New Zealand',
4236 'NI': 'Nicaragua',
4237 'NE': 'Niger',
4238 'NG': 'Nigeria',
4239 'NU': 'Niue',
4240 'NF': 'Norfolk Island',
4241 'MP': 'Northern Mariana Islands',
4242 'NO': 'Norway',
4243 'OM': 'Oman',
4244 'PK': 'Pakistan',
4245 'PW': 'Palau',
4246 'PS': 'Palestine, State of',
4247 'PA': 'Panama',
4248 'PG': 'Papua New Guinea',
4249 'PY': 'Paraguay',
4250 'PE': 'Peru',
4251 'PH': 'Philippines',
4252 'PN': 'Pitcairn',
4253 'PL': 'Poland',
4254 'PT': 'Portugal',
4255 'PR': 'Puerto Rico',
4256 'QA': 'Qatar',
4257 'RE': 'Réunion',
4258 'RO': 'Romania',
4259 'RU': 'Russian Federation',
4260 'RW': 'Rwanda',
4261 'BL': 'Saint Barthélemy',
4262 'SH': 'Saint Helena, Ascension and Tristan da Cunha',
4263 'KN': 'Saint Kitts and Nevis',
4264 'LC': 'Saint Lucia',
4265 'MF': 'Saint Martin (French part)',
4266 'PM': 'Saint Pierre and Miquelon',
4267 'VC': 'Saint Vincent and the Grenadines',
4268 'WS': 'Samoa',
4269 'SM': 'San Marino',
4270 'ST': 'Sao Tome and Principe',
4271 'SA': 'Saudi Arabia',
4272 'SN': 'Senegal',
4273 'RS': 'Serbia',
4274 'SC': 'Seychelles',
4275 'SL': 'Sierra Leone',
4276 'SG': 'Singapore',
4277 'SX': 'Sint Maarten (Dutch part)',
4278 'SK': 'Slovakia',
4279 'SI': 'Slovenia',
4280 'SB': 'Solomon Islands',
4281 'SO': 'Somalia',
4282 'ZA': 'South Africa',
4283 'GS': 'South Georgia and the South Sandwich Islands',
4284 'SS': 'South Sudan',
4285 'ES': 'Spain',
4286 'LK': 'Sri Lanka',
4287 'SD': 'Sudan',
4288 'SR': 'Suriname',
4289 'SJ': 'Svalbard and Jan Mayen',
4290 'SZ': 'Swaziland',
4291 'SE': 'Sweden',
4292 'CH': 'Switzerland',
4293 'SY': 'Syrian Arab Republic',
4294 'TW': 'Taiwan, Province of China',
4295 'TJ': 'Tajikistan',
4296 'TZ': 'Tanzania, United Republic of',
4297 'TH': 'Thailand',
4298 'TL': 'Timor-Leste',
4299 'TG': 'Togo',
4300 'TK': 'Tokelau',
4301 'TO': 'Tonga',
4302 'TT': 'Trinidad and Tobago',
4303 'TN': 'Tunisia',
4304 'TR': 'Turkey',
4305 'TM': 'Turkmenistan',
4306 'TC': 'Turks and Caicos Islands',
4307 'TV': 'Tuvalu',
4308 'UG': 'Uganda',
4309 'UA': 'Ukraine',
4310 'AE': 'United Arab Emirates',
4311 'GB': 'United Kingdom',
4312 'US': 'United States',
4313 'UM': 'United States Minor Outlying Islands',
4314 'UY': 'Uruguay',
4315 'UZ': 'Uzbekistan',
4316 'VU': 'Vanuatu',
4317 'VE': 'Venezuela, Bolivarian Republic of',
4318 'VN': 'Viet Nam',
4319 'VG': 'Virgin Islands, British',
4320 'VI': 'Virgin Islands, U.S.',
4321 'WF': 'Wallis and Futuna',
4322 'EH': 'Western Sahara',
4323 'YE': 'Yemen',
4324 'ZM': 'Zambia',
4325 'ZW': 'Zimbabwe',
4326 }
4327
4328 @classmethod
4329 def short2full(cls, code):
4330 """Convert an ISO 3166-2 country code to the corresponding full name"""
4331 return cls._country_map.get(code.upper())
4332
4333
773f291d
S
4334class GeoUtils(object):
4335 # Major IPv4 address blocks per country
4336 _country_ip_map = {
53896ca5 4337 'AD': '46.172.224.0/19',
773f291d
S
4338 'AE': '94.200.0.0/13',
4339 'AF': '149.54.0.0/17',
4340 'AG': '209.59.64.0/18',
4341 'AI': '204.14.248.0/21',
4342 'AL': '46.99.0.0/16',
4343 'AM': '46.70.0.0/15',
4344 'AO': '105.168.0.0/13',
53896ca5
S
4345 'AP': '182.50.184.0/21',
4346 'AQ': '23.154.160.0/24',
773f291d
S
4347 'AR': '181.0.0.0/12',
4348 'AS': '202.70.112.0/20',
53896ca5 4349 'AT': '77.116.0.0/14',
773f291d
S
4350 'AU': '1.128.0.0/11',
4351 'AW': '181.41.0.0/18',
53896ca5
S
4352 'AX': '185.217.4.0/22',
4353 'AZ': '5.197.0.0/16',
773f291d
S
4354 'BA': '31.176.128.0/17',
4355 'BB': '65.48.128.0/17',
4356 'BD': '114.130.0.0/16',
4357 'BE': '57.0.0.0/8',
53896ca5 4358 'BF': '102.178.0.0/15',
773f291d
S
4359 'BG': '95.42.0.0/15',
4360 'BH': '37.131.0.0/17',
4361 'BI': '154.117.192.0/18',
4362 'BJ': '137.255.0.0/16',
53896ca5 4363 'BL': '185.212.72.0/23',
773f291d
S
4364 'BM': '196.12.64.0/18',
4365 'BN': '156.31.0.0/16',
4366 'BO': '161.56.0.0/16',
4367 'BQ': '161.0.80.0/20',
53896ca5 4368 'BR': '191.128.0.0/12',
773f291d
S
4369 'BS': '24.51.64.0/18',
4370 'BT': '119.2.96.0/19',
4371 'BW': '168.167.0.0/16',
4372 'BY': '178.120.0.0/13',
4373 'BZ': '179.42.192.0/18',
4374 'CA': '99.224.0.0/11',
4375 'CD': '41.243.0.0/16',
53896ca5
S
4376 'CF': '197.242.176.0/21',
4377 'CG': '160.113.0.0/16',
773f291d 4378 'CH': '85.0.0.0/13',
53896ca5 4379 'CI': '102.136.0.0/14',
773f291d
S
4380 'CK': '202.65.32.0/19',
4381 'CL': '152.172.0.0/14',
53896ca5 4382 'CM': '102.244.0.0/14',
773f291d
S
4383 'CN': '36.128.0.0/10',
4384 'CO': '181.240.0.0/12',
4385 'CR': '201.192.0.0/12',
4386 'CU': '152.206.0.0/15',
4387 'CV': '165.90.96.0/19',
4388 'CW': '190.88.128.0/17',
53896ca5 4389 'CY': '31.153.0.0/16',
773f291d
S
4390 'CZ': '88.100.0.0/14',
4391 'DE': '53.0.0.0/8',
4392 'DJ': '197.241.0.0/17',
4393 'DK': '87.48.0.0/12',
4394 'DM': '192.243.48.0/20',
4395 'DO': '152.166.0.0/15',
4396 'DZ': '41.96.0.0/12',
4397 'EC': '186.68.0.0/15',
4398 'EE': '90.190.0.0/15',
4399 'EG': '156.160.0.0/11',
4400 'ER': '196.200.96.0/20',
4401 'ES': '88.0.0.0/11',
4402 'ET': '196.188.0.0/14',
4403 'EU': '2.16.0.0/13',
4404 'FI': '91.152.0.0/13',
4405 'FJ': '144.120.0.0/16',
53896ca5 4406 'FK': '80.73.208.0/21',
773f291d
S
4407 'FM': '119.252.112.0/20',
4408 'FO': '88.85.32.0/19',
4409 'FR': '90.0.0.0/9',
4410 'GA': '41.158.0.0/15',
4411 'GB': '25.0.0.0/8',
4412 'GD': '74.122.88.0/21',
4413 'GE': '31.146.0.0/16',
4414 'GF': '161.22.64.0/18',
4415 'GG': '62.68.160.0/19',
53896ca5
S
4416 'GH': '154.160.0.0/12',
4417 'GI': '95.164.0.0/16',
773f291d
S
4418 'GL': '88.83.0.0/19',
4419 'GM': '160.182.0.0/15',
4420 'GN': '197.149.192.0/18',
4421 'GP': '104.250.0.0/19',
4422 'GQ': '105.235.224.0/20',
4423 'GR': '94.64.0.0/13',
4424 'GT': '168.234.0.0/16',
4425 'GU': '168.123.0.0/16',
4426 'GW': '197.214.80.0/20',
4427 'GY': '181.41.64.0/18',
4428 'HK': '113.252.0.0/14',
4429 'HN': '181.210.0.0/16',
4430 'HR': '93.136.0.0/13',
4431 'HT': '148.102.128.0/17',
4432 'HU': '84.0.0.0/14',
4433 'ID': '39.192.0.0/10',
4434 'IE': '87.32.0.0/12',
4435 'IL': '79.176.0.0/13',
4436 'IM': '5.62.80.0/20',
4437 'IN': '117.192.0.0/10',
4438 'IO': '203.83.48.0/21',
4439 'IQ': '37.236.0.0/14',
4440 'IR': '2.176.0.0/12',
4441 'IS': '82.221.0.0/16',
4442 'IT': '79.0.0.0/10',
4443 'JE': '87.244.64.0/18',
4444 'JM': '72.27.0.0/17',
4445 'JO': '176.29.0.0/16',
53896ca5 4446 'JP': '133.0.0.0/8',
773f291d
S
4447 'KE': '105.48.0.0/12',
4448 'KG': '158.181.128.0/17',
4449 'KH': '36.37.128.0/17',
4450 'KI': '103.25.140.0/22',
4451 'KM': '197.255.224.0/20',
53896ca5 4452 'KN': '198.167.192.0/19',
773f291d
S
4453 'KP': '175.45.176.0/22',
4454 'KR': '175.192.0.0/10',
4455 'KW': '37.36.0.0/14',
4456 'KY': '64.96.0.0/15',
4457 'KZ': '2.72.0.0/13',
4458 'LA': '115.84.64.0/18',
4459 'LB': '178.135.0.0/16',
53896ca5 4460 'LC': '24.92.144.0/20',
773f291d
S
4461 'LI': '82.117.0.0/19',
4462 'LK': '112.134.0.0/15',
53896ca5 4463 'LR': '102.183.0.0/16',
773f291d
S
4464 'LS': '129.232.0.0/17',
4465 'LT': '78.56.0.0/13',
4466 'LU': '188.42.0.0/16',
4467 'LV': '46.109.0.0/16',
4468 'LY': '41.252.0.0/14',
4469 'MA': '105.128.0.0/11',
4470 'MC': '88.209.64.0/18',
4471 'MD': '37.246.0.0/16',
4472 'ME': '178.175.0.0/17',
4473 'MF': '74.112.232.0/21',
4474 'MG': '154.126.0.0/17',
4475 'MH': '117.103.88.0/21',
4476 'MK': '77.28.0.0/15',
4477 'ML': '154.118.128.0/18',
4478 'MM': '37.111.0.0/17',
4479 'MN': '49.0.128.0/17',
4480 'MO': '60.246.0.0/16',
4481 'MP': '202.88.64.0/20',
4482 'MQ': '109.203.224.0/19',
4483 'MR': '41.188.64.0/18',
4484 'MS': '208.90.112.0/22',
4485 'MT': '46.11.0.0/16',
4486 'MU': '105.16.0.0/12',
4487 'MV': '27.114.128.0/18',
53896ca5 4488 'MW': '102.70.0.0/15',
773f291d
S
4489 'MX': '187.192.0.0/11',
4490 'MY': '175.136.0.0/13',
4491 'MZ': '197.218.0.0/15',
4492 'NA': '41.182.0.0/16',
4493 'NC': '101.101.0.0/18',
4494 'NE': '197.214.0.0/18',
4495 'NF': '203.17.240.0/22',
4496 'NG': '105.112.0.0/12',
4497 'NI': '186.76.0.0/15',
4498 'NL': '145.96.0.0/11',
4499 'NO': '84.208.0.0/13',
4500 'NP': '36.252.0.0/15',
4501 'NR': '203.98.224.0/19',
4502 'NU': '49.156.48.0/22',
4503 'NZ': '49.224.0.0/14',
4504 'OM': '5.36.0.0/15',
4505 'PA': '186.72.0.0/15',
4506 'PE': '186.160.0.0/14',
4507 'PF': '123.50.64.0/18',
4508 'PG': '124.240.192.0/19',
4509 'PH': '49.144.0.0/13',
4510 'PK': '39.32.0.0/11',
4511 'PL': '83.0.0.0/11',
4512 'PM': '70.36.0.0/20',
4513 'PR': '66.50.0.0/16',
4514 'PS': '188.161.0.0/16',
4515 'PT': '85.240.0.0/13',
4516 'PW': '202.124.224.0/20',
4517 'PY': '181.120.0.0/14',
4518 'QA': '37.210.0.0/15',
53896ca5 4519 'RE': '102.35.0.0/16',
773f291d 4520 'RO': '79.112.0.0/13',
53896ca5 4521 'RS': '93.86.0.0/15',
773f291d 4522 'RU': '5.136.0.0/13',
53896ca5 4523 'RW': '41.186.0.0/16',
773f291d
S
4524 'SA': '188.48.0.0/13',
4525 'SB': '202.1.160.0/19',
4526 'SC': '154.192.0.0/11',
53896ca5 4527 'SD': '102.120.0.0/13',
773f291d 4528 'SE': '78.64.0.0/12',
53896ca5 4529 'SG': '8.128.0.0/10',
773f291d
S
4530 'SI': '188.196.0.0/14',
4531 'SK': '78.98.0.0/15',
53896ca5 4532 'SL': '102.143.0.0/17',
773f291d
S
4533 'SM': '89.186.32.0/19',
4534 'SN': '41.82.0.0/15',
53896ca5 4535 'SO': '154.115.192.0/18',
773f291d
S
4536 'SR': '186.179.128.0/17',
4537 'SS': '105.235.208.0/21',
4538 'ST': '197.159.160.0/19',
4539 'SV': '168.243.0.0/16',
4540 'SX': '190.102.0.0/20',
4541 'SY': '5.0.0.0/16',
4542 'SZ': '41.84.224.0/19',
4543 'TC': '65.255.48.0/20',
4544 'TD': '154.68.128.0/19',
4545 'TG': '196.168.0.0/14',
4546 'TH': '171.96.0.0/13',
4547 'TJ': '85.9.128.0/18',
4548 'TK': '27.96.24.0/21',
4549 'TL': '180.189.160.0/20',
4550 'TM': '95.85.96.0/19',
4551 'TN': '197.0.0.0/11',
4552 'TO': '175.176.144.0/21',
4553 'TR': '78.160.0.0/11',
4554 'TT': '186.44.0.0/15',
4555 'TV': '202.2.96.0/19',
4556 'TW': '120.96.0.0/11',
4557 'TZ': '156.156.0.0/14',
53896ca5
S
4558 'UA': '37.52.0.0/14',
4559 'UG': '102.80.0.0/13',
4560 'US': '6.0.0.0/8',
773f291d 4561 'UY': '167.56.0.0/13',
53896ca5 4562 'UZ': '84.54.64.0/18',
773f291d 4563 'VA': '212.77.0.0/19',
53896ca5 4564 'VC': '207.191.240.0/21',
773f291d 4565 'VE': '186.88.0.0/13',
53896ca5 4566 'VG': '66.81.192.0/20',
773f291d
S
4567 'VI': '146.226.0.0/16',
4568 'VN': '14.160.0.0/11',
4569 'VU': '202.80.32.0/20',
4570 'WF': '117.20.32.0/21',
4571 'WS': '202.4.32.0/19',
4572 'YE': '134.35.0.0/16',
4573 'YT': '41.242.116.0/22',
4574 'ZA': '41.0.0.0/11',
53896ca5
S
4575 'ZM': '102.144.0.0/13',
4576 'ZW': '102.177.192.0/18',
773f291d
S
4577 }
4578
4579 @classmethod
5f95927a
S
4580 def random_ipv4(cls, code_or_block):
4581 if len(code_or_block) == 2:
4582 block = cls._country_ip_map.get(code_or_block.upper())
4583 if not block:
4584 return None
4585 else:
4586 block = code_or_block
773f291d
S
4587 addr, preflen = block.split('/')
4588 addr_min = compat_struct_unpack('!L', socket.inet_aton(addr))[0]
4589 addr_max = addr_min | (0xffffffff >> int(preflen))
18a0defa 4590 return compat_str(socket.inet_ntoa(
4248dad9 4591 compat_struct_pack('!L', random.randint(addr_min, addr_max))))
773f291d
S
4592
4593
91410c9b 4594class PerRequestProxyHandler(compat_urllib_request.ProxyHandler):
2461f79d
PH
4595 def __init__(self, proxies=None):
4596 # Set default handlers
4597 for type in ('http', 'https'):
4598 setattr(self, '%s_open' % type,
4599 lambda r, proxy='__noproxy__', type=type, meth=self.proxy_open:
4600 meth(r, proxy, type))
38e87f6c 4601 compat_urllib_request.ProxyHandler.__init__(self, proxies)
2461f79d 4602
91410c9b 4603 def proxy_open(self, req, proxy, type):
2461f79d 4604 req_proxy = req.headers.get('Ytdl-request-proxy')
91410c9b
PH
4605 if req_proxy is not None:
4606 proxy = req_proxy
2461f79d
PH
4607 del req.headers['Ytdl-request-proxy']
4608
4609 if proxy == '__noproxy__':
4610 return None # No Proxy
51fb4995 4611 if compat_urlparse.urlparse(proxy).scheme.lower() in ('socks', 'socks4', 'socks4a', 'socks5'):
71aff188 4612 req.add_header('Ytdl-socks-proxy', proxy)
7a5c1cfe 4613 # yt-dlp's http/https handlers do wrapping the socket with socks
71aff188 4614 return None
91410c9b
PH
4615 return compat_urllib_request.ProxyHandler.proxy_open(
4616 self, req, proxy, type)
5bc880b9
YCH
4617
4618
0a5445dd
YCH
4619# Both long_to_bytes and bytes_to_long are adapted from PyCrypto, which is
4620# released into Public Domain
4621# https://github.com/dlitz/pycrypto/blob/master/lib/Crypto/Util/number.py#L387
4622
4623def long_to_bytes(n, blocksize=0):
4624 """long_to_bytes(n:long, blocksize:int) : string
4625 Convert a long integer to a byte string.
4626
4627 If optional blocksize is given and greater than zero, pad the front of the
4628 byte string with binary zeros so that the length is a multiple of
4629 blocksize.
4630 """
4631 # after much testing, this algorithm was deemed to be the fastest
4632 s = b''
4633 n = int(n)
4634 while n > 0:
4635 s = compat_struct_pack('>I', n & 0xffffffff) + s
4636 n = n >> 32
4637 # strip off leading zeros
4638 for i in range(len(s)):
4639 if s[i] != b'\000'[0]:
4640 break
4641 else:
4642 # only happens when n == 0
4643 s = b'\000'
4644 i = 0
4645 s = s[i:]
4646 # add back some pad bytes. this could be done more efficiently w.r.t. the
4647 # de-padding being done above, but sigh...
4648 if blocksize > 0 and len(s) % blocksize:
4649 s = (blocksize - len(s) % blocksize) * b'\000' + s
4650 return s
4651
4652
4653def bytes_to_long(s):
4654 """bytes_to_long(string) : long
4655 Convert a byte string to a long integer.
4656
4657 This is (essentially) the inverse of long_to_bytes().
4658 """
4659 acc = 0
4660 length = len(s)
4661 if length % 4:
4662 extra = (4 - length % 4)
4663 s = b'\000' * extra + s
4664 length = length + extra
4665 for i in range(0, length, 4):
4666 acc = (acc << 32) + compat_struct_unpack('>I', s[i:i + 4])[0]
4667 return acc
4668
4669
5bc880b9
YCH
4670def ohdave_rsa_encrypt(data, exponent, modulus):
4671 '''
4672 Implement OHDave's RSA algorithm. See http://www.ohdave.com/rsa/
4673
4674 Input:
4675 data: data to encrypt, bytes-like object
4676 exponent, modulus: parameter e and N of RSA algorithm, both integer
4677 Output: hex string of encrypted data
4678
4679 Limitation: supports one block encryption only
4680 '''
4681
4682 payload = int(binascii.hexlify(data[::-1]), 16)
4683 encrypted = pow(payload, exponent, modulus)
4684 return '%x' % encrypted
81bdc8fd
YCH
4685
4686
f48409c7
YCH
4687def pkcs1pad(data, length):
4688 """
4689 Padding input data with PKCS#1 scheme
4690
4691 @param {int[]} data input data
4692 @param {int} length target length
4693 @returns {int[]} padded data
4694 """
4695 if len(data) > length - 11:
4696 raise ValueError('Input data too long for PKCS#1 padding')
4697
4698 pseudo_random = [random.randint(0, 254) for _ in range(length - len(data) - 3)]
4699 return [0, 2] + pseudo_random + [0] + data
4700
4701
5eb6bdce 4702def encode_base_n(num, n, table=None):
59f898b7 4703 FULL_TABLE = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
59f898b7
YCH
4704 if not table:
4705 table = FULL_TABLE[:n]
4706
5eb6bdce
YCH
4707 if n > len(table):
4708 raise ValueError('base %d exceeds table length %d' % (n, len(table)))
4709
4710 if num == 0:
4711 return table[0]
4712
81bdc8fd
YCH
4713 ret = ''
4714 while num:
4715 ret = table[num % n] + ret
4716 num = num // n
4717 return ret
f52354a8
YCH
4718
4719
4720def decode_packed_codes(code):
06b3fe29 4721 mobj = re.search(PACKED_CODES_RE, code)
a0566bbf 4722 obfuscated_code, base, count, symbols = mobj.groups()
f52354a8
YCH
4723 base = int(base)
4724 count = int(count)
4725 symbols = symbols.split('|')
4726 symbol_table = {}
4727
4728 while count:
4729 count -= 1
5eb6bdce 4730 base_n_count = encode_base_n(count, base)
f52354a8
YCH
4731 symbol_table[base_n_count] = symbols[count] or base_n_count
4732
4733 return re.sub(
4734 r'\b(\w+)\b', lambda mobj: symbol_table[mobj.group(0)],
a0566bbf 4735 obfuscated_code)
e154c651 4736
4737
1ced2221
S
4738def caesar(s, alphabet, shift):
4739 if shift == 0:
4740 return s
4741 l = len(alphabet)
4742 return ''.join(
4743 alphabet[(alphabet.index(c) + shift) % l] if c in alphabet else c
4744 for c in s)
4745
4746
4747def rot47(s):
4748 return caesar(s, r'''!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~''', 47)
4749
4750
e154c651 4751def parse_m3u8_attributes(attrib):
4752 info = {}
4753 for (key, val) in re.findall(r'(?P<key>[A-Z0-9-]+)=(?P<val>"[^"]+"|[^",]+)(?:,|$)', attrib):
4754 if val.startswith('"'):
4755 val = val[1:-1]
4756 info[key] = val
4757 return info
1143535d
YCH
4758
4759
4760def urshift(val, n):
4761 return val >> n if val >= 0 else (val + 0x100000000) >> n
d3f8e038
YCH
4762
4763
4764# Based on png2str() written by @gdkchan and improved by @yokrysty
067aa17e 4765# Originally posted at https://github.com/ytdl-org/youtube-dl/issues/9706
d3f8e038
YCH
4766def decode_png(png_data):
4767 # Reference: https://www.w3.org/TR/PNG/
4768 header = png_data[8:]
4769
4770 if png_data[:8] != b'\x89PNG\x0d\x0a\x1a\x0a' or header[4:8] != b'IHDR':
4771 raise IOError('Not a valid PNG file.')
4772
4773 int_map = {1: '>B', 2: '>H', 4: '>I'}
4774 unpack_integer = lambda x: compat_struct_unpack(int_map[len(x)], x)[0]
4775
4776 chunks = []
4777
4778 while header:
4779 length = unpack_integer(header[:4])
4780 header = header[4:]
4781
4782 chunk_type = header[:4]
4783 header = header[4:]
4784
4785 chunk_data = header[:length]
4786 header = header[length:]
4787
4788 header = header[4:] # Skip CRC
4789
4790 chunks.append({
4791 'type': chunk_type,
4792 'length': length,
4793 'data': chunk_data
4794 })
4795
4796 ihdr = chunks[0]['data']
4797
4798 width = unpack_integer(ihdr[:4])
4799 height = unpack_integer(ihdr[4:8])
4800
4801 idat = b''
4802
4803 for chunk in chunks:
4804 if chunk['type'] == b'IDAT':
4805 idat += chunk['data']
4806
4807 if not idat:
4808 raise IOError('Unable to read PNG data.')
4809
4810 decompressed_data = bytearray(zlib.decompress(idat))
4811
4812 stride = width * 3
4813 pixels = []
4814
4815 def _get_pixel(idx):
4816 x = idx % stride
4817 y = idx // stride
4818 return pixels[y][x]
4819
4820 for y in range(height):
4821 basePos = y * (1 + stride)
4822 filter_type = decompressed_data[basePos]
4823
4824 current_row = []
4825
4826 pixels.append(current_row)
4827
4828 for x in range(stride):
4829 color = decompressed_data[1 + basePos + x]
4830 basex = y * stride + x
4831 left = 0
4832 up = 0
4833
4834 if x > 2:
4835 left = _get_pixel(basex - 3)
4836 if y > 0:
4837 up = _get_pixel(basex - stride)
4838
4839 if filter_type == 1: # Sub
4840 color = (color + left) & 0xff
4841 elif filter_type == 2: # Up
4842 color = (color + up) & 0xff
4843 elif filter_type == 3: # Average
4844 color = (color + ((left + up) >> 1)) & 0xff
4845 elif filter_type == 4: # Paeth
4846 a = left
4847 b = up
4848 c = 0
4849
4850 if x > 2 and y > 0:
4851 c = _get_pixel(basex - stride - 3)
4852
4853 p = a + b - c
4854
4855 pa = abs(p - a)
4856 pb = abs(p - b)
4857 pc = abs(p - c)
4858
4859 if pa <= pb and pa <= pc:
4860 color = (color + a) & 0xff
4861 elif pb <= pc:
4862 color = (color + b) & 0xff
4863 else:
4864 color = (color + c) & 0xff
4865
4866 current_row.append(color)
4867
4868 return width, height, pixels
efa97bdc
YCH
4869
4870
4871def write_xattr(path, key, value):
4872 # This mess below finds the best xattr tool for the job
4873 try:
4874 # try the pyxattr module...
4875 import xattr
4876
53a7e3d2
YCH
4877 if hasattr(xattr, 'set'): # pyxattr
4878 # Unicode arguments are not supported in python-pyxattr until
4879 # version 0.5.0
067aa17e 4880 # See https://github.com/ytdl-org/youtube-dl/issues/5498
53a7e3d2
YCH
4881 pyxattr_required_version = '0.5.0'
4882 if version_tuple(xattr.__version__) < version_tuple(pyxattr_required_version):
4883 # TODO: fallback to CLI tools
4884 raise XAttrUnavailableError(
4885 'python-pyxattr is detected but is too old. '
7a5c1cfe 4886 'yt-dlp requires %s or above while your version is %s. '
53a7e3d2
YCH
4887 'Falling back to other xattr implementations' % (
4888 pyxattr_required_version, xattr.__version__))
4889
4890 setxattr = xattr.set
4891 else: # xattr
4892 setxattr = xattr.setxattr
efa97bdc
YCH
4893
4894 try:
53a7e3d2 4895 setxattr(path, key, value)
efa97bdc
YCH
4896 except EnvironmentError as e:
4897 raise XAttrMetadataError(e.errno, e.strerror)
4898
4899 except ImportError:
4900 if compat_os_name == 'nt':
4901 # Write xattrs to NTFS Alternate Data Streams:
4902 # http://en.wikipedia.org/wiki/NTFS#Alternate_data_streams_.28ADS.29
4903 assert ':' not in key
4904 assert os.path.exists(path)
4905
4906 ads_fn = path + ':' + key
4907 try:
4908 with open(ads_fn, 'wb') as f:
4909 f.write(value)
4910 except EnvironmentError as e:
4911 raise XAttrMetadataError(e.errno, e.strerror)
4912 else:
4913 user_has_setfattr = check_executable('setfattr', ['--version'])
4914 user_has_xattr = check_executable('xattr', ['-h'])
4915
4916 if user_has_setfattr or user_has_xattr:
4917
4918 value = value.decode('utf-8')
4919 if user_has_setfattr:
4920 executable = 'setfattr'
4921 opts = ['-n', key, '-v', value]
4922 elif user_has_xattr:
4923 executable = 'xattr'
4924 opts = ['-w', key, value]
4925
3089bc74
S
4926 cmd = ([encodeFilename(executable, True)]
4927 + [encodeArgument(o) for o in opts]
4928 + [encodeFilename(path, True)])
efa97bdc
YCH
4929
4930 try:
d3c93ec2 4931 p = Popen(
efa97bdc
YCH
4932 cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
4933 except EnvironmentError as e:
4934 raise XAttrMetadataError(e.errno, e.strerror)
d3c93ec2 4935 stdout, stderr = p.communicate_or_kill()
efa97bdc
YCH
4936 stderr = stderr.decode('utf-8', 'replace')
4937 if p.returncode != 0:
4938 raise XAttrMetadataError(p.returncode, stderr)
4939
4940 else:
4941 # On Unix, and can't find pyxattr, setfattr, or xattr.
4942 if sys.platform.startswith('linux'):
4943 raise XAttrUnavailableError(
4944 "Couldn't find a tool to set the xattrs. "
4945 "Install either the python 'pyxattr' or 'xattr' "
4946 "modules, or the GNU 'attr' package "
4947 "(which contains the 'setfattr' tool).")
4948 else:
4949 raise XAttrUnavailableError(
4950 "Couldn't find a tool to set the xattrs. "
4951 "Install either the python 'xattr' module, "
4952 "or the 'xattr' binary.")
0c265486
YCH
4953
4954
4955def random_birthday(year_field, month_field, day_field):
aa374bc7
AS
4956 start_date = datetime.date(1950, 1, 1)
4957 end_date = datetime.date(1995, 12, 31)
4958 offset = random.randint(0, (end_date - start_date).days)
4959 random_date = start_date + datetime.timedelta(offset)
0c265486 4960 return {
aa374bc7
AS
4961 year_field: str(random_date.year),
4962 month_field: str(random_date.month),
4963 day_field: str(random_date.day),
0c265486 4964 }
732044af 4965
c76eb41b 4966
732044af 4967# Templates for internet shortcut files, which are plain text files.
4968DOT_URL_LINK_TEMPLATE = '''
4969[InternetShortcut]
4970URL=%(url)s
4971'''.lstrip()
4972
4973DOT_WEBLOC_LINK_TEMPLATE = '''
4974<?xml version="1.0" encoding="UTF-8"?>
4975<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
4976<plist version="1.0">
4977<dict>
4978\t<key>URL</key>
4979\t<string>%(url)s</string>
4980</dict>
4981</plist>
4982'''.lstrip()
4983
4984DOT_DESKTOP_LINK_TEMPLATE = '''
4985[Desktop Entry]
4986Encoding=UTF-8
4987Name=%(filename)s
4988Type=Link
4989URL=%(url)s
4990Icon=text-html
4991'''.lstrip()
4992
08438d2c 4993LINK_TEMPLATES = {
4994 'url': DOT_URL_LINK_TEMPLATE,
4995 'desktop': DOT_DESKTOP_LINK_TEMPLATE,
4996 'webloc': DOT_WEBLOC_LINK_TEMPLATE,
4997}
4998
732044af 4999
5000def iri_to_uri(iri):
5001 """
5002 Converts an IRI (Internationalized Resource Identifier, allowing Unicode characters) to a URI (Uniform Resource Identifier, ASCII-only).
5003
5004 The function doesn't add an additional layer of escaping; e.g., it doesn't escape `%3C` as `%253C`. Instead, it percent-escapes characters with an underlying UTF-8 encoding *besides* those already escaped, leaving the URI intact.
5005 """
5006
5007 iri_parts = compat_urllib_parse_urlparse(iri)
5008
5009 if '[' in iri_parts.netloc:
5010 raise ValueError('IPv6 URIs are not, yet, supported.')
5011 # Querying `.netloc`, when there's only one bracket, also raises a ValueError.
5012
5013 # The `safe` argument values, that the following code uses, contain the characters that should not be percent-encoded. Everything else but letters, digits and '_.-' will be percent-encoded with an underlying UTF-8 encoding. Everything already percent-encoded will be left as is.
5014
5015 net_location = ''
5016 if iri_parts.username:
5017 net_location += compat_urllib_parse_quote(iri_parts.username, safe=r"!$%&'()*+,~")
5018 if iri_parts.password is not None:
5019 net_location += ':' + compat_urllib_parse_quote(iri_parts.password, safe=r"!$%&'()*+,~")
5020 net_location += '@'
5021
5022 net_location += iri_parts.hostname.encode('idna').decode('utf-8') # Punycode for Unicode hostnames.
5023 # The 'idna' encoding produces ASCII text.
5024 if iri_parts.port is not None and iri_parts.port != 80:
5025 net_location += ':' + str(iri_parts.port)
5026
5027 return compat_urllib_parse_urlunparse(
5028 (iri_parts.scheme,
5029 net_location,
5030
5031 compat_urllib_parse_quote_plus(iri_parts.path, safe=r"!$%&'()*+,/:;=@|~"),
5032
5033 # Unsure about the `safe` argument, since this is a legacy way of handling parameters.
5034 compat_urllib_parse_quote_plus(iri_parts.params, safe=r"!$%&'()*+,/:;=@|~"),
5035
5036 # Not totally sure about the `safe` argument, since the source does not explicitly mention the query URI component.
5037 compat_urllib_parse_quote_plus(iri_parts.query, safe=r"!$%&'()*+,/:;=?@{|}~"),
5038
5039 compat_urllib_parse_quote_plus(iri_parts.fragment, safe=r"!#$%&'()*+,/:;=?@{|}~")))
5040
5041 # Source for `safe` arguments: https://url.spec.whatwg.org/#percent-encoded-bytes.
5042
5043
5044def to_high_limit_path(path):
5045 if sys.platform in ['win32', 'cygwin']:
5046 # Work around MAX_PATH limitation on Windows. The maximum allowed length for the individual path segments may still be quite limited.
5047 return r'\\?\ '.rstrip() + os.path.abspath(path)
5048
5049 return path
76d321f6 5050
c76eb41b 5051
b868936c 5052def format_field(obj, field=None, template='%s', ignore=(None, ''), default='', func=None):
e0ddbd02 5053 val = traverse_obj(obj, *variadic(field))
5054 if val in ignore:
5055 return default
5056 return template % (func(val) if func else val)
00dd0cd5 5057
5058
5059def clean_podcast_url(url):
5060 return re.sub(r'''(?x)
5061 (?:
5062 (?:
5063 chtbl\.com/track|
5064 media\.blubrry\.com| # https://create.blubrry.com/resources/podcast-media-download-statistics/getting-started/
5065 play\.podtrac\.com
5066 )/[^/]+|
5067 (?:dts|www)\.podtrac\.com/(?:pts/)?redirect\.[0-9a-z]{3,4}| # http://analytics.podtrac.com/how-to-measure
5068 flex\.acast\.com|
5069 pd(?:
5070 cn\.co| # https://podcorn.com/analytics-prefix/
5071 st\.fm # https://podsights.com/docs/
5072 )/e
5073 )/''', '', url)
ffcb8191
THD
5074
5075
5076_HEX_TABLE = '0123456789abcdef'
5077
5078
5079def random_uuidv4():
5080 return re.sub(r'[xy]', lambda x: _HEX_TABLE[random.randint(0, 15)], 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx')
0202b52a 5081
5082
5083def make_dir(path, to_screen=None):
5084 try:
5085 dn = os.path.dirname(path)
5086 if dn and not os.path.exists(dn):
5087 os.makedirs(dn)
5088 return True
5089 except (OSError, IOError) as err:
5090 if callable(to_screen) is not None:
5091 to_screen('unable to create directory ' + error_to_compat_str(err))
5092 return False
f74980cb 5093
5094
5095def get_executable_path():
c552ae88 5096 from zipimport import zipimporter
5097 if hasattr(sys, 'frozen'): # Running from PyInstaller
5098 path = os.path.dirname(sys.executable)
5099 elif isinstance(globals().get('__loader__'), zipimporter): # Running from ZIP
5100 path = os.path.join(os.path.dirname(__file__), '../..')
5101 else:
5102 path = os.path.join(os.path.dirname(__file__), '..')
f74980cb 5103 return os.path.abspath(path)
5104
5105
2f567473 5106def load_plugins(name, suffix, namespace):
3ae5e797 5107 classes = {}
f74980cb 5108 try:
019a94f7
ÁS
5109 plugins_spec = importlib.util.spec_from_file_location(
5110 name, os.path.join(get_executable_path(), 'ytdlp_plugins', name, '__init__.py'))
5111 plugins = importlib.util.module_from_spec(plugins_spec)
5112 sys.modules[plugins_spec.name] = plugins
5113 plugins_spec.loader.exec_module(plugins)
f74980cb 5114 for name in dir(plugins):
2f567473 5115 if name in namespace:
5116 continue
5117 if not name.endswith(suffix):
f74980cb 5118 continue
5119 klass = getattr(plugins, name)
3ae5e797 5120 classes[name] = namespace[name] = klass
019a94f7 5121 except FileNotFoundError:
f74980cb 5122 pass
f74980cb 5123 return classes
06167fbb 5124
5125
325ebc17 5126def traverse_obj(
352d63fd 5127 obj, *path_list, default=None, expected_type=None, get_all=True,
325ebc17 5128 casesense=True, is_user_input=False, traverse_string=False):
324ad820 5129 ''' Traverse nested list/dict/tuple
8f334380 5130 @param path_list A list of paths which are checked one by one.
5131 Each path is a list of keys where each key is a string,
1797b073 5132 a function, a tuple of strings/None or "...".
2614f646 5133 When a fuction is given, it takes the key as argument and
5134 returns whether the key matches or not. When a tuple is given,
8f334380 5135 all the keys given in the tuple are traversed, and
5136 "..." traverses all the keys in the object
1797b073 5137 "None" returns the object without traversal
325ebc17 5138 @param default Default value to return
352d63fd 5139 @param expected_type Only accept final value of this type (Can also be any callable)
5140 @param get_all Return all the values obtained from a path or only the first one
324ad820 5141 @param casesense Whether to consider dictionary keys as case sensitive
5142 @param is_user_input Whether the keys are generated from user input. If True,
5143 strings are converted to int/slice if necessary
5144 @param traverse_string Whether to traverse inside strings. If True, any
5145 non-compatible object will also be converted into a string
8f334380 5146 # TODO: Write tests
324ad820 5147 '''
325ebc17 5148 if not casesense:
dbf5416a 5149 _lower = lambda k: (k.lower() if isinstance(k, str) else k)
8f334380 5150 path_list = (map(_lower, variadic(path)) for path in path_list)
5151
5152 def _traverse_obj(obj, path, _current_depth=0):
5153 nonlocal depth
5154 path = tuple(variadic(path))
5155 for i, key in enumerate(path):
1797b073 5156 if None in (key, obj):
5157 return obj
8f334380 5158 if isinstance(key, (list, tuple)):
5159 obj = [_traverse_obj(obj, sub_key, _current_depth) for sub_key in key]
5160 key = ...
5161 if key is ...:
5162 obj = (obj.values() if isinstance(obj, dict)
5163 else obj if isinstance(obj, (list, tuple, LazyList))
5164 else str(obj) if traverse_string else [])
5165 _current_depth += 1
5166 depth = max(depth, _current_depth)
5167 return [_traverse_obj(inner_obj, path[i + 1:], _current_depth) for inner_obj in obj]
2614f646 5168 elif callable(key):
5169 if isinstance(obj, (list, tuple, LazyList)):
5170 obj = enumerate(obj)
5171 elif isinstance(obj, dict):
5172 obj = obj.items()
5173 else:
5174 if not traverse_string:
5175 return None
5176 obj = str(obj)
5177 _current_depth += 1
5178 depth = max(depth, _current_depth)
5179 return [_traverse_obj(v, path[i + 1:], _current_depth) for k, v in obj if key(k)]
575e17a1 5180 elif isinstance(obj, dict) and not (is_user_input and key == ':'):
325ebc17 5181 obj = (obj.get(key) if casesense or (key in obj)
5182 else next((v for k, v in obj.items() if _lower(k) == key), None))
5183 else:
5184 if is_user_input:
5185 key = (int_or_none(key) if ':' not in key
5186 else slice(*map(int_or_none, key.split(':'))))
8f334380 5187 if key == slice(None):
575e17a1 5188 return _traverse_obj(obj, (..., *path[i + 1:]), _current_depth)
325ebc17 5189 if not isinstance(key, (int, slice)):
9fea350f 5190 return None
8f334380 5191 if not isinstance(obj, (list, tuple, LazyList)):
325ebc17 5192 if not traverse_string:
5193 return None
5194 obj = str(obj)
5195 try:
5196 obj = obj[key]
5197 except IndexError:
324ad820 5198 return None
325ebc17 5199 return obj
5200
352d63fd 5201 if isinstance(expected_type, type):
5202 type_test = lambda val: val if isinstance(val, expected_type) else None
5203 elif expected_type is not None:
5204 type_test = expected_type
5205 else:
5206 type_test = lambda val: val
5207
8f334380 5208 for path in path_list:
5209 depth = 0
5210 val = _traverse_obj(obj, path)
325ebc17 5211 if val is not None:
8f334380 5212 if depth:
5213 for _ in range(depth - 1):
6586bca9 5214 val = itertools.chain.from_iterable(v for v in val if v is not None)
352d63fd 5215 val = [v for v in map(type_test, val) if v is not None]
8f334380 5216 if val:
352d63fd 5217 return val if get_all else val[0]
5218 else:
5219 val = type_test(val)
5220 if val is not None:
8f334380 5221 return val
325ebc17 5222 return default
324ad820 5223
5224
5225def traverse_dict(dictn, keys, casesense=True):
ee8dd27a 5226 write_string('DeprecationWarning: yt_dlp.utils.traverse_dict is deprecated '
5227 'and may be removed in a future version. Use yt_dlp.utils.traverse_obj instead')
5228 return traverse_obj(dictn, keys, casesense=casesense, is_user_input=True, traverse_string=True)
6606817a 5229
5230
ff91cf74 5231def get_first(obj, keys, **kwargs):
5232 return traverse_obj(obj, (..., *variadic(keys)), **kwargs, get_all=False)
5233
5234
4b4b7f74 5235def variadic(x, allowed_types=(str, bytes, dict)):
cb89cfc1 5236 return x if isinstance(x, collections.abc.Iterable) and not isinstance(x, allowed_types) else (x,)
bd50a52b
THD
5237
5238
3e9b66d7
LNO
5239def decode_base(value, digits):
5240 # This will convert given base-x string to scalar (long or int)
5241 table = {char: index for index, char in enumerate(digits)}
5242 result = 0
5243 base = len(digits)
5244 for chr in value:
5245 result *= base
5246 result += table[chr]
5247 return result
5248
5249
5250def time_seconds(**kwargs):
5251 t = datetime.datetime.now(datetime.timezone(datetime.timedelta(**kwargs)))
5252 return t.timestamp()
5253
5254
49fa4d9a
N
5255# create a JSON Web Signature (jws) with HS256 algorithm
5256# the resulting format is in JWS Compact Serialization
5257# implemented following JWT https://www.rfc-editor.org/rfc/rfc7519.html
5258# implemented following JWS https://www.rfc-editor.org/rfc/rfc7515.html
5259def jwt_encode_hs256(payload_data, key, headers={}):
5260 header_data = {
5261 'alg': 'HS256',
5262 'typ': 'JWT',
5263 }
5264 if headers:
5265 header_data.update(headers)
5266 header_b64 = base64.b64encode(json.dumps(header_data).encode('utf-8'))
5267 payload_b64 = base64.b64encode(json.dumps(payload_data).encode('utf-8'))
5268 h = hmac.new(key.encode('utf-8'), header_b64 + b'.' + payload_b64, hashlib.sha256)
5269 signature_b64 = base64.b64encode(h.digest())
5270 token = header_b64 + b'.' + payload_b64 + b'.' + signature_b64
5271 return token
819e0531 5272
5273
16b0d7e6 5274# can be extended in future to verify the signature and parse header and return the algorithm used if it's not HS256
5275def jwt_decode_hs256(jwt):
5276 header_b64, payload_b64, signature_b64 = jwt.split('.')
5277 payload_data = json.loads(base64.urlsafe_b64decode(payload_b64))
5278 return payload_data
5279
5280
819e0531 5281def supports_terminal_sequences(stream):
5282 if compat_os_name == 'nt':
e3c7d495 5283 from .compat import WINDOWS_VT_MODE # Must be imported locally
5284 if not WINDOWS_VT_MODE or get_windows_version() < (10, 0, 10586):
819e0531 5285 return False
5286 elif not os.getenv('TERM'):
5287 return False
5288 try:
5289 return stream.isatty()
5290 except BaseException:
5291 return False
5292
5293
ec11a9f4 5294_terminal_sequences_re = re.compile('\033\\[[^m]+m')
5295
5296
5297def remove_terminal_sequences(string):
5298 return _terminal_sequences_re.sub('', string)
5299
5300
5301def number_of_digits(number):
5302 return len('%d' % number)
34921b43 5303
5304
5305def join_nonempty(*values, delim='-', from_dict=None):
5306 if from_dict is not None:
c586f9e8 5307 values = map(from_dict.get, values)
34921b43 5308 return delim.join(map(str, filter(None, values)))
06e57990 5309
5310
27231526
ZM
5311def scale_thumbnails_to_max_format_width(formats, thumbnails, url_width_re):
5312 """
5313 Find the largest format dimensions in terms of video width and, for each thumbnail:
5314 * Modify the URL: Match the width with the provided regex and replace with the former width
5315 * Update dimensions
5316
5317 This function is useful with video services that scale the provided thumbnails on demand
5318 """
5319 _keys = ('width', 'height')
5320 max_dimensions = max(
5321 [tuple(format.get(k) or 0 for k in _keys) for format in formats],
5322 default=(0, 0))
5323 if not max_dimensions[0]:
5324 return thumbnails
5325 return [
5326 merge_dicts(
5327 {'url': re.sub(url_width_re, str(max_dimensions[0]), thumbnail['url'])},
5328 dict(zip(_keys, max_dimensions)), thumbnail)
5329 for thumbnail in thumbnails
5330 ]
5331
5332
93c8410d
LNO
5333def parse_http_range(range):
5334 """ Parse value of "Range" or "Content-Range" HTTP header into tuple. """
5335 if not range:
5336 return None, None, None
5337 crg = re.search(r'bytes[ =](\d+)-(\d+)?(?:/(\d+))?', range)
5338 if not crg:
5339 return None, None, None
5340 return int(crg.group(1)), int_or_none(crg.group(2)), int_or_none(crg.group(3))
5341
5342
06e57990 5343class Config:
5344 own_args = None
5345 filename = None
5346 __initialized = False
5347
5348 def __init__(self, parser, label=None):
5349 self._parser, self.label = parser, label
5350 self._loaded_paths, self.configs = set(), []
5351
5352 def init(self, args=None, filename=None):
5353 assert not self.__initialized
65662dff 5354 directory = ''
06e57990 5355 if filename:
5356 location = os.path.realpath(filename)
65662dff 5357 directory = os.path.dirname(location)
06e57990 5358 if location in self._loaded_paths:
5359 return False
5360 self._loaded_paths.add(location)
5361
5362 self.__initialized = True
5363 self.own_args, self.filename = args, filename
5364 for location in self._parser.parse_args(args)[0].config_locations or []:
65662dff 5365 location = os.path.join(directory, expand_path(location))
06e57990 5366 if os.path.isdir(location):
5367 location = os.path.join(location, 'yt-dlp.conf')
5368 if not os.path.exists(location):
5369 self._parser.error(f'config location {location} does not exist')
5370 self.append_config(self.read_file(location), location)
5371 return True
5372
5373 def __str__(self):
5374 label = join_nonempty(
5375 self.label, 'config', f'"{self.filename}"' if self.filename else '',
5376 delim=' ')
5377 return join_nonempty(
5378 self.own_args is not None and f'{label[0].upper()}{label[1:]}: {self.hide_login_info(self.own_args)}',
5379 *(f'\n{c}'.replace('\n', '\n| ')[1:] for c in self.configs),
5380 delim='\n')
5381
5382 @staticmethod
5383 def read_file(filename, default=[]):
5384 try:
5385 optionf = open(filename)
5386 except IOError:
5387 return default # silently skip if file is not present
5388 try:
5389 # FIXME: https://github.com/ytdl-org/youtube-dl/commit/dfe5fa49aed02cf36ba9f743b11b0903554b5e56
5390 contents = optionf.read()
5391 if sys.version_info < (3,):
5392 contents = contents.decode(preferredencoding())
5393 res = compat_shlex_split(contents, comments=True)
5394 finally:
5395 optionf.close()
5396 return res
5397
5398 @staticmethod
5399 def hide_login_info(opts):
5400 PRIVATE_OPTS = set(['-p', '--password', '-u', '--username', '--video-password', '--ap-password', '--ap-username'])
5401 eqre = re.compile('^(?P<key>' + ('|'.join(re.escape(po) for po in PRIVATE_OPTS)) + ')=.+$')
5402
5403 def _scrub_eq(o):
5404 m = eqre.match(o)
5405 if m:
5406 return m.group('key') + '=PRIVATE'
5407 else:
5408 return o
5409
5410 opts = list(map(_scrub_eq, opts))
5411 for idx, opt in enumerate(opts):
5412 if opt in PRIVATE_OPTS and idx + 1 < len(opts):
5413 opts[idx + 1] = 'PRIVATE'
5414 return opts
5415
5416 def append_config(self, *args, label=None):
5417 config = type(self)(self._parser, label)
5418 config._loaded_paths = self._loaded_paths
5419 if config.init(*args):
5420 self.configs.append(config)
5421
5422 @property
5423 def all_args(self):
5424 for config in reversed(self.configs):
5425 yield from config.all_args
5426 yield from self.own_args or []
5427
5428 def parse_args(self):
5429 return self._parser.parse_args(list(self.all_args))
da42679b
LNO
5430
5431
5432class WebSocketsWrapper():
5433 """Wraps websockets module to use in non-async scopes"""
5434
5435 def __init__(self, url, headers=None):
5436 self.loop = asyncio.events.new_event_loop()
5437 self.conn = compat_websockets.connect(
5438 url, extra_headers=headers, ping_interval=None,
5439 close_timeout=float('inf'), loop=self.loop, ping_timeout=float('inf'))
15dfb392 5440 atexit.register(self.__exit__, None, None, None)
da42679b
LNO
5441
5442 def __enter__(self):
5443 self.pool = self.run_with_loop(self.conn.__aenter__(), self.loop)
5444 return self
5445
5446 def send(self, *args):
5447 self.run_with_loop(self.pool.send(*args), self.loop)
5448
5449 def recv(self, *args):
5450 return self.run_with_loop(self.pool.recv(*args), self.loop)
5451
5452 def __exit__(self, type, value, traceback):
5453 try:
5454 return self.run_with_loop(self.conn.__aexit__(type, value, traceback), self.loop)
5455 finally:
5456 self.loop.close()
15dfb392 5457 self._cancel_all_tasks(self.loop)
da42679b
LNO
5458
5459 # taken from https://github.com/python/cpython/blob/3.9/Lib/asyncio/runners.py with modifications
5460 # for contributors: If there's any new library using asyncio needs to be run in non-async, move these function out of this class
5461 @staticmethod
5462 def run_with_loop(main, loop):
5463 if not asyncio.coroutines.iscoroutine(main):
5464 raise ValueError(f'a coroutine was expected, got {main!r}')
5465
5466 try:
5467 return loop.run_until_complete(main)
5468 finally:
5469 loop.run_until_complete(loop.shutdown_asyncgens())
5470 if hasattr(loop, 'shutdown_default_executor'):
5471 loop.run_until_complete(loop.shutdown_default_executor())
5472
5473 @staticmethod
5474 def _cancel_all_tasks(loop):
5475 to_cancel = asyncio.tasks.all_tasks(loop)
5476
5477 if not to_cancel:
5478 return
5479
5480 for task in to_cancel:
5481 task.cancel()
5482
5483 loop.run_until_complete(
5484 asyncio.tasks.gather(*to_cancel, loop=loop, return_exceptions=True))
5485
5486 for task in to_cancel:
5487 if task.cancelled():
5488 continue
5489 if task.exception() is not None:
5490 loop.call_exception_handler({
5491 'message': 'unhandled exception during asyncio.run() shutdown',
5492 'exception': task.exception(),
5493 'task': task,
5494 })
5495
5496
5497has_websockets = bool(compat_websockets)
8b7539d2 5498
5499
5500def merge_headers(*dicts):
08d30158 5501 """Merge dicts of http headers case insensitively, prioritizing the latter ones"""
76aa9913 5502 return {k.title(): v for k, v in itertools.chain.from_iterable(map(dict.items, dicts))}