2022-06-21 11:18:32 +00:00
|
|
|
import atexit
|
2022-08-24 07:33:33 +00:00
|
|
|
import contextlib
|
2021-05-25 19:43:08 +00:00
|
|
|
import hashlib
|
2012-12-30 18:49:14 +00:00
|
|
|
import json
|
2013-11-17 15:47:52 +00:00
|
|
|
import os
|
2021-02-14 17:10:54 +00:00
|
|
|
import platform
|
2022-06-29 01:13:24 +00:00
|
|
|
import re
|
2013-09-29 09:26:01 +00:00
|
|
|
import subprocess
|
2013-09-29 09:17:38 +00:00
|
|
|
import sys
|
2012-12-30 18:49:14 +00:00
|
|
|
from zipimport import zipimporter
|
|
|
|
|
2022-05-22 11:37:18 +00:00
|
|
|
from .compat import functools # isort: split
|
2022-08-14 13:33:58 +00:00
|
|
|
from .compat import compat_realpath, compat_shlex_quote
|
2022-06-29 01:13:24 +00:00
|
|
|
from .utils import (
|
|
|
|
Popen,
|
|
|
|
cached_method,
|
2022-08-30 15:28:28 +00:00
|
|
|
deprecation_warning,
|
2023-01-06 17:01:18 +00:00
|
|
|
remove_end,
|
2022-06-29 01:13:24 +00:00
|
|
|
shell_quote,
|
|
|
|
system_identifier,
|
|
|
|
traverse_obj,
|
|
|
|
version_tuple,
|
|
|
|
)
|
2022-07-29 15:03:01 +00:00
|
|
|
from .version import UPDATE_HINT, VARIANT, __version__
|
2012-12-30 18:49:14 +00:00
|
|
|
|
2022-06-21 11:32:56 +00:00
|
|
|
REPOSITORY = 'yt-dlp/yt-dlp'
|
2022-06-29 01:13:24 +00:00
|
|
|
API_URL = f'https://api.github.com/repos/{REPOSITORY}/releases'
|
2022-05-22 11:37:18 +00:00
|
|
|
|
|
|
|
|
2022-05-19 14:06:31 +00:00
|
|
|
@functools.cache
|
2022-05-22 11:37:18 +00:00
|
|
|
def _get_variant_and_executable_path():
|
2022-04-17 17:18:50 +00:00
|
|
|
"""@returns (variant, executable_path)"""
|
2022-11-11 03:13:08 +00:00
|
|
|
if getattr(sys, 'frozen', False):
|
2022-04-17 17:18:50 +00:00
|
|
|
path = sys.executable
|
2022-05-22 11:37:18 +00:00
|
|
|
if not hasattr(sys, '_MEIPASS'):
|
|
|
|
return 'py2exe', path
|
2022-11-11 03:13:08 +00:00
|
|
|
elif sys._MEIPASS == os.path.dirname(path):
|
2022-05-22 11:37:18 +00:00
|
|
|
return f'{sys.platform}_dir', path
|
2022-11-11 03:13:08 +00:00
|
|
|
elif sys.platform == 'darwin':
|
2022-11-11 01:49:24 +00:00
|
|
|
machine = '_legacy' if version_tuple(platform.mac_ver()[0]) < (10, 15) else ''
|
|
|
|
else:
|
|
|
|
machine = f'_{platform.machine().lower()}'
|
|
|
|
# Ref: https://en.wikipedia.org/wiki/Uname#Examples
|
|
|
|
if machine[1:] in ('x86', 'x86_64', 'amd64', 'i386', 'i686'):
|
|
|
|
machine = '_x86' if platform.architecture()[0][:2] == '32' else ''
|
2023-01-06 17:01:18 +00:00
|
|
|
return f'{remove_end(sys.platform, "32")}{machine}_exe', path
|
2022-05-22 11:37:18 +00:00
|
|
|
|
|
|
|
path = os.path.dirname(__file__)
|
2022-04-17 17:18:50 +00:00
|
|
|
if isinstance(__loader__, zipimporter):
|
|
|
|
return 'zip', os.path.join(path, '..')
|
2022-06-07 18:46:23 +00:00
|
|
|
elif (os.path.basename(sys.argv[0]) in ('__main__.py', '-m')
|
|
|
|
and os.path.exists(os.path.join(path, '../.git/HEAD'))):
|
2022-04-17 17:18:50 +00:00
|
|
|
return 'source', path
|
|
|
|
return 'unknown', path
|
|
|
|
|
|
|
|
|
|
|
|
def detect_variant():
|
2022-07-29 15:03:01 +00:00
|
|
|
return VARIANT or _get_variant_and_executable_path()[0]
|
2021-09-24 01:01:43 +00:00
|
|
|
|
|
|
|
|
2022-08-24 07:33:33 +00:00
|
|
|
@functools.cache
|
|
|
|
def current_git_head():
|
|
|
|
if detect_variant() != 'source':
|
|
|
|
return
|
|
|
|
with contextlib.suppress(Exception):
|
|
|
|
stdout, _, _ = Popen.run(
|
|
|
|
['git', 'rev-parse', '--short', 'HEAD'],
|
|
|
|
text=True, cwd=os.path.dirname(os.path.abspath(__file__)),
|
|
|
|
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
|
|
|
if re.fullmatch('[0-9a-f]+', stdout.strip()):
|
|
|
|
return stdout.strip()
|
|
|
|
|
|
|
|
|
2022-05-22 11:37:18 +00:00
|
|
|
_FILE_SUFFIXES = {
|
|
|
|
'zip': '',
|
|
|
|
'py2exe': '_min.exe',
|
2023-01-06 17:01:18 +00:00
|
|
|
'win_exe': '.exe',
|
|
|
|
'win_x86_exe': '_x86.exe',
|
2022-05-22 11:37:18 +00:00
|
|
|
'darwin_exe': '_macos',
|
2022-06-29 00:09:32 +00:00
|
|
|
'darwin_legacy_exe': '_macos_legacy',
|
2022-05-21 19:49:49 +00:00
|
|
|
'linux_exe': '_linux',
|
2022-11-11 01:49:24 +00:00
|
|
|
'linux_aarch64_exe': '_linux_aarch64',
|
|
|
|
'linux_armv7l_exe': '_linux_armv7l',
|
2022-05-22 11:37:18 +00:00
|
|
|
}
|
|
|
|
|
2021-10-03 20:55:13 +00:00
|
|
|
_NON_UPDATEABLE_REASONS = {
|
2022-05-22 11:37:18 +00:00
|
|
|
**{variant: None for variant in _FILE_SUFFIXES}, # Updatable
|
|
|
|
**{variant: f'Auto-update is not supported for unpackaged {name} executable; Re-download the latest release'
|
2022-05-21 19:49:49 +00:00
|
|
|
for variant, name in {'win32_dir': 'Windows', 'darwin_dir': 'MacOS', 'linux_dir': 'Linux'}.items()},
|
2021-10-11 04:25:30 +00:00
|
|
|
'source': 'You cannot update when running from source code; Use git to pull the latest changes',
|
2022-07-29 15:03:01 +00:00
|
|
|
'unknown': 'You installed yt-dlp with a package manager or setup.py; Use that to update',
|
|
|
|
'other': 'You are using an unofficial build of yt-dlp; Build the executable again',
|
2021-10-03 20:55:13 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
def is_non_updateable():
|
2022-07-29 15:03:01 +00:00
|
|
|
if UPDATE_HINT:
|
|
|
|
return UPDATE_HINT
|
|
|
|
return _NON_UPDATEABLE_REASONS.get(
|
|
|
|
detect_variant(), _NON_UPDATEABLE_REASONS['unknown' if VARIANT else 'other'])
|
2021-10-03 20:55:13 +00:00
|
|
|
|
|
|
|
|
2022-06-21 11:32:56 +00:00
|
|
|
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()
|
|
|
|
|
|
|
|
|
|
|
|
class Updater:
|
|
|
|
def __init__(self, ydl):
|
|
|
|
self.ydl = ydl
|
|
|
|
|
|
|
|
@functools.cached_property
|
2022-06-29 01:13:24 +00:00
|
|
|
def _tag(self):
|
2022-07-17 12:06:15 +00:00
|
|
|
if version_tuple(__version__) >= version_tuple(self.latest_version):
|
2022-06-29 22:07:48 +00:00
|
|
|
return 'latest'
|
|
|
|
|
2022-06-29 01:13:24 +00:00
|
|
|
identifier = f'{detect_variant()} {system_identifier()}'
|
|
|
|
for line in self._download('_update_spec', 'latest').decode().splitlines():
|
|
|
|
if not line.startswith('lock '):
|
|
|
|
continue
|
|
|
|
_, tag, pattern = line.split(' ', 2)
|
|
|
|
if re.match(pattern, identifier):
|
|
|
|
return f'tags/{tag}'
|
|
|
|
return 'latest'
|
|
|
|
|
|
|
|
@cached_method
|
|
|
|
def _get_version_info(self, tag):
|
|
|
|
self.ydl.write_debug(f'Fetching release info: {API_URL}/{tag}')
|
|
|
|
return json.loads(self.ydl.urlopen(f'{API_URL}/{tag}').read().decode())
|
2022-06-21 11:32:56 +00:00
|
|
|
|
|
|
|
@property
|
|
|
|
def current_version(self):
|
|
|
|
"""Current version"""
|
|
|
|
return __version__
|
|
|
|
|
|
|
|
@property
|
|
|
|
def new_version(self):
|
2022-07-17 12:06:15 +00:00
|
|
|
"""Version of the latest release we can update to"""
|
|
|
|
if self._tag.startswith('tags/'):
|
|
|
|
return self._tag[5:]
|
2022-06-29 01:13:24 +00:00
|
|
|
return self._get_version_info(self._tag)['tag_name']
|
2022-06-21 11:32:56 +00:00
|
|
|
|
2022-07-17 12:06:15 +00:00
|
|
|
@property
|
|
|
|
def latest_version(self):
|
|
|
|
"""Version of the latest release"""
|
|
|
|
return self._get_version_info('latest')['tag_name']
|
|
|
|
|
2022-06-21 11:32:56 +00:00
|
|
|
@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])
|
|
|
|
|
2022-06-29 01:13:24 +00:00
|
|
|
def _download(self, name, tag):
|
|
|
|
url = traverse_obj(self._get_version_info(tag), (
|
2022-06-21 11:32:56 +00:00
|
|
|
'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"""
|
2022-11-11 01:49:24 +00:00
|
|
|
return f'yt-dlp{_FILE_SUFFIXES[detect_variant()]}'
|
2022-06-21 11:32:56 +00:00
|
|
|
|
|
|
|
@functools.cached_property
|
|
|
|
def release_hash(self):
|
|
|
|
"""Hash of the latest release"""
|
2022-06-29 01:13:24 +00:00
|
|
|
hash_data = dict(ln.split()[::-1] for ln in self._download('SHA2-256SUMS', self._tag).decode().splitlines())
|
2022-06-21 11:32:56 +00:00
|
|
|
return hash_data[self.release_name]
|
|
|
|
|
|
|
|
def _report_error(self, msg, expected=False):
|
|
|
|
self.ydl.report_error(msg, tb=False if expected else None)
|
2022-11-06 21:07:23 +00:00
|
|
|
self.ydl._download_retcode = 100
|
2022-06-21 11:32:56 +00:00
|
|
|
|
|
|
|
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(
|
2022-07-17 12:06:15 +00:00
|
|
|
f'Latest version: {self.latest_version}, Current version: {self.current_version}')
|
|
|
|
if not self.has_update:
|
|
|
|
if self._tag == 'latest':
|
|
|
|
return self.ydl.to_screen(f'yt-dlp is up to date ({__version__})')
|
|
|
|
return self.ydl.report_warning(
|
|
|
|
'yt-dlp cannot be updated any further since you are on an older Python version')
|
2022-06-21 11:32:56 +00:00
|
|
|
except Exception:
|
|
|
|
return self._report_network_error('obtain version info', delim='; Please try again later or')
|
2021-10-11 04:25:30 +00:00
|
|
|
|
2022-06-21 11:32:56 +00:00
|
|
|
if not is_non_updateable():
|
|
|
|
self.ydl.to_screen(f'Current Build Hash {_sha256_file(self.filename)}')
|
|
|
|
return True
|
2021-05-25 19:43:08 +00:00
|
|
|
|
2022-06-21 11:32:56 +00:00
|
|
|
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} ...')
|
|
|
|
|
|
|
|
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)
|
|
|
|
|
|
|
|
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
|
2020-10-31 07:57:55 +00:00
|
|
|
|
2022-06-21 11:32:56 +00:00
|
|
|
try:
|
|
|
|
if os.path.exists(old_filename or ''):
|
|
|
|
os.remove(old_filename)
|
|
|
|
except OSError:
|
|
|
|
return self._report_error('Unable to remove the old version')
|
2021-09-27 03:51:28 +00:00
|
|
|
|
2022-06-21 11:32:56 +00:00
|
|
|
try:
|
2022-06-29 01:13:24 +00:00
|
|
|
newcontent = self._download(self.release_name, self._tag)
|
2022-06-21 11:32:56 +00:00
|
|
|
except OSError:
|
|
|
|
return self._report_network_error('download latest version')
|
|
|
|
except Exception:
|
|
|
|
return self._report_network_error('fetch updates')
|
2021-09-27 03:51:28 +00:00
|
|
|
|
2022-06-21 11:32:56 +00:00
|
|
|
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')
|
2012-12-30 18:49:14 +00:00
|
|
|
|
2022-06-21 11:32:56 +00:00
|
|
|
try:
|
|
|
|
with open(new_filename, 'wb') as outf:
|
|
|
|
outf.write(newcontent)
|
|
|
|
except OSError:
|
|
|
|
return self._report_permission_error(new_filename)
|
2022-04-17 17:18:50 +00:00
|
|
|
|
2022-08-14 13:33:58 +00:00
|
|
|
if old_filename:
|
2022-08-14 17:21:38 +00:00
|
|
|
mask = os.stat(self.filename).st_mode
|
2022-08-14 13:33:58 +00:00
|
|
|
try:
|
2022-06-21 11:32:56 +00:00
|
|
|
os.rename(self.filename, old_filename)
|
2022-08-14 13:33:58 +00:00
|
|
|
except OSError:
|
|
|
|
return self._report_error('Unable to move current version')
|
|
|
|
|
|
|
|
try:
|
2022-06-21 11:32:56 +00:00
|
|
|
os.rename(new_filename, self.filename)
|
2022-08-14 13:33:58 +00:00
|
|
|
except OSError:
|
|
|
|
self._report_error('Unable to overwrite current version')
|
|
|
|
return os.rename(old_filename, self.filename)
|
2022-05-22 11:37:18 +00:00
|
|
|
|
2023-01-06 17:01:18 +00:00
|
|
|
variant = detect_variant()
|
|
|
|
if variant.startswith('win') or variant == 'py2exe':
|
2022-06-21 11:18:32 +00:00
|
|
|
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)
|
2022-08-14 13:33:58 +00:00
|
|
|
elif old_filename:
|
|
|
|
try:
|
|
|
|
os.remove(old_filename)
|
|
|
|
except OSError:
|
|
|
|
self._report_error('Unable to remove the old version')
|
|
|
|
|
|
|
|
try:
|
2022-08-14 17:21:38 +00:00
|
|
|
os.chmod(self.filename, mask)
|
2022-08-14 13:33:58 +00:00
|
|
|
except OSError:
|
|
|
|
return self._report_error(
|
|
|
|
f'Unable to set permissions. Run: sudo chmod a+rx {compat_shlex_quote(self.filename)}')
|
2013-02-21 23:36:23 +00:00
|
|
|
|
2022-06-21 11:18:32 +00:00
|
|
|
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
|
2022-11-11 03:13:08 +00:00
|
|
|
elif getattr(sys, 'frozen', False):
|
2022-06-21 11:18:32 +00:00
|
|
|
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
|
2022-06-21 11:32:56 +00:00
|
|
|
|
2021-02-15 21:06:42 +00:00
|
|
|
|
2022-06-21 11:32:56 +00:00
|
|
|
def run_update(ydl):
|
|
|
|
"""Update the program file with the latest version from the repository
|
2022-06-27 00:50:06 +00:00
|
|
|
@returns Whether there was a successful update (No update = False)
|
2022-06-21 11:32:56 +00:00
|
|
|
"""
|
|
|
|
return Updater(ydl).update()
|
2013-02-21 23:36:23 +00:00
|
|
|
|
2014-11-23 19:41:03 +00:00
|
|
|
|
2021-11-29 17:46:06 +00:00
|
|
|
# Deprecated
|
2021-10-11 04:25:30 +00:00
|
|
|
def update_self(to_screen, verbose, opener):
|
2022-05-22 11:37:18 +00:00
|
|
|
import traceback
|
2022-06-21 11:32:56 +00:00
|
|
|
|
2022-08-30 15:28:28 +00:00
|
|
|
deprecation_warning(f'"{__name__}.update_self" is deprecated and may be removed '
|
|
|
|
f'in a future version. Use "{__name__}.run_update(ydl)" instead')
|
2021-10-11 04:25:30 +00:00
|
|
|
|
2022-05-22 11:37:18 +00:00
|
|
|
printfn = to_screen
|
|
|
|
|
2021-10-11 04:25:30 +00:00
|
|
|
class FakeYDL():
|
|
|
|
to_screen = printfn
|
|
|
|
|
2022-06-21 11:32:56 +00:00
|
|
|
def report_warning(self, msg, *args, **kwargs):
|
2022-05-22 11:37:18 +00:00
|
|
|
return printfn(f'WARNING: {msg}', *args, **kwargs)
|
2021-10-11 04:25:30 +00:00
|
|
|
|
2022-06-21 11:32:56 +00:00
|
|
|
def report_error(self, msg, tb=None):
|
2022-05-22 11:37:18 +00:00
|
|
|
printfn(f'ERROR: {msg}')
|
2021-10-11 04:25:30 +00:00
|
|
|
if not verbose:
|
|
|
|
return
|
|
|
|
if tb is None:
|
2022-05-22 11:37:18 +00:00
|
|
|
# Copied from YoutubeDL.trouble
|
2021-10-11 04:25:30 +00:00
|
|
|
if sys.exc_info()[0]:
|
|
|
|
tb = ''
|
|
|
|
if hasattr(sys.exc_info()[1], 'exc_info') and sys.exc_info()[1].exc_info[0]:
|
|
|
|
tb += ''.join(traceback.format_exception(*sys.exc_info()[1].exc_info))
|
2022-05-22 11:37:18 +00:00
|
|
|
tb += traceback.format_exc()
|
2021-10-11 04:25:30 +00:00
|
|
|
else:
|
|
|
|
tb_data = traceback.format_list(traceback.extract_stack())
|
|
|
|
tb = ''.join(tb_data)
|
|
|
|
if tb:
|
|
|
|
printfn(tb)
|
|
|
|
|
2022-06-21 11:32:56 +00:00
|
|
|
def write_debug(self, msg, *args, **kwargs):
|
|
|
|
printfn(f'[debug] {msg}', *args, **kwargs)
|
|
|
|
|
2022-05-22 11:37:18 +00:00
|
|
|
def urlopen(self, url):
|
|
|
|
return opener.open(url)
|
|
|
|
|
2021-10-11 04:25:30 +00:00
|
|
|
return run_update(FakeYDL())
|