-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathredistsCLI.py
326 lines (284 loc) · 12.4 KB
/
redistsCLI.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
import sys
import json
import os
import logging
import ctypes
import requests
import subprocess
import tempfile
import winreg
import time
import datetime
import appdirs
from concurrent.futures import ThreadPoolExecutor
from concurrent.futures import as_completed
# Embed the redistributables JSON data
EMBEDDED_REDISTS_JSON = """
{
"redistributables": {
"x86": [
{
"name": "Visual C++ 2005",
"version": "8.0.61001",
"online_url": "https://download.microsoft.com/download/8/B/4/8B42259F-5D70-43F4-AC2E-4B208FD8D66A/vcredist_x86.exe",
"install_command": "/q"
},
{
"name": "Visual C++ 2008",
"version": "9.0.30729.6161",
"online_url": "https://download.microsoft.com/download/5/D/8/5D8C65CB-C849-4025-8E95-C3966CAFD8AE/vcredist_x86.exe",
"install_command": "/qb"
}
],
"x64": [
{
"name": "Visual C++ 2005",
"version": "8.0.61000",
"online_url": "https://download.microsoft.com/download/8/B/4/8B42259F-5D70-43F4-AC2E-4B208FD8D66A/vcredist_x64.exe",
"install_command": "/q"
},
{
"name": "Visual C++ 2008",
"version": "9.0.30729.6161",
"online_url": "https://download.microsoft.com/download/5/D/8/5D8C65CB-C849-4025-8E95-C3966CAFD8AE/vcredist_x64.exe",
"install_command": "/qb"
}
],
"all": [
{
"name": "DirectX End-User Runtime",
"version": "9.29.1974.1",
"online_url": "https://download.microsoft.com/download/1/7/1/1718CCC4-6315-4D8E-9543-8E28A4E18C4C/dxwebsetup.exe",
"install_command": "/Q"
}
]
}
}
"""
class ConsoleRedistInstaller:
def __init__(self):
self.version = "1.0.0"
self.app_name = "AG Redist Installer Script"
self.settings_dir = appdirs.user_data_dir(self.app_name)
self.settings_file = os.path.join(self.settings_dir, "settings.json")
self.installations_performed = False
self.setup_logging()
self.load_settings()
self.load_redists_data()
def setup_logging(self):
log_dir = appdirs.user_log_dir(self.app_name)
os.makedirs(log_dir, exist_ok=True)
log_file = os.path.join(log_dir, 'redist_installer.log')
self.logger = logging.getLogger('RedistInstaller')
self.logger.setLevel(logging.DEBUG)
# File handler
fh = logging.FileHandler(log_file)
fh.setLevel(logging.DEBUG)
# Console handler
ch = logging.StreamHandler()
ch.setLevel(logging.INFO)
# Formatter
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
ch.setFormatter(formatter)
self.logger.addHandler(fh)
self.logger.addHandler(ch)
def load_settings(self):
try:
if os.path.exists(self.settings_file):
with open(self.settings_file, 'r') as f:
settings = json.load(f)
else:
settings = {}
self.arch = settings.get('architecture', self.detect_architecture())
except Exception as e:
self.logger.error(f"Error loading settings: {str(e)}")
self.arch = self.detect_architecture()
def save_settings(self):
settings = {
'architecture': self.arch,
'last_update_check': datetime.date.today().isoformat()
}
os.makedirs(self.settings_dir, exist_ok=True)
with open(self.settings_file, 'w') as f:
json.dump(settings, f)
def detect_architecture(self):
return 'x64' if os.environ.get('PROCESSOR_ARCHITECTURE', '').endswith('64') else 'x86'
def load_redists_data(self):
try:
github_data = self.fetch_github_json()
if github_data:
self.logger.info("Successfully loaded redistributables data from GitHub")
self.data = github_data
else:
self.logger.warning("Using embedded redistributables data")
self.data = json.loads(EMBEDDED_REDISTS_JSON)
except Exception as e:
self.logger.error(f"Error loading redists data: {str(e)}")
sys.exit(1)
def fetch_github_json(self):
url = "https://raw.githubusercontent.com/KaladinDMP/AG_Redist_Installer/main/redists.json"
try:
response = requests.get(url, timeout=10)
response.raise_for_status()
return response.json()
except Exception as e:
self.logger.error(f"Failed to fetch JSON from GitHub: {e}")
return None
def check_installation_status(self, redist):
name = redist['name']
version = redist['version']
registry_keys = [
r"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall",
r"SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall"
]
for key in registry_keys:
try:
with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, key) as reg_key:
for i in range(winreg.QueryInfoKey(reg_key)[0]):
try:
subkey_name = winreg.EnumKey(reg_key, i)
with winreg.OpenKey(reg_key, subkey_name) as subkey:
try:
display_name = winreg.QueryValueEx(subkey, "DisplayName")[0]
if name.lower() in display_name.lower():
display_version = winreg.QueryValueEx(subkey, "DisplayVersion")[0]
if self.compare_versions(display_version, version) >= 0:
return True
except WindowsError:
continue
except WindowsError:
continue
except WindowsError:
continue
return False
def compare_versions(self, version1, version2):
v1_parts = version1.split('.')
v2_parts = version2.split('.')
for i in range(max(len(v1_parts), len(v2_parts))):
v1 = int(v1_parts[i]) if i < len(v1_parts) else 0
v2 = int(v2_parts[i]) if i < len(v2_parts) else 0
if v1 > v2:
return 1
elif v1 < v2:
return -1
return 0
def install_redist(self, redist):
name = redist["name"]
version = redist["version"]
url = redist["online_url"]
install_command = redist.get("install_command", "/quiet /norestart")
self.logger.info(f"Starting installation of {name} {version}")
try:
# Create temporary file
with tempfile.NamedTemporaryFile(delete=False, suffix='.exe') as temp_file:
file_path = temp_file.name
# Download the file
self.logger.info(f"Downloading {name}...")
response = requests.get(url, stream=True)
total_size = int(response.headers.get('content-length', 0))
with open(file_path, 'wb') as f:
downloaded = 0
for data in response.iter_content(8192):
size = f.write(data)
downloaded += size
percent = int(downloaded / total_size * 100) if total_size > 0 else 0
print(f"\rDownloading {name}: {percent}%", end='', flush=True)
print() # New line after download completes
# Install the redistributable
self.logger.info(f"Installing {name}...")
for attempt in range(3):
try:
result = subprocess.run([file_path] + install_command.split(),
capture_output=True, text=True, timeout=300)
if result.returncode in (0, 3010):
self.installations_performed = True
self.logger.info(f"Successfully installed {name}")
return True
elif attempt < 2:
self.logger.warning(f"Installation attempt {attempt + 1} failed for {name}, retrying...")
time.sleep(5)
else:
self.logger.error(f"Failed to install {name} after 3 attempts")
return False
except subprocess.TimeoutExpired:
if attempt < 2:
self.logger.warning(f"Installation timed out for {name}, retrying...")
time.sleep(5)
else:
self.logger.error(f"Installation of {name} timed out after 3 attempts")
return False
except Exception as e:
self.logger.error(f"Error installing {name}: {str(e)}")
return False
finally:
if os.path.exists(file_path):
try:
os.unlink(file_path)
except Exception as e:
self.logger.error(f"Error removing temporary file {file_path}: {str(e)}")
return False
def install_all_redists(self):
redists = []
redists.extend(self.data['redistributables'].get(self.arch, []))
redists.extend(self.data['redistributables'].get('all', []))
total = len(redists)
successful = 0
failed = 0
self.logger.info(f"Starting installation of {total} redistributables...")
with ThreadPoolExecutor(max_workers=1) as executor:
future_to_redist = {executor.submit(self.install_redist, redist): redist for redist in redists}
for future in as_completed(future_to_redist):
redist = future_to_redist[future]
try:
success = future.result()
if success:
successful += 1
else:
failed += 1
except Exception as e:
self.logger.error(f"Error installing {redist['name']}: {str(e)}")
failed += 1
self.logger.info(f"\nInstallation complete:")
self.logger.info(f"Successful: {successful}")
self.logger.info(f"Failed: {failed}")
self.logger.info(f"Total: {total}")
if self.installations_performed:
self.logger.info("\nSome installations were performed. A system restart is recommended.")
return True
return False
def is_admin():
try:
return ctypes.windll.shell32.IsUserAnAdmin()
except:
return False
def run_as_admin():
ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, " ".join(sys.argv), None, 1)
def main():
if not is_admin():
print("This program requires administrative privileges. Requesting elevation...")
run_as_admin()
return
print("ARMGDDN Games Redist Installer Script")
print("----------------------------------------------")
installer = ConsoleRedistInstaller()
# Show detected architecture
print(f"\nDetected system architecture: {installer.arch}")
choice = input("Would you like to change the architecture? (y/N): ").lower()
if choice == 'y':
new_arch = input("Enter architecture (x86/x64): ").lower()
if new_arch in ['x86', 'x64']:
installer.arch = new_arch
installer.save_settings()
print("\nStarting installation process...")
needs_restart = installer.install_all_redists()
if needs_restart:
choice = input("\nWould you like to restart your computer now? (y/N): ").lower()
if choice == 'y':
subprocess.run(["shutdown", "/r", "/t", "10"])
print("System will restart in 10 seconds. Press Ctrl+C to cancel.")
else:
print("Please remember to restart your computer to complete the installation process.")
input("\nPress Enter to exit...")
if __name__ == '__main__':
main()