]> jfr.im git - yt-dlp.git/blame - youtube_dl/update.py
[utils] remove useless u prefix
[yt-dlp.git] / youtube_dl / update.py
CommitLineData
d2790370 1import io
d5ed35b6
FV
2import json
3import traceback
4import hashlib
ce02ed60 5import os
d2790370 6import subprocess
46353f67 7import sys
d5ed35b6
FV
8from zipimport import zipimporter
9
ce02ed60
PH
10from .utils import (
11 compat_str,
12 compat_urllib_request,
13)
d5ed35b6
FV
14from .version import __version__
15
5f6a1245 16
d5ed35b6
FV
17def rsa_verify(message, signature, key):
18 from struct import pack
19 from hashlib import sha256
20 from sys import version_info
5f6a1245 21
d5ed35b6 22 def b(x):
5f6a1245
JW
23 if version_info[0] == 2:
24 return x
25 else:
26 return x.encode('latin1')
d5ed35b6
FV
27 assert(type(message) == type(b('')))
28 block_size = 0
29 n = key[0]
30 while n:
31 block_size += 1
32 n >>= 8
33 signature = pow(int(signature, 16), key[1], key[0])
34 raw_bytes = []
35 while signature:
36 raw_bytes.insert(0, pack("B", signature & 0xFF))
37 signature >>= 8
38 signature = (block_size - len(raw_bytes)) * b('\x00') + b('').join(raw_bytes)
5f6a1245
JW
39 if signature[0:2] != b('\x00\x01'):
40 return False
d5ed35b6 41 signature = signature[2:]
5f6a1245
JW
42 if not b('\x00') in signature:
43 return False
2514d263 44 signature = signature[signature.index(b('\x00')) + 1:]
5f6a1245
JW
45 if not signature.startswith(b('\x30\x31\x30\x0D\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x01\x05\x00\x04\x20')):
46 return False
d5ed35b6 47 signature = signature[19:]
5f6a1245
JW
48 if signature != sha256(message).digest():
49 return False
d5ed35b6
FV
50 return True
51
d7386f62 52
46353f67 53def update_self(to_screen, verbose):
d5ed35b6
FV
54 """Update the program file with the latest version from the repository"""
55
43ff1a34 56 UPDATE_URL = "http://rg3.github.io/youtube-dl/update/"
d5ed35b6
FV
57 VERSION_URL = UPDATE_URL + 'LATEST_VERSION'
58 JSON_URL = UPDATE_URL + 'versions.json'
59 UPDATES_RSA_KEY = (0x9d60ee4d8f805312fdb15a62f87b95bd66177b91df176765d13514a0f1754bcd2057295c5b6f1d35daa6742c3ffc9a82d3e118861c207995a8031e151d863c9927e304576bc80692bc8e094896fcf11b66f3e29e04e3a71e9a11558558acea1840aec37fc396fb6b65dc81a1c4144e03bd1c011de62e3f1357b327d08426fe93, 65537)
60
d5ed35b6 61 if not isinstance(globals().get('__loader__'), zipimporter) and not hasattr(sys, "frozen"):
f9bd64c0 62 to_screen(u'It looks like you installed youtube-dl with a package manager, pip, setup.py or a tarball. Please use that to update.')
d5ed35b6
FV
63 return
64
65 # Check if there is a new version
66 try:
67 newversion = compat_urllib_request.urlopen(VERSION_URL).read().decode('utf-8').strip()
68 except:
5f6a1245
JW
69 if verbose:
70 to_screen(compat_str(traceback.format_exc()))
d5ed35b6
FV
71 to_screen(u'ERROR: can\'t find the current version. Please try again later.')
72 return
73 if newversion == __version__:
74 to_screen(u'youtube-dl is up-to-date (' + __version__ + ')')
75 return
76
77 # Download and check versions info
78 try:
79 versions_info = compat_urllib_request.urlopen(JSON_URL).read().decode('utf-8')
80 versions_info = json.loads(versions_info)
81 except:
5f6a1245
JW
82 if verbose:
83 to_screen(compat_str(traceback.format_exc()))
d5ed35b6
FV
84 to_screen(u'ERROR: can\'t obtain versions info. Please try again later.')
85 return
86 if not 'signature' in versions_info:
87 to_screen(u'ERROR: the versions file is not signed or corrupted. Aborting.')
88 return
89 signature = versions_info['signature']
90 del versions_info['signature']
91 if not rsa_verify(json.dumps(versions_info, sort_keys=True).encode('utf-8'), signature, UPDATES_RSA_KEY):
92 to_screen(u'ERROR: the versions file signature is invalid. Aborting.')
93 return
94
d2790370 95 version_id = versions_info['latest']
d7386f62
PH
96
97 def version_tuple(version_str):
98 return tuple(map(int, version_str.split('.')))
2e767313 99 if version_tuple(__version__) >= version_tuple(version_id):
d7386f62
PH
100 to_screen(u'youtube-dl is up to date (%s)' % __version__)
101 return
102
18a25c5d 103 to_screen(u'Updating to version ' + version_id + ' ...')
d2790370 104 version = versions_info['versions'][version_id]
3bf79c75 105
46a127ee 106 print_notes(to_screen, versions_info['versions'])
d5ed35b6 107
46353f67
PH
108 filename = sys.argv[0]
109 # Py2EXE: Filename could be different
110 if hasattr(sys, "frozen") and not os.path.isfile(filename):
111 if os.path.isfile(filename + u'.exe'):
112 filename += u'.exe'
113
d5ed35b6
FV
114 if not os.access(filename, os.W_OK):
115 to_screen(u'ERROR: no write permissions on %s' % filename)
116 return
117
118 # Py2EXE
119 if hasattr(sys, "frozen"):
120 exe = os.path.abspath(filename)
121 directory = os.path.dirname(exe)
122 if not os.access(directory, os.W_OK):
123 to_screen(u'ERROR: no write permissions on %s' % directory)
124 return
125
126 try:
127 urlh = compat_urllib_request.urlopen(version['exe'][0])
128 newcontent = urlh.read()
129 urlh.close()
0b63aed8 130 except (IOError, OSError):
5f6a1245
JW
131 if verbose:
132 to_screen(compat_str(traceback.format_exc()))
d5ed35b6
FV
133 to_screen(u'ERROR: unable to download latest version')
134 return
135
136 newcontent_hash = hashlib.sha256(newcontent).hexdigest()
137 if newcontent_hash != version['exe'][1]:
138 to_screen(u'ERROR: the downloaded file hash does not match. Aborting.')
139 return
140
141 try:
142 with open(exe + '.new', 'wb') as outf:
143 outf.write(newcontent)
0b63aed8 144 except (IOError, OSError):
5f6a1245
JW
145 if verbose:
146 to_screen(compat_str(traceback.format_exc()))
d5ed35b6
FV
147 to_screen(u'ERROR: unable to write the new version')
148 return
149
150 try:
151 bat = os.path.join(directory, 'youtube-dl-updater.bat')
d2790370
PH
152 with io.open(bat, 'w') as batfile:
153 batfile.write(u"""
154@echo off
155echo Waiting for file handle to be closed ...
d5ed35b6 156ping 127.0.0.1 -n 5 -w 1000 > NUL
d2790370
PH
157move /Y "%s.new" "%s" > NUL
158echo Updated youtube-dl to version %s.
159start /b "" cmd /c del "%%~f0"&exit /b"
160 \n""" % (exe, exe, version_id))
d5ed35b6 161
d2790370
PH
162 subprocess.Popen([bat]) # Continues to run in the background
163 return # Do not show premature success messages
0b63aed8 164 except (IOError, OSError):
5f6a1245
JW
165 if verbose:
166 to_screen(compat_str(traceback.format_exc()))
d5ed35b6
FV
167 to_screen(u'ERROR: unable to overwrite current version')
168 return
169
170 # Zip unix package
171 elif isinstance(globals().get('__loader__'), zipimporter):
172 try:
173 urlh = compat_urllib_request.urlopen(version['bin'][0])
174 newcontent = urlh.read()
175 urlh.close()
0b63aed8 176 except (IOError, OSError):
5f6a1245
JW
177 if verbose:
178 to_screen(compat_str(traceback.format_exc()))
d5ed35b6
FV
179 to_screen(u'ERROR: unable to download latest version')
180 return
181
182 newcontent_hash = hashlib.sha256(newcontent).hexdigest()
183 if newcontent_hash != version['bin'][1]:
184 to_screen(u'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)
0b63aed8 190 except (IOError, OSError):
5f6a1245
JW
191 if verbose:
192 to_screen(compat_str(traceback.format_exc()))
d5ed35b6
FV
193 to_screen(u'ERROR: unable to overwrite current version')
194 return
195
196 to_screen(u'Updated youtube-dl. Restart youtube-dl to use the new version.')
3bf79c75 197
5f6a1245 198
46a127ee 199def get_notes(versions, fromVersion):
3bf79c75 200 notes = []
5f6a1245 201 for v, vdata in sorted(versions.items()):
3bf79c75
PH
202 if v > fromVersion:
203 notes.extend(vdata.get('notes', []))
46a127ee
PH
204 return notes
205
5f6a1245 206
46a127ee
PH
207def print_notes(to_screen, versions, fromVersion=__version__):
208 notes = get_notes(versions, fromVersion)
3bf79c75
PH
209 if notes:
210 to_screen(u'PLEASE NOTE:')
211 for note in notes:
212 to_screen(note)