[update] Expose more functionality to API

This commit is contained in:
pukkandan 2022-06-21 17:02:56 +05:30
parent f0500bd1e4
commit 57e0f077a6
No known key found for this signature in database
GPG key ID: 7EEE9E1E817D0A39
4 changed files with 159 additions and 119 deletions

View file

@ -5,7 +5,6 @@ import sys
from PyInstaller.__main__ import run as run_pyinstaller from PyInstaller.__main__ import run as run_pyinstaller
OS_NAME, ARCH = sys.platform, platform.architecture()[0][:2] OS_NAME, ARCH = sys.platform, platform.architecture()[0][:2]

View file

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

View file

@ -11,8 +11,8 @@ from .compat import compat_realpath
from .utils import Popen, traverse_obj, version_tuple from .utils import Popen, traverse_obj, version_tuple
from .version import __version__ from .version import __version__
REPOSITORY = 'yt-dlp/yt-dlp'
RELEASE_JSON_URL = 'https://api.github.com/repos/yt-dlp/yt-dlp/releases/latest' API_URL = f'https://api.github.com/repos/{REPOSITORY}/releases/latest'
@functools.cache @functools.cache
@ -60,25 +60,7 @@ def is_non_updateable():
return _NON_UPDATEABLE_REASONS.get(detect_variant(), _NON_UPDATEABLE_REASONS['other']) return _NON_UPDATEABLE_REASONS.get(detect_variant(), _NON_UPDATEABLE_REASONS['other'])
def run_update(ydl): def _sha256_file(path):
"""
Update the program file with the latest version from the repository
Returns whether the program should terminate
"""
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)
def report_permission_error(file):
report_unable(f'write to {file}; Try running as administrator', True)
def report_network_error(action, delim=';'):
report_unable(f'{action}{delim} Visit https://github.com/yt-dlp/yt-dlp/releases/latest', True)
def calc_sha256sum(path):
h = hashlib.sha256() h = hashlib.sha256()
mv = memoryview(bytearray(128 * 1024)) mv = memoryview(bytearray(128 * 1024))
with open(os.path.realpath(path), 'rb', buffering=0) as f: with open(os.path.realpath(path), 'rb', buffering=0) as f:
@ -86,111 +68,168 @@ def run_update(ydl):
h.update(mv[:n]) h.update(mv[:n])
return h.hexdigest() return h.hexdigest()
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')
version_id = version_info['tag_name'] class Updater:
ydl.to_screen(f'Latest version: {version_id}, Current version: {__version__}') def __init__(self, ydl):
if version_tuple(__version__) >= version_tuple(version_id): self.ydl = ydl
ydl.to_screen(f'yt-dlp is up to date ({__version__})')
return
err = is_non_updateable() @functools.cached_property
if err: def _new_version_info(self):
return report_error(err, True) self.ydl.write_debug(f'Fetching release info: {API_URL}')
return json.loads(self.ydl.urlopen(API_URL).read().decode())
variant, filename = _get_variant_and_executable_path() @property
filename = compat_realpath(filename) # Absolute path, following symlinks def current_version(self):
"""Current version"""
return __version__
label = _FILE_SUFFIXES[variant] @property
def new_version(self):
"""Version of the latest release"""
return self._new_version_info['tag_name']
@property
def has_update(self):
"""Whether there is an update available"""
return version_tuple(__version__) < version_tuple(self.new_version)
@functools.cached_property
def filename(self):
"""Filename of the executable"""
return compat_realpath(_get_variant_and_executable_path()[1])
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:
raise Exception('Unable to find download URL')
self.ydl.write_debug(f'Downloading {name} from {url}')
return self.ydl.urlopen(url).read()
@functools.cached_property
def release_name(self):
"""The release filename"""
label = _FILE_SUFFIXES[detect_variant()]
if label and platform.architecture()[0][:2] == '32': if label and platform.architecture()[0][:2] == '32':
label = f'_x86{label}' label = f'_x86{label}'
release_name = f'yt-dlp{label}' return f'yt-dlp{label}'
ydl.to_screen(f'Current Build Hash {calc_sha256sum(filename)}') @functools.cached_property
ydl.to_screen(f'Updating to version {version_id} ...') 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 get_file(name, fatal=True): def _report_error(self, msg, expected=False):
error = report_network_error if fatal else lambda _: None self.ydl.report_error(msg, tb=False if expected else None)
url = traverse_obj(
version_info, ('assets', lambda _, v: v['name'] == name, 'browser_download_url'), get_all=False) def _report_permission_error(self, file):
if not url: self._report_error(f'Unable to write to {file}; Try running as administrator', True)
return error('fetch updates')
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: try:
return ydl.urlopen(url).read() self.ydl.to_screen(
except OSError: f'Latest version: {self.new_version}, Current version: {self.current_version}')
return error('download latest version') except Exception:
return self._report_network_error('obtain version info', delim='; Please try again later or')
def verify(content): if not self.has_update:
if not content: return self.ydl.to_screen(f'yt-dlp is up to date ({__version__})')
return False
hash_data = get_file('SHA2-256SUMS', fatal=False) or b'' if not is_non_updateable():
expected = dict(ln.split()[::-1] for ln in hash_data.decode().splitlines()).get(release_name) self.ydl.to_screen(f'Current Build Hash {_sha256_file(self.filename)}')
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')
return True return True
directory = os.path.dirname(filename) def update(self):
if not os.access(filename, os.W_OK): """Update yt-dlp executable to the latest version"""
return report_permission_error(filename) if not self.check_update():
elif not os.access(directory, os.W_OK): return
return report_permission_error(directory) 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' directory = os.path.dirname(self.filename)
if variant == 'zip': # Can be replaced in-place if not os.access(self.filename, os.W_OK):
new_filename, old_filename = filename, None return self._report_permission_error(self.filename)
elif not os.access(directory, os.W_OK):
return self._report_permission_error(directory)
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
try: try:
if os.path.exists(old_filename or ''): if os.path.exists(old_filename or ''):
os.remove(old_filename) os.remove(old_filename)
except OSError: except OSError:
return report_unable('remove the old version') return self._report_error('Unable to remove the old version')
try:
newcontent = self._download()
except OSError:
return self._report_network_error('download latest version')
except Exception:
return self._report_network_error('fetch updates')
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')
newcontent = get_file(release_name)
if not verify(newcontent):
return
try: try:
with open(new_filename, 'wb') as outf: with open(new_filename, 'wb') as outf:
outf.write(newcontent) outf.write(newcontent)
except OSError: except OSError:
return report_permission_error(new_filename) return self._report_permission_error(new_filename)
try: try:
if old_filename: if old_filename:
os.rename(filename, old_filename) os.rename(self.filename, old_filename)
except OSError: except OSError:
return report_unable('move current version') return self._report_error('Unable to move current version')
try: try:
if old_filename: if old_filename:
os.rename(new_filename, filename) os.rename(new_filename, self.filename)
except OSError: except OSError:
report_unable('overwrite current version') self._report_error('Unable to overwrite current version')
os.rename(old_filename, filename) return os.rename(old_filename, self.filename)
return
if variant not in ('win32_exe', 'py2exe'): if detect_variant() not in ('win32_exe', 'py2exe'):
if old_filename: if old_filename:
os.remove(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') self.ydl.to_screen(f'Updated yt-dlp to version {self.new_version}; Restart yt-dlp to use the new version')
return return
try: try:
# Continues to run in the background # Continues to run in the background
Popen(f'ping 127.0.0.1 -n 5 -w 1000 & del /F "{old_filename}"', Popen(f'ping 127.0.0.1 -n 5 -w 1000 & del /F "{old_filename}"',
shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
ydl.to_screen(f'Updated yt-dlp to version {version_id}') self.ydl.to_screen(f'Updated yt-dlp to version {self.new_version}')
return True # Exit app return True # Exit app
except OSError: except OSError:
report_unable('delete the old version') self._report_unable('delete the old version')
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 # Deprecated
def update_self(to_screen, verbose, opener): def update_self(to_screen, verbose, opener):
import traceback import traceback
from .utils import write_string from .utils import write_string
write_string( write_string(
@ -202,12 +241,10 @@ def update_self(to_screen, verbose, opener):
class FakeYDL(): class FakeYDL():
to_screen = printfn to_screen = printfn
@staticmethod def report_warning(self, msg, *args, **kwargs):
def report_warning(msg, *args, **kwargs):
return printfn(f'WARNING: {msg}', *args, **kwargs) return printfn(f'WARNING: {msg}', *args, **kwargs)
@staticmethod def report_error(self, msg, tb=None):
def report_error(msg, tb=None):
printfn(f'ERROR: {msg}') printfn(f'ERROR: {msg}')
if not verbose: if not verbose:
return return
@ -224,6 +261,9 @@ def update_self(to_screen, verbose, opener):
if tb: if tb:
printfn(tb) printfn(tb)
def write_debug(self, msg, *args, **kwargs):
printfn(f'[debug] {msg}', *args, **kwargs)
def urlopen(self, url): def urlopen(self, url):
return opener.open(url) return opener.open(url)

View file

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