4 from __future__
import unicode_literals
39 import xml
.etree
.ElementTree
44 compat_HTMLParseError
,
50 compat_ctypes_WINFUNCTYPE
,
51 compat_etree_fromstring
,
54 compat_html_entities_html5
,
68 compat_urllib_parse_urlencode
,
69 compat_urllib_parse_urlparse
,
70 compat_urllib_parse_urlunparse
,
71 compat_urllib_parse_quote
,
72 compat_urllib_parse_quote_plus
,
73 compat_urllib_parse_unquote_plus
,
74 compat_urllib_request
,
85 def register_socks_protocols():
86 # "Register" SOCKS protocols
87 # In Python < 2.6.5, urlsplit() suffers from bug https://bugs.python.org/issue7904
88 # URLs with protocols not in urlparse.uses_netloc are not handled correctly
89 for scheme
in ('socks', 'socks4', 'socks4a', 'socks5'):
90 if scheme
not in compat_urlparse
.uses_netloc
:
91 compat_urlparse
.uses_netloc
.append(scheme
)
94 # This is not clearly defined otherwise
95 compiled_regex_type
= type(re
.compile(''))
98 def random_user_agent():
99 _USER_AGENT_TPL
= 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Safari/537.36'
1678 return _USER_AGENT_TPL
% random
.choice(_CHROME_VERSIONS
)
1682 'User-Agent': random_user_agent(),
1683 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
1684 'Accept-Encoding': 'gzip, deflate',
1685 'Accept-Language': 'en-us,en;q=0.5',
1690 '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',
1694 NO_DEFAULT
= object()
1696 ENGLISH_MONTH_NAMES
= [
1697 'January', 'February', 'March', 'April', 'May', 'June',
1698 'July', 'August', 'September', 'October', 'November', 'December']
1701 'en': ENGLISH_MONTH_NAMES
,
1703 'janvier', 'février', 'mars', 'avril', 'mai', 'juin',
1704 'juillet', 'août', 'septembre', 'octobre', 'novembre', 'décembre'],
1707 KNOWN_EXTENSIONS
= (
1708 'mp4', 'm4a', 'm4p', 'm4b', 'm4r', 'm4v', 'aac',
1709 'flv', 'f4v', 'f4a', 'f4b',
1710 'webm', 'ogg', 'ogv', 'oga', 'ogx', 'spx', 'opus',
1711 'mkv', 'mka', 'mk3d',
1714 'asf', 'wmv', 'wma',
1720 'f4f', 'f4m', 'm3u8', 'smil')
1722 # needed for sanitizing filenames in restricted mode
1723 ACCENT_CHARS
= dict(zip('ÂÃÄÀÁÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖŐØŒÙÚÛÜŰÝÞßàáâãäåæçèéêëìíîïðñòóôõöőøœùúûüűýþÿ',
1724 itertools
.chain('AAAAAA', ['AE'], 'CEEEEIIIIDNOOOOOOO', ['OE'], 'UUUUUY', ['TH', 'ss'],
1725 'aaaaaa', ['ae'], 'ceeeeiiiionooooooo', ['oe'], 'uuuuuy', ['th'], 'y')))
1749 '%Y/%m/%d %H:%M:%S',
1754 '%Y-%m-%d %H:%M:%S',
1755 '%Y-%m-%d %H:%M:%S.%f',
1756 '%Y-%m-%d %H:%M:%S:%f',
1759 '%Y-%m-%dT%H:%M:%SZ',
1760 '%Y-%m-%dT%H:%M:%S.%fZ',
1761 '%Y-%m-%dT%H:%M:%S.%f0Z',
1762 '%Y-%m-%dT%H:%M:%S',
1763 '%Y-%m-%dT%H:%M:%S.%f',
1765 '%b %d %Y at %H:%M',
1766 '%b %d %Y at %H:%M:%S',
1767 '%B %d %Y at %H:%M',
1768 '%B %d %Y at %H:%M:%S',
1772 DATE_FORMATS_DAY_FIRST
= list(DATE_FORMATS
)
1773 DATE_FORMATS_DAY_FIRST
.extend([
1779 '%d/%m/%Y %H:%M:%S',
1782 DATE_FORMATS_MONTH_FIRST
= list(DATE_FORMATS
)
1783 DATE_FORMATS_MONTH_FIRST
.extend([
1788 '%m/%d/%Y %H:%M:%S',
1791 PACKED_CODES_RE
= r
"}\('(.+)',(\d+),(\d+),'([^']+)'\.split\('\|'\)"
1792 JSON_LD_RE
= r
'(?is)<script[^>]+type=(["\']?
)application
/ld\
+json\
1[^
>]*>(?P
<json_ld
>.+?
)</script
>'
1795 def preferredencoding():
1796 """Get preferred encoding.
1798 Returns the best encoding scheme for the system, based on
1799 locale.getpreferredencoding() and some further tweaks.
1802 pref = locale.getpreferredencoding()
1810 def write_json_file(obj, fn):
1811 """ Encode obj as JSON and write it to fn, atomically if possible """
1813 fn = encodeFilename(fn)
1814 if sys.version_info < (3, 0) and sys.platform != 'win32
':
1815 encoding = get_filesystem_encoding()
1816 # os.path.basename returns a bytes object, but NamedTemporaryFile
1817 # will fail if the filename contains non ascii characters unless we
1818 # use a unicode object
1819 path_basename = lambda f: os.path.basename(fn).decode(encoding)
1820 # the same for os.path.dirname
1821 path_dirname = lambda f: os.path.dirname(fn).decode(encoding)
1823 path_basename = os.path.basename
1824 path_dirname = os.path.dirname
1828 'prefix
': path_basename(fn) + '.',
1829 'dir': path_dirname(fn),
1833 # In Python 2.x, json.dump expects a bytestream.
1834 # In Python 3.x, it writes to a character stream
1835 if sys.version_info < (3, 0):
1840 'encoding
': 'utf
-8',
1843 tf = tempfile.NamedTemporaryFile(**compat_kwargs(args))
1847 json.dump(obj, tf, ensure_ascii=False)
1848 if sys.platform == 'win32
':
1849 # Need to remove existing file on Windows, else os.rename raises
1850 # WindowsError or FileExistsError.
1858 os.chmod(tf.name, 0o666 & ~mask)
1861 os.rename(tf.name, fn)
1870 if sys.version_info >= (2, 7):
1871 def find_xpath_attr(node, xpath, key, val=None):
1872 """ Find the xpath xpath[@key=val] """
1873 assert re.match(r'^
[a
-zA
-Z_
-]+$
', key)
1874 expr = xpath + ('[@%s]' % key if val is None else "[@%s='%s']" % (key, val))
1875 return node.find(expr)
1877 def find_xpath_attr(node, xpath, key, val=None):
1878 for f in node.findall(compat_xpath(xpath)):
1879 if key not in f.attrib:
1881 if val is None or f.attrib.get(key) == val:
1885 # On python2.6 the xml.etree.ElementTree.Element methods don't support
1886 # the namespace parameter
1889 def xpath_with_ns(path
, ns_map
):
1890 components
= [c
.split(':') for c
in path
.split('/')]
1892 for c
in components
:
1894 replaced
.append(c
[0])
1897 replaced
.append('{%s}%s' % (ns_map
[ns
], tag
))
1898 return '/'.join(replaced
)
1901 def xpath_element(node
, xpath
, name
=None, fatal
=False, default
=NO_DEFAULT
):
1902 def _find_xpath(xpath
):
1903 return node
.find(compat_xpath(xpath
))
1905 if isinstance(xpath
, (str, compat_str
)):
1906 n
= _find_xpath(xpath
)
1914 if default
is not NO_DEFAULT
:
1917 name
= xpath
if name
is None else name
1918 raise ExtractorError('Could not find XML element %s' % name
)
1924 def xpath_text(node
, xpath
, name
=None, fatal
=False, default
=NO_DEFAULT
):
1925 n
= xpath_element(node
, xpath
, name
, fatal
=fatal
, default
=default
)
1926 if n
is None or n
== default
:
1929 if default
is not NO_DEFAULT
:
1932 name
= xpath
if name
is None else name
1933 raise ExtractorError('Could not find XML element\'s text %s' % name
)
1939 def xpath_attr(node
, xpath
, key
, name
=None, fatal
=False, default
=NO_DEFAULT
):
1940 n
= find_xpath_attr(node
, xpath
, key
)
1942 if default
is not NO_DEFAULT
:
1945 name
= '%s[@%s]' % (xpath
, key
) if name
is None else name
1946 raise ExtractorError('Could not find XML attribute %s' % name
)
1949 return n
.attrib
[key
]
1952 def get_element_by_id(id, html
):
1953 """Return the content of the tag with the specified ID in the passed HTML document"""
1954 return get_element_by_attribute('id', id, html
)
1957 def get_element_html_by_id(id, html
):
1958 """Return the html of the tag with the specified ID in the passed HTML document"""
1959 return get_element_html_by_attribute('id', id, html
)
1962 def get_element_by_class(class_name
, html
):
1963 """Return the content of the first tag with the specified class in the passed HTML document"""
1964 retval
= get_elements_by_class(class_name
, html
)
1965 return retval
[0] if retval
else None
1968 def get_element_html_by_class(class_name
, html
):
1969 """Return the html of the first tag with the specified class in the passed HTML document"""
1970 retval
= get_elements_html_by_class(class_name
, html
)
1971 return retval
[0] if retval
else None
1974 def get_element_by_attribute(attribute
, value
, html
, escape_value
=True):
1975 retval
= get_elements_by_attribute(attribute
, value
, html
, escape_value
)
1976 return retval
[0] if retval
else None
1979 def get_element_html_by_attribute(attribute
, value
, html
, escape_value
=True):
1980 retval
= get_elements_html_by_attribute(attribute
, value
, html
, escape_value
)
1981 return retval
[0] if retval
else None
1984 def get_elements_by_class(class_name
, html
):
1985 """Return the content of all tags with the specified class in the passed HTML document as a list"""
1986 return get_elements_by_attribute(
1987 'class', r
'[^\'"]*\b%s\b[^\'"]*' % re.escape(class_name),
1988 html, escape_value=False)
1991 def get_elements_html_by_class(class_name, html):
1992 """Return the html of all tags with the specified class in the passed HTML document as a list"""
1993 return get_elements_html_by_attribute(
1994 'class', r'[^
\'"]*\b%s\b[^\'"]*' % re.escape(class_name),
1995 html, escape_value=False)
1998 def get_elements_by_attribute(*args, **kwargs):
1999 """Return the content of the tag with the specified attribute in the passed HTML document"""
2000 return [content for content, _ in get_elements_text_and_html_by_attribute(*args, **kwargs)]
2003 def get_elements_html_by_attribute(*args, **kwargs):
2004 """Return the html of the tag with the specified attribute in the passed HTML document"""
2005 return [whole for _, whole in get_elements_text_and_html_by_attribute(*args, **kwargs)]
2008 def get_elements_text_and_html_by_attribute(attribute, value, html, escape_value=True):
2010 Return the text (content) and the html (whole) of the tag with the specified
2011 attribute in the passed HTML document
2014 value_quote_optional = '' if re.match(r'''[\s"'`
=<>]''', value) else '?'
2016 value = re.escape(value) if escape_value else value
2018 partial_element_re = r'''(?x
)
2019 <(?P
<tag
>[a
-zA
-Z0
-9:._-]+)
2020 (?
:\
s(?
:[^
>"']|"[^
"]*"|
'[^']*')*)?
2021 \s%(attribute)s\s*=\s*(?P<_q>['"]%(vqo)s)(?-x:%(value)s)(?P=_q)
2022 ''' % {'attribute': re.escape(attribute), 'value': value, 'vqo': value_quote_optional}
2024 for m in re.finditer(partial_element_re, html):
2025 content, whole = get_element_text_and_html_by_tag(m.group('tag'), html[m.start():])
2028 unescapeHTML(re.sub(r'^(?P<q>["\'])(?P
<content
>.*)(?P
=q
)$
', r'\g
<content
>', content, flags=re.DOTALL)),
2033 class HTMLBreakOnClosingTagParser(compat_HTMLParser):
2035 HTML parser which raises HTMLBreakOnClosingTagException upon reaching the
2036 closing tag for the first opening tag it has encountered, and can be used
2037 as a context manager
2040 class HTMLBreakOnClosingTagException(Exception):
2044 self.tagstack = collections.deque()
2045 compat_HTMLParser.__init__(self)
2047 def __enter__(self):
2050 def __exit__(self, *_):
2054 # handle_endtag does not return upon raising HTMLBreakOnClosingTagException,
2055 # so data remains buffered; we no longer have any interest in it, thus
2056 # override this method to discard it
2059 def handle_starttag(self, tag, _):
2060 self.tagstack.append(tag)
2062 def handle_endtag(self, tag):
2063 if not self.tagstack:
2064 raise compat_HTMLParseError('no tags
in the stack
')
2065 while self.tagstack:
2066 inner_tag = self.tagstack.pop()
2067 if inner_tag == tag:
2070 raise compat_HTMLParseError(f'matching opening tag
for closing {tag} tag
not found
')
2071 if not self.tagstack:
2072 raise self.HTMLBreakOnClosingTagException()
2075 def get_element_text_and_html_by_tag(tag, html):
2077 For the first element with the specified tag in the passed HTML document
2078 return its' content (text
) and the whole
element (html
)
2080 def find_or_raise(haystack, needle, exc):
2082 return haystack.index(needle)
2085 closing_tag = f'</{tag}>'
2086 whole_start = find_or_raise(
2087 html, f'<{tag}', compat_HTMLParseError(f'opening {tag} tag not found'))
2088 content_start = find_or_raise(
2089 html[whole_start:], '>', compat_HTMLParseError(f'malformed opening {tag} tag'))
2090 content_start += whole_start + 1
2091 with HTMLBreakOnClosingTagParser() as parser:
2092 parser.feed(html[whole_start:content_start])
2093 if not parser.tagstack or parser.tagstack[0] != tag:
2094 raise compat_HTMLParseError(f'parser did not match opening {tag} tag')
2095 offset = content_start
2096 while offset < len(html):
2097 next_closing_tag_start = find_or_raise(
2098 html[offset:], closing_tag,
2099 compat_HTMLParseError(f'closing {tag} tag not found'))
2100 next_closing_tag_end = next_closing_tag_start + len(closing_tag)
2102 parser.feed(html[offset:offset + next_closing_tag_end])
2103 offset += next_closing_tag_end
2104 except HTMLBreakOnClosingTagParser.HTMLBreakOnClosingTagException:
2105 return html[content_start:offset + next_closing_tag_start], \
2106 html[whole_start:offset + next_closing_tag_end]
2107 raise compat_HTMLParseError('unexpected end of html')
2110 class HTMLAttributeParser(compat_HTMLParser):
2111 """Trivial HTML parser to gather the attributes
for a single element
"""
2115 compat_HTMLParser.__init__(self)
2117 def handle_starttag(self, tag, attrs):
2118 self.attrs = dict(attrs)
2121 class HTMLListAttrsParser(compat_HTMLParser):
2122 """HTML parser to gather the attributes
for the elements of a
list"""
2125 compat_HTMLParser.__init__(self)
2129 def handle_starttag(self, tag, attrs):
2130 if tag == 'li' and self._level == 0:
2131 self.items.append(dict(attrs))
2134 def handle_endtag(self, tag):
2138 def extract_attributes(html_element):
2139 """Given a string
for an HTML element such
as
2141 a
="foo" B
="bar" c
="&98;az" d
=boz
2142 empty
= noval entity
="&"
2145 Decode
and return a dictionary of attributes
.
2147 'a': 'foo', 'b': 'bar', c
: 'baz', d
: 'boz',
2148 'empty': '', 'noval': None, 'entity': '&',
2149 'sq': '"', 'dq': '\''
2151 NB HTMLParser
is stricter
in Python
2.6 & 3.2 than
in later versions
,
2152 but the cases
in the unit test will work
for all of
2.6, 2.7, 3.2-3.5.
2154 parser = HTMLAttributeParser()
2156 parser.feed(html_element)
2158 # Older Python may throw HTMLParseError in case of malformed HTML
2159 except compat_HTMLParseError:
2164 def parse_list(webpage):
2165 """Given a string
for an series of HTML
<li
> elements
,
2166 return a dictionary of their attributes
"""
2167 parser = HTMLListAttrsParser()
2168 parser.feed(webpage)
2173 def clean_html(html):
2174 """Clean an HTML snippet into a readable string
"""
2176 if html is None: # Convenience for sanitizing descriptions etc.
2180 html = html.replace('\n', ' ')
2181 html = re.sub(r'(?u)\s*<\s*br\s*/?\s*>\s*', '\n', html)
2182 html = re.sub(r'(?u)<\s*/\s*p\s*>\s*<\s*p[^>]*>', '\n', html)
2184 html = re.sub('<.*?>', '', html)
2185 # Replace html entities
2186 html = unescapeHTML(html)
2190 def sanitize_open(filename, open_mode):
2191 """Try to
open the given filename
, and slightly tweak it
if this fails
.
2193 Attempts to
open the given filename
. If this fails
, it tries to change
2194 the filename slightly
, step by step
, until it
's either able to open it
2195 or it fails and raises a final exception, like the standard open()
2198 It returns the tuple (stream, definitive_file_name).
2202 if sys.platform == 'win32
':
2204 msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
2205 return (sys.stdout.buffer if hasattr(sys.stdout, 'buffer') else sys.stdout, filename)
2206 stream = open(encodeFilename(filename), open_mode)
2207 return (stream, filename)
2208 except (IOError, OSError) as err:
2209 if err.errno in (errno.EACCES,):
2212 # In case of error, try to remove win32 forbidden chars
2213 alt_filename = sanitize_path(filename)
2214 if alt_filename == filename:
2217 # An exception here should be caught in the caller
2218 stream = open(encodeFilename(alt_filename), open_mode)
2219 return (stream, alt_filename)
2222 def timeconvert(timestr):
2223 """Convert RFC 2822 defined time string into system timestamp"""
2225 timetuple = email.utils.parsedate_tz(timestr)
2226 if timetuple is not None:
2227 timestamp = email.utils.mktime_tz(timetuple)
2231 def sanitize_filename(s, restricted=False, is_id=False):
2232 """Sanitizes a string so it could be used as part of a filename.
2233 If restricted is set, use a stricter subset of allowed characters.
2234 Set is_id if this is not an arbitrary string, but an ID that should be kept
2237 def replace_insane(char):
2238 if restricted and char in ACCENT_CHARS:
2239 return ACCENT_CHARS[char]
2240 elif not restricted and char == '\n':
2242 elif char == '?
' or ord(char) < 32 or ord(char) == 127:
2245 return '' if restricted else '\''
2247 return '_-' if restricted else ' -'
2248 elif char in '\\/|*<>':
2250 if restricted and (char in '!&\'()[]{}$;`^,#' or char.isspace()):
2252 if restricted and ord(char) > 127:
2259 s = re.sub(r'[0-9]+(?::[0-9]+)+', lambda m: m.group(0).replace(':', '_'), s)
2260 result = ''.join(map(replace_insane, s))
2262 while '__' in result:
2263 result = result.replace('__', '_')
2264 result = result.strip('_')
2265 # Common case of "Foreign band name
- English song title
"
2266 if restricted and result.startswith('-_'):
2268 if result.startswith('-'):
2269 result = '_' + result[len('-'):]
2270 result = result.lstrip('.')
2276 def sanitize_path(s, force=False):
2277 """Sanitizes and normalizes path on Windows"""
2278 if sys.platform == 'win32':
2280 drive_or_unc, _ = os.path.splitdrive(s)
2281 if sys.version_info < (2, 7) and not drive_or_unc:
2282 drive_or_unc, _ = os.path.splitunc(s)
2288 norm_path = os.path.normpath(remove_start(s, drive_or_unc)).split(os.path.sep)
2292 path_part if path_part in ['.', '..'] else re.sub(r'(?:[/<>:"\|
\\?\
*]|
[\s
.]$
)', '#', path_part)
2293 for path_part
in norm_path
]
2295 sanitized_path
.insert(0, drive_or_unc
+ os
.path
.sep
)
2296 elif force
and s
[0] == os
.path
.sep
:
2297 sanitized_path
.insert(0, os
.path
.sep
)
2298 return os
.path
.join(*sanitized_path
)
2301 def sanitize_url(url
):
2302 # Prepend protocol-less URLs with `http:` scheme in order to mitigate
2303 # the number of unwanted failures due to missing protocol
2304 if url
.startswith('//'):
2305 return 'http:%s' % url
2306 # Fix some common typos seen so far
2308 # https://github.com/ytdl-org/youtube-dl/issues/15649
2309 (r
'^httpss://', r
'https://'),
2310 # https://bx1.be/lives/direct-tv/
2311 (r
'^rmtp([es]?)://', r
'rtmp\1://'),
2313 for mistake
, fixup
in COMMON_TYPOS
:
2314 if re
.match(mistake
, url
):
2315 return re
.sub(mistake
, fixup
, url
)
2319 def extract_basic_auth(url
):
2320 parts
= compat_urlparse
.urlsplit(url
)
2321 if parts
.username
is None:
2323 url
= compat_urlparse
.urlunsplit(parts
._replace
(netloc
=(
2324 parts
.hostname
if parts
.port
is None
2325 else '%s:%d' % (parts
.hostname
, parts
.port
))))
2326 auth_payload
= base64
.b64encode(
2327 ('%s:%s' % (parts
.username
, parts
.password
or '')).encode('utf-8'))
2328 return url
, 'Basic ' + auth_payload
.decode('utf-8')
2331 def sanitized_Request(url
, *args
, **kwargs
):
2332 url
, auth_header
= extract_basic_auth(escape_url(sanitize_url(url
)))
2333 if auth_header
is not None:
2334 headers
= args
[1] if len(args
) >= 2 else kwargs
.setdefault('headers', {})
2335 headers
['Authorization'] = auth_header
2336 return compat_urllib_request
.Request(url
, *args
, **kwargs
)
2340 """Expand shell variables and ~"""
2341 return os
.path
.expandvars(compat_expanduser(s
))
2344 def orderedSet(iterable
):
2345 """ Remove all duplicates from the input iterable """
2353 def _htmlentity_transform(entity_with_semicolon
):
2354 """Transforms an HTML entity to a character."""
2355 entity
= entity_with_semicolon
[:-1]
2357 # Known non-numeric HTML entity
2358 if entity
in compat_html_entities
.name2codepoint
:
2359 return compat_chr(compat_html_entities
.name2codepoint
[entity
])
2361 # TODO: HTML5 allows entities without a semicolon. For example,
2362 # 'Éric' should be decoded as 'Éric'.
2363 if entity_with_semicolon
in compat_html_entities_html5
:
2364 return compat_html_entities_html5
[entity_with_semicolon
]
2366 mobj
= re
.match(r
'#(x[0-9a-fA-F]+|[0-9]+)', entity
)
2367 if mobj
is not None:
2368 numstr
= mobj
.group(1)
2369 if numstr
.startswith('x'):
2371 numstr
= '0%s' % numstr
2374 # See https://github.com/ytdl-org/youtube-dl/issues/7518
2376 return compat_chr(int(numstr
, base
))
2380 # Unknown entity in name, return its literal representation
2381 return '&%s;' % entity
2384 def unescapeHTML(s
):
2387 assert type(s
) == compat_str
2390 r
'&([^&;]+;)', lambda m
: _htmlentity_transform(m
.group(1)), s
)
2393 def escapeHTML(text
):
2396 .replace('&', '&')
2397 .replace('<', '<')
2398 .replace('>', '>')
2399 .replace('"', '"')
2400 .replace("'", ''')
2404 def process_communicate_or_kill(p
, *args
, **kwargs
):
2406 return p
.communicate(*args
, **kwargs
)
2407 except BaseException
: # Including KeyboardInterrupt
2413 class Popen(subprocess
.Popen
):
2414 if sys
.platform
== 'win32':
2415 _startupinfo
= subprocess
.STARTUPINFO()
2416 _startupinfo
.dwFlags |
= subprocess
.STARTF_USESHOWWINDOW
2420 def __init__(self
, *args
, **kwargs
):
2421 super(Popen
, self
).__init
__(*args
, **kwargs
, startupinfo
=self
._startupinfo
)
2423 def communicate_or_kill(self
, *args
, **kwargs
):
2424 return process_communicate_or_kill(self
, *args
, **kwargs
)
2427 def get_subprocess_encoding():
2428 if sys
.platform
== 'win32' and sys
.getwindowsversion()[0] >= 5:
2429 # For subprocess calls, encode with locale encoding
2430 # Refer to http://stackoverflow.com/a/9951851/35070
2431 encoding
= preferredencoding()
2433 encoding
= sys
.getfilesystemencoding()
2434 if encoding
is None:
2439 def encodeFilename(s
, for_subprocess
=False):
2441 @param s The name of the file
2444 assert type(s
) == compat_str
2446 # Python 3 has a Unicode API
2447 if sys
.version_info
>= (3, 0):
2450 # Pass '' directly to use Unicode APIs on Windows 2000 and up
2451 # (Detecting Windows NT 4 is tricky because 'major >= 4' would
2452 # match Windows 9x series as well. Besides, NT 4 is obsolete.)
2453 if not for_subprocess
and sys
.platform
== 'win32' and sys
.getwindowsversion()[0] >= 5:
2456 # Jython assumes filenames are Unicode strings though reported as Python 2.x compatible
2457 if sys
.platform
.startswith('java'):
2460 return s
.encode(get_subprocess_encoding(), 'ignore')
2463 def decodeFilename(b
, for_subprocess
=False):
2465 if sys
.version_info
>= (3, 0):
2468 if not isinstance(b
, bytes):
2471 return b
.decode(get_subprocess_encoding(), 'ignore')
2474 def encodeArgument(s
):
2475 if not isinstance(s
, compat_str
):
2476 # Legacy code that uses byte strings
2477 # Uncomment the following line after fixing all post processors
2478 # assert False, 'Internal error: %r should be of type %r, is %r' % (s, compat_str, type(s))
2479 s
= s
.decode('ascii')
2480 return encodeFilename(s
, True)
2483 def decodeArgument(b
):
2484 return decodeFilename(b
, True)
2487 def decodeOption(optval
):
2490 if isinstance(optval
, bytes):
2491 optval
= optval
.decode(preferredencoding())
2493 assert isinstance(optval
, compat_str
)
2497 _timetuple
= collections
.namedtuple('Time', ('hours', 'minutes', 'seconds', 'milliseconds'))
2500 def timetuple_from_msec(msec
):
2501 secs
, msec
= divmod(msec
, 1000)
2502 mins
, secs
= divmod(secs
, 60)
2503 hrs
, mins
= divmod(mins
, 60)
2504 return _timetuple(hrs
, mins
, secs
, msec
)
2507 def formatSeconds(secs
, delim
=':', msec
=False):
2508 time
= timetuple_from_msec(secs
* 1000)
2510 ret
= '%d%s%02d%s%02d' % (time
.hours
, delim
, time
.minutes
, delim
, time
.seconds
)
2512 ret
= '%d%s%02d' % (time
.minutes
, delim
, time
.seconds
)
2514 ret
= '%d' % time
.seconds
2515 return '%s.%03d' % (ret
, time
.milliseconds
) if msec
else ret
2518 def _ssl_load_windows_store_certs(ssl_context
, storename
):
2519 # Code adapted from _load_windows_store_certs in https://github.com/python/cpython/blob/main/Lib/ssl.py
2521 certs
= [cert
for cert
, encoding
, trust
in ssl
.enum_certificates(storename
)
2522 if encoding
== 'x509_asn' and (
2523 trust
is True or ssl
.Purpose
.SERVER_AUTH
.oid
in trust
)]
2524 except PermissionError
:
2528 ssl_context
.load_verify_locations(cadata
=cert
)
2529 except ssl
.SSLError
:
2533 def make_HTTPS_handler(params
, **kwargs
):
2534 opts_check_certificate
= not params
.get('nocheckcertificate')
2535 context
= ssl
.SSLContext(ssl
.PROTOCOL_TLS_CLIENT
)
2536 context
.check_hostname
= opts_check_certificate
2537 context
.verify_mode
= ssl
.CERT_REQUIRED
if opts_check_certificate
else ssl
.CERT_NONE
2538 if opts_check_certificate
:
2540 context
.load_default_certs()
2541 # Work around the issue in load_default_certs when there are bad certificates. See:
2542 # https://github.com/yt-dlp/yt-dlp/issues/1060,
2543 # https://bugs.python.org/issue35665, https://bugs.python.org/issue45312
2544 except ssl
.SSLError
:
2545 # enum_certificates is not present in mingw python. See https://github.com/yt-dlp/yt-dlp/issues/1151
2546 if sys
.platform
== 'win32' and hasattr(ssl
, 'enum_certificates'):
2547 # Create a new context to discard any certificates that were already loaded
2548 context
= ssl
.SSLContext(ssl
.PROTOCOL_TLS_CLIENT
)
2549 context
.check_hostname
, context
.verify_mode
= True, ssl
.CERT_REQUIRED
2550 for storename
in ('CA', 'ROOT'):
2551 _ssl_load_windows_store_certs(context
, storename
)
2552 context
.set_default_verify_paths()
2553 return YoutubeDLHTTPSHandler(params
, context
=context
, **kwargs
)
2556 def bug_reports_message(before
=';'):
2557 if ytdl_is_updateable():
2558 update_cmd
= 'type yt-dlp -U to update'
2560 update_cmd
= 'see https://github.com/yt-dlp/yt-dlp on how to update'
2561 msg
= 'please report this issue on https://github.com/yt-dlp/yt-dlp .'
2562 msg
+= ' Make sure you are using the latest version; %s.' % update_cmd
2563 msg
+= ' Be sure to call yt-dlp with the --verbose flag and include its complete output.'
2565 before
= before
.rstrip()
2566 if not before
or before
.endswith(('.', '!', '?')):
2567 msg
= msg
[0].title() + msg
[1:]
2569 return (before
+ ' ' if before
else '') + msg
2572 class YoutubeDLError(Exception):
2573 """Base exception for YoutubeDL errors."""
2576 def __init__(self
, msg
=None):
2579 elif self
.msg
is None:
2580 self
.msg
= type(self
).__name
__
2581 super().__init
__(self
.msg
)
2584 network_exceptions
= [compat_urllib_error
.URLError
, compat_http_client
.HTTPException
, socket
.error
]
2585 if hasattr(ssl
, 'CertificateError'):
2586 network_exceptions
.append(ssl
.CertificateError
)
2587 network_exceptions
= tuple(network_exceptions
)
2590 class ExtractorError(YoutubeDLError
):
2591 """Error during info extraction."""
2593 def __init__(self
, msg
, tb
=None, expected
=False, cause
=None, video_id
=None, ie
=None):
2594 """ tb, if given, is the original traceback (so that it can be printed out).
2595 If expected is set, this is a normal error message and most likely not a bug in yt-dlp.
2597 if sys
.exc_info()[0] in network_exceptions
:
2602 self
.expected
= expected
2604 self
.video_id
= video_id
2606 self
.exc_info
= sys
.exc_info() # preserve original exception
2608 super(ExtractorError
, self
).__init
__(''.join((
2609 format_field(ie
, template
='[%s] '),
2610 format_field(video_id
, template
='%s: '),
2612 format_field(cause
, template
=' (caused by %r)'),
2613 '' if expected
else bug_reports_message())))
2615 def format_traceback(self
):
2616 if self
.traceback
is None:
2618 return ''.join(traceback
.format_tb(self
.traceback
))
2621 class UnsupportedError(ExtractorError
):
2622 def __init__(self
, url
):
2623 super(UnsupportedError
, self
).__init
__(
2624 'Unsupported URL: %s' % url
, expected
=True)
2628 class RegexNotFoundError(ExtractorError
):
2629 """Error when a regex didn't match"""
2633 class GeoRestrictedError(ExtractorError
):
2634 """Geographic restriction Error exception.
2636 This exception may be thrown when a video is not available from your
2637 geographic location due to geographic restrictions imposed by a website.
2640 def __init__(self
, msg
, countries
=None, **kwargs
):
2641 kwargs
['expected'] = True
2642 super(GeoRestrictedError
, self
).__init
__(msg
, **kwargs
)
2643 self
.countries
= countries
2646 class DownloadError(YoutubeDLError
):
2647 """Download Error exception.
2649 This exception may be thrown by FileDownloader objects if they are not
2650 configured to continue on errors. They will contain the appropriate
2654 def __init__(self
, msg
, exc_info
=None):
2655 """ exc_info, if given, is the original exception that caused the trouble (as returned by sys.exc_info()). """
2656 super(DownloadError
, self
).__init
__(msg
)
2657 self
.exc_info
= exc_info
2660 class EntryNotInPlaylist(YoutubeDLError
):
2661 """Entry not in playlist exception.
2663 This exception will be thrown by YoutubeDL when a requested entry
2664 is not found in the playlist info_dict
2666 msg
= 'Entry not found in info'
2669 class SameFileError(YoutubeDLError
):
2670 """Same File exception.
2672 This exception will be thrown by FileDownloader objects if they detect
2673 multiple files would have to be downloaded to the same file on disk.
2675 msg
= 'Fixed output name but more than one file to download'
2677 def __init__(self
, filename
=None):
2678 if filename
is not None:
2679 self
.msg
+= f
': {filename}'
2680 super().__init
__(self
.msg
)
2683 class PostProcessingError(YoutubeDLError
):
2684 """Post Processing exception.
2686 This exception may be raised by PostProcessor's .run() method to
2687 indicate an error in the postprocessing task.
2691 class DownloadCancelled(YoutubeDLError
):
2692 """ Exception raised when the download queue should be interrupted """
2693 msg
= 'The download was cancelled'
2696 class ExistingVideoReached(DownloadCancelled
):
2697 """ --break-on-existing triggered """
2698 msg
= 'Encountered a video that is already in the archive, stopping due to --break-on-existing'
2701 class RejectedVideoReached(DownloadCancelled
):
2702 """ --break-on-reject triggered """
2703 msg
= 'Encountered a video that did not match filter, stopping due to --break-on-reject'
2706 class MaxDownloadsReached(DownloadCancelled
):
2707 """ --max-downloads limit has been reached. """
2708 msg
= 'Maximum number of downloads reached, stopping due to --max-downloads'
2711 class ReExtractInfo(YoutubeDLError
):
2712 """ Video info needs to be re-extracted. """
2714 def __init__(self
, msg
, expected
=False):
2715 super().__init
__(msg
)
2716 self
.expected
= expected
2719 class ThrottledDownload(ReExtractInfo
):
2720 """ Download speed below --throttled-rate. """
2721 msg
= 'The download speed is below throttle limit'
2724 super().__init
__(self
.msg
, expected
=False)
2727 class UnavailableVideoError(YoutubeDLError
):
2728 """Unavailable Format exception.
2730 This exception will be thrown when a video is requested
2731 in a format that is not available for that video.
2733 msg
= 'Unable to download video'
2735 def __init__(self
, err
=None):
2737 self
.msg
+= f
': {err}'
2738 super().__init
__(self
.msg
)
2741 class ContentTooShortError(YoutubeDLError
):
2742 """Content Too Short exception.
2744 This exception may be raised by FileDownloader objects when a file they
2745 download is too small for what the server announced first, indicating
2746 the connection was probably interrupted.
2749 def __init__(self
, downloaded
, expected
):
2750 super(ContentTooShortError
, self
).__init
__(
2751 'Downloaded {0} bytes, expected {1} bytes'.format(downloaded
, expected
)
2754 self
.downloaded
= downloaded
2755 self
.expected
= expected
2758 class XAttrMetadataError(YoutubeDLError
):
2759 def __init__(self
, code
=None, msg
='Unknown error'):
2760 super(XAttrMetadataError
, self
).__init
__(msg
)
2764 # Parsing code and msg
2765 if (self
.code
in (errno
.ENOSPC
, errno
.EDQUOT
)
2766 or 'No space left' in self
.msg
or 'Disk quota exceeded' in self
.msg
):
2767 self
.reason
= 'NO_SPACE'
2768 elif self
.code
== errno
.E2BIG
or 'Argument list too long' in self
.msg
:
2769 self
.reason
= 'VALUE_TOO_LONG'
2771 self
.reason
= 'NOT_SUPPORTED'
2774 class XAttrUnavailableError(YoutubeDLError
):
2778 def _create_http_connection(ydl_handler
, http_class
, is_https
, *args
, **kwargs
):
2779 # Working around python 2 bug (see http://bugs.python.org/issue17849) by limiting
2780 # expected HTTP responses to meet HTTP/1.0 or later (see also
2781 # https://github.com/ytdl-org/youtube-dl/issues/6727)
2782 if sys
.version_info
< (3, 0):
2783 kwargs
['strict'] = True
2784 hc
= http_class(*args
, **compat_kwargs(kwargs
))
2785 source_address
= ydl_handler
._params
.get('source_address')
2787 if source_address
is not None:
2788 # This is to workaround _create_connection() from socket where it will try all
2789 # address data from getaddrinfo() including IPv6. This filters the result from
2790 # getaddrinfo() based on the source_address value.
2791 # This is based on the cpython socket.create_connection() function.
2792 # https://github.com/python/cpython/blob/master/Lib/socket.py#L691
2793 def _create_connection(address
, timeout
=socket
._GLOBAL
_DEFAULT
_TIMEOUT
, source_address
=None):
2794 host
, port
= address
2796 addrs
= socket
.getaddrinfo(host
, port
, 0, socket
.SOCK_STREAM
)
2797 af
= socket
.AF_INET
if '.' in source_address
[0] else socket
.AF_INET6
2798 ip_addrs
= [addr
for addr
in addrs
if addr
[0] == af
]
2799 if addrs
and not ip_addrs
:
2800 ip_version
= 'v4' if af
== socket
.AF_INET
else 'v6'
2802 "No remote IP%s addresses available for connect, can't use '%s' as source address"
2803 % (ip_version
, source_address
[0]))
2804 for res
in ip_addrs
:
2805 af
, socktype
, proto
, canonname
, sa
= res
2808 sock
= socket
.socket(af
, socktype
, proto
)
2809 if timeout
is not socket
._GLOBAL
_DEFAULT
_TIMEOUT
:
2810 sock
.settimeout(timeout
)
2811 sock
.bind(source_address
)
2813 err
= None # Explicitly break reference cycle
2815 except socket
.error
as _
:
2817 if sock
is not None:
2822 raise socket
.error('getaddrinfo returns an empty list')
2823 if hasattr(hc
, '_create_connection'):
2824 hc
._create
_connection
= _create_connection
2825 sa
= (source_address
, 0)
2826 if hasattr(hc
, 'source_address'): # Python 2.7+
2827 hc
.source_address
= sa
2829 def _hc_connect(self
, *args
, **kwargs
):
2830 sock
= _create_connection(
2831 (self
.host
, self
.port
), self
.timeout
, sa
)
2833 self
.sock
= ssl
.wrap_socket(
2834 sock
, self
.key_file
, self
.cert_file
,
2835 ssl_version
=ssl
.PROTOCOL_TLSv1
)
2838 hc
.connect
= functools
.partial(_hc_connect
, hc
)
2843 def handle_youtubedl_headers(headers
):
2844 filtered_headers
= headers
2846 if 'Youtubedl-no-compression' in filtered_headers
:
2847 filtered_headers
= dict((k
, v
) for k
, v
in filtered_headers
.items() if k
.lower() != 'accept-encoding')
2848 del filtered_headers
['Youtubedl-no-compression']
2850 return filtered_headers
2853 class YoutubeDLHandler(compat_urllib_request
.HTTPHandler
):
2854 """Handler for HTTP requests and responses.
2856 This class, when installed with an OpenerDirector, automatically adds
2857 the standard headers to every HTTP request and handles gzipped and
2858 deflated responses from web servers. If compression is to be avoided in
2859 a particular request, the original request in the program code only has
2860 to include the HTTP header "Youtubedl-no-compression", which will be
2861 removed before making the real request.
2863 Part of this code was copied from:
2865 http://techknack.net/python-urllib2-handlers/
2867 Andrew Rowls, the author of that code, agreed to release it to the
2871 def __init__(self
, params
, *args
, **kwargs
):
2872 compat_urllib_request
.HTTPHandler
.__init
__(self
, *args
, **kwargs
)
2873 self
._params
= params
2875 def http_open(self
, req
):
2876 conn_class
= compat_http_client
.HTTPConnection
2878 socks_proxy
= req
.headers
.get('Ytdl-socks-proxy')
2880 conn_class
= make_socks_conn_class(conn_class
, socks_proxy
)
2881 del req
.headers
['Ytdl-socks-proxy']
2883 return self
.do_open(functools
.partial(
2884 _create_http_connection
, self
, conn_class
, False),
2892 return zlib
.decompress(data
, -zlib
.MAX_WBITS
)
2894 return zlib
.decompress(data
)
2896 def http_request(self
, req
):
2897 # According to RFC 3986, URLs can not contain non-ASCII characters, however this is not
2898 # always respected by websites, some tend to give out URLs with non percent-encoded
2899 # non-ASCII characters (see telemb.py, ard.py [#3412])
2900 # urllib chokes on URLs with non-ASCII characters (see http://bugs.python.org/issue3991)
2901 # To work around aforementioned issue we will replace request's original URL with
2902 # percent-encoded one
2903 # Since redirects are also affected (e.g. http://www.southpark.de/alle-episoden/s18e09)
2904 # the code of this workaround has been moved here from YoutubeDL.urlopen()
2905 url
= req
.get_full_url()
2906 url_escaped
= escape_url(url
)
2908 # Substitute URL if any change after escaping
2909 if url
!= url_escaped
:
2910 req
= update_Request(req
, url
=url_escaped
)
2912 for h
, v
in std_headers
.items():
2913 # Capitalize is needed because of Python bug 2275: http://bugs.python.org/issue2275
2914 # The dict keys are capitalized because of this bug by urllib
2915 if h
.capitalize() not in req
.headers
:
2916 req
.add_header(h
, v
)
2918 req
.headers
= handle_youtubedl_headers(req
.headers
)
2920 if sys
.version_info
< (2, 7) and '#' in req
.get_full_url():
2921 # Python 2.6 is brain-dead when it comes to fragments
2922 req
._Request
__original
= req
._Request
__original
.partition('#')[0]
2923 req
._Request
__r
_type
= req
._Request
__r
_type
.partition('#')[0]
2927 def http_response(self
, req
, resp
):
2930 if resp
.headers
.get('Content-encoding', '') == 'gzip':
2931 content
= resp
.read()
2932 gz
= gzip
.GzipFile(fileobj
=io
.BytesIO(content
), mode
='rb')
2934 uncompressed
= io
.BytesIO(gz
.read())
2935 except IOError as original_ioerror
:
2936 # There may be junk add the end of the file
2937 # See http://stackoverflow.com/q/4928560/35070 for details
2938 for i
in range(1, 1024):
2940 gz
= gzip
.GzipFile(fileobj
=io
.BytesIO(content
[:-i
]), mode
='rb')
2941 uncompressed
= io
.BytesIO(gz
.read())
2946 raise original_ioerror
2947 resp
= compat_urllib_request
.addinfourl(uncompressed
, old_resp
.headers
, old_resp
.url
, old_resp
.code
)
2948 resp
.msg
= old_resp
.msg
2949 del resp
.headers
['Content-encoding']
2951 if resp
.headers
.get('Content-encoding', '') == 'deflate':
2952 gz
= io
.BytesIO(self
.deflate(resp
.read()))
2953 resp
= compat_urllib_request
.addinfourl(gz
, old_resp
.headers
, old_resp
.url
, old_resp
.code
)
2954 resp
.msg
= old_resp
.msg
2955 del resp
.headers
['Content-encoding']
2956 # Percent-encode redirect URL of Location HTTP header to satisfy RFC 3986 (see
2957 # https://github.com/ytdl-org/youtube-dl/issues/6457).
2958 if 300 <= resp
.code
< 400:
2959 location
= resp
.headers
.get('Location')
2961 # As of RFC 2616 default charset is iso-8859-1 that is respected by python 3
2962 if sys
.version_info
>= (3, 0):
2963 location
= location
.encode('iso-8859-1').decode('utf-8')
2965 location
= location
.decode('utf-8')
2966 location_escaped
= escape_url(location
)
2967 if location
!= location_escaped
:
2968 del resp
.headers
['Location']
2969 if sys
.version_info
< (3, 0):
2970 location_escaped
= location_escaped
.encode('utf-8')
2971 resp
.headers
['Location'] = location_escaped
2974 https_request
= http_request
2975 https_response
= http_response
2978 def make_socks_conn_class(base_class
, socks_proxy
):
2979 assert issubclass(base_class
, (
2980 compat_http_client
.HTTPConnection
, compat_http_client
.HTTPSConnection
))
2982 url_components
= compat_urlparse
.urlparse(socks_proxy
)
2983 if url_components
.scheme
.lower() == 'socks5':
2984 socks_type
= ProxyType
.SOCKS5
2985 elif url_components
.scheme
.lower() in ('socks', 'socks4'):
2986 socks_type
= ProxyType
.SOCKS4
2987 elif url_components
.scheme
.lower() == 'socks4a':
2988 socks_type
= ProxyType
.SOCKS4A
2990 def unquote_if_non_empty(s
):
2993 return compat_urllib_parse_unquote_plus(s
)
2997 url_components
.hostname
, url_components
.port
or 1080,
2999 unquote_if_non_empty(url_components
.username
),
3000 unquote_if_non_empty(url_components
.password
),
3003 class SocksConnection(base_class
):
3005 self
.sock
= sockssocket()
3006 self
.sock
.setproxy(*proxy_args
)
3007 if type(self
.timeout
) in (int, float):
3008 self
.sock
.settimeout(self
.timeout
)
3009 self
.sock
.connect((self
.host
, self
.port
))
3011 if isinstance(self
, compat_http_client
.HTTPSConnection
):
3012 if hasattr(self
, '_context'): # Python > 2.6
3013 self
.sock
= self
._context
.wrap_socket(
3014 self
.sock
, server_hostname
=self
.host
)
3016 self
.sock
= ssl
.wrap_socket(self
.sock
)
3018 return SocksConnection
3021 class YoutubeDLHTTPSHandler(compat_urllib_request
.HTTPSHandler
):
3022 def __init__(self
, params
, https_conn_class
=None, *args
, **kwargs
):
3023 compat_urllib_request
.HTTPSHandler
.__init
__(self
, *args
, **kwargs
)
3024 self
._https
_conn
_class
= https_conn_class
or compat_http_client
.HTTPSConnection
3025 self
._params
= params
3027 def https_open(self
, req
):
3029 conn_class
= self
._https
_conn
_class
3031 if hasattr(self
, '_context'): # python > 2.6
3032 kwargs
['context'] = self
._context
3033 if hasattr(self
, '_check_hostname'): # python 3.x
3034 kwargs
['check_hostname'] = self
._check
_hostname
3036 socks_proxy
= req
.headers
.get('Ytdl-socks-proxy')
3038 conn_class
= make_socks_conn_class(conn_class
, socks_proxy
)
3039 del req
.headers
['Ytdl-socks-proxy']
3041 return self
.do_open(functools
.partial(
3042 _create_http_connection
, self
, conn_class
, True),
3046 class YoutubeDLCookieJar(compat_cookiejar
.MozillaCookieJar
):
3048 See [1] for cookie file format.
3050 1. https://curl.haxx.se/docs/http-cookies.html
3052 _HTTPONLY_PREFIX
= '#HttpOnly_'
3054 _HEADER
= '''# Netscape HTTP Cookie File
3055 # This file is generated by yt-dlp. Do not edit.
3058 _CookieFileEntry
= collections
.namedtuple(
3060 ('domain_name', 'include_subdomains', 'path', 'https_only', 'expires_at', 'name', 'value'))
3062 def save(self
, filename
=None, ignore_discard
=False, ignore_expires
=False):
3064 Save cookies to a file.
3066 Most of the code is taken from CPython 3.8 and slightly adapted
3067 to support cookie files with UTF-8 in both python 2 and 3.
3069 if filename
is None:
3070 if self
.filename
is not None:
3071 filename
= self
.filename
3073 raise ValueError(compat_cookiejar
.MISSING_FILENAME_TEXT
)
3075 # Store session cookies with `expires` set to 0 instead of an empty
3078 if cookie
.expires
is None:
3081 with io
.open(filename
, 'w', encoding
='utf-8') as f
:
3082 f
.write(self
._HEADER
)
3085 if not ignore_discard
and cookie
.discard
:
3087 if not ignore_expires
and cookie
.is_expired(now
):
3093 if cookie
.domain
.startswith('.'):
3094 initial_dot
= 'TRUE'
3096 initial_dot
= 'FALSE'
3097 if cookie
.expires
is not None:
3098 expires
= compat_str(cookie
.expires
)
3101 if cookie
.value
is None:
3102 # cookies.txt regards 'Set-Cookie: foo' as a cookie
3103 # with no name, whereas http.cookiejar regards it as a
3104 # cookie with no value.
3109 value
= cookie
.value
3111 '\t'.join([cookie
.domain
, initial_dot
, cookie
.path
,
3112 secure
, expires
, name
, value
]) + '\n')
3114 def load(self
, filename
=None, ignore_discard
=False, ignore_expires
=False):
3115 """Load cookies from a file."""
3116 if filename
is None:
3117 if self
.filename
is not None:
3118 filename
= self
.filename
3120 raise ValueError(compat_cookiejar
.MISSING_FILENAME_TEXT
)
3122 def prepare_line(line
):
3123 if line
.startswith(self
._HTTPONLY
_PREFIX
):
3124 line
= line
[len(self
._HTTPONLY
_PREFIX
):]
3125 # comments and empty lines are fine
3126 if line
.startswith('#') or not line
.strip():
3128 cookie_list
= line
.split('\t')
3129 if len(cookie_list
) != self
._ENTRY
_LEN
:
3130 raise compat_cookiejar
.LoadError('invalid length %d' % len(cookie_list
))
3131 cookie
= self
._CookieFileEntry
(*cookie_list
)
3132 if cookie
.expires_at
and not cookie
.expires_at
.isdigit():
3133 raise compat_cookiejar
.LoadError('invalid expires at %s' % cookie
.expires_at
)
3137 with io
.open(filename
, encoding
='utf-8') as f
:
3140 cf
.write(prepare_line(line
))
3141 except compat_cookiejar
.LoadError
as e
:
3143 'WARNING: skipping cookie file entry due to %s: %r\n'
3144 % (e
, line
), sys
.stderr
)
3147 self
._really
_load
(cf
, filename
, ignore_discard
, ignore_expires
)
3148 # Session cookies are denoted by either `expires` field set to
3149 # an empty string or 0. MozillaCookieJar only recognizes the former
3150 # (see [1]). So we need force the latter to be recognized as session
3151 # cookies on our own.
3152 # Session cookies may be important for cookies-based authentication,
3153 # e.g. usually, when user does not check 'Remember me' check box while
3154 # logging in on a site, some important cookies are stored as session
3155 # cookies so that not recognizing them will result in failed login.
3156 # 1. https://bugs.python.org/issue17164
3158 # Treat `expires=0` cookies as session cookies
3159 if cookie
.expires
== 0:
3160 cookie
.expires
= None
3161 cookie
.discard
= True
3164 class YoutubeDLCookieProcessor(compat_urllib_request
.HTTPCookieProcessor
):
3165 def __init__(self
, cookiejar
=None):
3166 compat_urllib_request
.HTTPCookieProcessor
.__init
__(self
, cookiejar
)
3168 def http_response(self
, request
, response
):
3169 # Python 2 will choke on next HTTP request in row if there are non-ASCII
3170 # characters in Set-Cookie HTTP header of last response (see
3171 # https://github.com/ytdl-org/youtube-dl/issues/6769).
3172 # In order to at least prevent crashing we will percent encode Set-Cookie
3173 # header before HTTPCookieProcessor starts processing it.
3174 # if sys.version_info < (3, 0) and response.headers:
3175 # for set_cookie_header in ('Set-Cookie', 'Set-Cookie2'):
3176 # set_cookie = response.headers.get(set_cookie_header)
3178 # set_cookie_escaped = compat_urllib_parse.quote(set_cookie, b"%/;:@&=+$,!~*'()?#[] ")
3179 # if set_cookie != set_cookie_escaped:
3180 # del response.headers[set_cookie_header]
3181 # response.headers[set_cookie_header] = set_cookie_escaped
3182 return compat_urllib_request
.HTTPCookieProcessor
.http_response(self
, request
, response
)
3184 https_request
= compat_urllib_request
.HTTPCookieProcessor
.http_request
3185 https_response
= http_response
3188 class YoutubeDLRedirectHandler(compat_urllib_request
.HTTPRedirectHandler
):
3189 """YoutubeDL redirect handler
3191 The code is based on HTTPRedirectHandler implementation from CPython [1].
3193 This redirect handler solves two issues:
3194 - ensures redirect URL is always unicode under python 2
3195 - introduces support for experimental HTTP response status code
3196 308 Permanent Redirect [2] used by some sites [3]
3198 1. https://github.com/python/cpython/blob/master/Lib/urllib/request.py
3199 2. https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/308
3200 3. https://github.com/ytdl-org/youtube-dl/issues/28768
3203 http_error_301
= http_error_303
= http_error_307
= http_error_308
= compat_urllib_request
.HTTPRedirectHandler
.http_error_302
3205 def redirect_request(self
, req
, fp
, code
, msg
, headers
, newurl
):
3206 """Return a Request or None in response to a redirect.
3208 This is called by the http_error_30x methods when a
3209 redirection response is received. If a redirection should
3210 take place, return a new Request to allow http_error_30x to
3211 perform the redirect. Otherwise, raise HTTPError if no-one
3212 else should try to handle this url. Return None if you can't
3213 but another Handler might.
3215 m
= req
.get_method()
3216 if (not (code
in (301, 302, 303, 307, 308) and m
in ("GET", "HEAD")
3217 or code
in (301, 302, 303) and m
== "POST")):
3218 raise compat_HTTPError(req
.full_url
, code
, msg
, headers
, fp
)
3219 # Strictly (according to RFC 2616), 301 or 302 in response to
3220 # a POST MUST NOT cause a redirection without confirmation
3221 # from the user (of urllib.request, in this case). In practice,
3222 # essentially all clients do redirect in this case, so we do
3225 # On python 2 urlh.geturl() may sometimes return redirect URL
3226 # as byte string instead of unicode. This workaround allows
3227 # to force it always return unicode.
3228 if sys
.version_info
[0] < 3:
3229 newurl
= compat_str(newurl
)
3231 # Be conciliant with URIs containing a space. This is mainly
3232 # redundant with the more complete encoding done in http_error_302(),
3233 # but it is kept for compatibility with other callers.
3234 newurl
= newurl
.replace(' ', '%20')
3236 CONTENT_HEADERS
= ("content-length", "content-type")
3237 # NB: don't use dict comprehension for python 2.6 compatibility
3238 newheaders
= dict((k
, v
) for k
, v
in req
.headers
.items()
3239 if k
.lower() not in CONTENT_HEADERS
)
3240 return compat_urllib_request
.Request(
3241 newurl
, headers
=newheaders
, origin_req_host
=req
.origin_req_host
,
3245 def extract_timezone(date_str
):
3248 ^.{8,}? # >=8 char non-TZ prefix, if present
3249 (?P<tz>Z| # just the UTC Z, or
3250 (?:(?<=.\b\d{4}|\b\d{2}:\d\d)| # preceded by 4 digits or hh:mm or
3251 (?<!.\b[a-zA-Z]{3}|[a-zA-Z]{4}|..\b\d\d)) # not preceded by 3 alpha word or >= 4 alpha or 2 digits
3252 [ ]? # optional space
3253 (?P<sign>\+|-) # +/-
3254 (?P<hours>[0-9]{2}):?(?P<minutes>[0-9]{2}) # hh[:]mm
3258 timezone
= datetime
.timedelta()
3260 date_str
= date_str
[:-len(m
.group('tz'))]
3261 if not m
.group('sign'):
3262 timezone
= datetime
.timedelta()
3264 sign
= 1 if m
.group('sign') == '+' else -1
3265 timezone
= datetime
.timedelta(
3266 hours
=sign
* int(m
.group('hours')),
3267 minutes
=sign
* int(m
.group('minutes')))
3268 return timezone
, date_str
3271 def parse_iso8601(date_str
, delimiter
='T', timezone
=None):
3272 """ Return a UNIX timestamp from the given date """
3274 if date_str
is None:
3277 date_str
= re
.sub(r
'\.[0-9]+', '', date_str
)
3279 if timezone
is None:
3280 timezone
, date_str
= extract_timezone(date_str
)
3283 date_format
= '%Y-%m-%d{0}%H:%M:%S'.format(delimiter
)
3284 dt
= datetime
.datetime
.strptime(date_str
, date_format
) - timezone
3285 return calendar
.timegm(dt
.timetuple())
3290 def date_formats(day_first
=True):
3291 return DATE_FORMATS_DAY_FIRST
if day_first
else DATE_FORMATS_MONTH_FIRST
3294 def unified_strdate(date_str
, day_first
=True):
3295 """Return a string with the date in the format YYYYMMDD"""
3297 if date_str
is None:
3301 date_str
= date_str
.replace(',', ' ')
3302 # Remove AM/PM + timezone
3303 date_str
= re
.sub(r
'(?i)\s*(?:AM|PM)(?:\s+[A-Z]+)?', '', date_str
)
3304 _
, date_str
= extract_timezone(date_str
)
3306 for expression
in date_formats(day_first
):
3308 upload_date
= datetime
.datetime
.strptime(date_str
, expression
).strftime('%Y%m%d')
3311 if upload_date
is None:
3312 timetuple
= email
.utils
.parsedate_tz(date_str
)
3315 upload_date
= datetime
.datetime(*timetuple
[:6]).strftime('%Y%m%d')
3318 if upload_date
is not None:
3319 return compat_str(upload_date
)
3322 def unified_timestamp(date_str
, day_first
=True):
3323 if date_str
is None:
3326 date_str
= re
.sub(r
'[,|]', '', date_str
)
3328 pm_delta
= 12 if re
.search(r
'(?i)PM', date_str
) else 0
3329 timezone
, date_str
= extract_timezone(date_str
)
3331 # Remove AM/PM + timezone
3332 date_str
= re
.sub(r
'(?i)\s*(?:AM|PM)(?:\s+[A-Z]+)?', '', date_str
)
3334 # Remove unrecognized timezones from ISO 8601 alike timestamps
3335 m
= re
.search(r
'\d{1,2}:\d{1,2}(?:\.\d+)?(?P<tz>\s*[A-Z]+)$', date_str
)
3337 date_str
= date_str
[:-len(m
.group('tz'))]
3339 # Python only supports microseconds, so remove nanoseconds
3340 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
)
3342 date_str
= m
.group(1)
3344 for expression
in date_formats(day_first
):
3346 dt
= datetime
.datetime
.strptime(date_str
, expression
) - timezone
+ datetime
.timedelta(hours
=pm_delta
)
3347 return calendar
.timegm(dt
.timetuple())
3350 timetuple
= email
.utils
.parsedate_tz(date_str
)
3352 return calendar
.timegm(timetuple
) + pm_delta
* 3600
3355 def determine_ext(url
, default_ext
='unknown_video'):
3356 if url
is None or '.' not in url
:
3358 guess
= url
.partition('?')[0].rpartition('.')[2]
3359 if re
.match(r
'^[A-Za-z0-9]+$', guess
):
3361 # Try extract ext from URLs like http://example.com/foo/bar.mp4/?download
3362 elif guess
.rstrip('/') in KNOWN_EXTENSIONS
:
3363 return guess
.rstrip('/')
3368 def subtitles_filename(filename
, sub_lang
, sub_format
, expected_real_ext
=None):
3369 return replace_extension(filename
, sub_lang
+ '.' + sub_format
, expected_real_ext
)
3372 def datetime_from_str(date_str
, precision
='auto', format
='%Y%m%d'):
3374 Return a datetime object from a string in the format YYYYMMDD or
3375 (now|today|date)[+-][0-9](microsecond|second|minute|hour|day|week|month|year)(s)?
3377 format: string date format used to return datetime object from
3378 precision: round the time portion of a datetime object.
3379 auto|microsecond|second|minute|hour|day.
3380 auto: round to the unit provided in date_str (if applicable).
3382 auto_precision
= False
3383 if precision
== 'auto':
3384 auto_precision
= True
3385 precision
= 'microsecond'
3386 today
= datetime_round(datetime
.datetime
.now(), precision
)
3387 if date_str
in ('now', 'today'):
3389 if date_str
== 'yesterday':
3390 return today
- datetime
.timedelta(days
=1)
3392 r
'(?P<start>.+)(?P<sign>[+-])(?P<time>\d+)(?P<unit>microsecond|second|minute|hour|day|week|month|year)(s)?',
3394 if match
is not None:
3395 start_time
= datetime_from_str(match
.group('start'), precision
, format
)
3396 time
= int(match
.group('time')) * (-1 if match
.group('sign') == '-' else 1)
3397 unit
= match
.group('unit')
3398 if unit
== 'month' or unit
== 'year':
3399 new_date
= datetime_add_months(start_time
, time
* 12 if unit
== 'year' else time
)
3405 delta
= datetime
.timedelta(**{unit + 's': time}
)
3406 new_date
= start_time
+ delta
3408 return datetime_round(new_date
, unit
)
3411 return datetime_round(datetime
.datetime
.strptime(date_str
, format
), precision
)
3414 def date_from_str(date_str
, format
='%Y%m%d'):
3416 Return a datetime object from a string in the format YYYYMMDD or
3417 (now|today|date)[+-][0-9](microsecond|second|minute|hour|day|week|month|year)(s)?
3419 format: string date format used to return datetime object from
3421 return datetime_from_str(date_str
, precision
='microsecond', format
=format
).date()
3424 def datetime_add_months(dt
, months
):
3425 """Increment/Decrement a datetime object by months."""
3426 month
= dt
.month
+ months
- 1
3427 year
= dt
.year
+ month
// 12
3428 month
= month
% 12 + 1
3429 day
= min(dt
.day
, calendar
.monthrange(year
, month
)[1])
3430 return dt
.replace(year
, month
, day
)
3433 def datetime_round(dt
, precision
='day'):
3435 Round a datetime object's time to a specific precision
3437 if precision
== 'microsecond':
3446 roundto
= lambda x
, n
: ((x
+ n
/ 2) // n
) * n
3447 timestamp
= calendar
.timegm(dt
.timetuple())
3448 return datetime
.datetime
.utcfromtimestamp(roundto(timestamp
, unit_seconds
[precision
]))
3451 def hyphenate_date(date_str
):
3453 Convert a date in 'YYYYMMDD' format to 'YYYY-MM-DD' format"""
3454 match
= re
.match(r
'^(\d\d\d\d)(\d\d)(\d\d)$', date_str
)
3455 if match
is not None:
3456 return '-'.join(match
.groups())
3461 class DateRange(object):
3462 """Represents a time interval between two dates"""
3464 def __init__(self
, start
=None, end
=None):
3465 """start and end must be strings in the format accepted by date"""
3466 if start
is not None:
3467 self
.start
= date_from_str(start
)
3469 self
.start
= datetime
.datetime
.min.date()
3471 self
.end
= date_from_str(end
)
3473 self
.end
= datetime
.datetime
.max.date()
3474 if self
.start
> self
.end
:
3475 raise ValueError('Date range: "%s" , the start date must be before the end date' % self
)
3479 """Returns a range that only contains the given day"""
3480 return cls(day
, day
)
3482 def __contains__(self
, date
):
3483 """Check if the date is in the range"""
3484 if not isinstance(date
, datetime
.date
):
3485 date
= date_from_str(date
)
3486 return self
.start
<= date
<= self
.end
3489 return '%s - %s' % (self
.start
.isoformat(), self
.end
.isoformat())
3492 def platform_name():
3493 """ Returns the platform name as a compat_str """
3494 res
= platform
.platform()
3495 if isinstance(res
, bytes):
3496 res
= res
.decode(preferredencoding())
3498 assert isinstance(res
, compat_str
)
3502 def get_windows_version():
3503 ''' Get Windows version. None if it's not running on Windows '''
3504 if compat_os_name
== 'nt':
3505 return version_tuple(platform
.win32_ver()[1])
3510 def _windows_write_string(s
, out
):
3511 """ Returns True if the string was written using special methods,
3512 False if it has yet to be written out."""
3513 # Adapted from http://stackoverflow.com/a/3259271/35070
3515 import ctypes
.wintypes
3523 fileno
= out
.fileno()
3524 except AttributeError:
3525 # If the output stream doesn't have a fileno, it's virtual
3527 except io
.UnsupportedOperation
:
3528 # Some strange Windows pseudo files?
3530 if fileno
not in WIN_OUTPUT_IDS
:
3533 GetStdHandle
= compat_ctypes_WINFUNCTYPE(
3534 ctypes
.wintypes
.HANDLE
, ctypes
.wintypes
.DWORD
)(
3535 ('GetStdHandle', ctypes
.windll
.kernel32
))
3536 h
= GetStdHandle(WIN_OUTPUT_IDS
[fileno
])
3538 WriteConsoleW
= compat_ctypes_WINFUNCTYPE(
3539 ctypes
.wintypes
.BOOL
, ctypes
.wintypes
.HANDLE
, ctypes
.wintypes
.LPWSTR
,
3540 ctypes
.wintypes
.DWORD
, ctypes
.POINTER(ctypes
.wintypes
.DWORD
),
3541 ctypes
.wintypes
.LPVOID
)(('WriteConsoleW', ctypes
.windll
.kernel32
))
3542 written
= ctypes
.wintypes
.DWORD(0)
3544 GetFileType
= compat_ctypes_WINFUNCTYPE(ctypes
.wintypes
.DWORD
, ctypes
.wintypes
.DWORD
)(('GetFileType', ctypes
.windll
.kernel32
))
3545 FILE_TYPE_CHAR
= 0x0002
3546 FILE_TYPE_REMOTE
= 0x8000
3547 GetConsoleMode
= compat_ctypes_WINFUNCTYPE(
3548 ctypes
.wintypes
.BOOL
, ctypes
.wintypes
.HANDLE
,
3549 ctypes
.POINTER(ctypes
.wintypes
.DWORD
))(
3550 ('GetConsoleMode', ctypes
.windll
.kernel32
))
3551 INVALID_HANDLE_VALUE
= ctypes
.wintypes
.DWORD(-1).value
3553 def not_a_console(handle
):
3554 if handle
== INVALID_HANDLE_VALUE
or handle
is None:
3556 return ((GetFileType(handle
) & ~FILE_TYPE_REMOTE
) != FILE_TYPE_CHAR
3557 or GetConsoleMode(handle
, ctypes
.byref(ctypes
.wintypes
.DWORD())) == 0)
3559 if not_a_console(h
):
3562 def next_nonbmp_pos(s
):
3564 return next(i
for i
, c
in enumerate(s
) if ord(c
) > 0xffff)
3565 except StopIteration:
3569 count
= min(next_nonbmp_pos(s
), 1024)
3571 ret
= WriteConsoleW(
3572 h
, s
, count
if count
else 2, ctypes
.byref(written
), None)
3574 raise OSError('Failed to write string')
3575 if not count
: # We just wrote a non-BMP character
3576 assert written
.value
== 2
3579 assert written
.value
> 0
3580 s
= s
[written
.value
:]
3584 def write_string(s
, out
=None, encoding
=None):
3587 assert type(s
) == compat_str
3589 if sys
.platform
== 'win32' and encoding
is None and hasattr(out
, 'fileno'):
3590 if _windows_write_string(s
, out
):
3593 if ('b' in getattr(out
, 'mode', '')
3594 or sys
.version_info
[0] < 3): # Python 2 lies about mode of sys.stderr
3595 byt
= s
.encode(encoding
or preferredencoding(), 'ignore')
3597 elif hasattr(out
, 'buffer'):
3598 enc
= encoding
or getattr(out
, 'encoding', None) or preferredencoding()
3599 byt
= s
.encode(enc
, 'ignore')
3600 out
.buffer.write(byt
)
3606 def bytes_to_intlist(bs
):
3609 if isinstance(bs
[0], int): # Python 3
3612 return [ord(c
) for c
in bs
]
3615 def intlist_to_bytes(xs
):
3618 return compat_struct_pack('%dB' % len(xs
), *xs
)
3621 # Cross-platform file locking
3622 if sys
.platform
== 'win32':
3623 import ctypes
.wintypes
3626 class OVERLAPPED(ctypes
.Structure
):
3628 ('Internal', ctypes
.wintypes
.LPVOID
),
3629 ('InternalHigh', ctypes
.wintypes
.LPVOID
),
3630 ('Offset', ctypes
.wintypes
.DWORD
),
3631 ('OffsetHigh', ctypes
.wintypes
.DWORD
),
3632 ('hEvent', ctypes
.wintypes
.HANDLE
),
3635 kernel32
= ctypes
.windll
.kernel32
3636 LockFileEx
= kernel32
.LockFileEx
3637 LockFileEx
.argtypes
= [
3638 ctypes
.wintypes
.HANDLE
, # hFile
3639 ctypes
.wintypes
.DWORD
, # dwFlags
3640 ctypes
.wintypes
.DWORD
, # dwReserved
3641 ctypes
.wintypes
.DWORD
, # nNumberOfBytesToLockLow
3642 ctypes
.wintypes
.DWORD
, # nNumberOfBytesToLockHigh
3643 ctypes
.POINTER(OVERLAPPED
) # Overlapped
3645 LockFileEx
.restype
= ctypes
.wintypes
.BOOL
3646 UnlockFileEx
= kernel32
.UnlockFileEx
3647 UnlockFileEx
.argtypes
= [
3648 ctypes
.wintypes
.HANDLE
, # hFile
3649 ctypes
.wintypes
.DWORD
, # dwReserved
3650 ctypes
.wintypes
.DWORD
, # nNumberOfBytesToLockLow
3651 ctypes
.wintypes
.DWORD
, # nNumberOfBytesToLockHigh
3652 ctypes
.POINTER(OVERLAPPED
) # Overlapped
3654 UnlockFileEx
.restype
= ctypes
.wintypes
.BOOL
3655 whole_low
= 0xffffffff
3656 whole_high
= 0x7fffffff
3658 def _lock_file(f
, exclusive
):
3659 overlapped
= OVERLAPPED()
3660 overlapped
.Offset
= 0
3661 overlapped
.OffsetHigh
= 0
3662 overlapped
.hEvent
= 0
3663 f
._lock
_file
_overlapped
_p
= ctypes
.pointer(overlapped
)
3664 handle
= msvcrt
.get_osfhandle(f
.fileno())
3665 if not LockFileEx(handle
, 0x2 if exclusive
else 0x0, 0,
3666 whole_low
, whole_high
, f
._lock
_file
_overlapped
_p
):
3667 raise OSError('Locking file failed: %r' % ctypes
.FormatError())
3669 def _unlock_file(f
):
3670 assert f
._lock
_file
_overlapped
_p
3671 handle
= msvcrt
.get_osfhandle(f
.fileno())
3672 if not UnlockFileEx(handle
, 0,
3673 whole_low
, whole_high
, f
._lock
_file
_overlapped
_p
):
3674 raise OSError('Unlocking file failed: %r' % ctypes
.FormatError())
3677 # Some platforms, such as Jython, is missing fcntl
3681 def _lock_file(f
, exclusive
):
3682 fcntl
.flock(f
, fcntl
.LOCK_EX
if exclusive
else fcntl
.LOCK_SH
)
3684 def _unlock_file(f
):
3685 fcntl
.flock(f
, fcntl
.LOCK_UN
)
3687 UNSUPPORTED_MSG
= 'file locking is not supported on this platform'
3689 def _lock_file(f
, exclusive
):
3690 raise IOError(UNSUPPORTED_MSG
)
3692 def _unlock_file(f
):
3693 raise IOError(UNSUPPORTED_MSG
)
3696 class locked_file(object):
3697 def __init__(self
, filename
, mode
, encoding
=None):
3698 assert mode
in ['r', 'a', 'w']
3699 self
.f
= io
.open(filename
, mode
, encoding
=encoding
)
3702 def __enter__(self
):
3703 exclusive
= self
.mode
!= 'r'
3705 _lock_file(self
.f
, exclusive
)
3711 def __exit__(self
, etype
, value
, traceback
):
3713 _unlock_file(self
.f
)
3720 def write(self
, *args
):
3721 return self
.f
.write(*args
)
3723 def read(self
, *args
):
3724 return self
.f
.read(*args
)
3727 def get_filesystem_encoding():
3728 encoding
= sys
.getfilesystemencoding()
3729 return encoding
if encoding
is not None else 'utf-8'
3732 def shell_quote(args
):
3734 encoding
= get_filesystem_encoding()
3736 if isinstance(a
, bytes):
3737 # We may get a filename encoded with 'encodeFilename'
3738 a
= a
.decode(encoding
)
3739 quoted_args
.append(compat_shlex_quote(a
))
3740 return ' '.join(quoted_args
)
3743 def smuggle_url(url
, data
):
3744 """ Pass additional data in a URL for internal use. """
3746 url
, idata
= unsmuggle_url(url
, {})
3748 sdata
= compat_urllib_parse_urlencode(
3749 {'__youtubedl_smuggle': json.dumps(data)}
)
3750 return url
+ '#' + sdata
3753 def unsmuggle_url(smug_url
, default
=None):
3754 if '#__youtubedl_smuggle' not in smug_url
:
3755 return smug_url
, default
3756 url
, _
, sdata
= smug_url
.rpartition('#')
3757 jsond
= compat_parse_qs(sdata
)['__youtubedl_smuggle'][0]
3758 data
= json
.loads(jsond
)
3762 def format_decimal_suffix(num
, fmt
='%d%s', *, factor
=1000):
3763 """ Formats numbers with decimal sufixes like K, M, etc """
3764 num
, factor
= float_or_none(num
), float(factor
)
3767 exponent
= 0 if num
== 0 else int(math
.log(num
, factor
))
3768 suffix
= ['', *'kMGTPEZY'][exponent
]
3770 suffix
= {'k': 'Ki', '': ''}
.get(suffix
, f
'{suffix}i')
3771 converted
= num
/ (factor
** exponent
)
3772 return fmt
% (converted
, suffix
)
3775 def format_bytes(bytes):
3776 return format_decimal_suffix(bytes, '%.2f%sB', factor
=1024) or 'N/A'
3779 def lookup_unit_table(unit_table
, s
):
3780 units_re
= '|'.join(re
.escape(u
) for u
in unit_table
)
3782 r
'(?P<num>[0-9]+(?:[,.][0-9]*)?)\s*(?P<unit>%s)\b' % units_re
, s
)
3785 num_str
= m
.group('num').replace(',', '.')
3786 mult
= unit_table
[m
.group('unit')]
3787 return int(float(num_str
) * mult
)
3790 def parse_filesize(s
):
3794 # The lower-case forms are of course incorrect and unofficial,
3795 # but we support those too
3812 'megabytes': 1000 ** 2,
3813 'mebibytes': 1024 ** 2,
3819 'gigabytes': 1000 ** 3,
3820 'gibibytes': 1024 ** 3,
3826 'terabytes': 1000 ** 4,
3827 'tebibytes': 1024 ** 4,
3833 'petabytes': 1000 ** 5,
3834 'pebibytes': 1024 ** 5,
3840 'exabytes': 1000 ** 6,
3841 'exbibytes': 1024 ** 6,
3847 'zettabytes': 1000 ** 7,
3848 'zebibytes': 1024 ** 7,
3854 'yottabytes': 1000 ** 8,
3855 'yobibytes': 1024 ** 8,
3858 return lookup_unit_table(_UNIT_TABLE
, s
)
3865 s
= re
.sub(r
'^[^\d]+\s', '', s
).strip()
3867 if re
.match(r
'^[\d,.]+$', s
):
3868 return str_to_int(s
)
3881 ret
= lookup_unit_table(_UNIT_TABLE
, s
)
3885 mobj
= re
.match(r
'([\d,.]+)(?:$|\s)', s
)
3887 return str_to_int(mobj
.group(1))
3890 def parse_resolution(s
):
3894 mobj
= re
.search(r
'(?<![a-zA-Z0-9])(?P<w>\d+)\s*[xX×,]\s*(?P<h>\d+)(?![a-zA-Z0-9])', s
)
3897 'width': int(mobj
.group('w')),
3898 'height': int(mobj
.group('h')),
3901 mobj
= re
.search(r
'(?<![a-zA-Z0-9])(\d+)[pPiI](?![a-zA-Z0-9])', s
)
3903 return {'height': int(mobj.group(1))}
3905 mobj
= re
.search(r
'\b([48])[kK]\b', s
)
3907 return {'height': int(mobj.group(1)) * 540}
3912 def parse_bitrate(s
):
3913 if not isinstance(s
, compat_str
):
3915 mobj
= re
.search(r
'\b(\d+)\s*kbps', s
)
3917 return int(mobj
.group(1))
3920 def month_by_name(name
, lang
='en'):
3921 """ Return the number of a month by (locale-independently) English name """
3923 month_names
= MONTH_NAMES
.get(lang
, MONTH_NAMES
['en'])
3926 return month_names
.index(name
) + 1
3931 def month_by_abbreviation(abbrev
):
3932 """ Return the number of a month by (locale-independently) English
3936 return [s
[:3] for s
in ENGLISH_MONTH_NAMES
].index(abbrev
) + 1
3941 def fix_xml_ampersands(xml_str
):
3942 """Replace all the '&' by '&' in XML"""
3944 r
'&(?!amp;|lt;|gt;|apos;|quot;|#x[0-9a-fA-F]{,4};|#[0-9]{,4};)',
3949 def setproctitle(title
):
3950 assert isinstance(title
, compat_str
)
3952 # ctypes in Jython is not complete
3953 # http://bugs.jython.org/issue2148
3954 if sys
.platform
.startswith('java'):
3958 libc
= ctypes
.cdll
.LoadLibrary('libc.so.6')
3962 # LoadLibrary in Windows Python 2.7.13 only expects
3963 # a bytestring, but since unicode_literals turns
3964 # every string into a unicode string, it fails.
3966 title_bytes
= title
.encode('utf-8')
3967 buf
= ctypes
.create_string_buffer(len(title_bytes
))
3968 buf
.value
= title_bytes
3970 libc
.prctl(15, buf
, 0, 0, 0)
3971 except AttributeError:
3972 return # Strange libc, just skip this
3975 def remove_start(s
, start
):
3976 return s
[len(start
):] if s
is not None and s
.startswith(start
) else s
3979 def remove_end(s
, end
):
3980 return s
[:-len(end
)] if s
is not None and s
.endswith(end
) else s
3983 def remove_quotes(s
):
3984 if s
is None or len(s
) < 2:
3986 for quote
in ('"', "'", ):
3987 if s
[0] == quote
and s
[-1] == quote
:
3992 def get_domain(url
):
3993 domain
= re
.match(r
'(?:https?:\/\/)?(?:www\.)?(?P<domain>[^\n\/]+\.[^\n\/]+)(?:\/(.*))?', url
)
3994 return domain
.group('domain') if domain
else None
3997 def url_basename(url
):
3998 path
= compat_urlparse
.urlparse(url
).path
3999 return path
.strip('/').split('/')[-1]
4003 return re
.match(r
'https?://[^?#&]+/', url
).group()
4006 def urljoin(base
, path
):
4007 if isinstance(path
, bytes):
4008 path
= path
.decode('utf-8')
4009 if not isinstance(path
, compat_str
) or not path
:
4011 if re
.match(r
'^(?:[a-zA-Z][a-zA-Z0-9+-.]*:)?//', path
):
4013 if isinstance(base
, bytes):
4014 base
= base
.decode('utf-8')
4015 if not isinstance(base
, compat_str
) or not re
.match(
4016 r
'^(?:https?:)?//', base
):
4018 return compat_urlparse
.urljoin(base
, path
)
4021 class HEADRequest(compat_urllib_request
.Request
):
4022 def get_method(self
):
4026 class PUTRequest(compat_urllib_request
.Request
):
4027 def get_method(self
):
4031 def int_or_none(v
, scale
=1, default
=None, get_attr
=None, invscale
=1):
4032 if get_attr
and v
is not None:
4033 v
= getattr(v
, get_attr
, None)
4035 return int(v
) * invscale
// scale
4036 except (ValueError, TypeError, OverflowError):
4040 def str_or_none(v
, default
=None):
4041 return default
if v
is None else compat_str(v
)
4044 def str_to_int(int_str
):
4045 """ A more relaxed version of int_or_none """
4046 if isinstance(int_str
, compat_integer_types
):
4048 elif isinstance(int_str
, compat_str
):
4049 int_str
= re
.sub(r
'[,\.\+]', '', int_str
)
4050 return int_or_none(int_str
)
4053 def float_or_none(v
, scale
=1, invscale
=1, default
=None):
4057 return float(v
) * invscale
/ scale
4058 except (ValueError, TypeError):
4062 def bool_or_none(v
, default
=None):
4063 return v
if isinstance(v
, bool) else default
4066 def strip_or_none(v
, default
=None):
4067 return v
.strip() if isinstance(v
, compat_str
) else default
4070 def url_or_none(url
):
4071 if not url
or not isinstance(url
, compat_str
):
4074 return url
if re
.match(r
'^(?:(?:https?|rt(?:m(?:pt?[es]?|fp)|sp[su]?)|mms|ftps?):)?//', url
) else None
4077 def strftime_or_none(timestamp
, date_format
, default
=None):
4078 datetime_object
= None
4080 if isinstance(timestamp
, compat_numeric_types
): # unix timestamp
4081 datetime_object
= datetime
.datetime
.utcfromtimestamp(timestamp
)
4082 elif isinstance(timestamp
, compat_str
): # assume YYYYMMDD
4083 datetime_object
= datetime
.datetime
.strptime(timestamp
, '%Y%m%d')
4084 return datetime_object
.strftime(date_format
)
4085 except (ValueError, TypeError, AttributeError):
4089 def parse_duration(s
):
4090 if not isinstance(s
, compat_basestring
):
4096 days
, hours
, mins
, secs
, ms
= [None] * 5
4097 m
= re
.match(r
'''(?x)
4099 (?:(?:(?P<days>[0-9]+):)?(?P<hours>[0-9]+):)?(?P<mins>[0-9]+):)?
4100 (?P<secs>(?(before_secs)[0-9]{1,2}|[0-9]+))
4101 (?P<ms>[.:][0-9]+)?Z?$
4104 days
, hours
, mins
, secs
, ms
= m
.group('days', 'hours', 'mins', 'secs', 'ms')
4109 [0-9]+\s*y(?:ears?)?\s*
4112 [0-9]+\s*m(?:onths?)?\s*
4115 [0-9]+\s*w(?:eeks?)?\s*
4118 (?P<days>[0-9]+)\s*d(?:ays?)?\s*
4122 (?P<hours>[0-9]+)\s*h(?:ours?)?\s*
4125 (?P<mins>[0-9]+)\s*m(?:in(?:ute)?s?)?\s*
4128 (?P<secs>[0-9]+)(?P<ms>\.[0-9]+)?\s*s(?:ec(?:ond)?s?)?\s*
4131 days
, hours
, mins
, secs
, ms
= m
.groups()
4133 m
= re
.match(r
'(?i)(?:(?P<hours>[0-9.]+)\s*(?:hours?)|(?P<mins>[0-9.]+)\s*(?:mins?\.?|minutes?)\s*)Z?$', s
)
4135 hours
, mins
= m
.groups()
4141 duration
+= float(secs
)
4143 duration
+= float(mins
) * 60
4145 duration
+= float(hours
) * 60 * 60
4147 duration
+= float(days
) * 24 * 60 * 60
4149 duration
+= float(ms
.replace(':', '.'))
4153 def prepend_extension(filename
, ext
, expected_real_ext
=None):
4154 name
, real_ext
= os
.path
.splitext(filename
)
4156 '{0}.{1}{2}'.format(name
, ext
, real_ext
)
4157 if not expected_real_ext
or real_ext
[1:] == expected_real_ext
4158 else '{0}.{1}'.format(filename
, ext
))
4161 def replace_extension(filename
, ext
, expected_real_ext
=None):
4162 name
, real_ext
= os
.path
.splitext(filename
)
4163 return '{0}.{1}'.format(
4164 name
if not expected_real_ext
or real_ext
[1:] == expected_real_ext
else filename
,
4168 def check_executable(exe
, args
=[]):
4169 """ Checks if the given binary is installed somewhere in PATH, and returns its name.
4170 args can be a list of arguments for a short output (like -version) """
4172 Popen([exe
] + args
, stdout
=subprocess
.PIPE
, stderr
=subprocess
.PIPE
).communicate_or_kill()
4178 def _get_exe_version_output(exe
, args
):
4180 # STDIN should be redirected too. On UNIX-like systems, ffmpeg triggers
4181 # SIGTTOU if yt-dlp is run in the background.
4182 # See https://github.com/ytdl-org/youtube-dl/issues/955#issuecomment-209789656
4184 [encodeArgument(exe
)] + args
, stdin
=subprocess
.PIPE
,
4185 stdout
=subprocess
.PIPE
, stderr
=subprocess
.STDOUT
).communicate_or_kill()
4188 if isinstance(out
, bytes): # Python 2.x
4189 out
= out
.decode('ascii', 'ignore')
4193 def detect_exe_version(output
, version_re
=None, unrecognized
='present'):
4194 assert isinstance(output
, compat_str
)
4195 if version_re
is None:
4196 version_re
= r
'version\s+([-0-9._a-zA-Z]+)'
4197 m
= re
.search(version_re
, output
)
4204 def get_exe_version(exe
, args
=['--version'],
4205 version_re
=None, unrecognized
='present'):
4206 """ Returns the version of the specified executable,
4207 or False if the executable is not present """
4208 out
= _get_exe_version_output(exe
, args
)
4209 return detect_exe_version(out
, version_re
, unrecognized
) if out
else False
4212 class LazyList(collections
.abc
.Sequence
):
4213 ''' Lazy immutable list from an iterable
4214 Note that slices of a LazyList are lists and not LazyList'''
4216 class IndexError(IndexError):
4219 def __init__(self
, iterable
, *, reverse
=False, _cache
=None):
4220 self
.__iterable
= iter(iterable
)
4221 self
.__cache
= [] if _cache
is None else _cache
4222 self
.__reversed
= reverse
4226 # We need to consume the entire iterable to iterate in reverse
4227 yield from self
.exhaust()
4229 yield from self
.__cache
4230 for item
in self
.__iterable
:
4231 self
.__cache
.append(item
)
4234 def __exhaust(self
):
4235 self
.__cache
.extend(self
.__iterable
)
4236 # Discard the emptied iterable to make it pickle-able
4237 self
.__iterable
= []
4241 ''' Evaluate the entire iterable '''
4242 return self
.__exhaust
()[::-1 if self
.__reversed
else 1]
4245 def __reverse_index(x
):
4246 return None if x
is None else -(x
+ 1)
4248 def __getitem__(self
, idx
):
4249 if isinstance(idx
, slice):
4251 idx
= slice(self
.__reverse
_index
(idx
.start
), self
.__reverse
_index
(idx
.stop
), -(idx
.step
or 1))
4252 start
, stop
, step
= idx
.start
, idx
.stop
, idx
.step
or 1
4253 elif isinstance(idx
, int):
4255 idx
= self
.__reverse
_index
(idx
)
4256 start
, stop
, step
= idx
, idx
, 0
4258 raise TypeError('indices must be integers or slices')
4259 if ((start
or 0) < 0 or (stop
or 0) < 0
4260 or (start
is None and step
< 0)
4261 or (stop
is None and step
> 0)):
4262 # We need to consume the entire iterable to be able to slice from the end
4263 # Obviously, never use this with infinite iterables
4266 return self
.__cache
[idx
]
4267 except IndexError as e
:
4268 raise self
.IndexError(e
) from e
4269 n
= max(start
or 0, stop
or 0) - len(self
.__cache
) + 1
4271 self
.__cache
.extend(itertools
.islice(self
.__iterable
, n
))
4273 return self
.__cache
[idx
]
4274 except IndexError as e
:
4275 raise self
.IndexError(e
) from e
4279 self
[-1] if self
.__reversed
else self
[0]
4280 except self
.IndexError:
4286 return len(self
.__cache
)
4288 def __reversed__(self
):
4289 return type(self
)(self
.__iterable
, reverse
=not self
.__reversed
, _cache
=self
.__cache
)
4292 return type(self
)(self
.__iterable
, reverse
=self
.__reversed
, _cache
=self
.__cache
)
4295 # repr and str should mimic a list. So we exhaust the iterable
4296 return repr(self
.exhaust())
4299 return repr(self
.exhaust())
4304 class IndexError(IndexError):
4308 # This is only useful for tests
4309 return len(self
.getslice())
4311 def __init__(self
, pagefunc
, pagesize
, use_cache
=True):
4312 self
._pagefunc
= pagefunc
4313 self
._pagesize
= pagesize
4314 self
._use
_cache
= use_cache
4317 def getpage(self
, pagenum
):
4318 page_results
= self
._cache
.get(pagenum
)
4319 if page_results
is None:
4320 page_results
= list(self
._pagefunc
(pagenum
))
4322 self
._cache
[pagenum
] = page_results
4325 def getslice(self
, start
=0, end
=None):
4326 return list(self
._getslice
(start
, end
))
4328 def _getslice(self
, start
, end
):
4329 raise NotImplementedError('This method must be implemented by subclasses')
4331 def __getitem__(self
, idx
):
4332 # NOTE: cache must be enabled if this is used
4333 if not isinstance(idx
, int) or idx
< 0:
4334 raise TypeError('indices must be non-negative integers')
4335 entries
= self
.getslice(idx
, idx
+ 1)
4337 raise self
.IndexError()
4341 class OnDemandPagedList(PagedList
):
4342 def _getslice(self
, start
, end
):
4343 for pagenum
in itertools
.count(start
// self
._pagesize
):
4344 firstid
= pagenum
* self
._pagesize
4345 nextfirstid
= pagenum
* self
._pagesize
+ self
._pagesize
4346 if start
>= nextfirstid
:
4350 start
% self
._pagesize
4351 if firstid
<= start
< nextfirstid
4354 ((end
- 1) % self
._pagesize
) + 1
4355 if (end
is not None and firstid
<= end
<= nextfirstid
)
4358 page_results
= self
.getpage(pagenum
)
4359 if startv
!= 0 or endv
is not None:
4360 page_results
= page_results
[startv
:endv
]
4361 yield from page_results
4363 # A little optimization - if current page is not "full", ie. does
4364 # not contain page_size videos then we can assume that this page
4365 # is the last one - there are no more ids on further pages -
4366 # i.e. no need to query again.
4367 if len(page_results
) + startv
< self
._pagesize
:
4370 # If we got the whole page, but the next page is not interesting,
4371 # break out early as well
4372 if end
== nextfirstid
:
4376 class InAdvancePagedList(PagedList
):
4377 def __init__(self
, pagefunc
, pagecount
, pagesize
):
4378 self
._pagecount
= pagecount
4379 PagedList
.__init
__(self
, pagefunc
, pagesize
, True)
4381 def _getslice(self
, start
, end
):
4382 start_page
= start
// self
._pagesize
4384 self
._pagecount
if end
is None else (end
// self
._pagesize
+ 1))
4385 skip_elems
= start
- start_page
* self
._pagesize
4386 only_more
= None if end
is None else end
- start
4387 for pagenum
in range(start_page
, end_page
):
4388 page_results
= self
.getpage(pagenum
)
4390 page_results
= page_results
[skip_elems
:]
4392 if only_more
is not None:
4393 if len(page_results
) < only_more
:
4394 only_more
-= len(page_results
)
4396 yield from page_results
[:only_more
]
4398 yield from page_results
4401 def uppercase_escape(s
):
4402 unicode_escape
= codecs
.getdecoder('unicode_escape')
4404 r
'\\U[0-9a-fA-F]{8}',
4405 lambda m
: unicode_escape(m
.group(0))[0],
4409 def lowercase_escape(s
):
4410 unicode_escape
= codecs
.getdecoder('unicode_escape')
4412 r
'\\u[0-9a-fA-F]{4}',
4413 lambda m
: unicode_escape(m
.group(0))[0],
4417 def escape_rfc3986(s
):
4418 """Escape non-ASCII characters as suggested by RFC 3986"""
4419 if sys
.version_info
< (3, 0) and isinstance(s
, compat_str
):
4420 s
= s
.encode('utf-8')
4421 return compat_urllib_parse
.quote(s
, b
"%/;:@&=+$,!~*'()?#[]")
4424 def escape_url(url
):
4425 """Escape URL as suggested by RFC 3986"""
4426 url_parsed
= compat_urllib_parse_urlparse(url
)
4427 return url_parsed
._replace
(
4428 netloc
=url_parsed
.netloc
.encode('idna').decode('ascii'),
4429 path
=escape_rfc3986(url_parsed
.path
),
4430 params
=escape_rfc3986(url_parsed
.params
),
4431 query
=escape_rfc3986(url_parsed
.query
),
4432 fragment
=escape_rfc3986(url_parsed
.fragment
)
4437 return compat_parse_qs(compat_urllib_parse_urlparse(url
).query
)
4440 def read_batch_urls(batch_fd
):
4442 if not isinstance(url
, compat_str
):
4443 url
= url
.decode('utf-8', 'replace')
4444 BOM_UTF8
= ('\xef\xbb\xbf', '\ufeff')
4445 for bom
in BOM_UTF8
:
4446 if url
.startswith(bom
):
4447 url
= url
[len(bom
):]
4449 if not url
or url
.startswith(('#', ';', ']')):
4451 # "#" cannot be stripped out since it is part of the URI
4452 # However, it can be safely stipped out if follwing a whitespace
4453 return re
.split(r
'\s#', url
, 1)[0].rstrip()
4455 with contextlib
.closing(batch_fd
) as fd
:
4456 return [url
for url
in map(fixup
, fd
) if url
]
4459 def urlencode_postdata(*args
, **kargs
):
4460 return compat_urllib_parse_urlencode(*args
, **kargs
).encode('ascii')
4463 def update_url_query(url
, query
):
4466 parsed_url
= compat_urlparse
.urlparse(url
)
4467 qs
= compat_parse_qs(parsed_url
.query
)
4469 return compat_urlparse
.urlunparse(parsed_url
._replace
(
4470 query
=compat_urllib_parse_urlencode(qs
, True)))
4473 def update_Request(req
, url
=None, data
=None, headers
={}, query={}
):
4474 req_headers
= req
.headers
.copy()
4475 req_headers
.update(headers
)
4476 req_data
= data
or req
.data
4477 req_url
= update_url_query(url
or req
.get_full_url(), query
)
4478 req_get_method
= req
.get_method()
4479 if req_get_method
== 'HEAD':
4480 req_type
= HEADRequest
4481 elif req_get_method
== 'PUT':
4482 req_type
= PUTRequest
4484 req_type
= compat_urllib_request
.Request
4486 req_url
, data
=req_data
, headers
=req_headers
,
4487 origin_req_host
=req
.origin_req_host
, unverifiable
=req
.unverifiable
)
4488 if hasattr(req
, 'timeout'):
4489 new_req
.timeout
= req
.timeout
4493 def _multipart_encode_impl(data
, boundary
):
4494 content_type
= 'multipart/form-data; boundary=%s' % boundary
4497 for k
, v
in data
.items():
4498 out
+= b
'--' + boundary
.encode('ascii') + b
'\r\n'
4499 if isinstance(k
, compat_str
):
4500 k
= k
.encode('utf-8')
4501 if isinstance(v
, compat_str
):
4502 v
= v
.encode('utf-8')
4503 # RFC 2047 requires non-ASCII field names to be encoded, while RFC 7578
4504 # suggests sending UTF-8 directly. Firefox sends UTF-8, too
4505 content
= b
'Content-Disposition: form-data; name="' + k
+ b
'"\r\n\r\n' + v
+ b
'\r\n'
4506 if boundary
.encode('ascii') in content
:
4507 raise ValueError('Boundary overlaps with data')
4510 out
+= b
'--' + boundary
.encode('ascii') + b
'--\r\n'
4512 return out
, content_type
4515 def multipart_encode(data
, boundary
=None):
4517 Encode a dict to RFC 7578-compliant form-data
4520 A dict where keys and values can be either Unicode or bytes-like
4523 If specified a Unicode object, it's used as the boundary. Otherwise
4524 a random boundary is generated.
4526 Reference: https://tools.ietf.org/html/rfc7578
4528 has_specified_boundary
= boundary
is not None
4531 if boundary
is None:
4532 boundary
= '---------------' + str(random
.randrange(0x0fffffff, 0xffffffff))
4535 out
, content_type
= _multipart_encode_impl(data
, boundary
)
4538 if has_specified_boundary
:
4542 return out
, content_type
4545 def dict_get(d
, key_or_keys
, default
=None, skip_false_values
=True):
4546 if isinstance(key_or_keys
, (list, tuple)):
4547 for key
in key_or_keys
:
4548 if key
not in d
or d
[key
] is None or skip_false_values
and not d
[key
]:
4552 return d
.get(key_or_keys
, default
)
4555 def try_get(src
, getter
, expected_type
=None):
4556 for get
in variadic(getter
):
4559 except (AttributeError, KeyError, TypeError, IndexError):
4562 if expected_type
is None or isinstance(v
, expected_type
):
4566 def merge_dicts(*dicts
):
4568 for a_dict
in dicts
:
4569 for k
, v
in a_dict
.items():
4573 or (isinstance(v
, compat_str
) and v
4574 and isinstance(merged
[k
], compat_str
)
4575 and not merged
[k
])):
4580 def encode_compat_str(string
, encoding
=preferredencoding(), errors
='strict'):
4581 return string
if isinstance(string
, compat_str
) else compat_str(string
, encoding
, errors
)
4593 TV_PARENTAL_GUIDELINES
= {
4603 def parse_age_limit(s
):
4605 return s
if 0 <= s
<= 21 else None
4606 if not isinstance(s
, compat_basestring
):
4608 m
= re
.match(r
'^(?P<age>\d{1,2})\+?$', s
)
4610 return int(m
.group('age'))
4613 return US_RATINGS
[s
]
4614 m
= re
.match(r
'^TV[_-]?(%s)$' % '|'.join(k
[3:] for k
in TV_PARENTAL_GUIDELINES
), s
)
4616 return TV_PARENTAL_GUIDELINES
['TV-' + m
.group(1)]
4620 def strip_jsonp(code
):
4623 (?:window\.)?(?P<func_name>[a-zA-Z0-9_.$]*)
4624 (?:\s*&&\s*(?P=func_name))?
4625 \s*\(\s*(?P<callback_data>.*)\);?
4626 \s*?(?://[^\n]*)*$''',
4627 r
'\g<callback_data>', code
)
4630 def js_to_json(code
, vars={}):
4631 # vars is a dict of var, val pairs to substitute
4632 COMMENT_RE
= r
'/\*(?:(?!\*/).)*?\*/|//[^\n]*\n'
4633 SKIP_RE
= r
'\s*(?:{comment})?\s*'.format(comment
=COMMENT_RE
)
4635 (r
'(?s)^(0[xX][0-9a-fA-F]+){skip}:?$'.format(skip
=SKIP_RE
), 16),
4636 (r
'(?s)^(0+[0-7]+){skip}:?$'.format(skip
=SKIP_RE
), 8),
4641 if v
in ('true', 'false', 'null'):
4643 elif v
in ('undefined', 'void 0'):
4645 elif v
.startswith('/*') or v
.startswith('//') or v
.startswith('!') or v
== ',':
4648 if v
[0] in ("'", '"'):
4649 v
= re
.sub(r
'(?s)\\.|"', lambda m
: {
4654 }.get(m
.group(0), m
.group(0)), v
[1:-1])
4656 for regex
, base
in INTEGER_TABLE
:
4657 im
= re
.match(regex
, v
)
4659 i
= int(im
.group(1), base
)
4660 return '"%d":' % i
if v
.endswith(':') else '%d' % i
4667 return re
.sub(r
'''(?sx)
4668 "(?:[^"\\]*(?:\\\\|\\['"nurtbfx/\n]))*[^"\\]*"|
4669 '(?:[^'\\]*(?:\\\\|\\['"nurtbfx/\n]))*[^'\\]*'|
4670 {comment}|,(?={skip}[\]}}])|
4671 void\s0|(?:(?<![0-9])[eE]|[a-df-zA-DF-Z_$])[.a-zA-Z_$0-9]*|
4672 \b(?:0[xX][0-9a-fA-F]+|0+[0-7]+)(?:{skip}:)?|
4675 '''.format(comment
=COMMENT_RE
, skip
=SKIP_RE
), fix_kv
, code
)
4678 def qualities(quality_ids
):
4679 """ Get a numeric quality value out of a list of possible values """
4682 return quality_ids
.index(qid
)
4688 POSTPROCESS_WHEN
= {'pre_process', 'before_dl', 'after_move', 'post_process', 'after_video', 'playlist'}
4692 'default': '%(title)s [%(id)s].%(ext)s',
4693 'chapter': '%(title)s - %(section_number)03d %(section_title)s [%(id)s].%(ext)s',
4699 'description': 'description',
4700 'annotation': 'annotations.xml',
4701 'infojson': 'info.json',
4704 'pl_thumbnail': None,
4705 'pl_description': 'description',
4706 'pl_infojson': 'info.json',
4709 # As of [1] format syntax is:
4710 # %[mapping_key][conversion_flags][minimum_width][.precision][length_modifier]type
4711 # 1. https://docs.python.org/2/library/stdtypes.html#string-formatting
4712 STR_FORMAT_RE_TMPL
= r
'''(?x)
4713 (?<!%)(?P<prefix>(?:%%)*)
4715 (?P<has_key>\((?P<key>{0})\))?
4717 (?P<conversion>[#0\-+ ]+)?
4719 (?P<precision>\.\d+)?
4720 (?P<len_mod>[hlL])? # unused in python
4721 {1} # conversion type
4726 STR_FORMAT_TYPES
= 'diouxXeEfFgGcrs'
4729 def limit_length(s
, length
):
4730 """ Add ellipses to overly long strings """
4735 return s
[:length
- len(ELLIPSES
)] + ELLIPSES
4739 def version_tuple(v
):
4740 return tuple(int(e
) for e
in re
.split(r
'[-.]', v
))
4743 def is_outdated_version(version
, limit
, assume_new
=True):
4745 return not assume_new
4747 return version_tuple(version
) < version_tuple(limit
)
4749 return not assume_new
4752 def ytdl_is_updateable():
4753 """ Returns if yt-dlp can be updated with -U """
4755 from .update
import is_non_updateable
4757 return not is_non_updateable()
4760 def args_to_str(args
):
4761 # Get a short string representation for a subprocess command
4762 return ' '.join(compat_shlex_quote(a
) for a
in args
)
4765 def error_to_compat_str(err
):
4767 # On python 2 error byte string must be decoded with proper
4768 # encoding rather than ascii
4769 if sys
.version_info
[0] < 3:
4770 err_str
= err_str
.decode(preferredencoding())
4774 def mimetype2ext(mt
):
4778 mt
, _
, params
= mt
.partition(';')
4783 # Per RFC 3003, audio/mpeg can be .mp1, .mp2 or .mp3. Here use .mp3 as
4784 # it's the most popular one
4785 'audio/mpeg': 'mp3',
4786 'audio/x-wav': 'wav',
4788 'audio/wave': 'wav',
4791 ext
= FULL_MAP
.get(mt
)
4797 'smptett+xml': 'tt',
4801 'x-mp4-fragmented': 'mp4',
4802 'x-ms-sami': 'sami',
4805 'x-mpegurl': 'm3u8',
4806 'vnd.apple.mpegurl': 'm3u8',
4810 'vnd.ms-sstr+xml': 'ism',
4814 'filmstrip+json': 'fs',
4818 _
, _
, subtype
= mt
.rpartition('/')
4819 ext
= SUBTYPE_MAP
.get(subtype
.lower())
4830 _
, _
, suffix
= subtype
.partition('+')
4831 ext
= SUFFIX_MAP
.get(suffix
)
4835 return subtype
.replace('+', '.')
4838 def ext2mimetype(ext_or_url
):
4841 if '.' not in ext_or_url
:
4842 ext_or_url
= f
'file.{ext_or_url}'
4843 return mimetypes
.guess_type(ext_or_url
)[0]
4846 def parse_codecs(codecs_str
):
4847 # http://tools.ietf.org/html/rfc6381
4850 split_codecs
= list(filter(None, map(
4851 str.strip
, codecs_str
.strip().strip(',').split(','))))
4852 vcodec
, acodec
, tcodec
, hdr
= None, None, None, None
4853 for full_codec
in split_codecs
:
4854 parts
= full_codec
.split('.')
4855 codec
= parts
[0].replace('0', '')
4856 if codec
in ('avc1', 'avc2', 'avc3', 'avc4', 'vp9', 'vp8', 'hev1', 'hev2',
4857 'h263', 'h264', 'mp4v', 'hvc1', 'av1', 'theora', 'dvh1', 'dvhe'):
4859 vcodec
= '.'.join(parts
[:4]) if codec
in ('vp9', 'av1', 'hvc1') else full_codec
4860 if codec
in ('dvh1', 'dvhe'):
4862 elif codec
== 'av1' and len(parts
) > 3 and parts
[3] == '10':
4864 elif full_codec
.replace('0', '').startswith('vp9.2'):
4866 elif codec
in ('flac', 'mp4a', 'opus', 'vorbis', 'mp3', 'aac', 'ac-3', 'ec-3', 'eac3', 'dtsc', 'dtse', 'dtsh', 'dtsl'):
4869 elif codec
in ('stpp', 'wvtt',):
4873 write_string('WARNING: Unknown codec %s\n' % full_codec
, sys
.stderr
)
4874 if vcodec
or acodec
or tcodec
:
4876 'vcodec': vcodec
or 'none',
4877 'acodec': acodec
or 'none',
4878 'dynamic_range': hdr
,
4879 **({'tcodec': tcodec}
if tcodec
is not None else {}),
4881 elif len(split_codecs
) == 2:
4883 'vcodec': split_codecs
[0],
4884 'acodec': split_codecs
[1],
4889 def urlhandle_detect_ext(url_handle
):
4890 getheader
= url_handle
.headers
.get
4892 cd
= getheader('Content-Disposition')
4894 m
= re
.match(r
'attachment;\s*filename="(?P<filename>[^"]+)"', cd
)
4896 e
= determine_ext(m
.group('filename'), default_ext
=None)
4900 return mimetype2ext(getheader('Content-Type'))
4903 def encode_data_uri(data
, mime_type
):
4904 return 'data:%s;base64,%s' % (mime_type
, base64
.b64encode(data
).decode('ascii'))
4907 def age_restricted(content_limit
, age_limit
):
4908 """ Returns True iff the content should be blocked """
4910 if age_limit
is None: # No limit set
4912 if content_limit
is None:
4913 return False # Content available for everyone
4914 return age_limit
< content_limit
4917 def is_html(first_bytes
):
4918 """ Detect whether a file contains HTML by examining its first bytes. """
4921 (b
'\xef\xbb\xbf', 'utf-8'),
4922 (b
'\x00\x00\xfe\xff', 'utf-32-be'),
4923 (b
'\xff\xfe\x00\x00', 'utf-32-le'),
4924 (b
'\xff\xfe', 'utf-16-le'),
4925 (b
'\xfe\xff', 'utf-16-be'),
4927 for bom
, enc
in BOMS
:
4928 if first_bytes
.startswith(bom
):
4929 s
= first_bytes
[len(bom
):].decode(enc
, 'replace')
4932 s
= first_bytes
.decode('utf-8', 'replace')
4934 return re
.match(r
'^\s*<', s
)
4937 def determine_protocol(info_dict
):
4938 protocol
= info_dict
.get('protocol')
4939 if protocol
is not None:
4942 url
= sanitize_url(info_dict
['url'])
4943 if url
.startswith('rtmp'):
4945 elif url
.startswith('mms'):
4947 elif url
.startswith('rtsp'):
4950 ext
= determine_ext(url
)
4956 return compat_urllib_parse_urlparse(url
).scheme
4959 def render_table(header_row
, data
, delim
=False, extra_gap
=0, hide_empty
=False):
4960 """ Render a list of rows, each as a list of values.
4961 Text after a \t will be right aligned """
4963 return len(remove_terminal_sequences(string
).replace('\t', ''))
4965 def get_max_lens(table
):
4966 return [max(width(str(v
)) for v
in col
) for col
in zip(*table
)]
4968 def filter_using_list(row
, filterArray
):
4969 return [col
for (take
, col
) in zip(filterArray
, row
) if take
]
4972 max_lens
= get_max_lens(data
)
4973 header_row
= filter_using_list(header_row
, max_lens
)
4974 data
= [filter_using_list(row
, max_lens
) for row
in data
]
4976 table
= [header_row
] + data
4977 max_lens
= get_max_lens(table
)
4980 table
= [header_row
, [delim
* (ml
+ extra_gap
) for ml
in max_lens
]] + data
4981 table
[1][-1] = table
[1][-1][:-extra_gap
] # Remove extra_gap from end of delimiter
4983 for pos
, text
in enumerate(map(str, row
)):
4985 row
[pos
] = text
.replace('\t', ' ' * (max_lens
[pos
] - width(text
))) + ' ' * extra_gap
4987 row
[pos
] = text
+ ' ' * (max_lens
[pos
] - width(text
) + extra_gap
)
4988 ret
= '\n'.join(''.join(row
).rstrip() for row
in table
)
4992 def _match_one(filter_part
, dct
, incomplete
):
4993 # TODO: Generalize code with YoutubeDL._build_format_filter
4994 STRING_OPERATORS
= {
4995 '*=': operator
.contains
,
4996 '^=': lambda attr
, value
: attr
.startswith(value
),
4997 '$=': lambda attr
, value
: attr
.endswith(value
),
4998 '~=': lambda attr
, value
: re
.search(value
, attr
),
5000 COMPARISON_OPERATORS
= {
5002 '<=': operator
.le
, # "<=" must be defined above "<"
5009 operator_rex
= re
.compile(r
'''(?x)\s*
5011 \s*(?P<negation>!\s*)?(?P<op>%s)(?P<none_inclusive>\s*\?)?\s*
5013 (?P<quote>["\'])(?P
<quotedstrval
>.+?
)(?P
=quote
)|
5017 ''' % '|'.join(map(re.escape, COMPARISON_OPERATORS.keys())))
5018 m = operator_rex.search(filter_part)
5021 unnegated_op = COMPARISON_OPERATORS[m['op']]
5023 op = lambda attr, value: not unnegated_op(attr, value)
5026 comparison_value = m['quotedstrval'] or m['strval'] or m['intval']
5028 comparison_value = comparison_value.replace(r'\%s' % m['quote'], m['quote'])
5029 actual_value = dct.get(m['key'])
5030 numeric_comparison = None
5031 if isinstance(actual_value, compat_numeric_types):
5032 # If the original field is a string and matching comparisonvalue is
5033 # a number we should respect the origin of the original field
5034 # and process comparison value as a string (see
5035 # https://github.com/ytdl-org/youtube-dl/issues/11082)
5037 numeric_comparison = int(comparison_value)
5039 numeric_comparison = parse_filesize(comparison_value)
5040 if numeric_comparison is None:
5041 numeric_comparison = parse_filesize(f'{comparison_value}B')
5042 if numeric_comparison is None:
5043 numeric_comparison = parse_duration(comparison_value)
5044 if numeric_comparison is not None and m['op'] in STRING_OPERATORS:
5045 raise ValueError('Operator %s only supports string values!' % m['op'])
5046 if actual_value is None:
5047 return incomplete or m['none_inclusive']
5048 return op(actual_value, comparison_value if numeric_comparison is None else numeric_comparison)
5051 '': lambda v: (v is True) if isinstance(v, bool) else (v is not None),
5052 '!': lambda v: (v is False) if isinstance(v, bool) else (v is None),
5054 operator_rex = re.compile(r'''(?x
)\s
*
5055 (?P
<op
>%s)\s
*(?P
<key
>[a
-z_
]+)
5057 ''' % '|'.join(map(re.escape, UNARY_OPERATORS.keys())))
5058 m = operator_rex.search(filter_part)
5060 op = UNARY_OPERATORS[m.group('op')]
5061 actual_value = dct.get(m.group('key'))
5062 if incomplete and actual_value is None:
5064 return op(actual_value)
5066 raise ValueError('Invalid filter part %r' % filter_part)
5069 def match_str(filter_str, dct, incomplete=False):
5070 """ Filter a dictionary with a simple string syntax. Returns True (=passes filter) or false
5071 When incomplete, all conditions passes on missing fields
5074 _match_one(filter_part.replace(r'\&', '&'), dct, incomplete)
5075 for filter_part in re.split(r'(?<!\\)&', filter_str))
5078 def match_filter_func(filter_str):
5079 def _match_func(info_dict, *args, **kwargs):
5080 if match_str(filter_str, info_dict, *args, **kwargs):
5083 video_title = info_dict.get('title', info_dict.get('id', 'video'))
5084 return '%s does not pass filter %s, skipping ..' % (video_title, filter_str)
5088 def parse_dfxp_time_expr(time_expr):
5092 mobj = re.match(r'^(?P<time_offset>\d+(?:\.\d+)?)s?$', time_expr)
5094 return float(mobj.group('time_offset'))
5096 mobj = re.match(r'^(\d+):(\d\d):(\d\d(?:(?:\.|:)\d+)?)$', time_expr)
5098 return 3600 * int(mobj.group(1)) + 60 * int(mobj.group(2)) + float(mobj.group(3).replace(':', '.'))
5101 def srt_subtitles_timecode(seconds):
5102 return '%02d:%02d:%02d,%03d' % timetuple_from_msec(seconds * 1000)
5105 def ass_subtitles_timecode(seconds):
5106 time = timetuple_from_msec(seconds * 1000)
5107 return '%01d:%02d:%02d.%02d' % (*time[:-1], time.milliseconds / 10)
5110 def dfxp2srt(dfxp_data):
5112 @param dfxp_data A
bytes-like
object containing DFXP data
5113 @returns A
unicode object containing converted SRT data
5115 LEGACY_NAMESPACES = (
5116 (b'http://www.w3.org/ns/ttml', [
5117 b'http://www.w3.org/2004/11/ttaf1',
5118 b'http://www.w3.org/2006/04/ttaf1',
5119 b'http://www.w3.org/2006/10/ttaf1',
5121 (b'http://www.w3.org/ns/ttml#styling', [
5122 b'http://www.w3.org/ns/ttml#style',
5126 SUPPORTED_STYLING = [
5135 _x = functools.partial(xpath_with_ns, ns_map={
5136 'xml': 'http://www.w3.org/XML/1998/namespace',
5137 'ttml': 'http://www.w3.org/ns/ttml',
5138 'tts': 'http://www.w3.org/ns/ttml#styling',
5144 class TTMLPElementParser(object):
5146 _unclosed_elements = []
5147 _applied_styles = []
5149 def start(self, tag, attrib):
5150 if tag in (_x('ttml:br'), 'br'):
5153 unclosed_elements = []
5155 element_style_id = attrib.get('style')
5157 style.update(default_style)
5158 if element_style_id:
5159 style.update(styles.get(element_style_id, {}))
5160 for prop in SUPPORTED_STYLING:
5161 prop_val = attrib.get(_x('tts:' + prop))
5163 style[prop] = prop_val
5166 for k, v in sorted(style.items()):
5167 if self._applied_styles and self._applied_styles[-1].get(k) == v:
5170 font += ' color="%s"' % v
5171 elif k == 'fontSize':
5172 font += ' size="%s"' % v
5173 elif k == 'fontFamily':
5174 font += ' face="%s"' % v
5175 elif k == 'fontWeight' and v == 'bold':
5177 unclosed_elements.append('b')
5178 elif k == 'fontStyle' and v == 'italic':
5180 unclosed_elements.append('i')
5181 elif k == 'textDecoration' and v == 'underline':
5183 unclosed_elements.append('u')
5185 self._out += '<font' + font + '>'
5186 unclosed_elements.append('font')
5188 if self._applied_styles:
5189 applied_style.update(self._applied_styles[-1])
5190 applied_style.update(style)
5191 self._applied_styles.append(applied_style)
5192 self._unclosed_elements.append(unclosed_elements)
5195 if tag not in (_x('ttml:br'), 'br'):
5196 unclosed_elements = self._unclosed_elements.pop()
5197 for element in reversed(unclosed_elements):
5198 self._out += '</%s>' % element
5199 if unclosed_elements and self._applied_styles:
5200 self._applied_styles.pop()
5202 def data(self, data):
5206 return self._out.strip()
5208 def parse_node(node):
5209 target = TTMLPElementParser()
5210 parser = xml.etree.ElementTree.XMLParser(target=target)
5211 parser.feed(xml.etree.ElementTree.tostring(node))
5212 return parser.close()
5214 for k, v in LEGACY_NAMESPACES:
5216 dfxp_data = dfxp_data.replace(ns, k)
5218 dfxp = compat_etree_fromstring(dfxp_data)
5220 paras = dfxp.findall(_x('.//ttml:p')) or dfxp.findall('.//p')
5223 raise ValueError('Invalid dfxp/TTML subtitle')
5227 for style in dfxp.findall(_x('.//ttml:style')):
5228 style_id = style.get('id') or style.get(_x('xml:id'))
5231 parent_style_id = style.get('style')
5233 if parent_style_id not in styles:
5236 styles[style_id] = styles[parent_style_id].copy()
5237 for prop in SUPPORTED_STYLING:
5238 prop_val = style.get(_x('tts:' + prop))
5240 styles.setdefault(style_id, {})[prop] = prop_val
5246 for p in ('body', 'div'):
5247 ele = xpath_element(dfxp, [_x('.//ttml:' + p), './/' + p])
5250 style = styles.get(ele.get('style'))
5253 default_style.update(style)
5255 for para, index in zip(paras, itertools.count(1)):
5256 begin_time = parse_dfxp_time_expr(para.attrib.get('begin'))
5257 end_time = parse_dfxp_time_expr(para.attrib.get('end'))
5258 dur = parse_dfxp_time_expr(para.attrib.get('dur'))
5259 if begin_time is None:
5264 end_time = begin_time + dur
5265 out.append('%d\n%s --> %s\n%s\n\n' % (
5267 srt_subtitles_timecode(begin_time),
5268 srt_subtitles_timecode(end_time),
5274 def cli_option(params, command_option, param):
5275 param = params.get(param)
5277 param = compat_str(param)
5278 return [command_option, param] if param is not None else []
5281 def cli_bool_option(params, command_option, param, true_value='true', false_value='false', separator=None):
5282 param = params.get(param)
5285 assert isinstance(param, bool)
5287 return [command_option + separator + (true_value if param else false_value)]
5288 return [command_option, true_value if param else false_value]
5291 def cli_valueless_option(params, command_option, param, expected_value=True):
5292 param = params.get(param)
5293 return [command_option] if param == expected_value else []
5296 def cli_configuration_args(argdict, keys, default=[], use_compat=True):
5297 if isinstance(argdict, (list, tuple)): # for backward compatibility
5304 assert isinstance(argdict, dict)
5306 assert isinstance(keys, (list, tuple))
5307 for key_list in keys:
5308 arg_list = list(filter(
5309 lambda x: x is not None,
5310 [argdict.get(key.lower()) for key in variadic(key_list)]))
5312 return [arg for args in arg_list for arg in args]
5316 def _configuration_args(main_key, argdict, exe, keys=None, default=[], use_compat=True):
5317 main_key, exe = main_key.lower(), exe.lower()
5318 root_key = exe if main_key == exe else f'{main_key}+{exe}'
5319 keys = [f'{root_key}{k}' for k in (keys or [''])]
5320 if root_key in keys:
5322 keys.append((main_key, exe))
5323 keys.append('default')
5326 return cli_configuration_args(argdict, keys, default, use_compat)
5329 class ISO639Utils(object):
5330 # See http://www.loc.gov/standards/iso639-2/ISO-639-2_utf-8.txt
5389 'iw': 'heb', # Replaced by he in 1989 revision
5399 'in': 'ind', # Replaced by id in 1989 revision
5514 'ji': 'yid', # Replaced by yi in 1989 revision
5522 def short2long(cls, code):
5523 """Convert language code from ISO 639-1 to ISO 639-2/T"""
5524 return cls._lang_map.get(code[:2])
5527 def long2short(cls, code):
5528 """Convert language code from ISO 639-2/T to ISO 639-1"""
5529 for short_name, long_name in cls._lang_map.items():
5530 if long_name == code:
5534 class ISO3166Utils(object):
5535 # From http://data.okfn.org/data/core/country-list
5537 'AF': 'Afghanistan',
5538 'AX': 'Åland Islands',
5541 'AS': 'American Samoa',
5546 'AG': 'Antigua and Barbuda',
5563 'BO': 'Bolivia, Plurinational State of',
5564 'BQ': 'Bonaire, Sint Eustatius and Saba',
5565 'BA': 'Bosnia and Herzegovina',
5567 'BV': 'Bouvet Island',
5569 'IO': 'British Indian Ocean Territory',
5570 'BN': 'Brunei Darussalam',
5572 'BF': 'Burkina Faso',
5578 'KY': 'Cayman Islands',
5579 'CF': 'Central African Republic',
5583 'CX': 'Christmas Island',
5584 'CC': 'Cocos (Keeling) Islands',
5588 'CD': 'Congo, the Democratic Republic of the',
5589 'CK': 'Cook Islands',
5591 'CI': 'Côte d\'Ivoire',
5596 'CZ': 'Czech Republic',
5600 'DO': 'Dominican Republic',
5603 'SV': 'El Salvador',
5604 'GQ': 'Equatorial Guinea',
5608 'FK': 'Falkland Islands (Malvinas)',
5609 'FO': 'Faroe Islands',
5613 'GF': 'French Guiana',
5614 'PF': 'French Polynesia',
5615 'TF': 'French Southern Territories',
5630 'GW': 'Guinea-Bissau',
5633 'HM': 'Heard Island and McDonald Islands',
5634 'VA': 'Holy See (Vatican City State)',
5641 'IR': 'Iran, Islamic Republic of',
5644 'IM': 'Isle of Man',
5654 'KP': 'Korea, Democratic People\'s Republic of',
5655 'KR': 'Korea, Republic of',
5658 'LA': 'Lao People\'s Democratic Republic',
5664 'LI': 'Liechtenstein',
5668 'MK': 'Macedonia, the Former Yugoslav Republic of',
5675 'MH': 'Marshall Islands',
5681 'FM': 'Micronesia, Federated States of',
5682 'MD': 'Moldova, Republic of',
5693 'NL': 'Netherlands',
5694 'NC': 'New Caledonia',
5695 'NZ': 'New Zealand',
5700 'NF': 'Norfolk Island',
5701 'MP': 'Northern Mariana Islands',
5706 'PS': 'Palestine, State of',
5708 'PG': 'Papua New Guinea',
5711 'PH': 'Philippines',
5715 'PR': 'Puerto Rico',
5719 'RU': 'Russian Federation',
5721 'BL': 'Saint Barthélemy',
5722 'SH': 'Saint Helena, Ascension and Tristan da Cunha',
5723 'KN': 'Saint Kitts and Nevis',
5724 'LC': 'Saint Lucia',
5725 'MF': 'Saint Martin (French part)',
5726 'PM': 'Saint Pierre and Miquelon',
5727 'VC': 'Saint Vincent and the Grenadines',
5730 'ST': 'Sao Tome and Principe',
5731 'SA': 'Saudi Arabia',
5735 'SL': 'Sierra Leone',
5737 'SX': 'Sint Maarten (Dutch part)',
5740 'SB': 'Solomon Islands',
5742 'ZA': 'South Africa',
5743 'GS': 'South Georgia and the South Sandwich Islands',
5744 'SS': 'South Sudan',
5749 'SJ': 'Svalbard and Jan Mayen',
5752 'CH': 'Switzerland',
5753 'SY': 'Syrian Arab Republic',
5754 'TW': 'Taiwan, Province of China',
5756 'TZ': 'Tanzania, United Republic of',
5758 'TL': 'Timor-Leste',
5762 'TT': 'Trinidad and Tobago',
5765 'TM': 'Turkmenistan',
5766 'TC': 'Turks and Caicos Islands',
5770 'AE': 'United Arab Emirates',
5771 'GB': 'United Kingdom',
5772 'US': 'United States',
5773 'UM': 'United States Minor Outlying Islands',
5777 'VE': 'Venezuela, Bolivarian Republic of',
5779 'VG': 'Virgin Islands, British',
5780 'VI': 'Virgin Islands, U.S.',
5781 'WF': 'Wallis and Futuna',
5782 'EH': 'Western Sahara',
5789 def short2full(cls, code):
5790 """Convert an ISO 3166-2 country code to the corresponding full name"""
5791 return cls._country_map.get(code.upper())
5794 class GeoUtils(object):
5795 # Major IPv4 address blocks per country
5797 'AD': '46.172.224.0/19',
5798 'AE': '94.200.0.0/13',
5799 'AF': '149.54.0.0/17',
5800 'AG': '209.59.64.0/18',
5801 'AI': '204.14.248.0/21',
5802 'AL': '46.99.0.0/16',
5803 'AM': '46.70.0.0/15',
5804 'AO': '105.168.0.0/13',
5805 'AP': '182.50.184.0/21',
5806 'AQ': '23.154.160.0/24',
5807 'AR': '181.0.0.0/12',
5808 'AS': '202.70.112.0/20',
5809 'AT': '77.116.0.0/14',
5810 'AU': '1.128.0.0/11',
5811 'AW': '181.41.0.0/18',
5812 'AX': '185.217.4.0/22',
5813 'AZ': '5.197.0.0/16',
5814 'BA': '31.176.128.0/17',
5815 'BB': '65.48.128.0/17',
5816 'BD': '114.130.0.0/16',
5818 'BF': '102.178.0.0/15',
5819 'BG': '95.42.0.0/15',
5820 'BH': '37.131.0.0/17',
5821 'BI': '154.117.192.0/18',
5822 'BJ': '137.255.0.0/16',
5823 'BL': '185.212.72.0/23',
5824 'BM': '196.12.64.0/18',
5825 'BN': '156.31.0.0/16',
5826 'BO': '161.56.0.0/16',
5827 'BQ': '161.0.80.0/20',
5828 'BR': '191.128.0.0/12',
5829 'BS': '24.51.64.0/18',
5830 'BT': '119.2.96.0/19',
5831 'BW': '168.167.0.0/16',
5832 'BY': '178.120.0.0/13',
5833 'BZ': '179.42.192.0/18',
5834 'CA': '99.224.0.0/11',
5835 'CD': '41.243.0.0/16',
5836 'CF': '197.242.176.0/21',
5837 'CG': '160.113.0.0/16',
5838 'CH': '85.0.0.0/13',
5839 'CI': '102.136.0.0/14',
5840 'CK': '202.65.32.0/19',
5841 'CL': '152.172.0.0/14',
5842 'CM': '102.244.0.0/14',
5843 'CN': '36.128.0.0/10',
5844 'CO': '181.240.0.0/12',
5845 'CR': '201.192.0.0/12',
5846 'CU': '152.206.0.0/15',
5847 'CV': '165.90.96.0/19',
5848 'CW': '190.88.128.0/17',
5849 'CY': '31.153.0.0/16',
5850 'CZ': '88.100.0.0/14',
5852 'DJ': '197.241.0.0/17',
5853 'DK': '87.48.0.0/12',
5854 'DM': '192.243.48.0/20',
5855 'DO': '152.166.0.0/15',
5856 'DZ': '41.96.0.0/12',
5857 'EC': '186.68.0.0/15',
5858 'EE': '90.190.0.0/15',
5859 'EG': '156.160.0.0/11',
5860 'ER': '196.200.96.0/20',
5861 'ES': '88.0.0.0/11',
5862 'ET': '196.188.0.0/14',
5863 'EU': '2.16.0.0/13',
5864 'FI': '91.152.0.0/13',
5865 'FJ': '144.120.0.0/16',
5866 'FK': '80.73.208.0/21',
5867 'FM': '119.252.112.0/20',
5868 'FO': '88.85.32.0/19',
5870 'GA': '41.158.0.0/15',
5872 'GD': '74.122.88.0/21',
5873 'GE': '31.146.0.0/16',
5874 'GF': '161.22.64.0/18',
5875 'GG': '62.68.160.0/19',
5876 'GH': '154.160.0.0/12',
5877 'GI': '95.164.0.0/16',
5878 'GL': '88.83.0.0/19',
5879 'GM': '160.182.0.0/15',
5880 'GN': '197.149.192.0/18',
5881 'GP': '104.250.0.0/19',
5882 'GQ': '105.235.224.0/20',
5883 'GR': '94.64.0.0/13',
5884 'GT': '168.234.0.0/16',
5885 'GU': '168.123.0.0/16',
5886 'GW': '197.214.80.0/20',
5887 'GY': '181.41.64.0/18',
5888 'HK': '113.252.0.0/14',
5889 'HN': '181.210.0.0/16',
5890 'HR': '93.136.0.0/13',
5891 'HT': '148.102.128.0/17',
5892 'HU': '84.0.0.0/14',
5893 'ID': '39.192.0.0/10',
5894 'IE': '87.32.0.0/12',
5895 'IL': '79.176.0.0/13',
5896 'IM': '5.62.80.0/20',
5897 'IN': '117.192.0.0/10',
5898 'IO': '203.83.48.0/21',
5899 'IQ': '37.236.0.0/14',
5900 'IR': '2.176.0.0/12',
5901 'IS': '82.221.0.0/16',
5902 'IT': '79.0.0.0/10',
5903 'JE': '87.244.64.0/18',
5904 'JM': '72.27.0.0/17',
5905 'JO': '176.29.0.0/16',
5906 'JP': '133.0.0.0/8',
5907 'KE': '105.48.0.0/12',
5908 'KG': '158.181.128.0/17',
5909 'KH': '36.37.128.0/17',
5910 'KI': '103.25.140.0/22',
5911 'KM': '197.255.224.0/20',
5912 'KN': '198.167.192.0/19',
5913 'KP': '175.45.176.0/22',
5914 'KR': '175.192.0.0/10',
5915 'KW': '37.36.0.0/14',
5916 'KY': '64.96.0.0/15',
5917 'KZ': '2.72.0.0/13',
5918 'LA': '115.84.64.0/18',
5919 'LB': '178.135.0.0/16',
5920 'LC': '24.92.144.0/20',
5921 'LI': '82.117.0.0/19',
5922 'LK': '112.134.0.0/15',
5923 'LR': '102.183.0.0/16',
5924 'LS': '129.232.0.0/17',
5925 'LT': '78.56.0.0/13',
5926 'LU': '188.42.0.0/16',
5927 'LV': '46.109.0.0/16',
5928 'LY': '41.252.0.0/14',
5929 'MA': '105.128.0.0/11',
5930 'MC': '88.209.64.0/18',
5931 'MD': '37.246.0.0/16',
5932 'ME': '178.175.0.0/17',
5933 'MF': '74.112.232.0/21',
5934 'MG': '154.126.0.0/17',
5935 'MH': '117.103.88.0/21',
5936 'MK': '77.28.0.0/15',
5937 'ML': '154.118.128.0/18',
5938 'MM': '37.111.0.0/17',
5939 'MN': '49.0.128.0/17',
5940 'MO': '60.246.0.0/16',
5941 'MP': '202.88.64.0/20',
5942 'MQ': '109.203.224.0/19',
5943 'MR': '41.188.64.0/18',
5944 'MS': '208.90.112.0/22',
5945 'MT': '46.11.0.0/16',
5946 'MU': '105.16.0.0/12',
5947 'MV': '27.114.128.0/18',
5948 'MW': '102.70.0.0/15',
5949 'MX': '187.192.0.0/11',
5950 'MY': '175.136.0.0/13',
5951 'MZ': '197.218.0.0/15',
5952 'NA': '41.182.0.0/16',
5953 'NC': '101.101.0.0/18',
5954 'NE': '197.214.0.0/18',
5955 'NF': '203.17.240.0/22',
5956 'NG': '105.112.0.0/12',
5957 'NI': '186.76.0.0/15',
5958 'NL': '145.96.0.0/11',
5959 'NO': '84.208.0.0/13',
5960 'NP': '36.252.0.0/15',
5961 'NR': '203.98.224.0/19',
5962 'NU': '49.156.48.0/22',
5963 'NZ': '49.224.0.0/14',
5964 'OM': '5.36.0.0/15',
5965 'PA': '186.72.0.0/15',
5966 'PE': '186.160.0.0/14',
5967 'PF': '123.50.64.0/18',
5968 'PG': '124.240.192.0/19',
5969 'PH': '49.144.0.0/13',
5970 'PK': '39.32.0.0/11',
5971 'PL': '83.0.0.0/11',
5972 'PM': '70.36.0.0/20',
5973 'PR': '66.50.0.0/16',
5974 'PS': '188.161.0.0/16',
5975 'PT': '85.240.0.0/13',
5976 'PW': '202.124.224.0/20',
5977 'PY': '181.120.0.0/14',
5978 'QA': '37.210.0.0/15',
5979 'RE': '102.35.0.0/16',
5980 'RO': '79.112.0.0/13',
5981 'RS': '93.86.0.0/15',
5982 'RU': '5.136.0.0/13',
5983 'RW': '41.186.0.0/16',
5984 'SA': '188.48.0.0/13',
5985 'SB': '202.1.160.0/19',
5986 'SC': '154.192.0.0/11',
5987 'SD': '102.120.0.0/13',
5988 'SE': '78.64.0.0/12',
5989 'SG': '8.128.0.0/10',
5990 'SI': '188.196.0.0/14',
5991 'SK': '78.98.0.0/15',
5992 'SL': '102.143.0.0/17',
5993 'SM': '89.186.32.0/19',
5994 'SN': '41.82.0.0/15',
5995 'SO': '154.115.192.0/18',
5996 'SR': '186.179.128.0/17',
5997 'SS': '105.235.208.0/21',
5998 'ST': '197.159.160.0/19',
5999 'SV': '168.243.0.0/16',
6000 'SX': '190.102.0.0/20',
6002 'SZ': '41.84.224.0/19',
6003 'TC': '65.255.48.0/20',
6004 'TD': '154.68.128.0/19',
6005 'TG': '196.168.0.0/14',
6006 'TH': '171.96.0.0/13',
6007 'TJ': '85.9.128.0/18',
6008 'TK': '27.96.24.0/21',
6009 'TL': '180.189.160.0/20',
6010 'TM': '95.85.96.0/19',
6011 'TN': '197.0.0.0/11',
6012 'TO': '175.176.144.0/21',
6013 'TR': '78.160.0.0/11',
6014 'TT': '186.44.0.0/15',
6015 'TV': '202.2.96.0/19',
6016 'TW': '120.96.0.0/11',
6017 'TZ': '156.156.0.0/14',
6018 'UA': '37.52.0.0/14',
6019 'UG': '102.80.0.0/13',
6021 'UY': '167.56.0.0/13',
6022 'UZ': '84.54.64.0/18',
6023 'VA': '212.77.0.0/19',
6024 'VC': '207.191.240.0/21',
6025 'VE': '186.88.0.0/13',
6026 'VG': '66.81.192.0/20',
6027 'VI': '146.226.0.0/16',
6028 'VN': '14.160.0.0/11',
6029 'VU': '202.80.32.0/20',
6030 'WF': '117.20.32.0/21',
6031 'WS': '202.4.32.0/19',
6032 'YE': '134.35.0.0/16',
6033 'YT': '41.242.116.0/22',
6034 'ZA': '41.0.0.0/11',
6035 'ZM': '102.144.0.0/13',
6036 'ZW': '102.177.192.0/18',
6040 def random_ipv4(cls, code_or_block):
6041 if len(code_or_block) == 2:
6042 block = cls._country_ip_map.get(code_or_block.upper())
6046 block = code_or_block
6047 addr, preflen = block.split('/')
6048 addr_min = compat_struct_unpack('!L', socket.inet_aton(addr))[0]
6049 addr_max = addr_min | (0xffffffff >> int(preflen))
6050 return compat_str(socket.inet_ntoa(
6051 compat_struct_pack('!L', random.randint(addr_min, addr_max))))
6054 class PerRequestProxyHandler(compat_urllib_request.ProxyHandler):
6055 def __init__(self, proxies=None):
6056 # Set default handlers
6057 for type in ('http', 'https'):
6058 setattr(self, '%s_open' % type,
6059 lambda r, proxy='__noproxy__', type=type, meth=self.proxy_open:
6060 meth(r, proxy, type))
6061 compat_urllib_request.ProxyHandler.__init__(self, proxies)
6063 def proxy_open(self, req, proxy, type):
6064 req_proxy = req.headers.get('Ytdl-request-proxy')
6065 if req_proxy is not None:
6067 del req.headers['Ytdl-request-proxy']
6069 if proxy == '__noproxy__':
6070 return None # No Proxy
6071 if compat_urlparse.urlparse(proxy).scheme.lower() in ('socks', 'socks4', 'socks4a', 'socks5'):
6072 req.add_header('Ytdl-socks-proxy', proxy)
6073 # yt-dlp's http/https handlers do wrapping the socket with socks
6075 return compat_urllib_request.ProxyHandler.proxy_open(
6076 self, req, proxy, type)
6079 # Both long_to_bytes and bytes_to_long are adapted from PyCrypto, which is
6080 # released into Public Domain
6081 # https://github.com/dlitz/pycrypto/blob/master/lib/Crypto/Util/number.py#L387
6083 def long_to_bytes(n, blocksize=0):
6084 """long_to_bytes(n:long, blocksize:int) : string
6085 Convert a long integer to a byte string.
6087 If optional blocksize is given and greater than zero, pad the front of the
6088 byte string with binary zeros so that the length is a multiple of
6091 # after much testing, this algorithm was deemed to be the fastest
6095 s = compat_struct_pack('>I', n & 0xffffffff) + s
6097 # strip off leading zeros
6098 for i in range(len(s)):
6099 if s[i] != b'\000'[0]:
6102 # only happens when n == 0
6106 # add back some pad bytes. this could be done more efficiently w.r.t. the
6107 # de-padding being done above, but sigh...
6108 if blocksize > 0 and len(s) % blocksize:
6109 s = (blocksize - len(s) % blocksize) * b'\000' + s
6113 def bytes_to_long(s):
6114 """bytes_to_long(string) : long
6115 Convert a byte string to a long integer.
6117 This is (essentially) the inverse of long_to_bytes().
6122 extra = (4 - length % 4)
6123 s = b'\000' * extra + s
6124 length = length + extra
6125 for i in range(0, length, 4):
6126 acc = (acc << 32) + compat_struct_unpack('>I', s[i:i + 4])[0]
6130 def ohdave_rsa_encrypt(data, exponent, modulus):
6132 Implement OHDave
's RSA algorithm. See http://www.ohdave.com/rsa/
6135 data: data to encrypt, bytes-like object
6136 exponent, modulus: parameter e and N of RSA algorithm, both integer
6137 Output: hex string of encrypted data
6139 Limitation: supports one block encryption only
6142 payload = int(binascii.hexlify(data[::-1]), 16)
6143 encrypted = pow(payload, exponent, modulus)
6144 return '%x' % encrypted
6147 def pkcs1pad(data, length):
6149 Padding input data with PKCS#1 scheme
6151 @param {int[]} data input data
6152 @param {int} length target length
6153 @returns {int[]} padded data
6155 if len(data) > length - 11:
6156 raise ValueError('Input data too
long for PKCS
#1 padding')
6158 pseudo_random
= [random
.randint(0, 254) for _
in range(length
- len(data
) - 3)]
6159 return [0, 2] + pseudo_random
+ [0] + data
6162 def encode_base_n(num
, n
, table
=None):
6163 FULL_TABLE
= '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
6165 table
= FULL_TABLE
[:n
]
6168 raise ValueError('base %d exceeds table length %d' % (n
, len(table
)))
6175 ret
= table
[num
% n
] + ret
6180 def decode_packed_codes(code
):
6181 mobj
= re
.search(PACKED_CODES_RE
, code
)
6182 obfuscated_code
, base
, count
, symbols
= mobj
.groups()
6185 symbols
= symbols
.split('|')
6190 base_n_count
= encode_base_n(count
, base
)
6191 symbol_table
[base_n_count
] = symbols
[count
] or base_n_count
6194 r
'\b(\w+)\b', lambda mobj
: symbol_table
[mobj
.group(0)],
6198 def caesar(s
, alphabet
, shift
):
6203 alphabet
[(alphabet
.index(c
) + shift
) % l
] if c
in alphabet
else c
6208 return caesar(s
, r
'''!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~''', 47)
6211 def parse_m3u8_attributes(attrib
):
6213 for (key
, val
) in re
.findall(r
'(?P<key>[A-Z0-9-]+)=(?P<val>"[^"]+"|[^",]+)(?:,|$)', attrib
):
6214 if val
.startswith('"'):
6220 def urshift(val
, n
):
6221 return val
>> n
if val
>= 0 else (val
+ 0x100000000) >> n
6224 # Based on png2str() written by @gdkchan and improved by @yokrysty
6225 # Originally posted at https://github.com/ytdl-org/youtube-dl/issues/9706
6226 def decode_png(png_data
):
6227 # Reference: https://www.w3.org/TR/PNG/
6228 header
= png_data
[8:]
6230 if png_data
[:8] != b
'\x89PNG\x0d\x0a\x1a\x0a' or header
[4:8] != b
'IHDR':
6231 raise IOError('Not a valid PNG file.')
6233 int_map
= {1: '>B', 2: '>H', 4: '>I'}
6234 unpack_integer
= lambda x
: compat_struct_unpack(int_map
[len(x
)], x
)[0]
6239 length
= unpack_integer(header
[:4])
6242 chunk_type
= header
[:4]
6245 chunk_data
= header
[:length
]
6246 header
= header
[length
:]
6248 header
= header
[4:] # Skip CRC
6256 ihdr
= chunks
[0]['data']
6258 width
= unpack_integer(ihdr
[:4])
6259 height
= unpack_integer(ihdr
[4:8])
6263 for chunk
in chunks
:
6264 if chunk
['type'] == b
'IDAT':
6265 idat
+= chunk
['data']
6268 raise IOError('Unable to read PNG data.')
6270 decompressed_data
= bytearray(zlib
.decompress(idat
))
6275 def _get_pixel(idx
):
6280 for y
in range(height
):
6281 basePos
= y
* (1 + stride
)
6282 filter_type
= decompressed_data
[basePos
]
6286 pixels
.append(current_row
)
6288 for x
in range(stride
):
6289 color
= decompressed_data
[1 + basePos
+ x
]
6290 basex
= y
* stride
+ x
6295 left
= _get_pixel(basex
- 3)
6297 up
= _get_pixel(basex
- stride
)
6299 if filter_type
== 1: # Sub
6300 color
= (color
+ left
) & 0xff
6301 elif filter_type
== 2: # Up
6302 color
= (color
+ up
) & 0xff
6303 elif filter_type
== 3: # Average
6304 color
= (color
+ ((left
+ up
) >> 1)) & 0xff
6305 elif filter_type
== 4: # Paeth
6311 c
= _get_pixel(basex
- stride
- 3)
6319 if pa
<= pb
and pa
<= pc
:
6320 color
= (color
+ a
) & 0xff
6322 color
= (color
+ b
) & 0xff
6324 color
= (color
+ c
) & 0xff
6326 current_row
.append(color
)
6328 return width
, height
, pixels
6331 def write_xattr(path
, key
, value
):
6332 # This mess below finds the best xattr tool for the job
6334 # try the pyxattr module...
6337 if hasattr(xattr
, 'set'): # pyxattr
6338 # Unicode arguments are not supported in python-pyxattr until
6340 # See https://github.com/ytdl-org/youtube-dl/issues/5498
6341 pyxattr_required_version
= '0.5.0'
6342 if version_tuple(xattr
.__version
__) < version_tuple(pyxattr_required_version
):
6343 # TODO: fallback to CLI tools
6344 raise XAttrUnavailableError(
6345 'python-pyxattr is detected but is too old. '
6346 'yt-dlp requires %s or above while your version is %s. '
6347 'Falling back to other xattr implementations' % (
6348 pyxattr_required_version
, xattr
.__version
__))
6350 setxattr
= xattr
.set
6352 setxattr
= xattr
.setxattr
6355 setxattr(path
, key
, value
)
6356 except EnvironmentError as e
:
6357 raise XAttrMetadataError(e
.errno
, e
.strerror
)
6360 if compat_os_name
== 'nt':
6361 # Write xattrs to NTFS Alternate Data Streams:
6362 # http://en.wikipedia.org/wiki/NTFS#Alternate_data_streams_.28ADS.29
6363 assert ':' not in key
6364 assert os
.path
.exists(path
)
6366 ads_fn
= path
+ ':' + key
6368 with open(ads_fn
, 'wb') as f
:
6370 except EnvironmentError as e
:
6371 raise XAttrMetadataError(e
.errno
, e
.strerror
)
6373 user_has_setfattr
= check_executable('setfattr', ['--version'])
6374 user_has_xattr
= check_executable('xattr', ['-h'])
6376 if user_has_setfattr
or user_has_xattr
:
6378 value
= value
.decode('utf-8')
6379 if user_has_setfattr
:
6380 executable
= 'setfattr'
6381 opts
= ['-n', key
, '-v', value
]
6382 elif user_has_xattr
:
6383 executable
= 'xattr'
6384 opts
= ['-w', key
, value
]
6386 cmd
= ([encodeFilename(executable
, True)]
6387 + [encodeArgument(o
) for o
in opts
]
6388 + [encodeFilename(path
, True)])
6392 cmd
, stdout
=subprocess
.PIPE
, stderr
=subprocess
.PIPE
, stdin
=subprocess
.PIPE
)
6393 except EnvironmentError as e
:
6394 raise XAttrMetadataError(e
.errno
, e
.strerror
)
6395 stdout
, stderr
= p
.communicate_or_kill()
6396 stderr
= stderr
.decode('utf-8', 'replace')
6397 if p
.returncode
!= 0:
6398 raise XAttrMetadataError(p
.returncode
, stderr
)
6401 # On Unix, and can't find pyxattr, setfattr, or xattr.
6402 if sys
.platform
.startswith('linux'):
6403 raise XAttrUnavailableError(
6404 "Couldn't find a tool to set the xattrs. "
6405 "Install either the python 'pyxattr' or 'xattr' "
6406 "modules, or the GNU 'attr' package "
6407 "(which contains the 'setfattr' tool).")
6409 raise XAttrUnavailableError(
6410 "Couldn't find a tool to set the xattrs. "
6411 "Install either the python 'xattr' module, "
6412 "or the 'xattr' binary.")
6415 def random_birthday(year_field
, month_field
, day_field
):
6416 start_date
= datetime
.date(1950, 1, 1)
6417 end_date
= datetime
.date(1995, 12, 31)
6418 offset
= random
.randint(0, (end_date
- start_date
).days
)
6419 random_date
= start_date
+ datetime
.timedelta(offset
)
6421 year_field
: str(random_date
.year
),
6422 month_field
: str(random_date
.month
),
6423 day_field
: str(random_date
.day
),
6427 # Templates for internet shortcut files, which are plain text files.
6428 DOT_URL_LINK_TEMPLATE
= '''
6433 DOT_WEBLOC_LINK_TEMPLATE
= '''
6434 <?xml version="1.0" encoding="UTF-8"?>
6435 <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
6436 <plist version="1.0">
6439 \t<string>%(url)s</string>
6444 DOT_DESKTOP_LINK_TEMPLATE
= '''
6454 'url': DOT_URL_LINK_TEMPLATE
,
6455 'desktop': DOT_DESKTOP_LINK_TEMPLATE
,
6456 'webloc': DOT_WEBLOC_LINK_TEMPLATE
,
6460 def iri_to_uri(iri
):
6462 Converts an IRI (Internationalized Resource Identifier, allowing Unicode characters) to a URI (Uniform Resource Identifier, ASCII-only).
6464 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.
6467 iri_parts
= compat_urllib_parse_urlparse(iri
)
6469 if '[' in iri_parts
.netloc
:
6470 raise ValueError('IPv6 URIs are not, yet, supported.')
6471 # Querying `.netloc`, when there's only one bracket, also raises a ValueError.
6473 # 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.
6476 if iri_parts
.username
:
6477 net_location
+= compat_urllib_parse_quote(iri_parts
.username
, safe
=r
"!$%&'()*+,~")
6478 if iri_parts
.password
is not None:
6479 net_location
+= ':' + compat_urllib_parse_quote(iri_parts
.password
, safe
=r
"!$%&'()*+,~")
6482 net_location
+= iri_parts
.hostname
.encode('idna').decode('utf-8') # Punycode for Unicode hostnames.
6483 # The 'idna' encoding produces ASCII text.
6484 if iri_parts
.port
is not None and iri_parts
.port
!= 80:
6485 net_location
+= ':' + str(iri_parts
.port
)
6487 return compat_urllib_parse_urlunparse(
6491 compat_urllib_parse_quote_plus(iri_parts
.path
, safe
=r
"!$%&'()*+,/:;=@|~"),
6493 # Unsure about the `safe` argument, since this is a legacy way of handling parameters.
6494 compat_urllib_parse_quote_plus(iri_parts
.params
, safe
=r
"!$%&'()*+,/:;=@|~"),
6496 # Not totally sure about the `safe` argument, since the source does not explicitly mention the query URI component.
6497 compat_urllib_parse_quote_plus(iri_parts
.query
, safe
=r
"!$%&'()*+,/:;=?@{|}~"),
6499 compat_urllib_parse_quote_plus(iri_parts
.fragment
, safe
=r
"!#$%&'()*+,/:;=?@{|}~")))
6501 # Source for `safe` arguments: https://url.spec.whatwg.org/#percent-encoded-bytes.
6504 def to_high_limit_path(path
):
6505 if sys
.platform
in ['win32', 'cygwin']:
6506 # Work around MAX_PATH limitation on Windows. The maximum allowed length for the individual path segments may still be quite limited.
6507 return r
'\\?\ '.rstrip() + os
.path
.abspath(path
)
6512 def format_field(obj
, field
=None, template
='%s', ignore
=(None, ''), default
='', func
=None):
6514 val
= obj
if obj
is not None else default
6516 val
= obj
.get(field
, default
)
6517 if func
and val
not in ignore
:
6519 return template
% val
if val
not in ignore
else default
6522 def clean_podcast_url(url
):
6523 return re
.sub(r
'''(?x)
6527 media\.blubrry\.com| # https://create.blubrry.com/resources/podcast-media-download-statistics/getting-started/
6530 (?:dts|www)\.podtrac\.com/(?:pts/)?redirect\.[0-9a-z]{3,4}| # http://analytics.podtrac.com/how-to-measure
6533 cn\.co| # https://podcorn.com/analytics-prefix/
6534 st\.fm # https://podsights.com/docs/
6539 _HEX_TABLE
= '0123456789abcdef'
6542 def random_uuidv4():
6543 return re
.sub(r
'[xy]', lambda x
: _HEX_TABLE
[random
.randint(0, 15)], 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx')
6546 def make_dir(path
, to_screen
=None):
6548 dn
= os
.path
.dirname(path
)
6549 if dn
and not os
.path
.exists(dn
):
6552 except (OSError, IOError) as err
:
6553 if callable(to_screen
) is not None:
6554 to_screen('unable to create directory ' + error_to_compat_str(err
))
6558 def get_executable_path():
6559 from zipimport
import zipimporter
6560 if hasattr(sys
, 'frozen'): # Running from PyInstaller
6561 path
= os
.path
.dirname(sys
.executable
)
6562 elif isinstance(globals().get('__loader__'), zipimporter
): # Running from ZIP
6563 path
= os
.path
.join(os
.path
.dirname(__file__
), '../..')
6565 path
= os
.path
.join(os
.path
.dirname(__file__
), '..')
6566 return os
.path
.abspath(path
)
6569 def load_plugins(name
, suffix
, namespace
):
6572 plugins_spec
= importlib
.util
.spec_from_file_location(
6573 name
, os
.path
.join(get_executable_path(), 'ytdlp_plugins', name
, '__init__.py'))
6574 plugins
= importlib
.util
.module_from_spec(plugins_spec
)
6575 sys
.modules
[plugins_spec
.name
] = plugins
6576 plugins_spec
.loader
.exec_module(plugins
)
6577 for name
in dir(plugins
):
6578 if name
in namespace
:
6580 if not name
.endswith(suffix
):
6582 klass
= getattr(plugins
, name
)
6583 classes
[name
] = namespace
[name
] = klass
6584 except FileNotFoundError
:
6590 obj
, *path_list
, default
=None, expected_type
=None, get_all
=True,
6591 casesense
=True, is_user_input
=False, traverse_string
=False):
6592 ''' Traverse nested list/dict/tuple
6593 @param path_list A list of paths which are checked one by one.
6594 Each path is a list of keys where each key is a string,
6595 a function, a tuple of strings/None or "...".
6596 When a fuction is given, it takes the key as argument and
6597 returns whether the key matches or not. When a tuple is given,
6598 all the keys given in the tuple are traversed, and
6599 "..." traverses all the keys in the object
6600 "None" returns the object without traversal
6601 @param default Default value to return
6602 @param expected_type Only accept final value of this type (Can also be any callable)
6603 @param get_all Return all the values obtained from a path or only the first one
6604 @param casesense Whether to consider dictionary keys as case sensitive
6605 @param is_user_input Whether the keys are generated from user input. If True,
6606 strings are converted to int/slice if necessary
6607 @param traverse_string Whether to traverse inside strings. If True, any
6608 non-compatible object will also be converted into a string
6612 _lower
= lambda k
: (k
.lower() if isinstance(k
, str) else k
)
6613 path_list
= (map(_lower
, variadic(path
)) for path
in path_list
)
6615 def _traverse_obj(obj
, path
, _current_depth
=0):
6617 path
= tuple(variadic(path
))
6618 for i
, key
in enumerate(path
):
6619 if None in (key
, obj
):
6621 if isinstance(key
, (list, tuple)):
6622 obj
= [_traverse_obj(obj
, sub_key
, _current_depth
) for sub_key
in key
]
6625 obj
= (obj
.values() if isinstance(obj
, dict)
6626 else obj
if isinstance(obj
, (list, tuple, LazyList
))
6627 else str(obj
) if traverse_string
else [])
6629 depth
= max(depth
, _current_depth
)
6630 return [_traverse_obj(inner_obj
, path
[i
+ 1:], _current_depth
) for inner_obj
in obj
]
6632 if isinstance(obj
, (list, tuple, LazyList
)):
6633 obj
= enumerate(obj
)
6634 elif isinstance(obj
, dict):
6637 if not traverse_string
:
6641 depth
= max(depth
, _current_depth
)
6642 return [_traverse_obj(v
, path
[i
+ 1:], _current_depth
) for k
, v
in obj
if key(k
)]
6643 elif isinstance(obj
, dict) and not (is_user_input
and key
== ':'):
6644 obj
= (obj
.get(key
) if casesense
or (key
in obj
)
6645 else next((v
for k
, v
in obj
.items() if _lower(k
) == key
), None))
6648 key
= (int_or_none(key
) if ':' not in key
6649 else slice(*map(int_or_none
, key
.split(':'))))
6650 if key
== slice(None):
6651 return _traverse_obj(obj
, (..., *path
[i
+ 1:]), _current_depth
)
6652 if not isinstance(key
, (int, slice)):
6654 if not isinstance(obj
, (list, tuple, LazyList
)):
6655 if not traverse_string
:
6664 if isinstance(expected_type
, type):
6665 type_test
= lambda val
: val
if isinstance(val
, expected_type
) else None
6666 elif expected_type
is not None:
6667 type_test
= expected_type
6669 type_test
= lambda val
: val
6671 for path
in path_list
:
6673 val
= _traverse_obj(obj
, path
)
6676 for _
in range(depth
- 1):
6677 val
= itertools
.chain
.from_iterable(v
for v
in val
if v
is not None)
6678 val
= [v
for v
in map(type_test
, val
) if v
is not None]
6680 return val
if get_all
else val
[0]
6682 val
= type_test(val
)
6688 def traverse_dict(dictn
, keys
, casesense
=True):
6689 write_string('DeprecationWarning: yt_dlp.utils.traverse_dict is deprecated '
6690 'and may be removed in a future version. Use yt_dlp.utils.traverse_obj instead')
6691 return traverse_obj(dictn
, keys
, casesense
=casesense
, is_user_input
=True, traverse_string
=True)
6694 def variadic(x
, allowed_types
=(str, bytes, dict)):
6695 return x
if isinstance(x
, collections
.abc
.Iterable
) and not isinstance(x
, allowed_types
) else (x
,)
6698 # create a JSON Web Signature (jws) with HS256 algorithm
6699 # the resulting format is in JWS Compact Serialization
6700 # implemented following JWT https://www.rfc-editor.org/rfc/rfc7519.html
6701 # implemented following JWS https://www.rfc-editor.org/rfc/rfc7515.html
6702 def jwt_encode_hs256(payload_data
, key
, headers
={}):
6708 header_data
.update(headers
)
6709 header_b64
= base64
.b64encode(json
.dumps(header_data
).encode('utf-8'))
6710 payload_b64
= base64
.b64encode(json
.dumps(payload_data
).encode('utf-8'))
6711 h
= hmac
.new(key
.encode('utf-8'), header_b64
+ b
'.' + payload_b64
, hashlib
.sha256
)
6712 signature_b64
= base64
.b64encode(h
.digest())
6713 token
= header_b64
+ b
'.' + payload_b64
+ b
'.' + signature_b64
6717 # can be extended in future to verify the signature and parse header and return the algorithm used if it's not HS256
6718 def jwt_decode_hs256(jwt
):
6719 header_b64
, payload_b64
, signature_b64
= jwt
.split('.')
6720 payload_data
= json
.loads(base64
.urlsafe_b64decode(payload_b64
))
6724 def supports_terminal_sequences(stream
):
6725 if compat_os_name
== 'nt':
6726 from .compat
import WINDOWS_VT_MODE
# Must be imported locally
6727 if not WINDOWS_VT_MODE
or get_windows_version() < (10, 0, 10586):
6729 elif not os
.getenv('TERM'):
6732 return stream
.isatty()
6733 except BaseException
:
6737 _terminal_sequences_re
= re
.compile('\033\\[[^m]+m')
6740 def remove_terminal_sequences(string
):
6741 return _terminal_sequences_re
.sub('', string
)
6744 def number_of_digits(number
):
6745 return len('%d' % number
)
6748 def join_nonempty(*values
, delim
='-', from_dict
=None):
6749 if from_dict
is not None:
6750 values
= map(from_dict
.get
, values
)
6751 return delim
.join(map(str, filter(None, values
)))
6757 __initialized
= False
6759 def __init__(self
, parser
, label
=None):
6760 self
._parser
, self
.label
= parser
, label
6761 self
._loaded
_paths
, self
.configs
= set(), []
6763 def init(self
, args
=None, filename
=None):
6764 assert not self
.__initialized
6766 location
= os
.path
.realpath(filename
)
6767 if location
in self
._loaded
_paths
:
6769 self
._loaded
_paths
.add(location
)
6771 self
.__initialized
= True
6772 self
.own_args
, self
.filename
= args
, filename
6773 for location
in self
._parser
.parse_args(args
)[0].config_locations
or []:
6774 location
= compat_expanduser(location
)
6775 if os
.path
.isdir(location
):
6776 location
= os
.path
.join(location
, 'yt-dlp.conf')
6777 if not os
.path
.exists(location
):
6778 self
._parser
.error(f
'config location {location} does not exist')
6779 self
.append_config(self
.read_file(location
), location
)
6783 label
= join_nonempty(
6784 self
.label
, 'config', f
'"{self.filename}"' if self
.filename
else '',
6786 return join_nonempty(
6787 self
.own_args
is not None and f
'{label[0].upper()}{label[1:]}: {self.hide_login_info(self.own_args)}',
6788 *(f
'\n{c}'.replace('\n', '\n| ')[1:] for c
in self
.configs
),
6792 def read_file(filename
, default
=[]):
6794 optionf
= open(filename
)
6796 return default
# silently skip if file is not present
6798 # FIXME: https://github.com/ytdl-org/youtube-dl/commit/dfe5fa49aed02cf36ba9f743b11b0903554b5e56
6799 contents
= optionf
.read()
6800 if sys
.version_info
< (3,):
6801 contents
= contents
.decode(preferredencoding())
6802 res
= compat_shlex_split(contents
, comments
=True)
6808 def hide_login_info(opts
):
6809 PRIVATE_OPTS
= set(['-p', '--password', '-u', '--username', '--video-password', '--ap-password', '--ap-username'])
6810 eqre
= re
.compile('^(?P<key>' + ('|'.join(re
.escape(po
) for po
in PRIVATE_OPTS
)) + ')=.+$')
6815 return m
.group('key') + '=PRIVATE'
6819 opts
= list(map(_scrub_eq
, opts
))
6820 for idx
, opt
in enumerate(opts
):
6821 if opt
in PRIVATE_OPTS
and idx
+ 1 < len(opts
):
6822 opts
[idx
+ 1] = 'PRIVATE'
6825 def append_config(self
, *args
, label
=None):
6826 config
= type(self
)(self
._parser
, label
)
6827 config
._loaded
_paths
= self
._loaded
_paths
6828 if config
.init(*args
):
6829 self
.configs
.append(config
)
6833 for config
in reversed(self
.configs
):
6834 yield from config
.all_args
6835 yield from self
.own_args
or []
6837 def parse_args(self
):
6838 return self
._parser
.parse_args(list(self
.all_args
))