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