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__
15 RELEASE_JSON_URL
= 'https://api.github.com/repos/yt-dlp/yt-dlp/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]) == '__main__.py':
34 return 'unknown', path
38 return _get_variant_and_executable_path()[0]
45 'darwin_exe': '_macos',
48 _NON_UPDATEABLE_REASONS
= {
49 **{variant: None for variant in _FILE_SUFFIXES}
, # Updatable
50 **{variant: f'Auto-update is not supported for unpackaged {name} executable
; Re
-download the latest release
'
51 for variant, name in {'win32_dir': 'Windows', 'darwin_dir': 'MacOS'}.items()},
52 'source
': 'You cannot update when running
from source code
; Use git to pull the latest changes
',
53 'unknown
': 'It looks like you installed yt
-dlp
with a package manager
, pip
or setup
.py
; Use that to update
',
54 'other
': 'It looks like you are using an unofficial build of yt
-dlp
; Build the executable again
',
58 def is_non_updateable():
59 return _NON_UPDATEABLE_REASONS.get(detect_variant(), _NON_UPDATEABLE_REASONS['other
'])
64 Update the program file with the latest version from the repository
65 Returns whether the program should terminate
68 def report_error(msg, expected=False):
69 ydl.report_error(msg, tb=False if expected else None)
71 def report_unable(action, expected=False):
72 report_error(f'Unable to {action}
', expected)
74 def report_permission_error(file):
75 report_unable(f'write to {file}
; Try running
as administrator
', True)
77 def report_network_error(action, delim=';'):
78 report_unable(f'{action}{delim} Visit https
://github
.com
/yt
-dlp
/yt
-dlp
/releases
/latest
', True)
80 def calc_sha256sum(path):
82 mv = memoryview(bytearray(128 * 1024))
83 with open(os.path.realpath(path), 'rb
', buffering=0) as f:
84 for n in iter(lambda: f.readinto(mv), 0):
89 version_info = json.loads(ydl.urlopen(RELEASE_JSON_URL).read().decode())
91 return report_network_error('obtain version info
', delim='; Please
try again later
or')
93 version_id = version_info['tag_name
']
94 ydl.to_screen(f'Latest version
: {version_id}
, Current version
: {__version__}
')
95 if version_tuple(__version__) >= version_tuple(version_id):
96 ydl.to_screen(f'yt
-dlp
is up to
date ({__version__}
)')
99 err = is_non_updateable()
101 return report_error(err, True)
103 variant, filename = _get_variant_and_executable_path()
104 filename = compat_realpath(filename) # Absolute path, following symlinks
106 label = _FILE_SUFFIXES[variant]
107 if label and platform.architecture()[0][:2] == '32':
108 label = f'_x86{label}
'
109 release_name = f'yt
-dlp{label}
'
111 ydl.to_screen(f'Current Build Hash {calc_sha256sum(filename)}
')
112 ydl.to_screen(f'Updating to version {version_id}
...')
114 def get_file(name, fatal=True):
115 error = report_network_error if fatal else lambda _: None
117 version_info, ('assets
', lambda _, v: v['name
'] == name, 'browser_download_url
'), get_all=False)
119 return error('fetch updates
')
121 return ydl.urlopen(url).read()
123 return error('download latest version
')
128 hash_data = get_file('SHA2
-256SUMS
', fatal=False) or b''
129 expected = dict(ln.split()[::-1] for ln in hash_data.decode().splitlines()).get(release_name)
131 ydl.report_warning('no
hash information found
for the release
')
132 elif hashlib.sha256(content).hexdigest() != expected:
133 return report_network_error('verify the new executable
')
136 directory = os.path.dirname(filename)
137 if not os.access(filename, os.W_OK):
138 return report_permission_error(filename)
139 elif not os.access(directory, os.W_OK):
140 return report_permission_error(directory)
142 new_filename, old_filename = f'{filename}
.new
', f'{filename}
.old
'
143 if variant == 'zip': # Can be replaced in-place
144 new_filename, old_filename = filename, None
147 if os.path.exists(old_filename or ''):
148 os.remove(old_filename)
150 return report_unable('remove the old version
')
152 newcontent = get_file(release_name)
153 if not verify(newcontent):
156 with open(new_filename, 'wb
') as outf:
157 outf.write(newcontent)
159 return report_permission_error(new_filename)
163 os.rename(filename, old_filename)
165 return report_unable('move current version
')
168 os.rename(new_filename, filename)
170 report_unable('overwrite current version
')
171 os.rename(old_filename, filename)
174 if variant not in ('win32_exe
', 'py2exe
'):
176 os.remove(old_filename)
177 ydl.to_screen(f'Updated yt
-dlp to version {version_id}
; Restart yt
-dlp to use the new version
')
181 # Continues to run in the background
182 Popen(f'ping
127.0.0.1 -n
5 -w
1000 & del /F
"{old_filename}"',
183 shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
184 ydl.to_screen(f'Updated yt
-dlp to version {version_id}
')
185 return True # Exit app
187 report_unable('delete the old version
')
191 def update_self(to_screen, verbose, opener):
193 from .utils import write_string
196 'DeprecationWarning: "yt_dlp.update.update_self" is deprecated
and may be removed
in a future version
. '
197 'Use
"yt_dlp.update.run_update(ydl)" instead
\n')
205 def report_warning(msg, *args, **kwargs):
206 return printfn(f'WARNING
: {msg}
', *args, **kwargs)
209 def report_error(msg, tb=None):
210 printfn(f'ERROR
: {msg}
')
214 # Copied from YoutubeDL.trouble
215 if sys.exc_info()[0]:
217 if hasattr(sys.exc_info()[1], 'exc_info
') and sys.exc_info()[1].exc_info[0]:
218 tb += ''.join(traceback.format_exception(*sys.exc_info()[1].exc_info))
219 tb += traceback.format_exc()
221 tb_data = traceback.format_list(traceback.extract_stack())
222 tb = ''.join(tb_data)
226 def urlopen(self, url):
227 return opener.open(url)
229 return run_update(FakeYDL())