]>
jfr.im git - yt-dlp.git/blob - yt_dlp/update.py
8 from zipimport
import zipimporter
10 from .compat
import compat_realpath
, functools
11 from .utils
import Popen
, encode_compat_str
, write_string
12 from .version
import __version__
16 def get_variant_and_executable_path():
17 """@returns (variant, executable_path)"""
18 if hasattr(sys
, 'frozen'):
20 prefix
= 'mac' if sys
.platform
== 'darwin' else 'win'
21 if getattr(sys
, '_MEIPASS', None):
22 if sys
._MEIPASS
== os
.path
.dirname(sys
.executable
):
23 return f
'{prefix}_dir', path
24 return f
'{prefix}_exe', path
27 path
= os
.path
.join(os
.path
.dirname(__file__
), '..')
28 if isinstance(__loader__
, zipimporter
):
29 return 'zip', os
.path
.join(path
, '..')
30 elif os
.path
.basename(sys
.argv
[0]) == '__main__.py':
32 return 'unknown', path
36 return get_variant_and_executable_path()[0]
39 _NON_UPDATEABLE_REASONS
= {
44 'win_dir': 'Auto-update is not supported for unpackaged windows executable; Re-download the latest release',
45 'mac_dir': 'Auto-update is not supported for unpackaged MacOS executable; Re-download the latest release',
46 'source': 'You cannot update when running from source code; Use git to pull the latest changes',
47 'unknown': 'It looks like you installed yt-dlp with a package manager, pip or setup.py; Use that to update',
51 def is_non_updateable():
52 return _NON_UPDATEABLE_REASONS
.get(detect_variant(), _NON_UPDATEABLE_REASONS
['unknown'])
57 Update the program file with the latest version from the repository
58 Returns whether the program should terminate
61 JSON_URL
= 'https://api.github.com/repos/yt-dlp/yt-dlp/releases/latest'
63 def report_error(msg
, expected
=False):
64 ydl
.report_error(msg
, tb
=False if expected
else None)
66 def report_unable(action
, expected
=False):
67 report_error(f
'Unable to {action}', expected
)
69 def report_permission_error(file):
70 report_unable(f
'write to {file}; Try running as administrator', True)
72 def report_network_error(action
, delim
=';'):
73 report_unable(f
'{action}{delim} Visit https://github.com/yt-dlp/yt-dlp/releases/latest', True)
75 def calc_sha256sum(path
):
77 b
= bytearray(128 * 1024)
79 with open(os
.path
.realpath(path
), 'rb', buffering
=0) as f
:
80 for n
in iter(lambda: f
.readinto(mv
), 0):
84 # Download and check versions info
86 version_info
= ydl
._opener
.open(JSON_URL
).read().decode()
87 version_info
= json
.loads(version_info
)
89 return report_network_error('obtain version info', delim
='; Please try again later or')
91 def version_tuple(version_str
):
92 return tuple(map(int, version_str
.split('.')))
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 ydl
.to_screen(f
'Current Build Hash {calc_sha256sum(filename)}')
108 ydl
.to_screen(f
'Updating to version {version_id} ...')
112 'win_exe_64': '.exe',
113 'py2exe_64': '_min.exe',
114 'win_exe_32': '_x86.exe',
115 'mac_exe_64': '_macos',
118 def get_bin_info(bin_or_exe
, version
):
119 label
= version_labels
[f
'{bin_or_exe}_{version}']
120 return next((i
for i
in version_info
['assets'] if i
['name'] == 'yt-dlp%s' % label
), {})
122 def get_sha256sum(bin_or_exe
, version
):
123 filename
= 'yt-dlp%s' % version_labels
[f
'{bin_or_exe}_{version}']
125 (i
for i
in version_info
['assets'] if i
['name'] in ('SHA2-256SUMS')),
126 {}).get('browser_download_url')
129 hash_data
= ydl
._opener
.open(urlh
).read().decode()
130 return dict(ln
.split()[::-1] for ln
in hash_data
.splitlines()).get(filename
)
132 if not os
.access(filename
, os
.W_OK
):
133 return report_permission_error(filename
)
135 if variant
in ('win_exe', 'py2exe'):
136 directory
= os
.path
.dirname(filename
)
137 if not os
.access(directory
, os
.W_OK
):
138 return report_permission_error(directory
)
140 if os
.path
.exists(filename
+ '.old'):
141 os
.remove(filename
+ '.old')
143 return report_unable('remove the old version')
146 arch
= platform
.architecture()[0][:2]
147 url
= get_bin_info(variant
, arch
).get('browser_download_url')
149 return report_network_error('fetch updates')
150 urlh
= ydl
._opener
.open(url
)
151 newcontent
= urlh
.read()
154 return report_network_error('download latest version')
157 with open(filename
+ '.new', 'wb') as outf
:
158 outf
.write(newcontent
)
160 return report_permission_error(f
'{filename}.new')
162 expected_sum
= get_sha256sum(variant
, arch
)
164 ydl
.report_warning('no hash information found for the release')
165 elif calc_sha256sum(filename
+ '.new') != expected_sum
:
166 report_network_error('verify the new executable')
168 os
.remove(filename
+ '.new')
170 return report_unable('remove corrupt download')
173 os
.rename(filename
, filename
+ '.old')
175 return report_unable('move current version')
177 os
.rename(filename
+ '.new', filename
)
179 report_unable('overwrite current version')
180 os
.rename(filename
+ '.old', filename
)
183 # Continues to run in the background
185 'ping 127.0.0.1 -n 5 -w 1000 & del /F "%s.old"' % filename
,
186 shell
=True, stdout
=subprocess
.DEVNULL
, stderr
=subprocess
.DEVNULL
)
187 ydl
.to_screen('Updated yt-dlp to version %s' % version_id
)
188 return True # Exit app
190 report_unable('delete the old version')
192 elif variant
in ('zip', 'mac_exe'):
193 pack_type
= '3' if variant
== 'zip' else '64'
195 url
= get_bin_info(variant
, pack_type
).get('browser_download_url')
197 return report_network_error('fetch updates')
198 urlh
= ydl
._opener
.open(url
)
199 newcontent
= urlh
.read()
202 return report_network_error('download the latest version')
204 expected_sum
= get_sha256sum(variant
, pack_type
)
206 ydl
.report_warning('no hash information found for the release')
207 elif hashlib
.sha256(newcontent
).hexdigest() != expected_sum
:
208 return report_network_error('verify the new package')
211 with open(filename
, 'wb') as outf
:
212 outf
.write(newcontent
)
214 return report_unable('overwrite current version')
216 ydl
.to_screen('Updated yt-dlp to version %s; Restart yt-dlp to use the new version' % version_id
)
219 assert False, f
'Unhandled variant: {variant}'
223 def update_self(to_screen
, verbose
, opener
):
228 'DeprecationWarning: "yt_dlp.update.update_self" is deprecated and may be removed in a future version. '
229 'Use "yt_dlp.update.run_update(ydl)" instead\n')
236 def report_warning(msg
, *args
, **kwargs
):
237 return printfn('WARNING: %s' % msg
, *args
, **kwargs
)
240 def report_error(msg
, tb
=None):
241 printfn('ERROR: %s' % msg
)
245 # Copied from YoutubeDl.trouble
246 if sys
.exc_info()[0]:
248 if hasattr(sys
.exc_info()[1], 'exc_info') and sys
.exc_info()[1].exc_info
[0]:
249 tb
+= ''.join(traceback
.format_exception(*sys
.exc_info()[1].exc_info
))
250 tb
+= encode_compat_str(traceback
.format_exc())
252 tb_data
= traceback
.format_list(traceback
.extract_stack())
253 tb
= ''.join(tb_data
)
257 return run_update(FakeYDL())