7 from zipimport
import zipimporter
9 from .compat
import functools
# isort: split
10 from .compat
import compat_realpath
11 from .utils
import Popen
, traverse_obj
, version_tuple
12 from .version
import __version__
14 REPOSITORY
= 'yt-dlp/yt-dlp'
15 API_URL
= f
'https://api.github.com/repos/{REPOSITORY}/releases/latest'
19 def _get_variant_and_executable_path():
20 """@returns (variant, executable_path)"""
21 if hasattr(sys
, 'frozen'):
23 if not hasattr(sys
, '_MEIPASS'):
25 if sys
._MEIPASS
== os
.path
.dirname(path
):
26 return f
'{sys.platform}_dir', path
27 return f
'{sys.platform}_exe', path
29 path
= os
.path
.dirname(__file__
)
30 if isinstance(__loader__
, zipimporter
):
31 return 'zip', os
.path
.join(path
, '..')
32 elif (os
.path
.basename(sys
.argv
[0]) in ('__main__.py', '-m')
33 and os
.path
.exists(os
.path
.join(path
, '../.git/HEAD'))):
35 return 'unknown', path
39 return _get_variant_and_executable_path()[0]
46 'darwin_exe': '_macos',
49 _NON_UPDATEABLE_REASONS
= {
50 **{variant: None for variant in _FILE_SUFFIXES}
, # Updatable
51 **{variant: f'Auto-update is not supported for unpackaged {name} executable
; Re
-download the latest release
'
52 for variant, name in {'win32_dir': 'Windows', 'darwin_dir': 'MacOS'}.items()},
53 'source
': 'You cannot update when running
from source code
; Use git to pull the latest changes
',
54 'unknown
': 'It looks like you installed yt
-dlp
with a package manager
, pip
or setup
.py
; Use that to update
',
55 'other
': 'It looks like you are using an unofficial build of yt
-dlp
; Build the executable again
',
59 def is_non_updateable():
60 return _NON_UPDATEABLE_REASONS.get(detect_variant(), _NON_UPDATEABLE_REASONS['other
'])
63 def _sha256_file(path):
65 mv = memoryview(bytearray(128 * 1024))
66 with open(os.path.realpath(path), 'rb
', buffering=0) as f:
67 for n in iter(lambda: f.readinto(mv), 0):
73 def __init__(self, ydl):
76 @functools.cached_property
77 def _new_version_info(self):
78 self.ydl.write_debug(f'Fetching release info
: {API_URL}
')
79 return json.loads(self.ydl.urlopen(API_URL).read().decode())
82 def current_version(self):
87 def new_version(self):
88 """Version of the latest release"""
89 return self._new_version_info['tag_name
']
93 """Whether there is an update available"""
94 return version_tuple(__version__) < version_tuple(self.new_version)
96 @functools.cached_property
98 """Filename of the executable"""
99 return compat_realpath(_get_variant_and_executable_path()[1])
101 def _download(self, name=None):
102 name = name or self.release_name
103 url = traverse_obj(self._new_version_info, (
104 'assets
', lambda _, v: v['name
'] == name, 'browser_download_url
'), get_all=False)
106 raise Exception('Unable to find download URL
')
107 self.ydl.write_debug(f'Downloading {name}
from {url}
')
108 return self.ydl.urlopen(url).read()
110 @functools.cached_property
111 def release_name(self):
112 """The release filename"""
113 label = _FILE_SUFFIXES[detect_variant()]
114 if label and platform.architecture()[0][:2] == '32':
115 label = f'_x86{label}
'
116 return f'yt
-dlp{label}
'
118 @functools.cached_property
119 def release_hash(self):
120 """Hash of the latest release"""
121 hash_data = dict(ln.split()[::-1] for ln in self._download('SHA2
-256SUMS
').decode().splitlines())
122 return hash_data[self.release_name]
124 def _report_error(self, msg, expected=False):
125 self.ydl.report_error(msg, tb=False if expected else None)
127 def _report_permission_error(self, file):
128 self._report_error(f'Unable to write to {file}
; Try running
as administrator
', True)
130 def _report_network_error(self, action, delim=';'):
131 self._report_error(f'Unable to {action}{delim} Visit https
://github
.com
/{REPOSITORY}
/releases
/latest
', True)
133 def check_update(self):
134 """Report whether there is an update available"""
137 f'Latest version
: {self.new_version}
, Current version
: {self.current_version}
')
139 return self._report_network_error('obtain version info
', delim='; Please
try again later
or')
141 if not self.has_update:
142 return self.ydl.to_screen(f'yt
-dlp
is up to
date ({__version__}
)')
144 if not is_non_updateable():
145 self.ydl.to_screen(f'Current Build Hash {_sha256_file(self.filename)}
')
149 """Update yt-dlp executable to the latest version"""
150 if not self.check_update():
152 err = is_non_updateable()
154 return self._report_error(err, True)
155 self.ydl.to_screen(f'Updating to version {self.new_version}
...')
157 directory = os.path.dirname(self.filename)
158 if not os.access(self.filename, os.W_OK):
159 return self._report_permission_error(self.filename)
160 elif not os.access(directory, os.W_OK):
161 return self._report_permission_error(directory)
163 new_filename, old_filename = f'{self.filename}
.new
', f'{self.filename}
.old
'
164 if detect_variant() == 'zip': # Can be replaced in-place
165 new_filename, old_filename = self.filename, None
168 if os.path.exists(old_filename or ''):
169 os.remove(old_filename)
171 return self._report_error('Unable to remove the old version
')
174 newcontent = self._download()
176 return self._report_network_error('download latest version
')
178 return self._report_network_error('fetch updates
')
181 expected_hash = self.release_hash
183 self.ydl.report_warning('no
hash information found
for the release
')
185 if hashlib.sha256(newcontent).hexdigest() != expected_hash:
186 return self._report_network_error('verify the new executable
')
189 with open(new_filename, 'wb
') as outf:
190 outf.write(newcontent)
192 return self._report_permission_error(new_filename)
196 os.rename(self.filename, old_filename)
198 return self._report_error('Unable to move current version
')
201 os.rename(new_filename, self.filename)
203 self._report_error('Unable to overwrite current version
')
204 return os.rename(old_filename, self.filename)
206 if detect_variant() not in ('win32_exe
', 'py2exe
'):
208 os.remove(old_filename)
209 self.ydl.to_screen(f'Updated yt
-dlp to version {self.new_version}
; Restart yt
-dlp to use the new version
')
213 # Continues to run in the background
214 Popen(f'ping
127.0.0.1 -n
5 -w
1000 & del /F
"{old_filename}"',
215 shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
216 self.ydl.to_screen(f'Updated yt
-dlp to version {self.new_version}
')
217 return True # Exit app
219 self._report_unable('delete the old version
')
223 """Update the program file with the latest version from the repository
224 @returns Whether there was a successfull update (No update = False)
226 return Updater(ydl).update()
230 def update_self(to_screen, verbose, opener):
233 from .utils import write_string
236 'DeprecationWarning: "yt_dlp.update.update_self" is deprecated
and may be removed
in a future version
. '
237 'Use
"yt_dlp.update.run_update(ydl)" instead
\n')
244 def report_warning(self, msg, *args, **kwargs):
245 return printfn(f'WARNING
: {msg}
', *args, **kwargs)
247 def report_error(self, msg, tb=None):
248 printfn(f'ERROR
: {msg}
')
252 # Copied from YoutubeDL.trouble
253 if sys.exc_info()[0]:
255 if hasattr(sys.exc_info()[1], 'exc_info
') and sys.exc_info()[1].exc_info[0]:
256 tb += ''.join(traceback.format_exception(*sys.exc_info()[1].exc_info))
257 tb += traceback.format_exc()
259 tb_data = traceback.format_list(traceback.extract_stack())
260 tb = ''.join(tb_data)
264 def write_debug(self, msg, *args, **kwargs):
265 printfn(f'[debug
] {msg}
', *args, **kwargs)
267 def urlopen(self, url):
268 return opener.open(url)
270 return run_update(FakeYDL())