]> jfr.im git - yt-dlp.git/blobdiff - yt_dlp/update.py
[utils] `write_xattr`: Use `os.setxattr` if available (#8205)
[yt-dlp.git] / yt_dlp / update.py
index 297539bb6867aa546109f5f81579c428cdd818ef..db79df1271655114270a43a64083c2d946521a35 100644 (file)
@@ -7,18 +7,18 @@
 import re
 import subprocess
 import sys
-import urllib.error
 from zipimport import zipimporter
 
 from .compat import functools  # isort: split
 from .compat import compat_realpath, compat_shlex_quote
+from .networking import Request
+from .networking.exceptions import HTTPError, network_exceptions
 from .utils import (
     Popen,
     cached_method,
     deprecation_warning,
     remove_end,
     remove_start,
-    sanitized_Request,
     shell_quote,
     system_identifier,
     version_tuple,
     'stable': 'yt-dlp/yt-dlp',
     'nightly': 'yt-dlp/yt-dlp-nightly-builds',
 }
+REPOSITORY = UPDATE_SOURCES['stable']
 
 _VERSION_RE = re.compile(r'(\d+\.)*\d+')
 
 API_BASE_URL = 'https://api.github.com/repos'
 
 # Backwards compatibility variables for the current channel
-REPOSITORY = UPDATE_SOURCES[CHANNEL]
 API_URL = f'{API_BASE_URL}/{REPOSITORY}/releases'
 
 
@@ -112,6 +112,31 @@ def is_non_updateable():
         detect_variant(), _NON_UPDATEABLE_REASONS['unknown' if VARIANT else 'other'])
 
 
+def _get_system_deprecation():
+    MIN_SUPPORTED, MIN_RECOMMENDED = (3, 7), (3, 8)
+
+    if sys.version_info > MIN_RECOMMENDED:
+        return None
+
+    major, minor = sys.version_info[:2]
+    if sys.version_info < MIN_SUPPORTED:
+        msg = f'Python version {major}.{minor} is no longer supported'
+    else:
+        msg = f'Support for Python version {major}.{minor} has been deprecated. '
+        # Temporary until `win_x86_exe` uses 3.8, which will deprecate Vista and Server 2008
+        if detect_variant() == 'win_x86_exe':
+            platform_name = platform.platform()
+            if any(platform_name.startswith(f'Windows-{name}') for name in ('Vista', '2008Server')):
+                msg = 'Support for Windows Vista/Server 2008 has been deprecated. '
+            else:
+                return None
+        msg += ('See  https://github.com/yt-dlp/yt-dlp/issues/7803  for details.'
+                '\nYou may stop receiving updates on this version at any time')
+
+    major, minor = MIN_RECOMMENDED
+    return f'{msg}! Please update to Python {major}.{minor} or above'
+
+
 def _sha256_file(path):
     h = hashlib.sha256()
     mv = memoryview(bytearray(128 * 1024))
@@ -128,27 +153,36 @@ def __init__(self, ydl, target=None):
         self.ydl = ydl
 
         self.target_channel, sep, self.target_tag = (target or CHANNEL).rpartition('@')
-        if not sep and self.target_tag in UPDATE_SOURCES:  # stable => stable@latest
-            self.target_channel, self.target_tag = self.target_tag, None
+        # stable => stable@latest
+        if not sep and ('/' in self.target_tag or self.target_tag in UPDATE_SOURCES):
+            self.target_channel = self.target_tag
+            self.target_tag = None
         elif not self.target_channel:
-            self.target_channel = CHANNEL
+            self.target_channel = CHANNEL.partition('@')[0]
 
         if not self.target_tag:
-            self.target_tag, self._exact = 'latest', False
+            self.target_tag = 'latest'
+            self._exact = False
         elif self.target_tag != 'latest':
             self.target_tag = f'tags/{self.target_tag}'
 
