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