Compare commits

..

4 Commits

Author SHA1 Message Date
pukkandan
230d5c8239
[jsinterp] Some optimizations and refactoring
Motivated by: https://github.com/ytdl-org/youtube-dl/issues/30641#issuecomment-1041904912

Authored by: dirkf, pukkandan
2022-06-21 23:23:48 +05:30
pukkandan
e4afcfde08
[build] Add Linux standalone builds 2022-06-21 17:02:57 +05:30
pukkandan
8372be7469
[update] Self-restart after update 2022-06-21 17:02:57 +05:30
pukkandan
57e0f077a6
[update] Expose more functionality to API 2022-06-21 17:02:56 +05:30
8 changed files with 321 additions and 240 deletions

View File

@ -70,14 +70,16 @@ jobs:
build_unix:
needs: create_release
runs-on: ubuntu-latest
runs-on: ubuntu-18.04 # Standalone executable should be built on minimum supported OS
outputs:
sha256_bin: ${{ steps.get_sha.outputs.sha256_bin }}
sha512_bin: ${{ steps.get_sha.outputs.sha512_bin }}
sha256_tar: ${{ steps.get_sha.outputs.sha256_tar }}
sha512_tar: ${{ steps.get_sha.outputs.sha512_tar }}
sha256_unix_zip: ${{ steps.get_sha.outputs.sha256_unix_zip }}
sha512_unix_zip: ${{ steps.get_sha.outputs.sha512_unix_zip }}
sha256_linux: ${{ steps.get_sha.outputs.sha256_linux }}
sha512_linux: ${{ steps.get_sha.outputs.sha512_linux }}
sha256_linux_zip: ${{ steps.get_sha.outputs.sha256_linux_zip }}
sha512_linux_zip: ${{ steps.get_sha.outputs.sha512_linux_zip }}
steps:
- uses: actions/checkout@v2
@ -94,9 +96,12 @@ jobs:
run: |
python devscripts/update-version.py ${{ needs.create_release.outputs.version_suffix }}
python devscripts/make_lazy_extractors.py
- name: Build UNIX executables
- name: Build Unix executables
run: |
make all tar
python pyinst.py --onedir
(cd ./dist/yt-dlp_linux && zip -r ../yt-dlp_linux.zip .)
python pyinst.py
- name: Get SHA2-SUMS
id: get_sha
run: |
@ -104,6 +109,10 @@ jobs:
echo "::set-output name=sha512_bin::$(sha512sum yt-dlp | awk '{print $1}')"
echo "::set-output name=sha256_tar::$(sha256sum yt-dlp.tar.gz | awk '{print $1}')"
echo "::set-output name=sha512_tar::$(sha512sum yt-dlp.tar.gz | awk '{print $1}')"
echo "::set-output name=sha256_linux::$(sha256sum dist/yt-dlp_linux | awk '{print $1}')"
echo "::set-output name=sha512_linux::$(sha512sum dist/yt-dlp_linux | awk '{print $1}')"
echo "::set-output name=sha256_linux_zip::$(sha256sum dist/yt-dlp_linux.zip | awk '{print $1}')"
echo "::set-output name=sha512_linux_zip::$(sha512sum dist/yt-dlp_linux.zip | awk '{print $1}')"
- name: Upload zip binary
uses: actions/upload-release-asset@v1
@ -123,6 +132,24 @@ jobs:
asset_path: ./yt-dlp.tar.gz
asset_name: yt-dlp.tar.gz
asset_content_type: application/gzip
- name: Upload standalone binary
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ needs.create_release.outputs.upload_url }}
asset_path: ./dist/yt-dlp_linux
asset_name: yt-dlp_linux
asset_content_type: application/octet-stream
- name: Upload onedir binary
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ needs.create_release.outputs.upload_url }}
asset_path: ./dist/yt-dlp_linux.zip
asset_name: yt-dlp_linux.zip
asset_content_type: application/zip
- name: Build and publish on PyPi
env:
@ -330,6 +357,8 @@ jobs:
run: |
echo "${{ needs.build_unix.outputs.sha256_bin }} yt-dlp" >> SHA2-256SUMS
echo "${{ needs.build_unix.outputs.sha256_tar }} yt-dlp.tar.gz" >> SHA2-256SUMS
echo "${{ needs.build_unix.outputs.sha256_linux }} yt-dlp_linux" >> SHA2-256SUMS
echo "${{ needs.build_unix.outputs.sha256_linux_zip }} yt-dlp_linux.zip" >> SHA2-256SUMS
echo "${{ needs.build_windows.outputs.sha256_win }} yt-dlp.exe" >> SHA2-256SUMS
echo "${{ needs.build_windows.outputs.sha256_py2exe }} yt-dlp_min.exe" >> SHA2-256SUMS
echo "${{ needs.build_windows32.outputs.sha256_win32 }} yt-dlp_x86.exe" >> SHA2-256SUMS
@ -338,6 +367,8 @@ jobs:
echo "${{ needs.build_macos.outputs.sha256_macos_zip }} yt-dlp_macos.zip" >> SHA2-256SUMS
echo "${{ needs.build_unix.outputs.sha512_bin }} yt-dlp" >> SHA2-512SUMS
echo "${{ needs.build_unix.outputs.sha512_tar }} yt-dlp.tar.gz" >> SHA2-512SUMS
echo "${{ needs.build_unix.outputs.sha512_linux }} yt-dlp_linux" >> SHA2-512SUMS
echo "${{ needs.build_unix.outputs.sha512_linux_zip }} yt-dlp_linux.zip" >> SHA2-512SUMS
echo "${{ needs.build_windows.outputs.sha512_win }} yt-dlp.exe" >> SHA2-512SUMS
echo "${{ needs.build_windows.outputs.sha512_py2exe }} yt-dlp_min.exe" >> SHA2-512SUMS
echo "${{ needs.build_windows32.outputs.sha512_win32 }} yt-dlp_x86.exe" >> SHA2-512SUMS

