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