]> jfr.im git - yt-dlp.git/blob - yt_dlp/update.py
[build] Overhaul and unify release workflow
[yt-dlp.git] / yt_dlp / update.py
1 import atexit
2 import contextlib
3 import hashlib
4 import json
5 import os
6 import platform
7 import re
8 import subprocess
9 import sys
10 from zipimport import zipimporter
11
12 from .compat import functools # isort: split
13 from .compat import compat_realpath, compat_shlex_quote
14 from .networking import Request
15 from .networking.exceptions import HTTPError, network_exceptions
16 from .utils import (
17 Popen,
18 cached_method,
19 deprecation_warning,
20 remove_end,
21 remove_start,
22 shell_quote,
23 system_identifier,
24 version_tuple,
25 )
26 from .version import CHANNEL, UPDATE_HINT, VARIANT, __version__
27
28 UPDATE_SOURCES = {
29 'stable': 'yt-dlp/yt-dlp',
30 'nightly': 'yt-dlp/yt-dlp-nightly-builds',
31 'master': 'yt-dlp/yt-dlp-master-builds',
32 }
33 REPOSITORY = UPDATE_SOURCES['stable']
34
35 _VERSION_RE = re.compile(r'(\d+\.)*\d+')
36
37 API_BASE_URL = 'https://api.github.com/repos'
38
39 # Backwards compatibility variables for the current channel
40 API_URL = f'{API_BASE_URL}/{REPOSITORY}/releases'
41
42
43 @functools.cache
44 def _get_variant_and_executable_path():
45 """@returns (variant, executable_path)"""
46 if getattr(sys, 'frozen', False):
47 path = sys.executable
48 if not hasattr(sys, '_MEIPASS'):
49 return 'py2exe', path
50 elif sys._MEIPASS == os.path.dirname(path):
51 return f'{sys.platform}_dir', path
52 elif sys.platform == 'darwin':
53 machine = '_legacy' if version_tuple(platform.mac_ver()[0]) < (10, 15) else ''
54 else:
55 machine = f'_{platform.machine().lower()}'
56 # Ref: https://en.wikipedia.org/wiki/Uname#Examples
57 if machine[1:] in ('x86', 'x86_64', 'amd64', 'i386', 'i686'):
58 machine = '_x86' if platform.architecture()[0][:2] == '32' else ''
59 return f'{remove_end(sys.platform, "32")}{machine}_exe', path
60
61 path = os.path.dirname(__file__)
62 if isinstance(__loader__, zipimporter):
63 return 'zip', os.path.join(path, '..')
64 elif (os.path.basename(sys.argv[0]) in ('__main__.py', '-m')
65 and os.path.exists(os.path.join(path, '../.git/HEAD'))):
66 return 'source', path
67 return 'unknown', path
68
69
70 def detect_variant():
71 return VARIANT or _get_variant_and_executable_path()[0]
72
73
74 @functools.cache
75 def current_git_head():
76 if detect_variant() != 'source':
77 return
78 with contextlib.suppress(Exception):
79 stdout, _, _ = Popen.run(
80 ['git', 'rev-parse', '--short', 'HEAD'],
81 text=True, cwd=os.path.dirname(os.path.abspath(__file__)),
82 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
83 if re.fullmatch('[0-9a-f]+', stdout.strip()):
84 return stdout.strip()
85
86
87 _FILE_SUFFIXES = {
88 'zip': '',
89 'py2exe': '_min.exe',
90 'win_exe': '.exe',
91 'win_x86_exe': '_x86.exe',
92 'darwin_exe': '_macos',
93 'darwin_legacy_exe': '_macos_legacy',
94 'linux_exe': '_linux',
95 'linux_aarch64_exe': '_linux_aarch64',
96 'linux_armv7l_exe': '_linux_armv7l',
97 }
98
99 _NON_UPDATEABLE_REASONS = {
100 **{variant: None for variant in _FILE_SUFFIXES}, # Updatable
101 **{variant: f'Auto-update is not supported for unpackaged {name} executable; Re-download the latest release'
102 for variant, name in {'win32_dir': 'Windows', 'darwin_dir': 'MacOS', 'linux_dir': 'Linux'}.items()},
103 'source': 'You cannot update when running from source code; Use git to pull the latest changes',
104 'unknown': 'You installed yt-dlp with a package manager or setup.py; Use that to update',
105 'other': 'You are using an unofficial build of yt-dlp; Build the executable again',
106 }
107
108
109 def is_non_updateable():
110 if UPDATE_HINT:
111 return UPDATE_HINT
112 return _NON_UPDATEABLE_REASONS.get(
113 detect_variant(), _NON_UPDATEABLE_REASONS['unknown' if VARIANT else 'other'])
114
115
116 def _get_system_deprecation():
117 MIN_SUPPORTED, MIN_RECOMMENDED = (3, 7), (3, 8)
118
119 if sys.version_info > MIN_RECOMMENDED:
120 return None
121
122 major, minor = sys.version_info[:2]
123 if sys.version_info < MIN_SUPPORTED:
124 msg = f'Python version {major}.{minor} is no longer supported'
125 else:
126 msg = f'Support for Python version {major}.{minor} has been deprecated. '
127 # Temporary until `win_x86_exe` uses 3.8, which will deprecate Vista and Server 2008
128 if detect_variant() == 'win_x86_exe':
129 platform_name = platform.platform()
130 if any(platform_name.startswith(f'Windows-{name}') for name in ('Vista', '2008Server')):
131 msg = 'Support for Windows Vista/Server 2008 has been deprecated. '
132 else:
133 return None
134 msg += ('See https://github.com/yt-dlp/yt-dlp/issues/7803 for details.'
135 '\nYou may stop receiving updates on this version at any time')
136
137 major, minor = MIN_RECOMMENDED
138 return f'{msg}! Please update to Python {major}.{minor} or above'
139
140
141 def _sha256_file(path):
142 h = hashlib.sha256()
143 mv = memoryview(bytearray(128 * 1024))
144 with open(os.path.realpath(path), 'rb', buffering=0) as f:
145 for n in iter(lambda: f.readinto(mv), 0):
146 h.update(mv[:n])
147 return h.hexdigest()
148
149
150 class Updater:
151 _exact = True
152
153 def __init__(self, ydl, target=None):
154 self.ydl = ydl
155
156 self.target_channel, sep, self.target_tag = (target or CHANNEL).rpartition('@')
157 # stable => stable@latest
158 if not sep and ('/' in self.target_tag or self.target_tag in UPDATE_SOURCES):
159 self.target_channel = self.target_tag
160 self.target_tag = None
161 elif not self.target_channel:
162 self.target_channel = CHANNEL.partition('@')[0]
163
164 if not self.target_tag:
165 self.target_tag = 'latest'
166 self._exact = False
167 elif self.target_tag != 'latest':
168 self.target_tag = f'tags/{self.target_tag}'
169
170 if '/' in self.target_channel:
171 self._target_repo = self.target_channel
172 if self.target_channel not in (CHANNEL, *UPDATE_SOURCES.values()):
173 self.ydl.report_warning(
174 f'You are switching to an {self.ydl._format_err("unofficial", "red")} executable '
175 f'from {self.ydl._format_err(self._target_repo, self.ydl.Styles.EMPHASIS)}. '
176 f'Run {self.ydl._format_err("at your own risk", "light red")}')
177 self._block_restart('Automatically restarting into custom builds is disabled for security reasons')
178 else:
179 self._target_repo = UPDATE_SOURCES.get(self.target_channel)
180 if not self._target_repo:
181 self._report_error(
182 f'Invalid update channel {self.target_channel!r} requested. '
183 f'Valid channels are {", ".join(UPDATE_SOURCES)}', True)
184
185 def _version_compare(self, a, b, channel=CHANNEL):
186 if self._exact and channel != self.target_channel:
187 return False
188
189 if _VERSION_RE.fullmatch(f'{a}.{b}'):
190 a, b = version_tuple(a), version_tuple(b)
191 return a == b if self._exact else a >= b
192 return a == b
193
194 @functools.cached_property
195 def _tag(self):
196 if self._version_compare(self.current_version, self.latest_version):
197 return self.target_tag
198
199 identifier = f'{detect_variant()} {self.target_channel} {system_identifier()}'
200 for line in self._download('_update_spec', 'latest').decode().splitlines():
201 if not line.startswith('lock '):
202 continue
203 _, tag, pattern = line.split(' ', 2)
204 if re.match(pattern, identifier):
205 if not self._exact:
206 return f'tags/{tag}'
207 elif self.target_tag == 'latest' or not self._version_compare(
208 tag, self.target_tag[5:], channel=self.target_channel):
209 self._report_error(
210 f'yt-dlp cannot be updated above {tag} since you are on an older Python version', True)
211 return f'tags/{self.current_version}'
212 return self.target_tag
213
214 @cached_method
215 def _get_version_info(self, tag):
216 url = f'{API_BASE_URL}/{self._target_repo}/releases/{tag}'
217 self.ydl.write_debug(f'Fetching release info: {url}')
218 return json.loads(self.ydl.urlopen(Request(url, headers={
219 'Accept': 'application/vnd.github+json',
220 'User-Agent': 'yt-dlp',
221 'X-GitHub-Api-Version': '2022-11-28',
222 })).read().decode())
223
224 @property
225 def current_version(self):
226 """Current version"""
227 return __version__
228
229 @staticmethod
230 def _label(channel, tag):
231 """Label for a given channel and tag"""
232 return f'{channel}@{remove_start(tag, "tags/")}'
233
234 def _get_actual_tag(self, tag):
235 if tag.startswith('tags/'):
236 return tag[5:]
237 return self._get_version_info(tag)['tag_name']
238
239 @property
240 def new_version(self):
241 """Version of the latest release we can update to"""
242 return self._get_actual_tag(self._tag)
243
244 @property
245 def latest_version(self):
246 """Version of the target release"""
247 return self._get_actual_tag(self.target_tag)
248
249 @property
250 def has_update(self):
251 """Whether there is an update available"""
252 return not self._version_compare(self.current_version, self.new_version)
253
254 @functools.cached_property
255 def filename(self):
256 """Filename of the executable"""
257 return compat_realpath(_get_variant_and_executable_path()[1])
258
259 def _download(self, name, tag):
260 slug = 'latest/download' if tag == 'latest' else f'download/{tag[5:]}'
261 url = f'https://github.com/{self._target_repo}/releases/{slug}/{name}'
262 self.ydl.write_debug(f'Downloading {name} from {url}')
263 return self.ydl.urlopen(url).read()
264
265 @functools.cached_property
266 def release_name(self):
267 """The release filename"""
268 return f'yt-dlp{_FILE_SUFFIXES[detect_variant()]}'
269
270 @functools.cached_property
271 def release_hash(self):
272 """Hash of the latest release"""
273 hash_data = dict(ln.split()[::-1] for ln in self._download('SHA2-256SUMS', self._tag).decode().splitlines())
274 return hash_data[self.release_name]
275
276 def _report_error(self, msg, expected=False):
277 self.ydl.report_error(msg, tb=False if expected else None)
278 self.ydl._download_retcode = 100
279
280 def _report_permission_error(self, file):
281 self._report_error(f'Unable to write to {file}; Try running as administrator', True)
282
283 def _report_network_error(self, action, delim=';'):
284 self._report_error(
285 f'Unable to {action}{delim} visit '
286 f'https://github.com/{self._target_repo}/releases/{self.target_tag.replace("tags/", "tag/")}', True)
287
288 def check_update(self):
289 """Report whether there is an update available"""
290 if not self._target_repo:
291 return False
292 try:
293 self.ydl.to_screen((
294 f'Available version: {self._label(self.target_channel, self.latest_version)}, ' if self.target_tag == 'latest' else ''
295 ) + f'Current version: {self._label(CHANNEL, self.current_version)}')
296 except network_exceptions as e:
297 return self._report_network_error(f'obtain version info ({e})', delim='; Please try again later or')
298
299 if not is_non_updateable():
300 self.ydl.to_screen(f'Current Build Hash: {_sha256_file(self.filename)}')
301
302 if self.has_update:
303 return True
304
305 if self.target_tag == self._tag:
306 self.ydl.to_screen(f'yt-dlp is up to date ({self._label(CHANNEL, self.current_version)})')
307 elif not self._exact:
308 self.ydl.report_warning('yt-dlp cannot be updated any further since you are on an older Python version')
309 return False
310
311 def update(self):
312 """Update yt-dlp executable to the latest version"""
313 if not self.check_update():
314 return
315 err = is_non_updateable()
316 if err:
317 return self._report_error(err, True)
318 self.ydl.to_screen(f'Updating to {self._label(self.target_channel, self.new_version)} ...')
319 if (_VERSION_RE.fullmatch(self.target_tag[5:])
320 and version_tuple(self.target_tag[5:]) < (2023, 3, 2)):
321 self.ydl.report_warning('You are downgrading to a version without --update-to')
322 self._block_restart('Cannot automatically restart to a version without --update-to')
323
324 directory = os.path.dirname(self.filename)
325 if not os.access(self.filename, os.W_OK):
326 return self._report_permission_error(self.filename)
327 elif not os.access(directory, os.W_OK):
328 return self._report_permission_error(directory)
329
330 new_filename, old_filename = f'{self.filename}.new', f'{self.filename}.old'
331 if detect_variant() == 'zip': # Can be replaced in-place
332 new_filename, old_filename = self.filename, None
333
334 try:
335 if os.path.exists(old_filename or ''):
336 os.remove(old_filename)
337 except OSError:
338 return self._report_error('Unable to remove the old version')
339
340 try:
341 newcontent = self._download(self.release_name, self._tag)
342 except network_exceptions as e:
343 if isinstance(e, HTTPError) and e.status == 404:
344 return self._report_error(
345 f'The requested tag {self._label(self.target_channel, self.target_tag)} does not exist', True)
346 return self._report_network_error(f'fetch updates: {e}')
347
348 try:
349 expected_hash = self.release_hash
350 except Exception:
351 self.ydl.report_warning('no hash information found for the release')
352 else:
353 if hashlib.sha256(newcontent).hexdigest() != expected_hash:
354 return self._report_network_error('verify the new executable')
355
356 try:
357 with open(new_filename, 'wb') as outf:
358 outf.write(newcontent)
359 except OSError:
360 return self._report_permission_error(new_filename)
361
362 if old_filename:
363 mask = os.stat(self.filename).st_mode
364 try:
365 os.rename(self.filename, old_filename)
366 except OSError:
367 return self._report_error('Unable to move current version')
368
369 try:
370 os.rename(new_filename, self.filename)
371 except OSError:
372 self._report_error('Unable to overwrite current version')
373 return os.rename(old_filename, self.filename)
374
375 variant = detect_variant()
376 if variant.startswith('win') or variant == 'py2exe':
377 atexit.register(Popen, f'ping 127.0.0.1 -n 5 -w 1000 & del /F "{old_filename}"',
378 shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
379 elif old_filename:
380 try:
381 os.remove(old_filename)
382 except OSError:
383 self._report_error('Unable to remove the old version')
384
385 try:
386 os.chmod(self.filename, mask)
387 except OSError:
388 return self._report_error(
389 f'Unable to set permissions. Run: sudo chmod a+rx {compat_shlex_quote(self.filename)}')
390
391 self.ydl.to_screen(f'Updated yt-dlp to {self._label(self.target_channel, self.new_version)}')
392 return True
393
394 @functools.cached_property
395 def cmd(self):
396 """The command-line to run the executable, if known"""
397 # There is no sys.orig_argv in py < 3.10. Also, it can be [] when frozen
398 if getattr(sys, 'orig_argv', None):
399 return sys.orig_argv
400 elif getattr(sys, 'frozen', False):
401 return sys.argv
402
403 def restart(self):
404 """Restart the executable"""
405 assert self.cmd, 'Must be frozen or Py >= 3.10'
406 self.ydl.write_debug(f'Restarting: {shell_quote(self.cmd)}')
407 _, _, returncode = Popen.run(self.cmd)
408 return returncode
409
410 def _block_restart(self, msg):
411 def wrapper():
412 self._report_error(f'{msg}. Restart yt-dlp to use the updated version', expected=True)
413 return self.ydl._download_retcode
414 self.restart = wrapper
415
416
417 def run_update(ydl):
418 """Update the program file with the latest version from the repository
419 @returns Whether there was a successful update (No update = False)
420 """
421 return Updater(ydl).update()
422
423
424 # Deprecated
425 def update_self(to_screen, verbose, opener):
426 import traceback
427
428 deprecation_warning(f'"{__name__}.update_self" is deprecated and may be removed '
429 f'in a future version. Use "{__name__}.run_update(ydl)" instead')
430
431 printfn = to_screen
432
433 class FakeYDL():
434 to_screen = printfn
435
436 def report_warning(self, msg, *args, **kwargs):
437 return printfn(f'WARNING: {msg}', *args, **kwargs)
438
439 def report_error(self, msg, tb=None):
440 printfn(f'ERROR: {msg}')
441 if not verbose:
442 return
443 if tb is None:
444 # Copied from YoutubeDL.trouble
445 if sys.exc_info()[0]:
446 tb = ''
447 if hasattr(sys.exc_info()[1], 'exc_info') and sys.exc_info()[1].exc_info[0]:
448 tb += ''.join(traceback.format_exception(*sys.exc_info()[1].exc_info))
449 tb += traceback.format_exc()
450 else:
451 tb_data = traceback.format_list(traceback.extract_stack())
452 tb = ''.join(tb_data)
453 if tb:
454 printfn(tb)
455
456 def write_debug(self, msg, *args, **kwargs):
457 printfn(f'[debug] {msg}', *args, **kwargs)
458
459 def urlopen(self, url):
460 return opener.open(url)
461
462 return run_update(FakeYDL())
463
464
465 __all__ = ['Updater']