View File

@ -248,6 +248,8 @@ File|Description
:---|:---
[yt-dlp_x86.exe](https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp_x86.exe)|Windows (Vista SP2+) standalone x86 (32-bit) binary
[yt-dlp_min.exe](https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp_min.exe)|Windows (Win7 SP1+) standalone x64 binary built with `py2exe`<br/> ([Not recommended](#standalone-py2exe-builds-windows))
[yt-dlp_linux](https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp_linux)|UNIX standalone x64 binary
[yt-dlp_linux.zip](https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp_linux.zip)|Unpackaged Unix executable (no auto-update)
[yt-dlp_win.zip](https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp_win.zip)|Unpackaged Windows executable (no auto-update)
[yt-dlp_macos.zip](https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp_macos.zip)|Unpackaged MacOS (10.15+) executable (no auto-update)

View File

@ -5,7 +5,6 @@ import sys
from PyInstaller.__main__ import run as run_pyinstaller
OS_NAME, ARCH = sys.platform, platform.architecture()[0][:2]
@ -64,7 +63,7 @@ def exe(onedir):
"""@returns (name, path)"""
name = '_'.join(filter(None, (
'yt-dlp',
OS_NAME == 'darwin' and 'macos',
{'win32': '', 'darwin': 'macos'}.get(OS_NAME, OS_NAME),
ARCH == '32' and 'x86'
)))
return name, ''.join(filter(None, (

View File

@ -26,7 +26,7 @@ from .postprocessor import (
MetadataFromFieldPP,
MetadataParserPP,
)
from .update import run_update
from .update import Updater
from .utils import (
NO_DEFAULT,
POSTPROCESS_WHEN,
@ -879,17 +879,23 @@ def _real_main(argv=None):
return
with YoutubeDL(ydl_opts) as ydl:
pre_process = opts.update_self or opts.rm_cachedir
actual_use = all_urls or opts.load_info_filename
if opts.rm_cachedir:
ydl.cache.remove()
if opts.update_self and run_update(ydl) and actual_use:
# If updater returns True, exit. Required for windows
return 100, 'ERROR: The program must exit for the update to complete'
updater = Updater(ydl)
if opts.update_self and updater.update() and actual_use:
if updater.cmd:
return updater.restart()
# This code is reachable only for zip variant in py < 3.10
# It makes sense to exit here, but the old behavior is to continue
ydl.report_warning('Restart yt-dlp to use the updated version')
# return 100, 'ERROR: The program must exit for the update to complete'
if not actual_use:
if opts.update_self or opts.rm_cachedir:
if pre_process:
return ydl._download_retcode
ydl.warn_if_short_id(sys.argv[1:] if argv is None else argv)

View File

@ -55,7 +55,7 @@ if compat_os_name == 'nt' and sys.version_info < (3, 8):
def compat_realpath(path):
while os.path.islink(path):
path = os.path.abspath(os.readlink(path))
return path
return os.path.realpath(path)
else:
compat_realpath = os.path.realpath

View File

@ -6,22 +6,19 @@ import re
from .utils import ExtractorError, remove_quotes
_OPERATORS = [
('|', operator.or_),
('^', operator.xor),
('&', operator.and_),
('>>', operator.rshift),
('<<', operator.lshift),
('-', operator.sub),
('+', operator.add),
('%', operator.mod),
('/', operator.truediv),
('*', operator.mul),
]
_ASSIGN_OPERATORS = [(op + '=', opfunc) for op, opfunc in _OPERATORS]
_ASSIGN_OPERATORS.append(('=', (lambda cur, right: right)))
_NAME_RE = r'[a-zA-Z_$][a-zA-Z_$0-9]*'
_NAME_RE = r'[a-zA-Z_$][\w$]*'
_OPERATORS = {
'|': operator.or_,
'^': operator.xor,
'&': operator.and_,
'>>': operator.rshift,
'<<': operator.lshift,
'-': operator.sub,
'+': operator.add,
'%': operator.mod,
'/': operator.truediv,
'*': operator.mul,
}
_MATCHING_PARENS = dict(zip('({[', ')}]'))
_QUOTES = '\'"'
@ -50,13 +47,11 @@ class LocalNameSpace(collections.ChainMap):
class JSInterpreter:
__named_object_counter = 0
def __init__(self, code, objects=None):
if objects is None:
objects = {}
self.code = code
self._functions = {}
self._objects = objects
self.__named_object_counter = 0
self.code, self._functions = code, {}
self._objects = {} if objects is None else objects
def _named_object(self, namespace, obj):
self.__named_object_counter += 1
@ -93,9 +88,9 @@ class JSInterpreter:
break
yield expr[start:]
@staticmethod
def _separate_at_paren(expr, delim):
separated = list(JSInterpreter._separate(expr, delim, 1))
@classmethod
def _separate_at_paren(cls, expr, delim):
separated = list(cls._separate(expr, delim, 1))
if len(separated) < 2:
raise ExtractorError(f'No terminating paren {delim} in {expr}')
return separated[0][1:].strip(), separated[1].strip()
@ -104,33 +99,29 @@ class JSInterpreter:
if allow_recursion < 0:
raise ExtractorError('Recursion limit reached')
sub_statements = list(self._separate(stmt, ';'))
stmt = (sub_statements or ['']).pop()
should_abort = False
sub_statements = list(self._separate(stmt, ';')) or ['']
stmt = sub_statements.pop().lstrip()
for sub_stmt in sub_statements:
ret, should_abort = self.interpret_statement(sub_stmt, local_vars, allow_recursion - 1)
if should_abort:
return ret
return ret, should_abort
should_abort = False
stmt = stmt.lstrip()
stmt_m = re.match(r'var\s', stmt)
if stmt_m:
expr = stmt[len(stmt_m.group(0)):]
m = re.match(r'(?P<var>var\s)|return(?:\s+|$)', stmt)
if not m: # Try interpreting it as an expression
expr = stmt
elif m.group('var'):
expr = stmt[len(m.group(0)):]
else:
return_m = re.match(r'return(?:\s+|$)', stmt)
if return_m:
expr = stmt[len(return_m.group(0)):]
should_abort = True
else:
# Try interpreting it as an expression
expr = stmt
expr = stmt[len(m.group(0)):]
should_abort = True
v = self.interpret_expression(expr, local_vars, allow_recursion)
return v, should_abort
return self.interpret_expression(expr, local_vars, allow_recursion), should_abort
def interpret_expression(self, expr, local_vars, allow_recursion):
expr = expr.strip()
if expr == '': # Empty expression
if not expr:
return None
if expr.startswith('{'):
@ -156,8 +147,8 @@ class JSInterpreter:
for item in self._separate(inner)])
expr = name + outer
m = re.match(r'try\s*', expr)
if m:
m = re.match(r'(?P<try>try)\s*|(?:(?P<catch>catch)|(?P<for>for)|(?P<switch>switch))\s*\(', expr)
if m and m.group('try'):
if expr[m.end()] == '{':
try_expr, expr = self._separate_at_paren(expr[m.end():], '}')
else:
@ -167,21 +158,19 @@ class JSInterpreter:
return ret
return self.interpret_statement(expr, local_vars, allow_recursion - 1)[0]
m = re.match(r'catch\s*\(', expr)
if m:
elif m and m.group('catch'):
# We ignore the catch block
_, expr = self._separate_at_paren(expr, '}')
return self.interpret_statement(expr, local_vars, allow_recursion - 1)[0]
m = re.match(r'for\s*\(', expr)
if m:
elif m and m.group('for'):
constructor, remaining = self._separate_at_paren(expr[m.end() - 1:], ')')
if remaining.startswith('{'):
body, expr = self._separate_at_paren(remaining, '}')
else:
m = re.match(r'switch\s*\(', remaining) # FIXME
if m:
switch_val, remaining = self._separate_at_paren(remaining[m.end() - 1:], ')')
switch_m = re.match(r'switch\s*\(', remaining) # FIXME
if switch_m:
switch_val, remaining = self._separate_at_paren(remaining[switch_m.end() - 1:], ')')
body, expr = self._separate_at_paren(remaining, '}')
body = 'switch(%s){%s}' % (switch_val, body)
else:
@ -206,8 +195,7 @@ class JSInterpreter:
f'Premature return in the initialization of a for loop in {constructor!r}')
return self.interpret_statement(expr, local_vars, allow_recursion - 1)[0]
m = re.match(r'switch\s*\(', expr)
if m:
elif m and m.group('switch'):
switch_val, remaining = self._separate_at_paren(expr[m.end() - 1:], ')')
switch_val = self.interpret_expression(switch_val, local_vars, allow_recursion)
body, expr = self._separate_at_paren(remaining, '}')
@ -250,55 +238,63 @@ class JSInterpreter:
ret = local_vars[var]
expr = expr[:start] + json.dumps(ret) + expr[end:]
for op, opfunc in _ASSIGN_OPERATORS:
m = re.match(rf'''(?x)
(?P<out>{_NAME_RE})(?:\[(?P<index>[^\]]+?)\])?
\s*{re.escape(op)}
(?P<expr>.*)$''', expr)
if not m:
continue
right_val = self.interpret_expression(m.group('expr'), local_vars, allow_recursion)
if not expr:
return None
if m.groupdict().get('index'):
lvar = local_vars[m.group('out')]
idx = self.interpret_expression(m.group('index'), local_vars, allow_recursion)
if not isinstance(idx, int):
raise ExtractorError(f'List indices must be integers: {idx}')
cur = lvar[idx]
val = opfunc(cur, right_val)
lvar[idx] = val
return val
m = re.match(fr'''(?x)
(?P<assign>
(?P<out>{_NAME_RE})(?:\[(?P<index>[^\]]+?)\])?\s*
(?P<op>{"|".join(map(re.escape, _OPERATORS))})?
=(?P<expr>.*)$
)|(?P<return>
(?!if|return|true|false|null)(?P<name>{_NAME_RE})$
)|(?P<indexing>
(?P<in>{_NAME_RE})\[(?P<idx>.+)\]$
)|(?P<attribute>
(?P<var>{_NAME_RE})(?:\.(?P<member>[^(]+)|\[(?P<member2>[^\]]+)\])\s*
)|(?P<function>
(?P<fname>{_NAME_RE})\((?P<args>[\w$,]*)\)$
)''', expr)
if m and m.group('assign'):
if not m.group('op'):
opfunc = lambda curr, right: right
else:
cur = local_vars.get(m.group('out'))
val = opfunc(cur, right_val)
local_vars[m.group('out')] = val
return val
opfunc = _OPERATORS[m.group('op')]
right_val = self.interpret_expression(m.group('expr'), local_vars, allow_recursion)
left_val = local_vars.get(m.group('out'))
if expr.isdigit():
if not m.group('index'):
local_vars[m.group('out')] = opfunc(left_val, right_val)
return local_vars[m.group('out')]
elif left_val is None:
raise ExtractorError(f'Cannot index undefined variable: {m.group("out")}')
idx = self.interpret_expression(m.group('index'), local_vars, allow_recursion)
if not isinstance(idx, int):
raise ExtractorError(f'List indices must be integers: {idx}')
left_val[idx] = opfunc(left_val[idx], right_val)
return left_val[idx]
elif expr.isdigit():
return int(expr)
if expr == 'break':
elif expr == 'break':
raise JS_Break()
elif expr == 'continue':
raise JS_Continue()
var_m = re.match(
r'(?!if|return|true|false|null)(?P<name>%s)$' % _NAME_RE,
expr)
if var_m:
return local_vars[var_m.group('name')]
elif m and m.group('return'):
return local_vars[m.group('name')]
with contextlib.suppress(ValueError):
return json.loads(expr)
m = re.match(
r'(?P<in>%s)\[(?P<idx>.+)\]$' % _NAME_RE, expr)
if m:
if m and m.group('indexing'):
val = local_vars[m.group('in')]
idx = self.interpret_expression(m.group('idx'), local_vars, allow_recursion)
return val[idx]
for op, opfunc in _OPERATORS:
for op, opfunc in _OPERATORS.items():
separated = list(self._separate(expr, op))
if len(separated) < 2:
continue
@ -314,10 +310,7 @@ class JSInterpreter:
raise ExtractorError(f'Premature right-side return of {op} in {expr!r}')
return opfunc(left_val or 0, right_val)
m = re.match(
r'(?P<var>%s)(?:\.(?P<member>[^(]+)|\[(?P<member2>[^]]+)\])\s*' % _NAME_RE,
expr)
if m:
if m and m.group('attribute'):
variable = m.group('var')
member = remove_quotes(m.group('member') or m.group('member2'))
arg_str = expr[m.end():]
@ -332,7 +325,6 @@ class JSInterpreter:
raise ExtractorError(f'{member} {msg}: {expr}')
def eval_method():
nonlocal member
if variable == 'String':
obj = str
elif variable in local_vars:
@ -342,8 +334,8 @@ class JSInterpreter:
self._objects[variable] = self.extract_object(variable)
obj = self._objects[variable]
# Member access
if arg_str is None:
# Member access
if member == 'length':
return len(obj)
return obj[member]
@ -418,9 +410,7 @@ class JSInterpreter:
except ValueError:
return -1
if isinstance(obj, list):
member = int(member)
return obj[member](argvals)
return obj[int(member) if isinstance(obj, list) else member](argvals)
if remaining:
return self.interpret_expression(
@ -429,9 +419,8 @@ class JSInterpreter:
else:
return eval_method()
m = re.match(r'^(?P<func>%s)\((?P<args>[a-zA-Z0-9_$,]*)\)$' % _NAME_RE, expr)
if m:
fname = m.group('func')
elif m and m.group('function'):
fname = m.group('fname')
argvals = tuple(
int(v) if v.isdigit() else local_vars[v]
for v in self._separate(m.group('args')))
@ -441,8 +430,7 @@ class JSInterpreter:
self._functions[fname] = self.extract_function(fname)
return self._functions[fname](argvals)
if expr:
raise ExtractorError('Unsupported JS expression %r' % expr)
raise ExtractorError(f'Unsupported JS expression {expr!r}')
def extract_object(self, objname):
_FUNC_NAME_RE = r'''(?:[a-zA-Z$0-9]+|"[a-zA-Z$0-9]+"|'[a-zA-Z$0-9]+')'''
@ -471,14 +459,17 @@ class JSInterpreter:
""" @returns argnames, code """
func_m = re.search(
r'''(?x)
(?:function\s+%s|[{;,]\s*%s\s*=\s*function|var\s+%s\s*=\s*function)\s*
(?:
function\s+%(name)s|
[{;,]\s*%(name)s\s*=\s*function|
var\s+%(name)s\s*=\s*function
)\s*
\((?P<args>[^)]*)\)\s*
(?P<code>\{(?:(?!};)[^"]|"([^"]|\\")*")+\})''' % (
re.escape(funcname), re.escape(funcname), re.escape(funcname)),
(?P<code>{(?:(?!};)[^"]|"([^"]|\\")*")+})''' % {'name': re.escape(funcname)},
self.code)
code, _ = self._separate_at_paren(func_m.group('code'), '}') # refine the match
if func_m is None:
raise ExtractorError('Could not find JS function %r' % funcname)
raise ExtractorError(f'Could not find JS function "{funcname}"')
return func_m.group('args').split(','), code
def extract_function(self, funcname):
@ -492,11 +483,9 @@ class JSInterpreter:
break
start, body_start = mobj.span()
body, remaining = self._separate_at_paren(code[body_start - 1:], '}')
name = self._named_object(
local_vars,
self.extract_function_from_code(
[str.strip(x) for x in mobj.group('args').split(',')],
body, local_vars, *global_stack))
name = self._named_object(local_vars, self.extract_function_from_code(
[x.strip() for x in mobj.group('args').split(',')],
body, local_vars, *global_stack))
code = code[:start] + name + remaining
return self.build_function(argnames, code, local_vars, *global_stack)

View File

@ -1,3 +1,4 @@
import atexit
import hashlib
import json
import os
@ -8,11 +9,11 @@ from zipimport import zipimporter
from .compat import functools # isort: split
from .compat import compat_realpath
from .utils import Popen, traverse_obj, version_tuple
from .utils import Popen, shell_quote, traverse_obj, version_tuple
from .version import __version__
RELEASE_JSON_URL = 'https://api.github.com/repos/yt-dlp/yt-dlp/releases/latest'
REPOSITORY = 'yt-dlp/yt-dlp'
API_URL = f'https://api.github.com/repos/{REPOSITORY}/releases/latest'
@functools.cache
@ -44,12 +45,13 @@ _FILE_SUFFIXES = {
'py2exe': '_min.exe',
'win32_exe': '.exe',
'darwin_exe': '_macos',
'linux_exe': '_linux',
}
_NON_UPDATEABLE_REASONS = {
**{variant: None for variant in _FILE_SUFFIXES}, # Updatable
**{variant: f'Auto-update is not supported for unpackaged {name} executable; Re-download the latest release'
for variant, name in {'win32_dir': 'Windows', 'darwin_dir': 'MacOS'}.items()},
for variant, name in {'win32_dir': 'Windows', 'darwin_dir': 'MacOS', 'linux_dir': 'Linux'}.items()},
'source': 'You cannot update when running from source code; Use git to pull the latest changes',
'unknown': 'It looks like you installed yt-dlp with a package manager, pip or setup.py; Use that to update',
'other': 'It looks like you are using an unofficial build of yt-dlp; Build the executable again',
@ -60,137 +62,187 @@ def is_non_updateable():
return _NON_UPDATEABLE_REASONS.get(detect_variant(), _NON_UPDATEABLE_REASONS['other'])
def run_update(ydl):
"""
Update the program file with the latest version from the repository
Returns whether the program should terminate
"""
def _sha256_file(path):
h = hashlib.sha256()
mv = memoryview(bytearray(128 * 1024))
with open(os.path.realpath(path), 'rb', buffering=0) as f:
for n in iter(lambda: f.readinto(mv), 0):
h.update(mv[:n])
return h.hexdigest()
def report_error(msg, expected=False):
ydl.report_error(msg, tb=False if expected else None)
def report_unable(action, expected=False):
report_error(f'Unable to {action}', expected)
class Updater:
def __init__(self, ydl):
self.ydl = ydl
def report_permission_error(file):
report_unable(f'write to {file}; Try running as administrator', True)
@functools.cached_property
def _new_version_info(self):
self.ydl.write_debug(f'Fetching release info: {API_URL}')
return json.loads(self.ydl.urlopen(API_URL).read().decode())
def report_network_error(action, delim=';'):
report_unable(f'{action}{delim} Visit https://github.com/yt-dlp/yt-dlp/releases/latest', True)
@property
def current_version(self):
"""Current version"""
return __version__
def calc_sha256sum(path):
h = hashlib.sha256()
mv = memoryview(bytearray(128 * 1024))
with open(os.path.realpath(path), 'rb', buffering=0) as f:
for n in iter(lambda: f.readinto(mv), 0):
h.update(mv[:n])
return h.hexdigest()
@property
def new_version(self):
"""Version of the latest release"""
return self._new_version_info['tag_name']
try:
version_info = json.loads(ydl.urlopen(RELEASE_JSON_URL).read().decode())
except Exception:
return report_network_error('obtain version info', delim='; Please try again later or')
@property
def has_update(self):
"""Whether there is an update available"""
return version_tuple(__version__) < version_tuple(self.new_version)
version_id = version_info['tag_name']
ydl.to_screen(f'Latest version: {version_id}, Current version: {__version__}')
if version_tuple(__version__) >= version_tuple(version_id):
ydl.to_screen(f'yt-dlp is up to date ({__version__})')
return
@functools.cached_property
def filename(self):
"""Filename of the executable"""
return compat_realpath(_get_variant_and_executable_path()[1])
err = is_non_updateable()
if err:
return report_error(err, True)
variant, filename = _get_variant_and_executable_path()
filename = compat_realpath(filename) # Absolute path, following symlinks
label = _FILE_SUFFIXES[variant]
if label and platform.architecture()[0][:2] == '32':
label = f'_x86{label}'
release_name = f'yt-dlp{label}'
ydl.to_screen(f'Current Build Hash {calc_sha256sum(filename)}')
ydl.to_screen(f'Updating to version {version_id} ...')
def get_file(name, fatal=True):
error = report_network_error if fatal else lambda _: None
url = traverse_obj(
version_info, ('assets', lambda _, v: v['name'] == name, 'browser_download_url'), get_all=False)
def _download(self, name=None):
name = name or self.release_name
url = traverse_obj(self._new_version_info, (
'assets', lambda _, v: v['name'] == name, 'browser_download_url'), get_all=False)
if not url:
return error('fetch updates')
try:
return ydl.urlopen(url).read()
except OSError:
return error('download latest version')
raise Exception('Unable to find download URL')
self.ydl.write_debug(f'Downloading {name} from {url}')
return self.ydl.urlopen(url).read()
def verify(content):
if not content:
return False
hash_data = get_file('SHA2-256SUMS', fatal=False) or b''
expected = dict(ln.split()[::-1] for ln in hash_data.decode().splitlines()).get(release_name)
if not expected:
ydl.report_warning('no hash information found for the release')
elif hashlib.sha256(content).hexdigest() != expected:
return report_network_error('verify the new executable')
@functools.cached_property
def release_name(self):
"""The release filename"""
label = _FILE_SUFFIXES[detect_variant()]
if label and platform.architecture()[0][:2] == '32':
label = f'_x86{label}'
return f'yt-dlp{label}'
@functools.cached_property
def release_hash(self):
"""Hash of the latest release"""
hash_data = dict(ln.split()[::-1] for ln in self._download('SHA2-256SUMS').decode().splitlines())
return hash_data[self.release_name]
def _report_error(self, msg, expected=False):
self.ydl.report_error(msg, tb=False if expected else None)
def _report_permission_error(self, file):
self._report_error(f'Unable to write to {file}; Try running as administrator', True)
def _report_network_error(self, action, delim=';'):
self._report_error(f'Unable to {action}{delim} Visit https://github.com/{REPOSITORY}/releases/latest', True)
def check_update(self):
"""Report whether there is an update available"""
try:
self.ydl.to_screen(
f'Latest version: {self.new_version}, Current version: {self.current_version}')
except Exception:
return self._report_network_error('obtain version info', delim='; Please try again later or')
if not self.has_update:
return self.ydl.to_screen(f'yt-dlp is up to date ({__version__})')
if not is_non_updateable():
self.ydl.to_screen(f'Current Build Hash {_sha256_file(self.filename)}')
return True
directory = os.path.dirname(filename)
if not os.access(filename, os.W_OK):
return report_permission_error(filename)
elif not os.access(directory, os.W_OK):
return report_permission_error(directory)
def update(self):
"""Update yt-dlp executable to the latest version"""
if not self.check_update():
return
err = is_non_updateable()
if err:
return self._report_error(err, True)
self.ydl.to_screen(f'Updating to version {self.new_version} ...')
new_filename, old_filename = f'{filename}.new', f'{filename}.old'
if variant == 'zip': # Can be replaced in-place
new_filename, old_filename = filename, None
directory = os.path.dirname(self.filename)
if not os.access(self.filename, os.W_OK):
return self._report_permission_error(self.filename)
elif not os.access(directory, os.W_OK):
return self._report_permission_error(directory)
try:
if os.path.exists(old_filename or ''):
os.remove(old_filename)
except OSError:
return report_unable('remove the old version')
new_filename, old_filename = f'{self.filename}.new', f'{self.filename}.old'
if detect_variant() == 'zip': # Can be replaced in-place
new_filename, old_filename = self.filename, None
newcontent = get_file(release_name)
if not verify(newcontent):
return
try:
with open(new_filename, 'wb') as outf:
outf.write(newcontent)
except OSError:
return report_permission_error(new_filename)
try:
if os.path.exists(old_filename or ''):
os.remove(old_filename)
except OSError:
return self._report_error('Unable to remove the old version')
try:
if old_filename:
os.rename(filename, old_filename)
except OSError:
return report_unable('move current version')
try:
if old_filename:
os.rename(new_filename, filename)
except OSError:
report_unable('overwrite current version')
os.rename(old_filename, filename)
return
try:
newcontent = self._download()
except OSError:
return self._report_network_error('download latest version')
except Exception:
return self._report_network_error('fetch updates')
if variant not in ('win32_exe', 'py2exe'):
if old_filename:
os.remove(old_filename)
ydl.to_screen(f'Updated yt-dlp to version {version_id}; Restart yt-dlp to use the new version')
return
try:
expected_hash = self.release_hash
except Exception:
self.ydl.report_warning('no hash information found for the release')
else:
if hashlib.sha256(newcontent).hexdigest() != expected_hash:
return self._report_network_error('verify the new executable')
try:
# Continues to run in the background
Popen(f'ping 127.0.0.1 -n 5 -w 1000 & del /F "{old_filename}"',
shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
ydl.to_screen(f'Updated yt-dlp to version {version_id}')
return True # Exit app
except OSError:
report_unable('delete the old version')
try:
with open(new_filename, 'wb') as outf:
outf.write(newcontent)
except OSError:
return self._report_permission_error(new_filename)
try:
if old_filename:
os.rename(self.filename, old_filename)
except OSError:
return self._report_error('Unable to move current version')
try:
if old_filename:
os.rename(new_filename, self.filename)
except OSError:
self._report_error('Unable to overwrite current version')
return os.rename(old_filename, self.filename)
if detect_variant() not in ('win32_exe', 'py2exe'):
if old_filename:
os.remove(old_filename)
else:
atexit.register(Popen, f'ping 127.0.0.1 -n 5 -w 1000 & del /F "{old_filename}"',
shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
self.ydl.to_screen(f'Updated yt-dlp to version {self.new_version}')
return True
@functools.cached_property
def cmd(self):
"""The command-line to run the executable, if known"""
# There is no sys.orig_argv in py < 3.10. Also, it can be [] when frozen
if getattr(sys, 'orig_argv', None):
return sys.orig_argv
elif hasattr(sys, 'frozen'):
return sys.argv
def restart(self):
"""Restart the executable"""
assert self.cmd, 'Must be frozen or Py >= 3.10'
self.ydl.write_debug(f'Restarting: {shell_quote(self.cmd)}')
_, _, returncode = Popen.run(self.cmd)
return returncode
def run_update(ydl):
"""Update the program file with the latest version from the repository
@returns Whether there was a successfull update (No update = False)
"""
return Updater(ydl).update()
# Deprecated
def update_self(to_screen, verbose, opener):
import traceback
from .utils import write_string
write_string(
@ -202,12 +254,10 @@ def update_self(to_screen, verbose, opener):
class FakeYDL():
to_screen = printfn
@staticmethod
def report_warning(msg, *args, **kwargs):
def report_warning(self, msg, *args, **kwargs):
return printfn(f'WARNING: {msg}', *args, **kwargs)
@staticmethod
def report_error(msg, tb=None):
def report_error(self, msg, tb=None):
printfn(f'ERROR: {msg}')
if not verbose:
return
@ -224,6 +274,9 @@ def update_self(to_screen, verbose, opener):
if tb:
printfn(tb)
def write_debug(self, msg, *args, **kwargs):
printfn(f'[debug] {msg}', *args, **kwargs)
def urlopen(self, url):
return opener.open(url)

View File

@ -991,9 +991,10 @@ def make_HTTPS_handler(params, **kwargs):
def bug_reports_message(before=';'):
msg = ('please report this issue on https://github.com/yt-dlp/yt-dlp/issues?q= , '
'filling out the appropriate issue template. '
'Confirm you are on the latest version using yt-dlp -U')
from .update import REPOSITORY
msg = (f'please report this issue on https://github.com/{REPOSITORY}/issues?q= , '
'filling out the appropriate issue template. Confirm you are on the latest version using yt-dlp -U')
before = before.rstrip()
if not before or before.endswith(('.', '!', '?')):