-    @property
-    def _target_repo(self):
-        try:
-            return UPDATE_SOURCES[self.target_channel]
-        except KeyError:
-            return self._report_error(
-                f'Invalid update channel {self.target_channel!r} requested. '
-                f'Valid channels are {", ".join(UPDATE_SOURCES)}', True)
+        if '/' in self.target_channel:
+            self._target_repo = self.target_channel
+            if self.target_channel not in (CHANNEL, *UPDATE_SOURCES.values()):
+                self.ydl.report_warning(
+                    f'You are switching to an {self.ydl._format_err("unofficial", "red")} executable '
+                    f'from {self.ydl._format_err(self._target_repo, self.ydl.Styles.EMPHASIS)}. '
+                    f'Run {self.ydl._format_err("at your own risk", "light red")}')
+                self._block_restart('Automatically restarting into custom builds is disabled for security reasons')
+        else:
+            self._target_repo = UPDATE_SOURCES.get(self.target_channel)
+            if not self._target_repo:
+                self._report_error(
+                    f'Invalid update channel {self.target_channel!r} requested. '
+                    f'Valid channels are {", ".join(UPDATE_SOURCES)}', True)
 
     def _version_compare(self, a, b, channel=CHANNEL):
-        if channel != self.target_channel:
+        if self._exact and channel != self.target_channel:
             return False
 
         if _VERSION_RE.fullmatch(f'{a}.{b}'):
@@ -180,7 +214,7 @@ def _tag(self):
     def _get_version_info(self, tag):
         url = f'{API_BASE_URL}/{self._target_repo}/releases/{tag}'
         self.ydl.write_debug(f'Fetching release info: {url}')
-        return json.loads(self.ydl.urlopen(sanitized_Request(url, headers={
+        return json.loads(self.ydl.urlopen(Request(url, headers={
             'Accept': 'application/vnd.github+json',
             'User-Agent': 'yt-dlp',
             'X-GitHub-Api-Version': '2022-11-28',
@@ -258,8 +292,8 @@ def check_update(self):
             self.ydl.to_screen((
                 f'Available version: {self._label(self.target_channel, self.latest_version)}, ' if self.target_tag == 'latest' else ''
             ) + f'Current version: {self._label(CHANNEL, self.current_version)}')
-        except Exception:
-            return self._report_network_error('obtain version info', delim='; Please try again later or')
+        except network_exceptions as e:
+            return self._report_network_error(f'obtain version info ({e})', delim='; Please try again later or')
 
         if not is_non_updateable():
             self.ydl.to_screen(f'Current Build Hash: {_sha256_file(self.filename)}')
@@ -284,6 +318,7 @@ def update(self):
         if (_VERSION_RE.fullmatch(self.target_tag[5:])
                 and version_tuple(self.target_tag[5:]) < (2023, 3, 2)):
             self.ydl.report_warning('You are downgrading to a version without --update-to')
+            self._block_restart('Cannot automatically restart to a version without --update-to')
 
         directory = os.path.dirname(self.filename)
         if not os.access(self.filename, os.W_OK):
@@ -303,8 +338,8 @@ def update(self):
 
         try:
             newcontent = self._download(self.release_name, self._tag)
-        except Exception as e:
-            if isinstance(e, urllib.error.HTTPError) and e.code == 404:
+        except network_exceptions as e:
+            if isinstance(e, HTTPError) and e.status == 404:
                 return self._report_error(
                     f'The requested tag {self._label(self.target_channel, self.target_tag)} does not exist', True)
             return self._report_network_error(f'fetch updates: {e}')
@@ -371,6 +406,12 @@ def restart(self):
         _, _, returncode = Popen.run(self.cmd)
         return returncode
 
+    def _block_restart(self, msg):
+        def wrapper():
+            self._report_error(f'{msg}. Restart yt-dlp to use the updated version', expected=True)
+            return self.ydl._download_retcode
+        self.restart = wrapper
+
 
 def run_update(ydl):
     """Update the program file with the latest version from the repository