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]) 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
'])
65 Update the program file with the latest version from the repository
66 Returns whether the program should terminate
69 def report_error(msg, expected=False):
70 ydl.report_error(msg, tb=False if expected else None)
72 def report_unable(action, expected=False):
73 report_error(f'Unable to {action}
', expected)
75 def report_permission_error(file):
76 report_unable(f'write to {file}
; Try running
as administrator
', True)
78 def report_network_error(action, delim=';'):
79 report_unable(f'{action}{delim} Visit https
://github
.com
/yt
-dlp
/yt
-dlp
/releases
/latest
', True)
81 def calc_sha256sum(path):
83 mv = memoryview(bytearray(128 * 1024))
84 with open(os.path.realpath(path), 'rb
', buffering=0) as f:
85 for n in iter(lambda: f.readinto(mv), 0):
90 version_info = json.loads(ydl.urlopen(RELEASE_JSON_URL).read().decode())
92 return report_network_error('obtain version info
', delim='; Please
try again later
or')
94 version_id = version_info['tag_name
']
95 ydl.to_screen(f'Latest version
: {version_id}
, Current version
: {__version__}
')
96 if version_tuple(__version__) >= version_tuple(version_id):
97 ydl.to_screen(f'yt
-dlp
is up to
date ({__version__}
)')
100 err = is_non_updateable()
102 return report_error(err, True)
104 variant, filename = _get_variant_and_executable_path()
105 filename = compat_realpath(filename) # Absolute path, following symlinks
107 label = _FILE_SUFFIXES[variant]
108 if label and platform.architecture()[0][:2] == '32':
109 label = f'_x86{label}
'
110 release_name = f'yt
-dlp{label}
'
112 ydl.to_screen(f'Current Build Hash {calc_sha256sum(filename)}
')
113 ydl.to_screen(f'Updating to version {version_id}
...')
115 def get_file(name, fatal=True):
116 error = report_network_error if fatal else lambda _: None
118 version_info, ('assets
', lambda _, v: v['name
'] == name, 'browser_download_url
'), get_all=False)
120 return error('fetch updates
')
122 return ydl.urlopen(url).read()
124 return error('download latest version
')
129 hash_data = get_file('SHA2
-256SUMS
', fatal=False) or b''
130 expected = dict(ln.split()[::-1] for ln in hash_data.decode().splitlines()).get(release_name)
132 ydl.report_warning('no
hash information found
for the release
')
133 elif hashlib.sha256(content).hexdigest() != expected:
134 return report_network_error('verify the new executable
')
137 directory = os.path.dirname(filename)
138 if not os.access(filename, os.W_OK):
139 return report_permission_error(filename)
140 elif not os.access(directory, os.W_OK):
141 return report_permission_error(directory)
143 new_filename, old_filename = f'{filename}
.new
', f'{filename}
.old
'
144 if variant == 'zip': # Can be replaced in-place
145 new_filename, old_filename = filename, None
148 if os.path.exists(old_filename or ''):
149 os.remove(old_filename)
151 return report_unable('remove the old version
')
153 newcontent = get_file(release_name)
154 if not verify(newcontent):
157 with open(new_filename, 'wb
') as outf:
158 outf.write(newcontent)
160 return report_permission_error(new_filename)
164 os.rename(filename, old_filename)
166 return report_unable('move current version
')
169 os.rename(new_filename, filename)
171 report_unable('overwrite current version
')
172 os.rename(old_filename, filename)
175 if variant not in ('win32_exe
', 'py2exe
'):
177 os.remove(old_filename)
178 ydl.to_screen(f'Updated yt
-dlp to version {version_id}
; Restart yt
-dlp to use the new version
')
182 # Continues to run in the background
183 Popen(f'ping
127.0.0.1 -n
5 -w
1000 & del /F
"{old_filename}"',
184 shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
185 ydl.to_screen(f'Updated yt
-dlp to version {version_id}
')
186 return True # Exit app
188 report_unable('delete the old version
')
192 def update_self(to_screen, verbose, opener):
194 from .utils import write_string
197 'DeprecationWarning: "yt_dlp.update.update_self" is deprecated
and may be removed
in a future version
. '
198 'Use
"yt_dlp.update.run_update(ydl)" instead
\n')
206 def report_warning(msg, *args, **kwargs):
207 return printfn(f'WARNING
: {msg}
', *args, **kwargs)
210 def report_error(msg, tb=None):
211 printfn(f'ERROR
: {msg}
')
215 # Copied from YoutubeDL.trouble
216 if sys.exc_info()[0]:
218 if hasattr(sys.exc_info()[1], 'exc_info
') and sys.exc_info()[1].exc_info[0]:
219 tb += ''.join(traceback.format_exception(*sys.exc_info()[1].exc_info))
220 tb += traceback.format_exc()
222 tb_data = traceback.format_list(traceback.extract_stack())
223 tb = ''.join(tb_data)
227 def urlopen(self, url):
228 return opener.open(url)
230 return run_update(FakeYDL())