]> jfr.im git - yt-dlp.git/blob - youtube_dlc/update.py
12b6c8608788a487d82669026107819670534187
[yt-dlp.git] / youtube_dlc / update.py
1 from __future__ import unicode_literals
2
3 import io
4 import json
5 import traceback
6 import hashlib
7 import os
8 import subprocess
9 import sys
10 from zipimport import zipimporter
11
12 from .compat import compat_realpath
13 from .utils import encode_compat_str
14
15 from .version import __version__
16
17
18 def rsa_verify(message, signature, key):
19 from hashlib import sha256
20 assert isinstance(message, bytes)
21 byte_size = (len(bin(key[0])) - 2 + 8 - 1) // 8
22 signature = ('%x' % pow(int(signature, 16), key[1], key[0])).encode()
23 signature = (byte_size * 2 - len(signature)) * b'0' + signature
24 asn1 = b'3031300d060960864801650304020105000420'
25 asn1 += sha256(message).hexdigest().encode()
26 if byte_size < len(asn1) // 2 + 11:
27 return False
28 expected = b'0001' + (byte_size - len(asn1) // 2 - 3) * b'ff' + b'00' + asn1
29 return expected == signature
30
31
32 def update_self(to_screen, verbose, opener):
33 """Update the program file with the latest version from the repository"""
34
35 return to_screen('Update is currently broken.\nVisit https://github.com/pukkandan/yt-dlc/releases/latest to get the latest version')
36
37 UPDATE_URL = 'https://blackjack4494.github.io//update/'
38 VERSION_URL = UPDATE_URL + 'LATEST_VERSION'
39 JSON_URL = UPDATE_URL + 'versions.json'
40 UPDATES_RSA_KEY = (0x9d60ee4d8f805312fdb15a62f87b95bd66177b91df176765d13514a0f1754bcd2057295c5b6f1d35daa6742c3ffc9a82d3e118861c207995a8031e151d863c9927e304576bc80692bc8e094896fcf11b66f3e29e04e3a71e9a11558558acea1840aec37fc396fb6b65dc81a1c4144e03bd1c011de62e3f1357b327d08426fe93, 65537)
41
42 def sha256sum():
43 h = hashlib.sha256()
44 b = bytearray(128 * 1024)
45 mv = memoryview(b)
46 with open(os.path.realpath(sys.executable), 'rb', buffering=0) as f:
47 for n in iter(lambda: f.readinto(mv), 0):
48 h.update(mv[:n])
49 return h.hexdigest()
50
51 to_screen('Current Build Hash %s' % sha256sum())
52
53 if not isinstance(globals().get('__loader__'), zipimporter) and not hasattr(sys, 'frozen'):
54 to_screen('It looks like you installed youtube-dlc with a package manager, pip, setup.py or a tarball. Please use that to update.')
55 return
56
57 # compiled file.exe can find itself by
58 # to_screen(os.path.basename(sys.executable))
59 # and path to py or exe
60 # to_screen(os.path.realpath(sys.executable))
61
62 # Check if there is a new version
63 try:
64 newversion = opener.open(VERSION_URL).read().decode('utf-8').strip()
65 except Exception:
66 if verbose:
67 to_screen(encode_compat_str(traceback.format_exc()))
68 to_screen('ERROR: can\'t find the current version. Please try again later.')
69 to_screen('Visit https://github.com/blackjack4494/yt-dlc/releases/latest')
70 return
71 if newversion == __version__:
72 to_screen('youtube-dlc is up-to-date (' + __version__ + ')')
73 return
74
75 # Download and check versions info
76 try:
77 versions_info = opener.open(JSON_URL).read().decode('utf-8')
78 versions_info = json.loads(versions_info)
79 except Exception:
80 if verbose:
81 to_screen(encode_compat_str(traceback.format_exc()))
82 to_screen('ERROR: can\'t obtain versions info. Please try again later.')
83 to_screen('Visit https://github.com/blackjack4494/yt-dlc/releases/latest')
84 return
85 if 'signature' not in versions_info:
86 to_screen('ERROR: the versions file is not signed or corrupted. Aborting.')
87 return
88 signature = versions_info['signature']
89 del versions_info['signature']
90 if not rsa_verify(json.dumps(versions_info, sort_keys=True).encode('utf-8'), signature, UPDATES_RSA_KEY):
91 to_screen('ERROR: the versions file signature is invalid. Aborting.')
92 return
93
94 version_id = versions_info['latest']
95
96 def version_tuple(version_str):
97 return tuple(map(int, version_str.split('.')))
98 if version_tuple(__version__) >= version_tuple(version_id):
99 to_screen('youtube-dlc is up to date (%s)' % __version__)
100 return
101
102 to_screen('Updating to version ' + version_id + ' ...')
103 version = versions_info['versions'][version_id]
104
105 print_notes(to_screen, versions_info['versions'])
106
107 # sys.executable is set to the full pathname of the exe-file for py2exe
108 # though symlinks are not followed so that we need to do this manually
109 # with help of realpath
110 filename = compat_realpath(sys.executable if hasattr(sys, 'frozen') else sys.argv[0])
111
112 if not os.access(filename, os.W_OK):
113 to_screen('ERROR: no write permissions on %s' % filename)
114 return
115
116 # Py2EXE
117 if hasattr(sys, 'frozen'):
118 exe = filename
119 directory = os.path.dirname(exe)
120 if not os.access(directory, os.W_OK):
121 to_screen('ERROR: no write permissions on %s' % directory)
122 return
123
124 try:
125 urlh = opener.open(version['exe'][0])
126 newcontent = urlh.read()
127 urlh.close()
128 except (IOError, OSError):
129 if verbose:
130 to_screen(encode_compat_str(traceback.format_exc()))
131 to_screen('ERROR: unable to download latest version')
132 to_screen('Visit https://github.com/blackjack4494/yt-dlc/releases/latest')
133 return
134
135 newcontent_hash = hashlib.sha256(newcontent).hexdigest()
136 if newcontent_hash != version['exe'][1]:
137 to_screen('ERROR: the downloaded file hash does not match. Aborting.')
138 return
139
140 try:
141 with open(exe + '.new', 'wb') as outf:
142 outf.write(newcontent)
143 except (IOError, OSError):
144 if verbose:
145 to_screen(encode_compat_str(traceback.format_exc()))
146 to_screen('ERROR: unable to write the new version')
147 return
148
149 try:
150 bat = os.path.join(directory, 'youtube-dlc-updater.bat')
151 with io.open(bat, 'w') as batfile:
152 batfile.write('''
153 @echo off
154 echo Waiting for file handle to be closed ...
155 ping 127.0.0.1 -n 5 -w 1000 > NUL
156 move /Y "%s.new" "%s" > NUL
157 echo Updated youtube-dlc to version %s.
158 start /b "" cmd /c del "%%~f0"&exit /b"
159 \n''' % (exe, exe, version_id))
160
161 subprocess.Popen([bat]) # Continues to run in the background
162 return # Do not show premature success messages
163 except (IOError, OSError):
164 if verbose:
165 to_screen(encode_compat_str(traceback.format_exc()))
166 to_screen('ERROR: unable to overwrite current version')
167 return
168
169 # Zip unix package
170 elif isinstance(globals().get('__loader__'), zipimporter):
171 try:
172 urlh = opener.open(version['bin'][0])
173 newcontent = urlh.read()
174 urlh.close()
175 except (IOError, OSError):
176 if verbose:
177 to_screen(encode_compat_str(traceback.format_exc()))
178 to_screen('ERROR: unable to download latest version')
179 to_screen('Visit https://github.com/blackjack4494/yt-dlc/releases/latest')
180 return
181
182 newcontent_hash = hashlib.sha256(newcontent).hexdigest()
183 if newcontent_hash != version['bin'][1]:
184 to_screen('ERROR: the downloaded file hash does not match. Aborting.')
185 return
186
187 try:
188 with open(filename, 'wb') as outf:
189 outf.write(newcontent)
190 except (IOError, OSError):
191 if verbose:
192 to_screen(encode_compat_str(traceback.format_exc()))
193 to_screen('ERROR: unable to overwrite current version')
194 return
195
196 to_screen('Updated youtube-dlc. Restart youtube-dlc to use the new version.')
197
198
199 def get_notes(versions, fromVersion):
200 notes = []
201 for v, vdata in sorted(versions.items()):
202 if v > fromVersion:
203 notes.extend(vdata.get('notes', []))
204 return notes
205
206
207 def print_notes(to_screen, versions, fromVersion=__version__):
208 notes = get_notes(versions, fromVersion)
209 if notes:
210 to_screen('PLEASE NOTE:')
211 for note in notes:
212 to_screen(note)