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
'(?:(?:(?:(?P<days>[0-9]+):)?(?P<hours>[0-9]+):)?(?P<mins>[0-9]+):)?(?P<secs>[0-9]+)(?P<ms>\.[0-9]+)?Z?$', s
)
4099 days
, hours
, mins
, secs
, ms
= m
.groups()
4104 [0-9]+\s*y(?:ears?)?\s*
4107 [0-9]+\s*m(?:onths?)?\s*
4110 [0-9]+\s*w(?:eeks?)?\s*
4113 (?P<days>[0-9]+)\s*d(?:ays?)?\s*
4117 (?P<hours>[0-9]+)\s*h(?:ours?)?\s*
4120 (?P<mins>[0-9]+)\s*m(?:in(?:ute)?s?)?\s*
4123 (?P<secs>[0-9]+)(?P<ms>\.[0-9]+)?\s*s(?:ec(?:ond)?s?)?\s*
4126 days
, hours
, mins
, secs
, ms
= m
.groups()
4128 m
= re
.match(r
'(?i)(?:(?P<hours>[0-9.]+)\s*(?:hours?)|(?P<mins>[0-9.]+)\s*(?:mins?\.?|minutes?)\s*)Z?$', s
)
4130 hours
, mins
= m
.groups()
4136 duration
+= float(secs
)
4138 duration
+= float(mins
) * 60
4140 duration
+= float(hours
) * 60 * 60
4142 duration
+= float(days
) * 24 * 60 * 60
4144 duration
+= float(ms
)
4148 def prepend_extension(filename
, ext
, expected_real_ext
=None):
4149 name
, real_ext
= os
.path
.splitext(filename
)
4151 '{0}.{1}{2}'.format(name
, ext
, real_ext
)
4152 if not expected_real_ext
or real_ext
[1:] == expected_real_ext
4153 else '{0}.{1}'.format(filename
, ext
))
4156 def replace_extension(filename
, ext
, expected_real_ext
=None):
4157 name
, real_ext
= os
.path
.splitext(filename
)
4158 return '{0}.{1}'.format(
4159 name
if not expected_real_ext
or real_ext
[1:] == expected_real_ext
else filename
,
4163 def check_executable(exe
, args
=[]):
4164 """ Checks if the given binary is installed somewhere in PATH, and returns its name.
4165 args can be a list of arguments for a short output (like -version) """
4167 Popen([exe
] + args
, stdout
=subprocess
.PIPE
, stderr
=subprocess
.PIPE
).communicate_or_kill()
4173 def _get_exe_version_output(exe
, args
):
4175 # STDIN should be redirected too. On UNIX-like systems, ffmpeg triggers
4176 # SIGTTOU if yt-dlp is run in the background.
4177 # See https://github.com/ytdl-org/youtube-dl/issues/955#issuecomment-209789656
4179 [encodeArgument(exe
)] + args
, stdin
=subprocess
.PIPE
,
4180 stdout
=subprocess
.PIPE
, stderr
=subprocess
.STDOUT
).communicate_or_kill()
4183 if isinstance(out
, bytes): # Python 2.x
4184 out
= out
.decode('ascii', 'ignore')
4188 def detect_exe_version(output
, version_re
=None, unrecognized
='present'):
4189 assert isinstance(output
, compat_str
)
4190 if version_re
is None:
4191 version_re
= r
'version\s+([-0-9._a-zA-Z]+)'
4192 m
= re
.search(version_re
, output
)
4199 def get_exe_version(exe
, args
=['--version'],
4200 version_re
=None, unrecognized
='present'):
4201 """ Returns the version of the specified executable,
4202 or False if the executable is not present """
4203 out
= _get_exe_version_output(exe
, args
)
4204 return detect_exe_version(out
, version_re
, unrecognized
) if out
else False
4207 class LazyList(collections
.abc
.Sequence
):
4208 ''' Lazy immutable list from an iterable
4209 Note that slices of a LazyList are lists and not LazyList'''
4211 class IndexError(IndexError):
4214 def __init__(self
, iterable
, *, reverse
=False, _cache
=None):
4215 self
.__iterable
= iter(iterable
)
4216 self
.__cache
= [] if _cache
is None else _cache
4217 self
.__reversed
= reverse
4221 # We need to consume the entire iterable to iterate in reverse
4222 yield from self
.exhaust()
4224 yield from self
.__cache
4225 for item
in self
.__iterable
:
4226 self
.__cache
.append(item
)
4229 def __exhaust(self
):
4230 self
.__cache
.extend(self
.__iterable
)
4231 # Discard the emptied iterable to make it pickle-able
4232 self
.__iterable
= []
4236 ''' Evaluate the entire iterable '''
4237 return self
.__exhaust
()[::-1 if self
.__reversed
else 1]
4240 def __reverse_index(x
):
4241 return None if x
is None else -(x
+ 1)
4243 def __getitem__(self
, idx
):
4244 if isinstance(idx
, slice):
4246 idx
= slice(self
.__reverse
_index
(idx
.start
), self
.__reverse
_index
(idx
.stop
), -(idx
.step
or 1))
4247 start
, stop
, step
= idx
.start
, idx
.stop
, idx
.step
or 1
4248 elif isinstance(idx
, int):
4250 idx
= self
.__reverse
_index
(idx
)
4251 start
, stop
, step
= idx
, idx
, 0
4253 raise TypeError('indices must be integers or slices')
4254 if ((start
or 0) < 0 or (stop
or 0) < 0
4255 or (start
is None and step
< 0)
4256 or (stop
is None and step
> 0)):
4257 # We need to consume the entire iterable to be able to slice from the end
4258 # Obviously, never use this with infinite iterables
4261 return self
.__cache
[idx
]
4262 except IndexError as e
:
4263 raise self
.IndexError(e
) from e
4264 n
= max(start
or 0, stop
or 0) - len(self
.__cache
) + 1
4266 self
.__cache
.extend(itertools
.islice(self
.__iterable
, n
))
4268 return self
.__cache
[idx
]
4269 except IndexError as e
:
4270 raise self
.IndexError(e
) from e
4274 self
[-1] if self
.__reversed
else self
[0]
4275 except self
.IndexError:
4281 return len(self
.__cache
)
4283 def __reversed__(self
):
4284 return type(self
)(self
.__iterable
, reverse
=not self
.__reversed
, _cache
=self
.__cache
)
4287 return type(self
)(self
.__iterable
, reverse
=self
.__reversed
, _cache
=self
.__cache
)
4290 # repr and str should mimic a list. So we exhaust the iterable
4291 return repr(self
.exhaust())
4294 return repr(self
.exhaust())
4299 class IndexError(IndexError):
4303 # This is only useful for tests
4304 return len(self
.getslice())
4306 def __init__(self
, pagefunc
, pagesize
, use_cache
=True):
4307 self
._pagefunc
= pagefunc
4308 self
._pagesize
= pagesize
4309 self
._use
_cache
= use_cache
4312 def getpage(self
, pagenum
):
4313 page_results
= self
._cache
.get(pagenum
)
4314 if page_results
is None:
4315 page_results
= list(self
._pagefunc
(pagenum
))
4317 self
._cache
[pagenum
] = page_results
4320 def getslice(self
, start
=0, end
=None):
4321 return list(self
._getslice
(start
, end
))
4323 def _getslice(self
, start
, end
):
4324 raise NotImplementedError('This method must be implemented by subclasses')
4326 def __getitem__(self
, idx
):
4327 # NOTE: cache must be enabled if this is used
4328 if not isinstance(idx
, int) or idx
< 0:
4329 raise TypeError('indices must be non-negative integers')
4330 entries
= self
.getslice(idx
, idx
+ 1)
4332 raise self
.IndexError()
4336 class OnDemandPagedList(PagedList
):
4337 def _getslice(self
, start
, end
):
4338 for pagenum
in itertools
.count(start
// self
._pagesize
):
4339 firstid
= pagenum
* self
._pagesize
4340 nextfirstid
= pagenum
* self
._pagesize
+ self
._pagesize
4341 if start
>= nextfirstid
:
4345 start
% self
._pagesize
4346 if firstid
<= start
< nextfirstid
4349 ((end
- 1) % self
._pagesize
) + 1
4350 if (end
is not None and firstid
<= end
<= nextfirstid
)
4353 page_results
= self
.getpage(pagenum
)
4354 if startv
!= 0 or endv
is not None:
4355 page_results
= page_results
[startv
:endv
]
4356 yield from page_results
4358 # A little optimization - if current page is not "full", ie. does
4359 # not contain page_size videos then we can assume that this page
4360 # is the last one - there are no more ids on further pages -
4361 # i.e. no need to query again.
4362 if len(page_results
) + startv
< self
._pagesize
:
4365 # If we got the whole page, but the next page is not interesting,
4366 # break out early as well
4367 if end
== nextfirstid
:
4371 class InAdvancePagedList(PagedList
):
4372 def __init__(self
, pagefunc
, pagecount
, pagesize
):
4373 self
._pagecount
= pagecount
4374 PagedList
.__init
__(self
, pagefunc
, pagesize
, True)
4376 def _getslice(self
, start
, end
):
4377 start_page
= start
// self
._pagesize
4379 self
._pagecount
if end
is None else (end
// self
._pagesize
+ 1))
4380 skip_elems
= start
- start_page
* self
._pagesize
4381 only_more
= None if end
is None else end
- start
4382 for pagenum
in range(start_page
, end_page
):
4383 page_results
= self
.getpage(pagenum
)
4385 page_results
= page_results
[skip_elems
:]
4387 if only_more
is not None:
4388 if len(page_results
) < only_more
:
4389 only_more
-= len(page_results
)
4391 yield from page_results
[:only_more
]
4393 yield from page_results
4396 def uppercase_escape(s
):
4397 unicode_escape
= codecs
.getdecoder('unicode_escape')
4399 r
'\\U[0-9a-fA-F]{8}',
4400 lambda m
: unicode_escape(m
.group(0))[0],
4404 def lowercase_escape(s
):
4405 unicode_escape
= codecs
.getdecoder('unicode_escape')
4407 r
'\\u[0-9a-fA-F]{4}',
4408 lambda m
: unicode_escape(m
.group(0))[0],
4412 def escape_rfc3986(s
):
4413 """Escape non-ASCII characters as suggested by RFC 3986"""
4414 if sys
.version_info
< (3, 0) and isinstance(s
, compat_str
):
4415 s
= s
.encode('utf-8')
4416 return compat_urllib_parse
.quote(s
, b
"%/;:@&=+$,!~*'()?#[]")
4419 def escape_url(url
):
4420 """Escape URL as suggested by RFC 3986"""
4421 url_parsed
= compat_urllib_parse_urlparse(url
)
4422 return url_parsed
._replace
(
4423 netloc
=url_parsed
.netloc
.encode('idna').decode('ascii'),
4424 path
=escape_rfc3986(url_parsed
.path
),
4425 params
=escape_rfc3986(url_parsed
.params
),
4426 query
=escape_rfc3986(url_parsed
.query
),
4427 fragment
=escape_rfc3986(url_parsed
.fragment
)
4432 return compat_parse_qs(compat_urllib_parse_urlparse(url
).query
)
4435 def read_batch_urls(batch_fd
):
4437 if not isinstance(url
, compat_str
):
4438 url
= url
.decode('utf-8', 'replace')
4439 BOM_UTF8
= ('\xef\xbb\xbf', '\ufeff')
4440 for bom
in BOM_UTF8
:
4441 if url
.startswith(bom
):
4442 url
= url
[len(bom
):]
4444 if not url
or url
.startswith(('#', ';', ']')):
4446 # "#" cannot be stripped out since it is part of the URI
4447 # However, it can be safely stipped out if follwing a whitespace
4448 return re
.split(r
'\s#', url
, 1)[0].rstrip()
4450 with contextlib
.closing(batch_fd
) as fd
:
4451 return [url
for url
in map(fixup
, fd
) if url
]
4454 def urlencode_postdata(*args
, **kargs
):
4455 return compat_urllib_parse_urlencode(*args
, **kargs
).encode('ascii')
4458 def update_url_query(url
, query
):
4461 parsed_url
= compat_urlparse
.urlparse(url
)
4462 qs
= compat_parse_qs(parsed_url
.query
)
4464 return compat_urlparse
.urlunparse(parsed_url
._replace
(
4465 query
=compat_urllib_parse_urlencode(qs
, True)))
4468 def update_Request(req
, url
=None, data
=None, headers
={}, query={}
):
4469 req_headers
= req
.headers
.copy()
4470 req_headers
.update(headers
)
4471 req_data
= data
or req
.data
4472 req_url
= update_url_query(url
or req
.get_full_url(), query
)
4473 req_get_method
= req
.get_method()
4474 if req_get_method
== 'HEAD':
4475 req_type
= HEADRequest
4476 elif req_get_method
== 'PUT':
4477 req_type
= PUTRequest
4479 req_type
= compat_urllib_request
.Request
4481 req_url
, data
=req_data
, headers
=req_headers
,
4482 origin_req_host
=req
.origin_req_host
, unverifiable
=req
.unverifiable
)
4483 if hasattr(req
, 'timeout'):
4484 new_req
.timeout
= req
.timeout
4488 def _multipart_encode_impl(data
, boundary
):
4489 content_type
= 'multipart/form-data; boundary=%s' % boundary
4492 for k
, v
in data
.items():
4493 out
+= b
'--' + boundary
.encode('ascii') + b
'\r\n'
4494 if isinstance(k
, compat_str
):
4495 k
= k
.encode('utf-8')
4496 if isinstance(v
, compat_str
):
4497 v
= v
.encode('utf-8')
4498 # RFC 2047 requires non-ASCII field names to be encoded, while RFC 7578
4499 # suggests sending UTF-8 directly. Firefox sends UTF-8, too
4500 content
= b
'Content-Disposition: form-data; name="' + k
+ b
'"\r\n\r\n' + v
+ b
'\r\n'
4501 if boundary
.encode('ascii') in content
:
4502 raise ValueError('Boundary overlaps with data')
4505 out
+= b
'--' + boundary
.encode('ascii') + b
'--\r\n'
4507 return out
, content_type
4510 def multipart_encode(data
, boundary
=None):
4512 Encode a dict to RFC 7578-compliant form-data
4515 A dict where keys and values can be either Unicode or bytes-like
4518 If specified a Unicode object, it's used as the boundary. Otherwise
4519 a random boundary is generated.
4521 Reference: https://tools.ietf.org/html/rfc7578
4523 has_specified_boundary
= boundary
is not None
4526 if boundary
is None:
4527 boundary
= '---------------' + str(random
.randrange(0x0fffffff, 0xffffffff))
4530 out
, content_type
= _multipart_encode_impl(data
, boundary
)
4533 if has_specified_boundary
:
4537 return out
, content_type
4540 def dict_get(d
, key_or_keys
, default
=None, skip_false_values
=True):
4541 if isinstance(key_or_keys
, (list, tuple)):
4542 for key
in key_or_keys
:
4543 if key
not in d
or d
[key
] is None or skip_false_values
and not d
[key
]:
4547 return d
.get(key_or_keys
, default
)
4550 def try_get(src
, getter
, expected_type
=None):
4551 for get
in variadic(getter
):
4554 except (AttributeError, KeyError, TypeError, IndexError):
4557 if expected_type
is None or isinstance(v
, expected_type
):
4561 def merge_dicts(*dicts
):
4563 for a_dict
in dicts
:
4564 for k
, v
in a_dict
.items():
4568 or (isinstance(v
, compat_str
) and v
4569 and isinstance(merged
[k
], compat_str
)
4570 and not merged
[k
])):
4575 def encode_compat_str(string
, encoding
=preferredencoding(), errors
='strict'):
4576 return string
if isinstance(string
, compat_str
) else compat_str(string
, encoding
, errors
)
4588 TV_PARENTAL_GUIDELINES
= {
4598 def parse_age_limit(s
):
4600 return s
if 0 <= s
<= 21 else None
4601 if not isinstance(s
, compat_basestring
):
4603 m
= re
.match(r
'^(?P<age>\d{1,2})\+?$', s
)
4605 return int(m
.group('age'))
4608 return US_RATINGS
[s
]
4609 m
= re
.match(r
'^TV[_-]?(%s)$' % '|'.join(k
[3:] for k
in TV_PARENTAL_GUIDELINES
), s
)
4611 return TV_PARENTAL_GUIDELINES
['TV-' + m
.group(1)]
4615 def strip_jsonp(code
):
4618 (?:window\.)?(?P<func_name>[a-zA-Z0-9_.$]*)
4619 (?:\s*&&\s*(?P=func_name))?
4620 \s*\(\s*(?P<callback_data>.*)\);?
4621 \s*?(?://[^\n]*)*$''',
4622 r
'\g<callback_data>', code
)
4625 def js_to_json(code
, vars={}):
4626 # vars is a dict of var, val pairs to substitute
4627 COMMENT_RE
= r
'/\*(?:(?!\*/).)*?\*/|//[^\n]*\n'
4628 SKIP_RE
= r
'\s*(?:{comment})?\s*'.format(comment
=COMMENT_RE
)
4630 (r
'(?s)^(0[xX][0-9a-fA-F]+){skip}:?$'.format(skip
=SKIP_RE
), 16),
4631 (r
'(?s)^(0+[0-7]+){skip}:?$'.format(skip
=SKIP_RE
), 8),
4636 if v
in ('true', 'false', 'null'):
4638 elif v
in ('undefined', 'void 0'):
4640 elif v
.startswith('/*') or v
.startswith('//') or v
.startswith('!') or v
== ',':
4643 if v
[0] in ("'", '"'):
4644 v
= re
.sub(r
'(?s)\\.|"', lambda m
: {
4649 }.get(m
.group(0), m
.group(0)), v
[1:-1])
4651 for regex
, base
in INTEGER_TABLE
:
4652 im
= re
.match(regex
, v
)
4654 i
= int(im
.group(1), base
)
4655 return '"%d":' % i
if v
.endswith(':') else '%d' % i
4662 return re
.sub(r
'''(?sx)
4663 "(?:[^"\\]*(?:\\\\|\\['"nurtbfx/\n]))*[^"\\]*"|
4664 '(?:[^'\\]*(?:\\\\|\\['"nurtbfx/\n]))*[^'\\]*'|
4665 {comment}|,(?={skip}[\]}}])|
4666 void\s0|(?:(?<![0-9])[eE]|[a-df-zA-DF-Z_$])[.a-zA-Z_$0-9]*|
4667 \b(?:0[xX][0-9a-fA-F]+|0+[0-7]+)(?:{skip}:)?|
4670 '''.format(comment
=COMMENT_RE
, skip
=SKIP_RE
), fix_kv
, code
)
4673 def qualities(quality_ids
):
4674 """ Get a numeric quality value out of a list of possible values """
4677 return quality_ids
.index(qid
)
4683 POSTPROCESS_WHEN
= {'pre_process', 'before_dl', 'after_move', 'post_process', 'after_video', 'playlist'}
4687 'default': '%(title)s [%(id)s].%(ext)s',
4688 'chapter': '%(title)s - %(section_number)03d %(section_title)s [%(id)s].%(ext)s',
4694 'description': 'description',
4695 'annotation': 'annotations.xml',
4696 'infojson': 'info.json',
4699 'pl_thumbnail': None,
4700 'pl_description': 'description',
4701 'pl_infojson': 'info.json',
4704 # As of [1] format syntax is:
4705 # %[mapping_key][conversion_flags][minimum_width][.precision][length_modifier]type
4706 # 1. https://docs.python.org/2/library/stdtypes.html#string-formatting
4707 STR_FORMAT_RE_TMPL
= r
'''(?x)
4708 (?<!%)(?P<prefix>(?:%%)*)
4710 (?P<has_key>\((?P<key>{0})\))?
4712 (?P<conversion>[#0\-+ ]+)?
4714 (?P<precision>\.\d+)?
4715 (?P<len_mod>[hlL])? # unused in python
4716 {1} # conversion type
4721 STR_FORMAT_TYPES
= 'diouxXeEfFgGcrs'
4724 def limit_length(s
, length
):
4725 """ Add ellipses to overly long strings """
4730 return s
[:length
- len(ELLIPSES
)] + ELLIPSES
4734 def version_tuple(v
):
4735 return tuple(int(e
) for e
in re
.split(r
'[-.]', v
))
4738 def is_outdated_version(version
, limit
, assume_new
=True):
4740 return not assume_new
4742 return version_tuple(version
) < version_tuple(limit
)
4744 return not assume_new
4747 def ytdl_is_updateable():
4748 """ Returns if yt-dlp can be updated with -U """
4750 from .update
import is_non_updateable
4752 return not is_non_updateable()
4755 def args_to_str(args
):
4756 # Get a short string representation for a subprocess command
4757 return ' '.join(compat_shlex_quote(a
) for a
in args
)
4760 def error_to_compat_str(err
):
4762 # On python 2 error byte string must be decoded with proper
4763 # encoding rather than ascii
4764 if sys
.version_info
[0] < 3:
4765 err_str
= err_str
.decode(preferredencoding())
4769 def mimetype2ext(mt
):
4773 mt
, _
, params
= mt
.partition(';')
4778 # Per RFC 3003, audio/mpeg can be .mp1, .mp2 or .mp3. Here use .mp3 as
4779 # it's the most popular one
4780 'audio/mpeg': 'mp3',
4781 'audio/x-wav': 'wav',
4783 'audio/wave': 'wav',
4786 ext
= FULL_MAP
.get(mt
)
4792 'smptett+xml': 'tt',
4796 'x-mp4-fragmented': 'mp4',
4797 'x-ms-sami': 'sami',
4800 'x-mpegurl': 'm3u8',
4801 'vnd.apple.mpegurl': 'm3u8',
4805 'vnd.ms-sstr+xml': 'ism',
4809 'filmstrip+json': 'fs',
4813 _
, _
, subtype
= mt
.rpartition('/')
4814 ext
= SUBTYPE_MAP
.get(subtype
.lower())
4825 _
, _
, suffix
= subtype
.partition('+')
4826 ext
= SUFFIX_MAP
.get(suffix
)
4830 return subtype
.replace('+', '.')
4833 def ext2mimetype(ext_or_url
):
4836 if '.' not in ext_or_url
:
4837 ext_or_url
= f
'file.{ext_or_url}'
4838 return mimetypes
.guess_type(ext_or_url
)[0]
4841 def parse_codecs(codecs_str
):
4842 # http://tools.ietf.org/html/rfc6381
4845 split_codecs
= list(filter(None, map(
4846 str.strip
, codecs_str
.strip().strip(',').split(','))))
4847 vcodec
, acodec
, tcodec
, hdr
= None, None, None, None
4848 for full_codec
in split_codecs
:
4849 parts
= full_codec
.split('.')
4850 codec
= parts
[0].replace('0', '')
4851 if codec
in ('avc1', 'avc2', 'avc3', 'avc4', 'vp9', 'vp8', 'hev1', 'hev2',
4852 'h263', 'h264', 'mp4v', 'hvc1', 'av1', 'theora', 'dvh1', 'dvhe'):
4854 vcodec
= '.'.join(parts
[:4]) if codec
in ('vp9', 'av1', 'hvc1') else full_codec
4855 if codec
in ('dvh1', 'dvhe'):
4857 elif codec
== 'av1' and len(parts
) > 3 and parts
[3] == '10':
4859 elif full_codec
.replace('0', '').startswith('vp9.2'):
4861 elif codec
in ('flac', 'mp4a', 'opus', 'vorbis', 'mp3', 'aac', 'ac-3', 'ec-3', 'eac3', 'dtsc', 'dtse', 'dtsh', 'dtsl'):
4864 elif codec
in ('stpp', 'wvtt',):
4868 write_string('WARNING: Unknown codec %s\n' % full_codec
, sys
.stderr
)
4869 if vcodec
or acodec
or tcodec
:
4871 'vcodec': vcodec
or 'none',
4872 'acodec': acodec
or 'none',
4873 'dynamic_range': hdr
,
4874 **({'tcodec': tcodec}
if tcodec
is not None else {}),
4876 elif len(split_codecs
) == 2:
4878 'vcodec': split_codecs
[0],
4879 'acodec': split_codecs
[1],
4884 def urlhandle_detect_ext(url_handle
):
4885 getheader
= url_handle
.headers
.get
4887 cd
= getheader('Content-Disposition')
4889 m
= re
.match(r
'attachment;\s*filename="(?P<filename>[^"]+)"', cd
)
4891 e
= determine_ext(m
.group('filename'), default_ext
=None)
4895 return mimetype2ext(getheader('Content-Type'))
4898 def encode_data_uri(data
, mime_type
):
4899 return 'data:%s;base64,%s' % (mime_type
, base64
.b64encode(data
).decode('ascii'))
4902 def age_restricted(content_limit
, age_limit
):
4903 """ Returns True iff the content should be blocked """
4905 if age_limit
is None: # No limit set
4907 if content_limit
is None:
4908 return False # Content available for everyone
4909 return age_limit
< content_limit
4912 def is_html(first_bytes
):
4913 """ Detect whether a file contains HTML by examining its first bytes. """
4916 (b
'\xef\xbb\xbf', 'utf-8'),
4917 (b
'\x00\x00\xfe\xff', 'utf-32-be'),
4918 (b
'\xff\xfe\x00\x00', 'utf-32-le'),
4919 (b
'\xff\xfe', 'utf-16-le'),
4920 (b
'\xfe\xff', 'utf-16-be'),
4922 for bom
, enc
in BOMS
:
4923 if first_bytes
.startswith(bom
):
4924 s
= first_bytes
[len(bom
):].decode(enc
, 'replace')
4927 s
= first_bytes
.decode('utf-8', 'replace')
4929 return re
.match(r
'^\s*<', s
)
4932 def determine_protocol(info_dict
):
4933 protocol
= info_dict
.get('protocol')
4934 if protocol
is not None:
4937 url
= sanitize_url(info_dict
['url'])
4938 if url
.startswith('rtmp'):
4940 elif url
.startswith('mms'):
4942 elif url
.startswith('rtsp'):
4945 ext
= determine_ext(url
)
4951 return compat_urllib_parse_urlparse(url
).scheme
4954 def render_table(header_row
, data
, delim
=False, extra_gap
=0, hide_empty
=False):
4955 """ Render a list of rows, each as a list of values.
4956 Text after a \t will be right aligned """
4958 return len(remove_terminal_sequences(string
).replace('\t', ''))
4960 def get_max_lens(table
):
4961 return [max(width(str(v
)) for v
in col
) for col
in zip(*table
)]
4963 def filter_using_list(row
, filterArray
):
4964 return [col
for (take
, col
) in zip(filterArray
, row
) if take
]
4967 max_lens
= get_max_lens(data
)
4968 header_row
= filter_using_list(header_row
, max_lens
)
4969 data
= [filter_using_list(row
, max_lens
) for row
in data
]
4971 table
= [header_row
] + data
4972 max_lens
= get_max_lens(table
)
4975 table
= [header_row
, [delim
* (ml
+ extra_gap
) for ml
in max_lens
]] + data
4976 table
[1][-1] = table
[1][-1][:-extra_gap
] # Remove extra_gap from end of delimiter
4978 for pos
, text
in enumerate(map(str, row
)):
4980 row
[pos
] = text
.replace('\t', ' ' * (max_lens
[pos
] - width(text
))) + ' ' * extra_gap
4982 row
[pos
] = text
+ ' ' * (max_lens
[pos
] - width(text
) + extra_gap
)
4983 ret
= '\n'.join(''.join(row
).rstrip() for row
in table
)
4987 def _match_one(filter_part
, dct
, incomplete
):
4988 # TODO: Generalize code with YoutubeDL._build_format_filter
4989 STRING_OPERATORS
= {
4990 '*=': operator
.contains
,
4991 '^=': lambda attr
, value
: attr
.startswith(value
),
4992 '$=': lambda attr
, value
: attr
.endswith(value
),
4993 '~=': lambda attr
, value
: re
.search(value
, attr
),
4995 COMPARISON_OPERATORS
= {
4997 '<=': operator
.le
, # "<=" must be defined above "<"
5004 operator_rex
= re
.compile(r
'''(?x)\s*
5006 \s*(?P<negation>!\s*)?(?P<op>%s)(?P<none_inclusive>\s*\?)?\s*
5008 (?P<quote>["\'])(?P
<quotedstrval
>.+?
)(?P
=quote
)|
5012 ''' % '|'.join(map(re.escape, COMPARISON_OPERATORS.keys())))
5013 m = operator_rex.search(filter_part)
5016 unnegated_op = COMPARISON_OPERATORS[m['op']]
5018 op = lambda attr, value: not unnegated_op(attr, value)
5021 comparison_value = m['quotedstrval'] or m['strval'] or m['intval']
5023 comparison_value = comparison_value.replace(r'\%s' % m['quote'], m['quote'])
5024 actual_value = dct.get(m['key'])
5025 numeric_comparison = None
5026 if isinstance(actual_value, compat_numeric_types):
5027 # If the original field is a string and matching comparisonvalue is
5028 # a number we should respect the origin of the original field
5029 # and process comparison value as a string (see
5030 # https://github.com/ytdl-org/youtube-dl/issues/11082)
5032 numeric_comparison = int(comparison_value)
5034 numeric_comparison = parse_filesize(comparison_value)
5035 if numeric_comparison is None:
5036 numeric_comparison = parse_filesize(f'{comparison_value}B')
5037 if numeric_comparison is None:
5038 numeric_comparison = parse_duration(comparison_value)
5039 if numeric_comparison is not None and m['op'] in STRING_OPERATORS:
5040 raise ValueError('Operator %s only supports string values!' % m['op'])
5041 if actual_value is None:
5042 return incomplete or m['none_inclusive']
5043 return op(actual_value, comparison_value if numeric_comparison is None else numeric_comparison)
5046 '': lambda v: (v is True) if isinstance(v, bool) else (v is not None),
5047 '!': lambda v: (v is False) if isinstance(v, bool) else (v is None),
5049 operator_rex = re.compile(r'''(?x
)\s
*
5050 (?P
<op
>%s)\s
*(?P
<key
>[a
-z_
]+)
5052 ''' % '|'.join(map(re.escape, UNARY_OPERATORS.keys())))
5053 m = operator_rex.search(filter_part)
5055 op = UNARY_OPERATORS[m.group('op')]
5056 actual_value = dct.get(m.group('key'))
5057 if incomplete and actual_value is None:
5059 return op(actual_value)
5061 raise ValueError('Invalid filter part %r' % filter_part)
5064 def match_str(filter_str, dct, incomplete=False):
5065 """ Filter a dictionary with a simple string syntax. Returns True (=passes filter) or false
5066 When incomplete, all conditions passes on missing fields
5069 _match_one(filter_part.replace(r'\&', '&'), dct, incomplete)
5070 for filter_part in re.split(r'(?<!\\)&', filter_str))
5073 def match_filter_func(filter_str):
5074 def _match_func(info_dict, *args, **kwargs):
5075 if match_str(filter_str, info_dict, *args, **kwargs):
5078 video_title = info_dict.get('title', info_dict.get('id', 'video'))
5079 return '%s does not pass filter %s, skipping ..' % (video_title, filter_str)
5083 def parse_dfxp_time_expr(time_expr):
5087 mobj = re.match(r'^(?P<time_offset>\d+(?:\.\d+)?)s?$', time_expr)
5089 return float(mobj.group('time_offset'))
5091 mobj = re.match(r'^(\d+):(\d\d):(\d\d(?:(?:\.|:)\d+)?)$', time_expr)
5093 return 3600 * int(mobj.group(1)) + 60 * int(mobj.group(2)) + float(mobj.group(3).replace(':', '.'))
5096 def srt_subtitles_timecode(seconds):
5097 return '%02d:%02d:%02d,%03d' % timetuple_from_msec(seconds * 1000)
5100 def ass_subtitles_timecode(seconds):
5101 time = timetuple_from_msec(seconds * 1000)
5102 return '%01d:%02d:%02d.%02d' % (*time[:-1], time.milliseconds / 10)
5105 def dfxp2srt(dfxp_data):
5107 @param dfxp_data A
bytes-like
object containing DFXP data
5108 @returns A
unicode object containing converted SRT data
5110 LEGACY_NAMESPACES = (
5111 (b'http://www.w3.org/ns/ttml', [
5112 b'http://www.w3.org/2004/11/ttaf1',
5113 b'http://www.w3.org/2006/04/ttaf1',
5114 b'http://www.w3.org/2006/10/ttaf1',
5116 (b'http://www.w3.org/ns/ttml#styling', [
5117 b'http://www.w3.org/ns/ttml#style',
5121 SUPPORTED_STYLING = [
5130 _x = functools.partial(xpath_with_ns, ns_map={
5131 'xml': 'http://www.w3.org/XML/1998/namespace',
5132 'ttml': 'http://www.w3.org/ns/ttml',
5133 'tts': 'http://www.w3.org/ns/ttml#styling',
5139 class TTMLPElementParser(object):
5141 _unclosed_elements = []
5142 _applied_styles = []
5144 def start(self, tag, attrib):
5145 if tag in (_x('ttml:br'), 'br'):
5148 unclosed_elements = []
5150 element_style_id = attrib.get('style')
5152 style.update(default_style)
5153 if element_style_id:
5154 style.update(styles.get(element_style_id, {}))
5155 for prop in SUPPORTED_STYLING:
5156 prop_val = attrib.get(_x('tts:' + prop))
5158 style[prop] = prop_val
5161 for k, v in sorted(style.items()):
5162 if self._applied_styles and self._applied_styles[-1].get(k) == v:
5165 font += ' color="%s"' % v
5166 elif k == 'fontSize':
5167 font += ' size="%s"' % v
5168 elif k == 'fontFamily':
5169 font += ' face="%s"' % v
5170 elif k == 'fontWeight' and v == 'bold':
5172 unclosed_elements.append('b')
5173 elif k == 'fontStyle' and v == 'italic':
5175 unclosed_elements.append('i')
5176 elif k == 'textDecoration' and v == 'underline':
5178 unclosed_elements.append('u')
5180 self._out += '<font' + font + '>'
5181 unclosed_elements.append('font')
5183 if self._applied_styles:
5184 applied_style.update(self._applied_styles[-1])
5185 applied_style.update(style)
5186 self._applied_styles.append(applied_style)
5187 self._unclosed_elements.append(unclosed_elements)
5190 if tag not in (_x('ttml:br'), 'br'):
5191 unclosed_elements = self._unclosed_elements.pop()
5192 for element in reversed(unclosed_elements):
5193 self._out += '</%s>' % element
5194 if unclosed_elements and self._applied_styles:
5195 self._applied_styles.pop()
5197 def data(self, data):
5201 return self._out.strip()
5203 def parse_node(node):
5204 target = TTMLPElementParser()
5205 parser = xml.etree.ElementTree.XMLParser(target=target)
5206 parser.feed(xml.etree.ElementTree.tostring(node))
5207 return parser.close()
5209 for k, v in LEGACY_NAMESPACES:
5211 dfxp_data = dfxp_data.replace(ns, k)
5213 dfxp = compat_etree_fromstring(dfxp_data)
5215 paras = dfxp.findall(_x('.//ttml:p')) or dfxp.findall('.//p')
5218 raise ValueError('Invalid dfxp/TTML subtitle')
5222 for style in dfxp.findall(_x('.//ttml:style')):
5223 style_id = style.get('id') or style.get(_x('xml:id'))
5226 parent_style_id = style.get('style')
5228 if parent_style_id not in styles:
5231 styles[style_id] = styles[parent_style_id].copy()
5232 for prop in SUPPORTED_STYLING:
5233 prop_val = style.get(_x('tts:' + prop))
5235 styles.setdefault(style_id, {})[prop] = prop_val
5241 for p in ('body', 'div'):
5242 ele = xpath_element(dfxp, [_x('.//ttml:' + p), './/' + p])
5245 style = styles.get(ele.get('style'))
5248 default_style.update(style)
5250 for para, index in zip(paras, itertools.count(1)):
5251 begin_time = parse_dfxp_time_expr(para.attrib.get('begin'))
5252 end_time = parse_dfxp_time_expr(para.attrib.get('end'))
5253 dur = parse_dfxp_time_expr(para.attrib.get('dur'))
5254 if begin_time is None:
5259 end_time = begin_time + dur
5260 out.append('%d\n%s --> %s\n%s\n\n' % (
5262 srt_subtitles_timecode(begin_time),
5263 srt_subtitles_timecode(end_time),
5269 def cli_option(params, command_option, param):
5270 param = params.get(param)
5272 param = compat_str(param)
5273 return [command_option, param] if param is not None else []
5276 def cli_bool_option(params, command_option, param, true_value='true', false_value='false', separator=None):
5277 param = params.get(param)
5280 assert isinstance(param, bool)
5282 return [command_option + separator + (true_value if param else false_value)]
5283 return [command_option, true_value if param else false_value]
5286 def cli_valueless_option(params, command_option, param, expected_value=True):
5287 param = params.get(param)
5288 return [command_option] if param == expected_value else []
5291 def cli_configuration_args(argdict, keys, default=[], use_compat=True):
5292 if isinstance(argdict, (list, tuple)): # for backward compatibility
5299 assert isinstance(argdict, dict)
5301 assert isinstance(keys, (list, tuple))
5302 for key_list in keys:
5303 arg_list = list(filter(
5304 lambda x: x is not None,
5305 [argdict.get(key.lower()) for key in variadic(key_list)]))
5307 return [arg for args in arg_list for arg in args]
5311 def _configuration_args(main_key, argdict, exe, keys=None, default=[], use_compat=True):
5312 main_key, exe = main_key.lower(), exe.lower()
5313 root_key = exe if main_key == exe else f'{main_key}+{exe}'
5314 keys = [f'{root_key}{k}' for k in (keys or [''])]
5315 if root_key in keys:
5317 keys.append((main_key, exe))
5318 keys.append('default')
5321 return cli_configuration_args(argdict, keys, default, use_compat)
5324 class ISO639Utils(object):
5325 # See http://www.loc.gov/standards/iso639-2/ISO-639-2_utf-8.txt
5384 'iw': 'heb', # Replaced by he in 1989 revision
5394 'in': 'ind', # Replaced by id in 1989 revision
5509 'ji': 'yid', # Replaced by yi in 1989 revision
5517 def short2long(cls, code):
5518 """Convert language code from ISO 639-1 to ISO 639-2/T"""
5519 return cls._lang_map.get(code[:2])
5522 def long2short(cls, code):
5523 """Convert language code from ISO 639-2/T to ISO 639-1"""
5524 for short_name, long_name in cls._lang_map.items():
5525 if long_name == code:
5529 class ISO3166Utils(object):
5530 # From http://data.okfn.org/data/core/country-list
5532 'AF': 'Afghanistan',
5533 'AX': 'Åland Islands',
5536 'AS': 'American Samoa',
5541 'AG': 'Antigua and Barbuda',
5558 'BO': 'Bolivia, Plurinational State of',
5559 'BQ': 'Bonaire, Sint Eustatius and Saba',
5560 'BA': 'Bosnia and Herzegovina',
5562 'BV': 'Bouvet Island',
5564 'IO': 'British Indian Ocean Territory',
5565 'BN': 'Brunei Darussalam',
5567 'BF': 'Burkina Faso',
5573 'KY': 'Cayman Islands',
5574 'CF': 'Central African Republic',
5578 'CX': 'Christmas Island',
5579 'CC': 'Cocos (Keeling) Islands',
5583 'CD': 'Congo, the Democratic Republic of the',
5584 'CK': 'Cook Islands',
5586 'CI': 'Côte d\'Ivoire',
5591 'CZ': 'Czech Republic',
5595 'DO': 'Dominican Republic',
5598 'SV': 'El Salvador',
5599 'GQ': 'Equatorial Guinea',
5603 'FK': 'Falkland Islands (Malvinas)',
5604 'FO': 'Faroe Islands',
5608 'GF': 'French Guiana',
5609 'PF': 'French Polynesia',
5610 'TF': 'French Southern Territories',
5625 'GW': 'Guinea-Bissau',
5628 'HM': 'Heard Island and McDonald Islands',
5629 'VA': 'Holy See (Vatican City State)',
5636 'IR': 'Iran, Islamic Republic of',
5639 'IM': 'Isle of Man',
5649 'KP': 'Korea, Democratic People\'s Republic of',
5650 'KR': 'Korea, Republic of',
5653 'LA': 'Lao People\'s Democratic Republic',
5659 'LI': 'Liechtenstein',
5663 'MK': 'Macedonia, the Former Yugoslav Republic of',
5670 'MH': 'Marshall Islands',
5676 'FM': 'Micronesia, Federated States of',
5677 'MD': 'Moldova, Republic of',
5688 'NL': 'Netherlands',
5689 'NC': 'New Caledonia',
5690 'NZ': 'New Zealand',
5695 'NF': 'Norfolk Island',
5696 'MP': 'Northern Mariana Islands',
5701 'PS': 'Palestine, State of',
5703 'PG': 'Papua New Guinea',
5706 'PH': 'Philippines',
5710 'PR': 'Puerto Rico',
5714 'RU': 'Russian Federation',
5716 'BL': 'Saint Barthélemy',
5717 'SH': 'Saint Helena, Ascension and Tristan da Cunha',
5718 'KN': 'Saint Kitts and Nevis',
5719 'LC': 'Saint Lucia',
5720 'MF': 'Saint Martin (French part)',
5721 'PM': 'Saint Pierre and Miquelon',
5722 'VC': 'Saint Vincent and the Grenadines',
5725 'ST': 'Sao Tome and Principe',
5726 'SA': 'Saudi Arabia',
5730 'SL': 'Sierra Leone',
5732 'SX': 'Sint Maarten (Dutch part)',
5735 'SB': 'Solomon Islands',
5737 'ZA': 'South Africa',
5738 'GS': 'South Georgia and the South Sandwich Islands',
5739 'SS': 'South Sudan',
5744 'SJ': 'Svalbard and Jan Mayen',
5747 'CH': 'Switzerland',
5748 'SY': 'Syrian Arab Republic',
5749 'TW': 'Taiwan, Province of China',
5751 'TZ': 'Tanzania, United Republic of',
5753 'TL': 'Timor-Leste',
5757 'TT': 'Trinidad and Tobago',
5760 'TM': 'Turkmenistan',
5761 'TC': 'Turks and Caicos Islands',
5765 'AE': 'United Arab Emirates',
5766 'GB': 'United Kingdom',
5767 'US': 'United States',
5768 'UM': 'United States Minor Outlying Islands',
5772 'VE': 'Venezuela, Bolivarian Republic of',
5774 'VG': 'Virgin Islands, British',
5775 'VI': 'Virgin Islands, U.S.',
5776 'WF': 'Wallis and Futuna',
5777 'EH': 'Western Sahara',
5784 def short2full(cls, code):
5785 """Convert an ISO 3166-2 country code to the corresponding full name"""
5786 return cls._country_map.get(code.upper())
5789 class GeoUtils(object):
5790 # Major IPv4 address blocks per country
5792 'AD': '46.172.224.0/19',
5793 'AE': '94.200.0.0/13',
5794 'AF': '149.54.0.0/17',
5795 'AG': '209.59.64.0/18',
5796 'AI': '204.14.248.0/21',
5797 'AL': '46.99.0.0/16',
5798 'AM': '46.70.0.0/15',
5799 'AO': '105.168.0.0/13',
5800 'AP': '182.50.184.0/21',
5801 'AQ': '23.154.160.0/24',
5802 'AR': '181.0.0.0/12',
5803 'AS': '202.70.112.0/20',
5804 'AT': '77.116.0.0/14',
5805 'AU': '1.128.0.0/11',
5806 'AW': '181.41.0.0/18',
5807 'AX': '185.217.4.0/22',
5808 'AZ': '5.197.0.0/16',
5809 'BA': '31.176.128.0/17',
5810 'BB': '65.48.128.0/17',
5811 'BD': '114.130.0.0/16',
5813 'BF': '102.178.0.0/15',
5814 'BG': '95.42.0.0/15',
5815 'BH': '37.131.0.0/17',
5816 'BI': '154.117.192.0/18',
5817 'BJ': '137.255.0.0/16',
5818 'BL': '185.212.72.0/23',
5819 'BM': '196.12.64.0/18',
5820 'BN': '156.31.0.0/16',
5821 'BO': '161.56.0.0/16',
5822 'BQ': '161.0.80.0/20',
5823 'BR': '191.128.0.0/12',
5824 'BS': '24.51.64.0/18',
5825 'BT': '119.2.96.0/19',
5826 'BW': '168.167.0.0/16',
5827 'BY': '178.120.0.0/13',
5828 'BZ': '179.42.192.0/18',
5829 'CA': '99.224.0.0/11',
5830 'CD': '41.243.0.0/16',
5831 'CF': '197.242.176.0/21',
5832 'CG': '160.113.0.0/16',
5833 'CH': '85.0.0.0/13',
5834 'CI': '102.136.0.0/14',
5835 'CK': '202.65.32.0/19',
5836 'CL': '152.172.0.0/14',
5837 'CM': '102.244.0.0/14',
5838 'CN': '36.128.0.0/10',
5839 'CO': '181.240.0.0/12',
5840 'CR': '201.192.0.0/12',
5841 'CU': '152.206.0.0/15',
5842 'CV': '165.90.96.0/19',
5843 'CW': '190.88.128.0/17',
5844 'CY': '31.153.0.0/16',
5845 'CZ': '88.100.0.0/14',
5847 'DJ': '197.241.0.0/17',
5848 'DK': '87.48.0.0/12',
5849 'DM': '192.243.48.0/20',
5850 'DO': '152.166.0.0/15',
5851 'DZ': '41.96.0.0/12',
5852 'EC': '186.68.0.0/15',
5853 'EE': '90.190.0.0/15',
5854 'EG': '156.160.0.0/11',
5855 'ER': '196.200.96.0/20',
5856 'ES': '88.0.0.0/11',
5857 'ET': '196.188.0.0/14',
5858 'EU': '2.16.0.0/13',
5859 'FI': '91.152.0.0/13',
5860 'FJ': '144.120.0.0/16',
5861 'FK': '80.73.208.0/21',
5862 'FM': '119.252.112.0/20',
5863 'FO': '88.85.32.0/19',
5865 'GA': '41.158.0.0/15',
5867 'GD': '74.122.88.0/21',
5868 'GE': '31.146.0.0/16',
5869 'GF': '161.22.64.0/18',
5870 'GG': '62.68.160.0/19',
5871 'GH': '154.160.0.0/12',
5872 'GI': '95.164.0.0/16',
5873 'GL': '88.83.0.0/19',
5874 'GM': '160.182.0.0/15',
5875 'GN': '197.149.192.0/18',
5876 'GP': '104.250.0.0/19',
5877 'GQ': '105.235.224.0/20',
5878 'GR': '94.64.0.0/13',
5879 'GT': '168.234.0.0/16',
5880 'GU': '168.123.0.0/16',
5881 'GW': '197.214.80.0/20',
5882 'GY': '181.41.64.0/18',
5883 'HK': '113.252.0.0/14',
5884 'HN': '181.210.0.0/16',
5885 'HR': '93.136.0.0/13',
5886 'HT': '148.102.128.0/17',
5887 'HU': '84.0.0.0/14',
5888 'ID': '39.192.0.0/10',
5889 'IE': '87.32.0.0/12',
5890 'IL': '79.176.0.0/13',
5891 'IM': '5.62.80.0/20',
5892 'IN': '117.192.0.0/10',
5893 'IO': '203.83.48.0/21',
5894 'IQ': '37.236.0.0/14',
5895 'IR': '2.176.0.0/12',
5896 'IS': '82.221.0.0/16',
5897 'IT': '79.0.0.0/10',
5898 'JE': '87.244.64.0/18',
5899 'JM': '72.27.0.0/17',
5900 'JO': '176.29.0.0/16',
5901 'JP': '133.0.0.0/8',
5902 'KE': '105.48.0.0/12',
5903 'KG': '158.181.128.0/17',
5904 'KH': '36.37.128.0/17',
5905 'KI': '103.25.140.0/22',
5906 'KM': '197.255.224.0/20',
5907 'KN': '198.167.192.0/19',
5908 'KP': '175.45.176.0/22',
5909 'KR': '175.192.0.0/10',
5910 'KW': '37.36.0.0/14',
5911 'KY': '64.96.0.0/15',
5912 'KZ': '2.72.0.0/13',
5913 'LA': '115.84.64.0/18',
5914 'LB': '178.135.0.0/16',
5915 'LC': '24.92.144.0/20',
5916 'LI': '82.117.0.0/19',
5917 'LK': '112.134.0.0/15',
5918 'LR': '102.183.0.0/16',
5919 'LS': '129.232.0.0/17',
5920 'LT': '78.56.0.0/13',
5921 'LU': '188.42.0.0/16',
5922 'LV': '46.109.0.0/16',
5923 'LY': '41.252.0.0/14',
5924 'MA': '105.128.0.0/11',
5925 'MC': '88.209.64.0/18',
5926 'MD': '37.246.0.0/16',
5927 'ME': '178.175.0.0/17',
5928 'MF': '74.112.232.0/21',
5929 'MG': '154.126.0.0/17',
5930 'MH': '117.103.88.0/21',
5931 'MK': '77.28.0.0/15',
5932 'ML': '154.118.128.0/18',
5933 'MM': '37.111.0.0/17',
5934 'MN': '49.0.128.0/17',
5935 'MO': '60.246.0.0/16',
5936 'MP': '202.88.64.0/20',
5937 'MQ': '109.203.224.0/19',
5938 'MR': '41.188.64.0/18',
5939 'MS': '208.90.112.0/22',
5940 'MT': '46.11.0.0/16',
5941 'MU': '105.16.0.0/12',
5942 'MV': '27.114.128.0/18',
5943 'MW': '102.70.0.0/15',
5944 'MX': '187.192.0.0/11',
5945 'MY': '175.136.0.0/13',
5946 'MZ': '197.218.0.0/15',
5947 'NA': '41.182.0.0/16',
5948 'NC': '101.101.0.0/18',
5949 'NE': '197.214.0.0/18',
5950 'NF': '203.17.240.0/22',
5951 'NG': '105.112.0.0/12',
5952 'NI': '186.76.0.0/15',
5953 'NL': '145.96.0.0/11',
5954 'NO': '84.208.0.0/13',
5955 'NP': '36.252.0.0/15',
5956 'NR': '203.98.224.0/19',
5957 'NU': '49.156.48.0/22',
5958 'NZ': '49.224.0.0/14',
5959 'OM': '5.36.0.0/15',
5960 'PA': '186.72.0.0/15',
5961 'PE': '186.160.0.0/14',
5962 'PF': '123.50.64.0/18',
5963 'PG': '124.240.192.0/19',
5964 'PH': '49.144.0.0/13',
5965 'PK': '39.32.0.0/11',
5966 'PL': '83.0.0.0/11',
5967 'PM': '70.36.0.0/20',
5968 'PR': '66.50.0.0/16',
5969 'PS': '188.161.0.0/16',
5970 'PT': '85.240.0.0/13',
5971 'PW': '202.124.224.0/20',
5972 'PY': '181.120.0.0/14',
5973 'QA': '37.210.0.0/15',
5974 'RE': '102.35.0.0/16',
5975 'RO': '79.112.0.0/13',
5976 'RS': '93.86.0.0/15',
5977 'RU': '5.136.0.0/13',
5978 'RW': '41.186.0.0/16',
5979 'SA': '188.48.0.0/13',
5980 'SB': '202.1.160.0/19',
5981 'SC': '154.192.0.0/11',
5982 'SD': '102.120.0.0/13',
5983 'SE': '78.64.0.0/12',
5984 'SG': '8.128.0.0/10',
5985 'SI': '188.196.0.0/14',
5986 'SK': '78.98.0.0/15',
5987 'SL': '102.143.0.0/17',
5988 'SM': '89.186.32.0/19',
5989 'SN': '41.82.0.0/15',
5990 'SO': '154.115.192.0/18',
5991 'SR': '186.179.128.0/17',
5992 'SS': '105.235.208.0/21',
5993 'ST': '197.159.160.0/19',
5994 'SV': '168.243.0.0/16',
5995 'SX': '190.102.0.0/20',
5997 'SZ': '41.84.224.0/19',
5998 'TC': '65.255.48.0/20',
5999 'TD': '154.68.128.0/19',
6000 'TG': '196.168.0.0/14',
6001 'TH': '171.96.0.0/13',
6002 'TJ': '85.9.128.0/18',
6003 'TK': '27.96.24.0/21',
6004 'TL': '180.189.160.0/20',
6005 'TM': '95.85.96.0/19',
6006 'TN': '197.0.0.0/11',
6007 'TO': '175.176.144.0/21',
6008 'TR': '78.160.0.0/11',
6009 'TT': '186.44.0.0/15',
6010 'TV': '202.2.96.0/19',
6011 'TW': '120.96.0.0/11',
6012 'TZ': '156.156.0.0/14',
6013 'UA': '37.52.0.0/14',
6014 'UG': '102.80.0.0/13',
6016 'UY': '167.56.0.0/13',
6017 'UZ': '84.54.64.0/18',
6018 'VA': '212.77.0.0/19',
6019 'VC': '207.191.240.0/21',
6020 'VE': '186.88.0.0/13',
6021 'VG': '66.81.192.0/20',
6022 'VI': '146.226.0.0/16',
6023 'VN': '14.160.0.0/11',
6024 'VU': '202.80.32.0/20',
6025 'WF': '117.20.32.0/21',
6026 'WS': '202.4.32.0/19',
6027 'YE': '134.35.0.0/16',
6028 'YT': '41.242.116.0/22',
6029 'ZA': '41.0.0.0/11',
6030 'ZM': '102.144.0.0/13',
6031 'ZW': '102.177.192.0/18',
6035 def random_ipv4(cls, code_or_block):
6036 if len(code_or_block) == 2:
6037 block = cls._country_ip_map.get(code_or_block.upper())
6041 block = code_or_block
6042 addr, preflen = block.split('/')
6043 addr_min = compat_struct_unpack('!L', socket.inet_aton(addr))[0]
6044 addr_max = addr_min | (0xffffffff >> int(preflen))
6045 return compat_str(socket.inet_ntoa(
6046 compat_struct_pack('!L', random.randint(addr_min, addr_max))))
6049 class PerRequestProxyHandler(compat_urllib_request.ProxyHandler):
6050 def __init__(self, proxies=None):
6051 # Set default handlers
6052 for type in ('http', 'https'):
6053 setattr(self, '%s_open' % type,
6054 lambda r, proxy='__noproxy__', type=type, meth=self.proxy_open:
6055 meth(r, proxy, type))
6056 compat_urllib_request.ProxyHandler.__init__(self, proxies)
6058 def proxy_open(self, req, proxy, type):
6059 req_proxy = req.headers.get('Ytdl-request-proxy')
6060 if req_proxy is not None:
6062 del req.headers['Ytdl-request-proxy']
6064 if proxy == '__noproxy__':
6065 return None # No Proxy
6066 if compat_urlparse.urlparse(proxy).scheme.lower() in ('socks', 'socks4', 'socks4a', 'socks5'):
6067 req.add_header('Ytdl-socks-proxy', proxy)
6068 # yt-dlp's http/https handlers do wrapping the socket with socks
6070 return compat_urllib_request.ProxyHandler.proxy_open(
6071 self, req, proxy, type)
6074 # Both long_to_bytes and bytes_to_long are adapted from PyCrypto, which is
6075 # released into Public Domain
6076 # https://github.com/dlitz/pycrypto/blob/master/lib/Crypto/Util/number.py#L387
6078 def long_to_bytes(n, blocksize=0):
6079 """long_to_bytes(n:long, blocksize:int) : string
6080 Convert a long integer to a byte string.
6082 If optional blocksize is given and greater than zero, pad the front of the
6083 byte string with binary zeros so that the length is a multiple of
6086 # after much testing, this algorithm was deemed to be the fastest
6090 s = compat_struct_pack('>I', n & 0xffffffff) + s
6092 # strip off leading zeros
6093 for i in range(len(s)):
6094 if s[i] != b'\000'[0]:
6097 # only happens when n == 0
6101 # add back some pad bytes. this could be done more efficiently w.r.t. the
6102 # de-padding being done above, but sigh...
6103 if blocksize > 0 and len(s) % blocksize:
6104 s = (blocksize - len(s) % blocksize) * b'\000' + s
6108 def bytes_to_long(s):
6109 """bytes_to_long(string) : long
6110 Convert a byte string to a long integer.
6112 This is (essentially) the inverse of long_to_bytes().
6117 extra = (4 - length % 4)
6118 s = b'\000' * extra + s
6119 length = length + extra
6120 for i in range(0, length, 4):
6121 acc = (acc << 32) + compat_struct_unpack('>I', s[i:i + 4])[0]
6125 def ohdave_rsa_encrypt(data, exponent, modulus):
6127 Implement OHDave
's RSA algorithm. See http://www.ohdave.com/rsa/
6130 data: data to encrypt, bytes-like object
6131 exponent, modulus: parameter e and N of RSA algorithm, both integer
6132 Output: hex string of encrypted data
6134 Limitation: supports one block encryption only
6137 payload = int(binascii.hexlify(data[::-1]), 16)
6138 encrypted = pow(payload, exponent, modulus)
6139 return '%x' % encrypted
6142 def pkcs1pad(data, length):
6144 Padding input data with PKCS#1 scheme
6146 @param {int[]} data input data
6147 @param {int} length target length
6148 @returns {int[]} padded data
6150 if len(data) > length - 11:
6151 raise ValueError('Input data too
long for PKCS
#1 padding')
6153 pseudo_random
= [random
.randint(0, 254) for _
in range(length
- len(data
) - 3)]
6154 return [0, 2] + pseudo_random
+ [0] + data
6157 def encode_base_n(num
, n
, table
=None):
6158 FULL_TABLE
= '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
6160 table
= FULL_TABLE
[:n
]
6163 raise ValueError('base %d exceeds table length %d' % (n
, len(table
)))
6170 ret
= table
[num
% n
] + ret
6175 def decode_packed_codes(code
):
6176 mobj
= re
.search(PACKED_CODES_RE
, code
)
6177 obfuscated_code
, base
, count
, symbols
= mobj
.groups()
6180 symbols
= symbols
.split('|')
6185 base_n_count
= encode_base_n(count
, base
)
6186 symbol_table
[base_n_count
] = symbols
[count
] or base_n_count
6189 r
'\b(\w+)\b', lambda mobj
: symbol_table
[mobj
.group(0)],
6193 def caesar(s
, alphabet
, shift
):
6198 alphabet
[(alphabet
.index(c
) + shift
) % l
] if c
in alphabet
else c
6203 return caesar(s
, r
'''!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~''', 47)
6206 def parse_m3u8_attributes(attrib
):
6208 for (key
, val
) in re
.findall(r
'(?P<key>[A-Z0-9-]+)=(?P<val>"[^"]+"|[^",]+)(?:,|$)', attrib
):
6209 if val
.startswith('"'):
6215 def urshift(val
, n
):
6216 return val
>> n
if val
>= 0 else (val
+ 0x100000000) >> n
6219 # Based on png2str() written by @gdkchan and improved by @yokrysty
6220 # Originally posted at https://github.com/ytdl-org/youtube-dl/issues/9706
6221 def decode_png(png_data
):
6222 # Reference: https://www.w3.org/TR/PNG/
6223 header
= png_data
[8:]
6225 if png_data
[:8] != b
'\x89PNG\x0d\x0a\x1a\x0a' or header
[4:8] != b
'IHDR':
6226 raise IOError('Not a valid PNG file.')
6228 int_map
= {1: '>B', 2: '>H', 4: '>I'}
6229 unpack_integer
= lambda x
: compat_struct_unpack(int_map
[len(x
)], x
)[0]
6234 length
= unpack_integer(header
[:4])
6237 chunk_type
= header
[:4]
6240 chunk_data
= header
[:length
]
6241 header
= header
[length
:]
6243 header
= header
[4:] # Skip CRC
6251 ihdr
= chunks
[0]['data']
6253 width
= unpack_integer(ihdr
[:4])
6254 height
= unpack_integer(ihdr
[4:8])
6258 for chunk
in chunks
:
6259 if chunk
['type'] == b
'IDAT':
6260 idat
+= chunk
['data']
6263 raise IOError('Unable to read PNG data.')
6265 decompressed_data
= bytearray(zlib
.decompress(idat
))
6270 def _get_pixel(idx
):
6275 for y
in range(height
):
6276 basePos
= y
* (1 + stride
)
6277 filter_type
= decompressed_data
[basePos
]
6281 pixels
.append(current_row
)
6283 for x
in range(stride
):
6284 color
= decompressed_data
[1 + basePos
+ x
]
6285 basex
= y
* stride
+ x
6290 left
= _get_pixel(basex
- 3)
6292 up
= _get_pixel(basex
- stride
)
6294 if filter_type
== 1: # Sub
6295 color
= (color
+ left
) & 0xff
6296 elif filter_type
== 2: # Up
6297 color
= (color
+ up
) & 0xff
6298 elif filter_type
== 3: # Average
6299 color
= (color
+ ((left
+ up
) >> 1)) & 0xff
6300 elif filter_type
== 4: # Paeth
6306 c
= _get_pixel(basex
- stride
- 3)
6314 if pa
<= pb
and pa
<= pc
:
6315 color
= (color
+ a
) & 0xff
6317 color
= (color
+ b
) & 0xff
6319 color
= (color
+ c
) & 0xff
6321 current_row
.append(color
)
6323 return width
, height
, pixels
6326 def write_xattr(path
, key
, value
):
6327 # This mess below finds the best xattr tool for the job
6329 # try the pyxattr module...
6332 if hasattr(xattr
, 'set'): # pyxattr
6333 # Unicode arguments are not supported in python-pyxattr until
6335 # See https://github.com/ytdl-org/youtube-dl/issues/5498
6336 pyxattr_required_version
= '0.5.0'
6337 if version_tuple(xattr
.__version
__) < version_tuple(pyxattr_required_version
):
6338 # TODO: fallback to CLI tools
6339 raise XAttrUnavailableError(
6340 'python-pyxattr is detected but is too old. '
6341 'yt-dlp requires %s or above while your version is %s. '
6342 'Falling back to other xattr implementations' % (
6343 pyxattr_required_version
, xattr
.__version
__))
6345 setxattr
= xattr
.set
6347 setxattr
= xattr
.setxattr
6350 setxattr(path
, key
, value
)
6351 except EnvironmentError as e
:
6352 raise XAttrMetadataError(e
.errno
, e
.strerror
)
6355 if compat_os_name
== 'nt':
6356 # Write xattrs to NTFS Alternate Data Streams:
6357 # http://en.wikipedia.org/wiki/NTFS#Alternate_data_streams_.28ADS.29
6358 assert ':' not in key
6359 assert os
.path
.exists(path
)
6361 ads_fn
= path
+ ':' + key
6363 with open(ads_fn
, 'wb') as f
:
6365 except EnvironmentError as e
:
6366 raise XAttrMetadataError(e
.errno
, e
.strerror
)
6368 user_has_setfattr
= check_executable('setfattr', ['--version'])
6369 user_has_xattr
= check_executable('xattr', ['-h'])
6371 if user_has_setfattr
or user_has_xattr
:
6373 value
= value
.decode('utf-8')
6374 if user_has_setfattr
:
6375 executable
= 'setfattr'
6376 opts
= ['-n', key
, '-v', value
]
6377 elif user_has_xattr
:
6378 executable
= 'xattr'
6379 opts
= ['-w', key
, value
]
6381 cmd
= ([encodeFilename(executable
, True)]
6382 + [encodeArgument(o
) for o
in opts
]
6383 + [encodeFilename(path
, True)])
6387 cmd
, stdout
=subprocess
.PIPE
, stderr
=subprocess
.PIPE
, stdin
=subprocess
.PIPE
)
6388 except EnvironmentError as e
:
6389 raise XAttrMetadataError(e
.errno
, e
.strerror
)
6390 stdout
, stderr
= p
.communicate_or_kill()
6391 stderr
= stderr
.decode('utf-8', 'replace')
6392 if p
.returncode
!= 0:
6393 raise XAttrMetadataError(p
.returncode
, stderr
)
6396 # On Unix, and can't find pyxattr, setfattr, or xattr.
6397 if sys
.platform
.startswith('linux'):
6398 raise XAttrUnavailableError(
6399 "Couldn't find a tool to set the xattrs. "
6400 "Install either the python 'pyxattr' or 'xattr' "
6401 "modules, or the GNU 'attr' package "
6402 "(which contains the 'setfattr' tool).")
6404 raise XAttrUnavailableError(
6405 "Couldn't find a tool to set the xattrs. "
6406 "Install either the python 'xattr' module, "
6407 "or the 'xattr' binary.")
6410 def random_birthday(year_field
, month_field
, day_field
):
6411 start_date
= datetime
.date(1950, 1, 1)
6412 end_date
= datetime
.date(1995, 12, 31)
6413 offset
= random
.randint(0, (end_date
- start_date
).days
)
6414 random_date
= start_date
+ datetime
.timedelta(offset
)
6416 year_field
: str(random_date
.year
),
6417 month_field
: str(random_date
.month
),
6418 day_field
: str(random_date
.day
),
6422 # Templates for internet shortcut files, which are plain text files.
6423 DOT_URL_LINK_TEMPLATE
= '''
6428 DOT_WEBLOC_LINK_TEMPLATE
= '''
6429 <?xml version="1.0" encoding="UTF-8"?>
6430 <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
6431 <plist version="1.0">
6434 \t<string>%(url)s</string>
6439 DOT_DESKTOP_LINK_TEMPLATE
= '''
6449 'url': DOT_URL_LINK_TEMPLATE
,
6450 'desktop': DOT_DESKTOP_LINK_TEMPLATE
,
6451 'webloc': DOT_WEBLOC_LINK_TEMPLATE
,
6455 def iri_to_uri(iri
):
6457 Converts an IRI (Internationalized Resource Identifier, allowing Unicode characters) to a URI (Uniform Resource Identifier, ASCII-only).
6459 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.
6462 iri_parts
= compat_urllib_parse_urlparse(iri
)
6464 if '[' in iri_parts
.netloc
:
6465 raise ValueError('IPv6 URIs are not, yet, supported.')
6466 # Querying `.netloc`, when there's only one bracket, also raises a ValueError.
6468 # 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.
6471 if iri_parts
.username
:
6472 net_location
+= compat_urllib_parse_quote(iri_parts
.username
, safe
=r
"!$%&'()*+,~")
6473 if iri_parts
.password
is not None:
6474 net_location
+= ':' + compat_urllib_parse_quote(iri_parts
.password
, safe
=r
"!$%&'()*+,~")
6477 net_location
+= iri_parts
.hostname
.encode('idna').decode('utf-8') # Punycode for Unicode hostnames.
6478 # The 'idna' encoding produces ASCII text.
6479 if iri_parts
.port
is not None and iri_parts
.port
!= 80:
6480 net_location
+= ':' + str(iri_parts
.port
)
6482 return compat_urllib_parse_urlunparse(
6486 compat_urllib_parse_quote_plus(iri_parts
.path
, safe
=r
"!$%&'()*+,/:;=@|~"),
6488 # Unsure about the `safe` argument, since this is a legacy way of handling parameters.
6489 compat_urllib_parse_quote_plus(iri_parts
.params
, safe
=r
"!$%&'()*+,/:;=@|~"),
6491 # Not totally sure about the `safe` argument, since the source does not explicitly mention the query URI component.
6492 compat_urllib_parse_quote_plus(iri_parts
.query
, safe
=r
"!$%&'()*+,/:;=?@{|}~"),
6494 compat_urllib_parse_quote_plus(iri_parts
.fragment
, safe
=r
"!#$%&'()*+,/:;=?@{|}~")))
6496 # Source for `safe` arguments: https://url.spec.whatwg.org/#percent-encoded-bytes.
6499 def to_high_limit_path(path
):
6500 if sys
.platform
in ['win32', 'cygwin']:
6501 # Work around MAX_PATH limitation on Windows. The maximum allowed length for the individual path segments may still be quite limited.
6502 return r
'\\?\ '.rstrip() + os
.path
.abspath(path
)
6507 def format_field(obj
, field
=None, template
='%s', ignore
=(None, ''), default
='', func
=None):
6509 val
= obj
if obj
is not None else default
6511 val
= obj
.get(field
, default
)
6512 if func
and val
not in ignore
:
6514 return template
% val
if val
not in ignore
else default
6517 def clean_podcast_url(url
):
6518 return re
.sub(r
'''(?x)
6522 media\.blubrry\.com| # https://create.blubrry.com/resources/podcast-media-download-statistics/getting-started/
6525 (?:dts|www)\.podtrac\.com/(?:pts/)?redirect\.[0-9a-z]{3,4}| # http://analytics.podtrac.com/how-to-measure
6528 cn\.co| # https://podcorn.com/analytics-prefix/
6529 st\.fm # https://podsights.com/docs/
6534 _HEX_TABLE
= '0123456789abcdef'
6537 def random_uuidv4():
6538 return re
.sub(r
'[xy]', lambda x
: _HEX_TABLE
[random
.randint(0, 15)], 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx')
6541 def make_dir(path
, to_screen
=None):
6543 dn
= os
.path
.dirname(path
)
6544 if dn
and not os
.path
.exists(dn
):
6547 except (OSError, IOError) as err
:
6548 if callable(to_screen
) is not None:
6549 to_screen('unable to create directory ' + error_to_compat_str(err
))
6553 def get_executable_path():
6554 from zipimport
import zipimporter
6555 if hasattr(sys
, 'frozen'): # Running from PyInstaller
6556 path
= os
.path
.dirname(sys
.executable
)
6557 elif isinstance(globals().get('__loader__'), zipimporter
): # Running from ZIP
6558 path
= os
.path
.join(os
.path
.dirname(__file__
), '../..')
6560 path
= os
.path
.join(os
.path
.dirname(__file__
), '..')
6561 return os
.path
.abspath(path
)
6564 def load_plugins(name
, suffix
, namespace
):
6567 plugins_spec
= importlib
.util
.spec_from_file_location(
6568 name
, os
.path
.join(get_executable_path(), 'ytdlp_plugins', name
, '__init__.py'))
6569 plugins
= importlib
.util
.module_from_spec(plugins_spec
)
6570 sys
.modules
[plugins_spec
.name
] = plugins
6571 plugins_spec
.loader
.exec_module(plugins
)
6572 for name
in dir(plugins
):
6573 if name
in namespace
:
6575 if not name
.endswith(suffix
):
6577 klass
= getattr(plugins
, name
)
6578 classes
[name
] = namespace
[name
] = klass
6579 except FileNotFoundError
:
6585 obj
, *path_list
, default
=None, expected_type
=None, get_all
=True,
6586 casesense
=True, is_user_input
=False, traverse_string
=False):
6587 ''' Traverse nested list/dict/tuple
6588 @param path_list A list of paths which are checked one by one.
6589 Each path is a list of keys where each key is a string,
6590 a function, a tuple of strings/None or "...".
6591 When a fuction is given, it takes the key as argument and
6592 returns whether the key matches or not. When a tuple is given,
6593 all the keys given in the tuple are traversed, and
6594 "..." traverses all the keys in the object
6595 "None" returns the object without traversal
6596 @param default Default value to return
6597 @param expected_type Only accept final value of this type (Can also be any callable)
6598 @param get_all Return all the values obtained from a path or only the first one
6599 @param casesense Whether to consider dictionary keys as case sensitive
6600 @param is_user_input Whether the keys are generated from user input. If True,
6601 strings are converted to int/slice if necessary
6602 @param traverse_string Whether to traverse inside strings. If True, any
6603 non-compatible object will also be converted into a string
6607 _lower
= lambda k
: (k
.lower() if isinstance(k
, str) else k
)
6608 path_list
= (map(_lower
, variadic(path
)) for path
in path_list
)
6610 def _traverse_obj(obj
, path
, _current_depth
=0):
6612 path
= tuple(variadic(path
))
6613 for i
, key
in enumerate(path
):
6614 if None in (key
, obj
):
6616 if isinstance(key
, (list, tuple)):
6617 obj
= [_traverse_obj(obj
, sub_key
, _current_depth
) for sub_key
in key
]
6620 obj
= (obj
.values() if isinstance(obj
, dict)
6621 else obj
if isinstance(obj
, (list, tuple, LazyList
))
6622 else str(obj
) if traverse_string
else [])
6624 depth
= max(depth
, _current_depth
)
6625 return [_traverse_obj(inner_obj
, path
[i
+ 1:], _current_depth
) for inner_obj
in obj
]
6627 if isinstance(obj
, (list, tuple, LazyList
)):
6628 obj
= enumerate(obj
)
6629 elif isinstance(obj
, dict):
6632 if not traverse_string
:
6636 depth
= max(depth
, _current_depth
)
6637 return [_traverse_obj(v
, path
[i
+ 1:], _current_depth
) for k
, v
in obj
if key(k
)]
6638 elif isinstance(obj
, dict) and not (is_user_input
and key
== ':'):
6639 obj
= (obj
.get(key
) if casesense
or (key
in obj
)
6640 else next((v
for k
, v
in obj
.items() if _lower(k
) == key
), None))
6643 key
= (int_or_none(key
) if ':' not in key
6644 else slice(*map(int_or_none
, key
.split(':'))))
6645 if key
== slice(None):
6646 return _traverse_obj(obj
, (..., *path
[i
+ 1:]), _current_depth
)
6647 if not isinstance(key
, (int, slice)):
6649 if not isinstance(obj
, (list, tuple, LazyList
)):
6650 if not traverse_string
:
6659 if isinstance(expected_type
, type):
6660 type_test
= lambda val
: val
if isinstance(val
, expected_type
) else None
6661 elif expected_type
is not None:
6662 type_test
= expected_type
6664 type_test
= lambda val
: val
6666 for path
in path_list
:
6668 val
= _traverse_obj(obj
, path
)
6671 for _
in range(depth
- 1):
6672 val
= itertools
.chain
.from_iterable(v
for v
in val
if v
is not None)
6673 val
= [v
for v
in map(type_test
, val
) if v
is not None]
6675 return val
if get_all
else val
[0]
6677 val
= type_test(val
)
6683 def traverse_dict(dictn
, keys
, casesense
=True):
6684 write_string('DeprecationWarning: yt_dlp.utils.traverse_dict is deprecated '
6685 'and may be removed in a future version. Use yt_dlp.utils.traverse_obj instead')
6686 return traverse_obj(dictn
, keys
, casesense
=casesense
, is_user_input
=True, traverse_string
=True)
6689 def variadic(x
, allowed_types
=(str, bytes, dict)):
6690 return x
if isinstance(x
, collections
.abc
.Iterable
) and not isinstance(x
, allowed_types
) else (x
,)
6693 # create a JSON Web Signature (jws) with HS256 algorithm
6694 # the resulting format is in JWS Compact Serialization
6695 # implemented following JWT https://www.rfc-editor.org/rfc/rfc7519.html
6696 # implemented following JWS https://www.rfc-editor.org/rfc/rfc7515.html
6697 def jwt_encode_hs256(payload_data
, key
, headers
={}):
6703 header_data
.update(headers
)
6704 header_b64
= base64
.b64encode(json
.dumps(header_data
).encode('utf-8'))
6705 payload_b64
= base64
.b64encode(json
.dumps(payload_data
).encode('utf-8'))
6706 h
= hmac
.new(key
.encode('utf-8'), header_b64
+ b
'.' + payload_b64
, hashlib
.sha256
)
6707 signature_b64
= base64
.b64encode(h
.digest())
6708 token
= header_b64
+ b
'.' + payload_b64
+ b
'.' + signature_b64
6712 # can be extended in future to verify the signature and parse header and return the algorithm used if it's not HS256
6713 def jwt_decode_hs256(jwt
):
6714 header_b64
, payload_b64
, signature_b64
= jwt
.split('.')
6715 payload_data
= json
.loads(base64
.urlsafe_b64decode(payload_b64
))
6719 def supports_terminal_sequences(stream
):
6720 if compat_os_name
== 'nt':
6721 from .compat
import WINDOWS_VT_MODE
# Must be imported locally
6722 if not WINDOWS_VT_MODE
or get_windows_version() < (10, 0, 10586):
6724 elif not os
.getenv('TERM'):
6727 return stream
.isatty()
6728 except BaseException
:
6732 _terminal_sequences_re
= re
.compile('\033\\[[^m]+m')
6735 def remove_terminal_sequences(string
):
6736 return _terminal_sequences_re
.sub('', string
)
6739 def number_of_digits(number
):
6740 return len('%d' % number
)
6743 def join_nonempty(*values
, delim
='-', from_dict
=None):
6744 if from_dict
is not None:
6745 values
= map(from_dict
.get
, values
)
6746 return delim
.join(map(str, filter(None, values
)))
6752 __initialized
= False
6754 def __init__(self
, parser
, label
=None):
6755 self
._parser
, self
.label
= parser
, label
6756 self
._loaded
_paths
, self
.configs
= set(), []
6758 def init(self
, args
=None, filename
=None):
6759 assert not self
.__initialized
6761 location
= os
.path
.realpath(filename
)
6762 if location
in self
._loaded
_paths
:
6764 self
._loaded
_paths
.add(location
)
6766 self
.__initialized
= True
6767 self
.own_args
, self
.filename
= args
, filename
6768 for location
in self
._parser
.parse_args(args
)[0].config_locations
or []:
6769 location
= compat_expanduser(location
)
6770 if os
.path
.isdir(location
):
6771 location
= os
.path
.join(location
, 'yt-dlp.conf')
6772 if not os
.path
.exists(location
):
6773 self
._parser
.error(f
'config location {location} does not exist')
6774 self
.append_config(self
.read_file(location
), location
)
6778 label
= join_nonempty(
6779 self
.label
, 'config', f
'"{self.filename}"' if self
.filename
else '',
6781 return join_nonempty(
6782 self
.own_args
is not None and f
'{label[0].upper()}{label[1:]}: {self.hide_login_info(self.own_args)}',
6783 *(f
'\n{c}'.replace('\n', '\n| ')[1:] for c
in self
.configs
),
6787 def read_file(filename
, default
=[]):
6789 optionf
= open(filename
)
6791 return default
# silently skip if file is not present
6793 # FIXME: https://github.com/ytdl-org/youtube-dl/commit/dfe5fa49aed02cf36ba9f743b11b0903554b5e56
6794 contents
= optionf
.read()
6795 if sys
.version_info
< (3,):
6796 contents
= contents
.decode(preferredencoding())
6797 res
= compat_shlex_split(contents
, comments
=True)
6803 def hide_login_info(opts
):
6804 PRIVATE_OPTS
= set(['-p', '--password', '-u', '--username', '--video-password', '--ap-password', '--ap-username'])
6805 eqre
= re
.compile('^(?P<key>' + ('|'.join(re
.escape(po
) for po
in PRIVATE_OPTS
)) + ')=.+$')
6810 return m
.group('key') + '=PRIVATE'
6814 opts
= list(map(_scrub_eq
, opts
))
6815 for idx
, opt
in enumerate(opts
):
6816 if opt
in PRIVATE_OPTS
and idx
+ 1 < len(opts
):
6817 opts
[idx
+ 1] = 'PRIVATE'
6820 def append_config(self
, *args
, label
=None):
6821 config
= type(self
)(self
._parser
, label
)
6822 config
._loaded
_paths
= self
._loaded
_paths
6823 if config
.init(*args
):
6824 self
.configs
.append(config
)
6828 for config
in reversed(self
.configs
):
6829 yield from config
.all_args
6830 yield from self
.own_args
or []
6832 def parse_args(self
):
6833 return self
._parser
.parse_args(list(self
.all_args
))