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