]>
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
34 def update_self(to_screen
, verbose
, opener
):
35 ''' Exists for backward compatibility. Use run_update(ydl) instead '''
44 def report_warning(msg
, *args
, **kwargs
):
45 return printfn('WARNING: %s' % msg
, *args
, **kwargs
)
48 def report_error(msg
, tb
=None):
49 printfn('ERROR: %s' % msg
)
53 # Copied from YoutubeDl.trouble
56 if hasattr(sys
.exc_info()[1], 'exc_info') and sys
.exc_info()[1].exc_info
[0]:
57 tb
+= ''.join(traceback
.format_exception(*sys
.exc_info()[1].exc_info
))
58 tb
+= encode_compat_str(traceback
.format_exc())
60 tb_data
= traceback
.format_list(traceback
.extract_stack())
65 return run_update(FakeYDL())
70 Update the program file with the latest version from the repository
71 Returns whether the program should terminate
74 JSON_URL
= 'https://api.github.com/repos/yt-dlp/yt-dlp/releases/latest'
76 def report_error(msg
, network
=False, expected
=False, delim
=';'):
78 msg
+= '%s Visit https://github.com/yt-dlp/yt-dlp/releases/latest' % delim
79 ydl
.report_error(msg
, tb
='' if network
or expected
else None)
81 def calc_sha256sum(path
):
83 b
= bytearray(128 * 1024)
85 with open(os
.path
.realpath(path
), 'rb', buffering
=0) as f
:
86 for n
in iter(lambda: f
.readinto(mv
), 0):
90 if not isinstance(globals().get('__loader__'), zipimporter
) and not hasattr(sys
, 'frozen'):
92 'It looks like you installed yt-dlp with a package manager, pip, setup.py or a tarball. '
93 'Please use that to update', expected
=True)
95 # sys.executable is set to the full pathname of the exe-file for py2exe
96 # though symlinks are not followed so that we need to do this manually
97 # with help of realpath
98 filename
= compat_realpath(sys
.executable
if hasattr(sys
, 'frozen') else sys
.argv
[0])
99 ydl
.to_screen('Current Build Hash %s' % calc_sha256sum(filename
))
101 # Download and check versions info
103 version_info
= ydl
._opener
.open(JSON_URL
).read().decode('utf-8')
104 version_info
= json
.loads(version_info
)
106 return report_error('can\'t obtain versions info. Please try again later ', True, delim
='or')
108 def version_tuple(version_str
):
109 return tuple(map(int, version_str
.split('.')))
111 version_id
= version_info
['tag_name']
112 if version_tuple(__version__
) >= version_tuple(version_id
):
113 ydl
.to_screen('yt-dlp is up to date (%s)' % __version__
)
116 ydl
.to_screen('Updating to version ' + version_id
+ ' ...')
122 'exe_32': '_x86.exe',
125 def get_bin_info(bin_or_exe
, version
):
126 label
= version_labels
['%s_%s' % (bin_or_exe
, version
)]
127 return next((i
for i
in version_info
['assets'] if i
['name'] == 'yt-dlp%s' % label
), {})
129 def get_sha256sum(bin_or_exe
, version
):
130 label
= version_labels
['%s_%s' % (bin_or_exe
, version
)]
132 (i
for i
in version_info
['assets'] if i
['name'] in ('SHA2-256SUMS')),
133 {}).get('browser_download_url')
136 hash_data
= ydl
._opener
.open(urlh
).read().decode('utf-8')
137 hashes
= list(map(lambda x
: x
.split(':'), hash_data
.splitlines()))
138 return next((i
[1] for i
in hashes
if i
[0] == 'yt-dlp%s' % label
), None)
140 if not os
.access(filename
, os
.W_OK
):
141 return report_error('no write permissions on %s' % filename
, expected
=True)
144 if hasattr(sys
, 'frozen'):
146 directory
= os
.path
.dirname(exe
)
147 if not os
.access(directory
, os
.W_OK
):
148 return report_error('no write permissions on %s' % directory
, expected
=True)
150 if os
.path
.exists(filename
+ '.old'):
151 os
.remove(filename
+ '.old')
152 except (IOError, OSError):
153 return report_error('unable to remove the old version')
156 arch
= platform
.architecture()[0][:2]
157 url
= get_bin_info('exe', arch
).get('browser_download_url')
159 return report_error('unable to fetch updates', True)
160 urlh
= ydl
._opener
.open(url
)
161 newcontent
= urlh
.read()
163 except (IOError, OSError, StopIteration):
164 return report_error('unable to download latest version', True)
167 with open(exe
+ '.new', 'wb') as outf
:
168 outf
.write(newcontent
)
169 except (IOError, OSError):
170 return report_error('unable to 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_error('unable to verify the new executable', True)
178 os
.remove(exe
+ '.new')
180 return report_error('unable to remove corrupt download')
183 os
.rename(exe
, exe
+ '.old')
184 except (IOError, OSError):
185 return report_error('unable to move current version')
187 os
.rename(exe
+ '.new', exe
)
188 except (IOError, OSError):
189 report_error('unable to 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_error('unable to delete old version')
203 elif isinstance(globals().get('__loader__'), zipimporter
):
205 py_ver
= platform
.python_version()[0]
206 url
= get_bin_info('zip', py_ver
).get('browser_download_url')
208 return report_error('unable to fetch updates', True)
209 urlh
= ydl
._opener
.open(url
)
210 newcontent
= urlh
.read()
212 except (IOError, OSError, StopIteration):
213 return report_error('unable to download latest version', True)
215 expected_sum
= get_sha256sum('zip', py_ver
)
216 if expected_sum
and hashlib
.sha256(newcontent
).hexdigest() != expected_sum
:
217 return report_error('unable to verify the new zip', True)
220 with open(filename
, 'wb') as outf
:
221 outf
.write(newcontent
)
222 except (IOError, OSError):
223 return report_error('unable to overwrite current version')
225 ydl
.to_screen('Updated yt-dlp to version %s; Restart yt-dlp to use the new version' % version_id
)
229 def get_notes(versions, fromVersion):
231 for v, vdata in sorted(versions.items()):
233 notes.extend(vdata.get('notes', []))
237 def print_notes(to_screen, versions, fromVersion=__version__):
238 notes = get_notes(versions, fromVersion)
240 to_screen('PLEASE NOTE:')