]> jfr.im git - yt-dlp.git/blob - youtube_dlc/update.py
69bc5d2537a9e29a0bb76f85629b6a686c30a05d
[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 ''' # Not signed
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:
28 return False
29 expected = b'0001' + (byte_size - len(asn1) // 2 - 3) * b'ff' + b'00' + asn1
30 return expected == signature
31 '''
32
33
34 def update_self(to_screen, verbose, opener):
35 """Update the program file with the latest version from the repository"""
36
37 JSON_URL = 'https://api.github.com/repos/pukkandan/yt-dlp/releases/latest'
38
39 def sha256sum():
40 h = hashlib.sha256()
41 b = bytearray(128 * 1024)
42 mv = memoryview(b)
43 with open(os.path.realpath(sys.executable), 'rb', buffering=0) as f:
44 for n in iter(lambda: f.readinto(mv), 0):
45 h.update(mv[:n])
46 return h.hexdigest()
47
48 to_screen('Current Build Hash %s' % sha256sum())
49
50 if not isinstance(globals().get('__loader__'), zipimporter) and not hasattr(sys, 'frozen'):
51 to_screen('It looks like you installed youtube-dlc with a package manager, pip, setup.py or a tarball. Please use that to update.')
52 return
53
54 # Download and check versions info
55 try:
56 version_info = opener.open(JSON_URL).read().decode('utf-8')
57 version_info = json.loads(version_info)
58 except Exception:
59 if verbose:
60 to_screen(encode_compat_str(traceback.format_exc()))
61 to_screen('ERROR: can\'t obtain versions info. Please try again later.')
62 to_screen('Visit https://github.com/pukkandan/yt-dlp/releases/lastest')
63 return
64
65 version_id = version_info['tag_name']
66 if version_id == __version__:
67 to_screen('youtube-dlc is up-to-date (' + __version__ + ')')
68 return
69
70 def version_tuple(version_str):
71 return tuple(map(int, version_str.split('.')))
72
73 if version_tuple(__version__) >= version_tuple(version_id):
74 to_screen('youtube-dlc is up to date (%s)' % __version__)
75 return
76
77 to_screen('Updating to version ' + version_id + ' ...')
78
79 version = {
80 'bin': next(i for i in version_info['assets'] if i['name'] == 'youtube-dlc'),
81 'exe': next(i for i in version_info['assets'] if i['name'] == 'youtube-dlc.exe'),
82 'exe_x86': next(i for i in version_info['assets'] if i['name'] == 'youtube-dlc_x86.exe'),
83 }
84
85 # sys.executable is set to the full pathname of the exe-file for py2exe
86 # though symlinks are not followed so that we need to do this manually
87 # with help of realpath
88 filename = compat_realpath(sys.executable if hasattr(sys, 'frozen') else sys.argv[0])
89
90 if not os.access(filename, os.W_OK):
91 to_screen('ERROR: no write permissions on %s' % filename)
92 return
93
94 # PyInstaller
95 if hasattr(sys, 'frozen'):
96 exe = filename
97 directory = os.path.dirname(exe)
98 if not os.access(directory, os.W_OK):
99 to_screen('ERROR: no write permissions on %s' % directory)
100 return
101
102 try:
103 urlh = opener.open(version['exe']['browser_download_url'])
104 newcontent = urlh.read()
105 urlh.close()
106 except (IOError, OSError):
107 if verbose:
108 to_screen(encode_compat_str(traceback.format_exc()))
109 to_screen('ERROR: unable to download latest version')
110 to_screen('Visit https://github.com/pukkandan/yt-dlp/releases/lastest')
111 return
112
113 try:
114 with open(exe + '.new', 'wb') as outf:
115 outf.write(newcontent)
116 except (IOError, OSError):
117 if verbose:
118 to_screen(encode_compat_str(traceback.format_exc()))
119 to_screen('ERROR: unable to write the new version')
120 return
121
122 try:
123 bat = os.path.join(directory, 'yt-dlp-updater.cmd')
124 with io.open(bat, 'w') as batfile:
125 batfile.write('''
126 @(
127 echo.Waiting for file handle to be closed ...
128 ping 127.0.0.1 -n 5 -w 1000 > NUL
129 move /Y "%s.new" "%s" > NUL
130 echo.Updated youtube-dlc to version %s.
131 )
132 @start /b "" cmd /c del "%%~f0"&exit /b
133 ''' % (exe, exe, version_id))
134
135 subprocess.Popen([bat]) # Continues to run in the background
136 return # Do not show premature success messages
137 except (IOError, OSError):
138 if verbose:
139 to_screen(encode_compat_str(traceback.format_exc()))
140 to_screen('ERROR: unable to overwrite current version')
141 return
142
143 # Zip unix package
144 elif isinstance(globals().get('__loader__'), zipimporter):
145 try:
146 urlh = opener.open(version['bin']['browser_download_url'])
147 newcontent = urlh.read()
148 urlh.close()
149 except (IOError, OSError):
150 if verbose:
151 to_screen(encode_compat_str(traceback.format_exc()))
152 to_screen('ERROR: unable to download latest version')
153 to_screen('Visit https://github.com/pukkandan/yt-dlp/releases/lastest')
154 return
155
156 try:
157 with open(filename, 'wb') as outf:
158 outf.write(newcontent)
159 except (IOError, OSError):
160 if verbose:
161 to_screen(encode_compat_str(traceback.format_exc()))
162 to_screen('ERROR: unable to overwrite current version')
163 return
164
165 to_screen('Updated youtube-dlc. Restart youtube-dlc to use the new version.')
166
167
168 ''' # UNUSED
169 def get_notes(versions, fromVersion):
170 notes = []
171 for v, vdata in sorted(versions.items()):
172 if v > fromVersion:
173 notes.extend(vdata.get('notes', []))
174 return notes
175
176
177 def print_notes(to_screen, versions, fromVersion=__version__):
178 notes = get_notes(versions, fromVersion)
179 if notes:
180 to_screen('PLEASE NOTE:')
181 for note in notes:
182 to_screen(note)
183 '''