]>
jfr.im git - yt-dlp.git/blob - yt_dlp/update.py
1 from __future__
import unicode_literals
10 from zipimport
import zipimporter
12 from .compat
import compat_realpath
13 from .utils
import encode_compat_str
15 from .version
import __version__
19 def rsa_verify(message, signature, key):
20 from hashlib import sha256
21 assert isinstance(message, bytes)
22 byte_size = (len(bin(key[0])) - 2 + 8 - 1) // 8
23 signature = ('%x' % pow(int(signature, 16), key[1], key[0])).encode()
24 signature = (byte_size * 2 - len(signature)) * b'0' + signature
25 asn1 = b'3031300d060960864801650304020105000420'
26 asn1 += sha256(message).hexdigest().encode()
27 if byte_size < len(asn1) // 2 + 11:
29 expected = b'0001' + (byte_size - len(asn1) // 2 - 3) * b'ff' + b'00' + asn1
30 return expected == signature
35 if hasattr(sys
, 'frozen'):
36 if getattr(sys
, '_MEIPASS', None):
37 if sys
._MEIPASS
== os
.path
.dirname(sys
.executable
):
41 elif isinstance(globals().get('__loader__'), zipimporter
):
43 elif os
.path
.basename(sys
.argv
[0]) == '__main__.py':
48 _NON_UPDATEABLE_REASONS
= {
51 'dir': 'Auto-update is not supported for unpackaged windows executable; Re-download the latest release',
52 'py2exe': 'There is no official release for py2exe executable; Build it again with the latest source code',
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, setup.py or a tarball; Use that to update',
58 def is_non_updateable():
59 return _NON_UPDATEABLE_REASONS
.get(detect_variant(), _NON_UPDATEABLE_REASONS
['unknown'])
64 Update the program file with the latest version from the repository
65 Returns whether the program should terminate
68 JSON_URL
= 'https://api.github.com/repos/yt-dlp/yt-dlp/releases/latest'
70 def report_error(msg
, expected
=False):
71 ydl
.report_error(msg
, tb
='' if expected
else None)
73 def report_unable(action
, expected
=False):
74 report_error(f
'Unable to {action}', expected
)
76 def report_permission_error(file):
77 report_unable(f
'write to {file}; Try running as administrator', True)
79 def report_network_error(action
, delim
=';'):
80 report_unable(f
'{action}{delim} Visit https://github.com/yt-dlp/yt-dlp/releases/latest', True)
82 def calc_sha256sum(path
):
84 b
= bytearray(128 * 1024)
86 with open(os
.path
.realpath(path
), 'rb', buffering
=0) as f
:
87 for n
in iter(lambda: f
.readinto(mv
), 0):
91 # Download and check versions info
93 version_info
= ydl
._opener
.open(JSON_URL
).read().decode('utf-8')
94 version_info
= json
.loads(version_info
)
96 return report_network_error('obtain version info', delim
='; Please try again later or')
98 def version_tuple(version_str
):
99 return tuple(map(int, version_str
.split('.')))
101 version_id
= version_info
['tag_name']
102 if version_tuple(__version__
) >= version_tuple(version_id
):
103 ydl
.to_screen(f
'yt-dlp is up to date ({__version__})')
106 err
= is_non_updateable()
108 ydl
.to_screen(f
'Latest version: {version_id}, Current version: {__version__}')
109 return report_error(err
, True)
111 # sys.executable is set to the full pathname of the exe-file for py2exe
112 # though symlinks are not followed so that we need to do this manually
113 # with help of realpath
114 filename
= compat_realpath(sys
.executable
if hasattr(sys
, 'frozen') else sys
.argv
[0])
115 ydl
.to_screen(f
'Current version {__version__}; Build Hash {calc_sha256sum(filename)}')
116 ydl
.to_screen(f
'Updating to version {version_id} ...')
121 'exe_32': '_x86.exe',
124 def get_bin_info(bin_or_exe
, version
):
125 label
= version_labels
['%s_%s' % (bin_or_exe
, version
)]
126 return next((i
for i
in version_info
['assets'] if i
['name'] == 'yt-dlp%s' % label
), {})
128 def get_sha256sum(bin_or_exe
, version
):
129 filename
= 'yt-dlp%s' % version_labels
['%s_%s' % (bin_or_exe
, version
)]
131 (i
for i
in version_info
['assets'] if i
['name'] in ('SHA2-256SUMS')),
132 {}).get('browser_download_url')
135 hash_data
= ydl
._opener
.open(urlh
).read().decode('utf-8')
136 return dict(ln
.split()[::-1] for ln
in hash_data
.splitlines()).get(filename
)
138 if not os
.access(filename
, os
.W_OK
):
139 return report_permission_error(filename
)
142 if hasattr(sys
, 'frozen'):
144 directory
= os
.path
.dirname(exe
)
145 if not os
.access(directory
, os
.W_OK
):
146 return report_permission_error(directory
)
148 if os
.path
.exists(filename
+ '.old'):
149 os
.remove(filename
+ '.old')
150 except (IOError, OSError):
151 return report_unable('remove the old version')
154 arch
= platform
.architecture()[0][:2]
155 url
= get_bin_info('exe', arch
).get('browser_download_url')
157 return report_network_error('fetch updates')
158 urlh
= ydl
._opener
.open(url
)
159 newcontent
= urlh
.read()
161 except (IOError, OSError):
162 return report_network_error('download latest version')
164 if not os
.access(exe
+ '.new', os
.W_OK
):
165 return report_permission_error(f
'{exe}.new')
167 with open(exe
+ '.new', 'wb') as outf
:
168 outf
.write(newcontent
)
169 except (IOError, OSError):
170 return report_unable('write the new version')
172 expected_sum
= get_sha256sum('exe', arch
)
174 ydl
.report_warning('no hash information found for the release')
175 elif calc_sha256sum(exe
+ '.new') != expected_sum
:
176 report_network_error('verify the new executable')
178 os
.remove(exe
+ '.new')
180 return report_unable('remove corrupt download')
183 os
.rename(exe
, exe
+ '.old')
184 except (IOError, OSError):
185 return report_unable('move current version')
187 os
.rename(exe
+ '.new', exe
)
188 except (IOError, OSError):
189 report_unable('overwrite current version')
190 os
.rename(exe
+ '.old', exe
)
193 # Continues to run in the background
195 'ping 127.0.0.1 -n 5 -w 1000 & del /F "%s.old"' % exe
,
196 shell
=True, stdout
=subprocess
.DEVNULL
, stderr
=subprocess
.DEVNULL
)
197 ydl
.to_screen('Updated yt-dlp to version %s' % version_id
)
198 return True # Exit app
200 report_unable('delete the old version')
203 elif isinstance(globals().get('__loader__'), zipimporter
):
205 url
= get_bin_info('zip', '3').get('browser_download_url')
207 return report_network_error('fetch updates')
208 urlh
= ydl
._opener
.open(url
)
209 newcontent
= urlh
.read()
211 except (IOError, OSError):
212 return report_network_error('download the latest version')
214 expected_sum
= get_sha256sum('zip', '3')
216 ydl
.report_warning('no hash information found for the release')
217 elif hashlib
.sha256(newcontent
).hexdigest() != expected_sum
:
218 return report_network_error('verify the new zip')
221 with open(filename
, 'wb') as outf
:
222 outf
.write(newcontent
)
223 except (IOError, OSError):
224 return report_unable('overwrite current version')
226 ydl
.to_screen('Updated yt-dlp to version %s; Restart yt-dlp to use the new version' % version_id
)
230 def get_notes(versions, fromVersion):
232 for v, vdata in sorted(versions.items()):
234 notes.extend(vdata.get('notes', []))
238 def print_notes(to_screen, versions, fromVersion=__version__):
239 notes = get_notes(versions, fromVersion)
241 to_screen('PLEASE NOTE:')
247 def update_self(to_screen
, verbose
, opener
):
248 ''' Exists for backward compatibility '''
253 'WARNING: "yt_dlp.update.update_self" is deprecated and may be removed in a future version. '
254 'Use "yt_dlp.update.run_update(ydl)" instead')
261 def report_warning(msg
, *args
, **kwargs
):
262 return printfn('WARNING: %s' % msg
, *args
, **kwargs
)
265 def report_error(msg
, tb
=None):
266 printfn('ERROR: %s' % msg
)
270 # Copied from YoutubeDl.trouble
271 if sys
.exc_info()[0]:
273 if hasattr(sys
.exc_info()[1], 'exc_info') and sys
.exc_info()[1].exc_info
[0]:
274 tb
+= ''.join(traceback
.format_exception(*sys
.exc_info()[1].exc_info
))
275 tb
+= encode_compat_str(traceback
.format_exc())
277 tb_data
= traceback
.format_list(traceback
.extract_stack())
278 tb
= ''.join(tb_data
)
282 return run_update(FakeYDL())