11 from zipimport
import zipimporter
13 from .compat
import functools
# isort: split
14 from .compat
import compat_realpath
, compat_shlex_quote
27 from .version
import CHANNEL
, UPDATE_HINT
, VARIANT
, __version__
30 'stable': 'yt-dlp/yt-dlp',
31 'nightly': 'yt-dlp/yt-dlp-nightly-builds',
33 REPOSITORY
= UPDATE_SOURCES
['stable']
35 _VERSION_RE
= re
.compile(r
'(\d+\.)*\d+')
37 API_BASE_URL
= 'https://api.github.com/repos'
39 # Backwards compatibility variables for the current channel
40 API_URL
= f
'{API_BASE_URL}/{REPOSITORY}/releases'
44 def _get_variant_and_executable_path():
45 """@returns (variant, executable_path)"""
46 if getattr(sys
, 'frozen', False):
48 if not hasattr(sys
, '_MEIPASS'):
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 ''
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
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'))):
67 return 'unknown', path
71 return VARIANT
or _get_variant_and_executable_path()[0]
75 def current_git_head():
76 if detect_variant() != 'source':
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()):
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',
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
',
109 def is_non_updateable():
112 return _NON_UPDATEABLE_REASONS.get(
113 detect_variant(), _NON_UPDATEABLE_REASONS['unknown
' if VARIANT else 'other
'])
116 def _sha256_file(path):
118 mv = memoryview(bytearray(128 * 1024))
119 with open(os.path.realpath(path), 'rb
', buffering=0) as f:
120 for n in iter(lambda: f.readinto(mv), 0):
128 def __init__(self, ydl, target=None):
131 self.target_channel, sep, self.target_tag = (target or CHANNEL).rpartition('@')
132 # stable => stable@latest
133 if not sep and ('/' in self.target_tag or self.target_tag in UPDATE_SOURCES):
134 self.target_channel = self.target_tag
135 self.target_tag = None
136 elif not self.target_channel:
137 self.target_channel = CHANNEL.partition('@')[0]
139 if not self.target_tag:
140 self.target_tag = 'latest
'
142 elif self.target_tag != 'latest
':
143 self.target_tag = f'tags
/{self.target_tag}
'
145 if '/' in self.target_channel:
146 self._target_repo = self.target_channel
147 if self.target_channel not in (CHANNEL, *UPDATE_SOURCES.values()):
148 self.ydl.report_warning(
149 f'You are switching to an {self.ydl._format_err("unofficial", "red")} executable
'
150 f'from {self.ydl._format_err(self._target_repo, self.ydl.Styles.EMPHASIS)}
. '
151 f'Run {self.ydl._format_err("at your own risk", "light red")}
')
152 self._block_restart('Automatically restarting into custom builds
is disabled
for security reasons
')
154 self._target_repo = UPDATE_SOURCES.get(self.target_channel)
155 if not self._target_repo:
157 f'Invalid update channel {self.target_channel!r} requested
. '
158 f'Valid channels are {", ".join(UPDATE_SOURCES)}
', True)
160 def _version_compare(self, a, b, channel=CHANNEL):
161 if self._exact and channel != self.target_channel:
164 if _VERSION_RE.fullmatch(f'{a}
.{b}
'):
165 a, b = version_tuple(a), version_tuple(b)
166 return a == b if self._exact else a >= b
169 @functools.cached_property
171 if self._version_compare(self.current_version, self.latest_version):
172 return self.target_tag
174 identifier = f'{detect_variant()} {self.target_channel} {system_identifier()}
'
175 for line in self._download('_update_spec
', 'latest
').decode().splitlines():
176 if not line.startswith('lock
'):
178 _, tag, pattern = line.split(' ', 2)
179 if re.match(pattern, identifier):
182 elif self.target_tag == 'latest
' or not self._version_compare(
183 tag, self.target_tag[5:], channel=self.target_channel):
185 f'yt
-dlp cannot be updated above {tag} since you are on an older Python version
', True)
186 return f'tags
/{self.current_version}
'
187 return self.target_tag
190 def _get_version_info(self, tag):
191 url = f'{API_BASE_URL}
/{self._target_repo}
/releases
/{tag}
'
192 self.ydl.write_debug(f'Fetching release info
: {url}
')
193 return json.loads(self.ydl.urlopen(sanitized_Request(url, headers={
194 'Accept
': 'application
/vnd
.github
+json
',
195 'User
-Agent
': 'yt
-dlp
',
196 'X
-GitHub
-Api
-Version
': '2022-11-28',
200 def current_version(self):
201 """Current version"""
205 def _label(channel, tag):
206 """Label for a given channel and tag"""
207 return f'{channel}
@{remove_start(tag, "tags/")}
'
209 def _get_actual_tag(self, tag):
210 if tag.startswith('tags
/'):
212 return self._get_version_info(tag)['tag_name
']
215 def new_version(self):
216 """Version of the latest release we can update to"""
217 return self._get_actual_tag(self._tag)
220 def latest_version(self):
221 """Version of the target release"""
222 return self._get_actual_tag(self.target_tag)
225 def has_update(self):
226 """Whether there is an update available"""
227 return not self._version_compare(self.current_version, self.new_version)
229 @functools.cached_property
231 """Filename of the executable"""
232 return compat_realpath(_get_variant_and_executable_path()[1])
234 def _download(self, name, tag):
235 slug = 'latest
/download
' if tag == 'latest
' else f'download
/{tag[5:]}
'
236 url = f'https
://github
.com
/{self._target_repo}
/releases
/{slug}
/{name}
'
237 self.ydl.write_debug(f'Downloading {name}
from {url}
')
238 return self.ydl.urlopen(url).read()
240 @functools.cached_property
241 def release_name(self):
242 """The release filename"""
243 return f'yt
-dlp{_FILE_SUFFIXES[detect_variant()]}
'
245 @functools.cached_property
246 def release_hash(self):
247 """Hash of the latest release"""
248 hash_data = dict(ln.split()[::-1] for ln in self._download('SHA2
-256SUMS
', self._tag).decode().splitlines())
249 return hash_data[self.release_name]
251 def _report_error(self, msg, expected=False):
252 self.ydl.report_error(msg, tb=False if expected else None)
253 self.ydl._download_retcode = 100
255 def _report_permission_error(self, file):
256 self._report_error(f'Unable to write to {file}
; Try running
as administrator
', True)
258 def _report_network_error(self, action, delim=';'):
260 f'Unable to {action}{delim} visit
'
261 f'https
://github
.com
/{self._target_repo}
/releases
/{self.target_tag.replace("tags/", "tag/")}
', True)
263 def check_update(self):
264 """Report whether there is an update available"""
265 if not self._target_repo:
269 f'Available version
: {self._label(self.target_channel, self.latest_version)}
, ' if self.target_tag == 'latest
' else ''
270 ) + f'Current version
: {self._label(CHANNEL, self.current_version)}
')
271 except network_exceptions as e:
272 return self._report_network_error(f'obtain version
info ({e}
)', delim='; Please
try again later
or')
274 if not is_non_updateable():
275 self.ydl.to_screen(f'Current Build Hash
: {_sha256_file(self.filename)}
')
280 if self.target_tag == self._tag:
281 self.ydl.to_screen(f'yt
-dlp
is up to
date ({self._label(CHANNEL, self.current_version)}
)')
282 elif not self._exact:
283 self.ydl.report_warning('yt
-dlp cannot be updated any further since you are on an older Python version
')
287 """Update yt-dlp executable to the latest version"""
288 if not self.check_update():
290 err = is_non_updateable()
292 return self._report_error(err, True)
293 self.ydl.to_screen(f'Updating to {self._label(self.target_channel, self.new_version)}
...')
294 if (_VERSION_RE.fullmatch(self.target_tag[5:])
295 and version_tuple(self.target_tag[5:]) < (2023, 3, 2)):
296 self.ydl.report_warning('You are downgrading to a version without
--update
-to
')
297 self._block_restart('Cannot automatically restart to a version without
--update
-to
')
299 directory = os.path.dirname(self.filename)
300 if not os.access(self.filename, os.W_OK):
301 return self._report_permission_error(self.filename)
302 elif not os.access(directory, os.W_OK):
303 return self._report_permission_error(directory)
305 new_filename, old_filename = f'{self.filename}
.new
', f'{self.filename}
.old
'
306 if detect_variant() == 'zip': # Can be replaced in-place
307 new_filename, old_filename = self.filename, None
310 if os.path.exists(old_filename or ''):
311 os.remove(old_filename)
313 return self._report_error('Unable to remove the old version
')
316 newcontent = self._download(self.release_name, self._tag)
317 except network_exceptions as e:
318 if isinstance(e, urllib.error.HTTPError) and e.code == 404:
319 return self._report_error(
320 f'The requested tag {self._label(self.target_channel, self.target_tag)} does
not exist
', True)
321 return self._report_network_error(f'fetch updates
: {e}
')
324 expected_hash = self.release_hash
326 self.ydl.report_warning('no
hash information found
for the release
')
328 if hashlib.sha256(newcontent).hexdigest() != expected_hash:
329 return self._report_network_error('verify the new executable
')
332 with open(new_filename, 'wb
') as outf:
333 outf.write(newcontent)
335 return self._report_permission_error(new_filename)
338 mask = os.stat(self.filename).st_mode
340 os.rename(self.filename, old_filename)
342 return self._report_error('Unable to move current version
')
345 os.rename(new_filename, self.filename)
347 self._report_error('Unable to overwrite current version
')
348 return os.rename(old_filename, self.filename)
350 variant = detect_variant()
351 if variant.startswith('win
') or variant == 'py2exe
':
352 atexit.register(Popen, f'ping
127.0.0.1 -n
5 -w
1000 & del /F
"{old_filename}"',
353 shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
356 os.remove(old_filename)
358 self._report_error('Unable to remove the old version
')
361 os.chmod(self.filename, mask)
363 return self._report_error(
364 f'Unable to
set permissions
. Run
: sudo chmod a
+rx {compat_shlex_quote(self.filename)}
')
366 self.ydl.to_screen(f'Updated yt
-dlp to {self._label(self.target_channel, self.new_version)}
')
369 @functools.cached_property
371 """The command-line to run the executable, if known"""
372 # There is no sys.orig_argv in py < 3.10. Also, it can be [] when frozen
373 if getattr(sys, 'orig_argv
', None):
375 elif getattr(sys, 'frozen
', False):
379 """Restart the executable"""
380 assert self.cmd, 'Must be frozen
or Py
>= 3.10'
381 self.ydl.write_debug(f'Restarting
: {shell_quote(self.cmd)}
')
382 _, _, returncode = Popen.run(self.cmd)
385 def _block_restart(self, msg):
387 self._report_error(f'{msg}
. Restart yt
-dlp to use the updated version
', expected=True)
388 return self.ydl._download_retcode
389 self.restart = wrapper
393 """Update the program file with the latest version from the repository
394 @returns Whether there was a successful update (No update = False)
396 return Updater(ydl).update()
400 def update_self(to_screen, verbose, opener):
403 deprecation_warning(f'"{__name__}.update_self" is deprecated
and may be removed
'
404 f'in a future version
. Use
"{__name__}.run_update(ydl)" instead
')
411 def report_warning(self, msg, *args, **kwargs):
412 return printfn(f'WARNING
: {msg}
', *args, **kwargs)
414 def report_error(self, msg, tb=None):
415 printfn(f'ERROR
: {msg}
')
419 # Copied from YoutubeDL.trouble
420 if sys.exc_info()[0]:
422 if hasattr(sys.exc_info()[1], 'exc_info
') and sys.exc_info()[1].exc_info[0]:
423 tb += ''.join(traceback.format_exception(*sys.exc_info()[1].exc_info))
424 tb += traceback.format_exc()
426 tb_data = traceback.format_list(traceback.extract_stack())
427 tb = ''.join(tb_data)
431 def write_debug(self, msg, *args, **kwargs):
432 printfn(f'[debug
] {msg}
', *args, **kwargs)
434 def urlopen(self, url):
435 return opener.open(url)
437 return run_update(FakeYDL())
440 __all__ = ['Updater
']