8 from zipimport
import zipimporter
10 from .compat
import functools
# isort: split
11 from .compat
import compat_realpath
12 from .utils
import Popen
, shell_quote
, traverse_obj
, version_tuple
13 from .version
import __version__
15 REPOSITORY
= 'yt-dlp/yt-dlp'
16 API_URL
= f
'https://api.github.com/repos/{REPOSITORY}/releases/latest'
20 def _get_variant_and_executable_path():
21 """@returns (variant, executable_path)"""
22 if hasattr(sys
, 'frozen'):
24 if not hasattr(sys
, '_MEIPASS'):
26 if sys
._MEIPASS
== os
.path
.dirname(path
):
27 return f
'{sys.platform}_dir', path
28 if sys
.platform
== 'darwin' and version_tuple(platform
.mac_ver()[0]) < (10, 15):
29 return 'darwin_legacy_exe', path
30 return f
'{sys.platform}_exe', path
32 path
= os
.path
.dirname(__file__
)
33 if isinstance(__loader__
, zipimporter
):
34 return 'zip', os
.path
.join(path
, '..')
35 elif (os
.path
.basename(sys
.argv
[0]) in ('__main__.py', '-m')
36 and os
.path
.exists(os
.path
.join(path
, '../.git/HEAD'))):
38 return 'unknown', path
42 return _get_variant_and_executable_path()[0]
49 'darwin_exe': '_macos',
50 'darwin_legacy_exe': '_macos_legacy',
51 'linux_exe': '_linux',
54 _NON_UPDATEABLE_REASONS
= {
55 **{variant: None for variant in _FILE_SUFFIXES}
, # Updatable
56 **{variant: f'Auto-update is not supported for unpackaged {name} executable
; Re
-download the latest release
'
57 for variant, name in {'win32_dir': 'Windows', 'darwin_dir': 'MacOS', 'linux_dir': 'Linux'}.items()},
58 'source
': 'You cannot update when running
from source code
; Use git to pull the latest changes
',
59 'unknown
': 'It looks like you installed yt
-dlp
with a package manager
, pip
or setup
.py
; Use that to update
',
60 'other
': 'It looks like you are using an unofficial build of yt
-dlp
; Build the executable again
',
64 def is_non_updateable():
65 return _NON_UPDATEABLE_REASONS.get(detect_variant(), _NON_UPDATEABLE_REASONS['other
'])
68 def _sha256_file(path):
70 mv = memoryview(bytearray(128 * 1024))
71 with open(os.path.realpath(path), 'rb
', buffering=0) as f:
72 for n in iter(lambda: f.readinto(mv), 0):
78 def __init__(self, ydl):
81 @functools.cached_property
82 def _new_version_info(self):
83 self.ydl.write_debug(f'Fetching release info
: {API_URL}
')
84 return json.loads(self.ydl.urlopen(API_URL).read().decode())
87 def current_version(self):
92 def new_version(self):
93 """Version of the latest release"""
94 return self._new_version_info['tag_name
']
98 """Whether there is an update available"""
99 return version_tuple(__version__) < version_tuple(self.new_version)
101 @functools.cached_property
103 """Filename of the executable"""
104 return compat_realpath(_get_variant_and_executable_path()[1])
106 def _download(self, name=None):
107 name = name or self.release_name
108 url = traverse_obj(self._new_version_info, (
109 'assets
', lambda _, v: v['name
'] == name, 'browser_download_url
'), get_all=False)
111 raise Exception('Unable to find download URL
')
112 self.ydl.write_debug(f'Downloading {name}
from {url}
')
113 return self.ydl.urlopen(url).read()
115 @functools.cached_property
116 def release_name(self):
117 """The release filename"""
118 label = _FILE_SUFFIXES[detect_variant()]
119 if label and platform.architecture()[0][:2] == '32':
120 label = f'_x86{label}
'
121 return f'yt
-dlp{label}
'
123 @functools.cached_property
124 def release_hash(self):
125 """Hash of the latest release"""
126 hash_data = dict(ln.split()[::-1] for ln in self._download('SHA2
-256SUMS
').decode().splitlines())
127 return hash_data[self.release_name]
129 def _report_error(self, msg, expected=False):
130 self.ydl.report_error(msg, tb=False if expected else None)
132 def _report_permission_error(self, file):
133 self._report_error(f'Unable to write to {file}
; Try running
as administrator
', True)
135 def _report_network_error(self, action, delim=';'):
136 self._report_error(f'Unable to {action}{delim} Visit https
://github
.com
/{REPOSITORY}
/releases
/latest
', True)
138 def check_update(self):
139 """Report whether there is an update available"""
142 f'Latest version
: {self.new_version}
, Current version
: {self.current_version}
')
144 return self._report_network_error('obtain version info
', delim='; Please
try again later
or')
146 if not self.has_update:
147 return self.ydl.to_screen(f'yt
-dlp
is up to
date ({__version__}
)')
149 if not is_non_updateable():
150 self.ydl.to_screen(f'Current Build Hash {_sha256_file(self.filename)}
')
154 """Update yt-dlp executable to the latest version"""
155 if not self.check_update():
157 err = is_non_updateable()
159 return self._report_error(err, True)
160 self.ydl.to_screen(f'Updating to version {self.new_version}
...')
162 directory = os.path.dirname(self.filename)
163 if not os.access(self.filename, os.W_OK):
164 return self._report_permission_error(self.filename)
165 elif not os.access(directory, os.W_OK):
166 return self._report_permission_error(directory)
168 new_filename, old_filename = f'{self.filename}
.new
', f'{self.filename}
.old
'
169 if detect_variant() == 'zip': # Can be replaced in-place
170 new_filename, old_filename = self.filename, None
173 if os.path.exists(old_filename or ''):
174 os.remove(old_filename)
176 return self._report_error('Unable to remove the old version
')
179 newcontent = self._download()
181 return self._report_network_error('download latest version
')
183 return self._report_network_error('fetch updates
')
186 expected_hash = self.release_hash
188 self.ydl.report_warning('no
hash information found
for the release
')
190 if hashlib.sha256(newcontent).hexdigest() != expected_hash:
191 return self._report_network_error('verify the new executable
')
194 with open(new_filename, 'wb
') as outf:
195 outf.write(newcontent)
197 return self._report_permission_error(new_filename)
201 os.rename(self.filename, old_filename)
203 return self._report_error('Unable to move current version
')
206 os.rename(new_filename, self.filename)
208 self._report_error('Unable to overwrite current version
')
209 return os.rename(old_filename, self.filename)
211 if detect_variant() not in ('win32_exe
', 'py2exe
'):
213 os.remove(old_filename)
215 atexit.register(Popen, f'ping
127.0.0.1 -n
5 -w
1000 & del /F
"{old_filename}"',
216 shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
218 self.ydl.to_screen(f'Updated yt
-dlp to version {self.new_version}
')
221 @functools.cached_property
223 """The command-line to run the executable, if known"""
224 # There is no sys.orig_argv in py < 3.10. Also, it can be [] when frozen
225 if getattr(sys, 'orig_argv
', None):
227 elif hasattr(sys, 'frozen
'):
231 """Restart the executable"""
232 assert self.cmd, 'Must be frozen
or Py
>= 3.10'
233 self.ydl.write_debug(f'Restarting
: {shell_quote(self.cmd)}
')
234 _, _, returncode = Popen.run(self.cmd)
239 """Update the program file with the latest version from the repository
240 @returns Whether there was a successful update (No update = False)
242 return Updater(ydl).update()
246 def update_self(to_screen, verbose, opener):
249 from .utils import write_string
252 'DeprecationWarning: "yt_dlp.update.update_self" is deprecated
and may be removed
in a future version
. '
253 'Use
"yt_dlp.update.run_update(ydl)" instead
\n')
260 def report_warning(self, msg, *args, **kwargs):
261 return printfn(f'WARNING
: {msg}
', *args, **kwargs)
263 def report_error(self, msg, tb=None):
264 printfn(f'ERROR
: {msg}
')
268 # Copied from YoutubeDL.trouble
269 if sys.exc_info()[0]:
271 if hasattr(sys.exc_info()[1], 'exc_info
') and sys.exc_info()[1].exc_info[0]:
272 tb += ''.join(traceback.format_exception(*sys.exc_info()[1].exc_info))
273 tb += traceback.format_exc()
275 tb_data = traceback.format_list(traceback.extract_stack())
276 tb = ''.join(tb_data)
280 def write_debug(self, msg, *args, **kwargs):
281 printfn(f'[debug
] {msg}
', *args, **kwargs)
283 def urlopen(self, url):
284 return opener.open(url)
286 return run_update(FakeYDL())