-
-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathmtkclient_installer.py
More file actions
1553 lines (1299 loc) · 62.9 KB
/
mtkclient_installer.py
File metadata and controls
1553 lines (1299 loc) · 62.9 KB
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
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import sys
import os
import ctypes
import shutil
import subprocess
import threading
import time
import winreg
import tempfile
import re
import urllib.request
import urllib.error
from datetime import datetime, timezone
from pathlib import Path
from typing import Optional, List, Tuple, Dict
from PyQt6 import QtCore, QtWidgets, QtGui
VERSION = "V1.2.2"
LOGFILE = Path(os.getenv("TEMP") or tempfile.gettempdir()) / f"mtkclient_installer_{VERSION}.log"
TIMEOUT_WINGET = 60 * 30
TIMEOUT_VS = 60 * 60
TIMEOUT_DOWNLOAD = 60 * 20
PIP_TIMEOUT = 60 * 30
PCT_RE = re.compile(r"(\d{1,3})%")
_LOG_LOCK = threading.Lock()
def timestamped(text: str) -> str:
return f"[{datetime.now(timezone.utc).strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3]}Z] {text}"
def log_to_file(text: str):
try:
with _LOG_LOCK:
with open(LOGFILE, "a", encoding="utf-8") as f:
f.write(timestamped(text))
except Exception:
pass
def is_admin() -> bool:
try:
return ctypes.windll.shell32.IsUserAnAdmin() != 0
except Exception:
return False
def relaunch_as_admin():
python_exe = sys.executable
params = " ".join([f'"{arg}"' for arg in sys.argv])
cwd = os.getcwd()
ctypes.windll.shell32.ShellExecuteW(None, "runas", python_exe, params, cwd, 1)
sys.exit(0)
def enable_long_paths():
try:
key_path = r"SYSTEM\CurrentControlSet\Control\FileSystem"
with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, key_path, 0, winreg.KEY_SET_VALUE) as key:
winreg.SetValueEx(key, "LongPathsEnabled", 0, winreg.REG_DWORD, 1)
log_to_file("LongPathsEnabled set to 1 in Registry.")
return True
except Exception as e:
log_to_file(f"Failed to enable Long Paths: {e}")
return False
def refresh_environment_path() -> bool:
try:
key = winreg.OpenKey(
winreg.HKEY_LOCAL_MACHINE,
r"SYSTEM\CurrentControlSet\Control\Session Manager\Environment",
)
sys_path, _ = winreg.QueryValueEx(key, "PATH")
sys_path = os.path.expandvars(sys_path)
winreg.CloseKey(key)
try:
key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, r"Environment")
user_path, _ = winreg.QueryValueEx(key, "PATH")
user_path = os.path.expandvars(user_path)
winreg.CloseKey(key)
except FileNotFoundError:
user_path = ""
os.environ["PATH"] = f"{sys_path};{user_path}"
return True
except Exception as e:
log_to_file(f"Failed to refresh PATH: {e}\n")
return False
def _ps_single_quote_escape(s: str) -> str:
return s.replace("'", "''")
def resource_path(relative: str) -> str:
if hasattr(sys, "_MEIPASS"):
return os.path.join(sys._MEIPASS, relative)
return os.path.join(os.path.abspath("."), relative)
def get_user_runtime_dir(appname: str = "mtkclient") -> Path:
base = os.getenv("LOCALAPPDATA") or os.getenv("APPDATA") or str(Path.home())
runtime = Path(base) / appname
runtime.mkdir(parents=True, exist_ok=True)
return runtime
def _ps_encode_command(script: str) -> str:
import base64
encoded = script.encode('utf-16le')
return base64.b64encode(encoded).decode('ascii')
def _download_with_retry(download_func, max_attempts: int = 3, base_delay: float = 2.0):
for attempt in range(max_attempts):
success, msg = download_func()
if success:
return True, msg
if attempt < max_attempts - 1:
delay = base_delay * (2 ** attempt)
time.sleep(delay)
return False, msg
def find_python_executable() -> str:
is_frozen = getattr(sys, 'frozen', False)
py = shutil.which("python")
if py:
if not (is_frozen and os.path.samefile(py, sys.executable)):
return py
roots = [
Path(os.environ.get("ProgramFiles", r"C:\Program Files")) / "Python",
Path(os.environ.get("LOCALAPPDATA", "")) / "Programs" / "Python",
Path(r"C:\Python")
]
found_exes = []
for root in roots:
if root.exists():
for folder in root.iterdir():
if folder.is_dir() and folder.name.lower().startswith("python3"):
exe_path = folder / "python.exe"
if exe_path.exists():
found_exes.append(exe_path)
if found_exes:
found_exes.sort(key=lambda x: x.parent.name, reverse=True)
return str(found_exes[0])
pylauncher = shutil.which("py")
if pylauncher:
try:
out = subprocess.check_output([pylauncher, "-3", "-c", "import sys;print(sys.executable)"],
text=True, timeout=5).strip()
if out and Path(out).exists():
return out
except:
pass
return sys.executable if not is_frozen else ""
class CommandResult:
def __init__(self, exitcode: int, stdout: str, stderr: str):
self.exitcode = exitcode
self.stdout = stdout
self.stderr = stderr
class InstallerWorker(QtCore.QThread):
progress_changed = QtCore.pyqtSignal(int)
current_progress_changed = QtCore.pyqtSignal(int)
set_indeterminate = QtCore.pyqtSignal(bool)
status_changed = QtCore.pyqtSignal(str)
log_summary = QtCore.pyqtSignal(str)
log_debug = QtCore.pyqtSignal(str)
step_failed = QtCore.pyqtSignal(str, int)
step_succeeded = QtCore.pyqtSignal(str, int)
finished_all = QtCore.pyqtSignal()
reboot_required = QtCore.pyqtSignal()
def __init__(self, start_from_step: int = 0, parent=None):
super().__init__(parent)
self._stop_requested = False
self._start_from_step = start_from_step
self._needs_reboot = False
self._current_proc: Optional[subprocess.Popen] = None
self._reader_threads: List[threading.Thread] = []
self.steps: List[Tuple[str, callable]] = []
self._setup_steps()
def request_stop(self):
self._stop_requested = True
self.kill_current_process_tree()
def kill_current_process_tree(self):
try:
proc = self._current_proc
if proc and proc.poll() is None:
try:
proc.kill()
except Exception:
pass
try:
subprocess.run(["taskkill", "/PID", str(proc.pid), "/T", "/F"],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
except Exception:
pass
except Exception:
pass
def _setup_steps(self):
self.steps = [
("Ensure winget", self.step_ensure_winget),
("Install Git & Python 3.1x", self.step_install_git_python),
("Refresh Environment PATH", self.step_refresh_path),
("Install WinFsp and UsbDk", self.step_install_winfsp_usbdk),
("Install Visual Studio Build Tools", self.step_install_build_tools),
("Clone mtkclient Repo", self.step_clone_repo),
("Install Python Requirements", self.step_pip_install_requirements),
("Verify Installation", self.step_verify),
]
def _run_proc(self, cmd: List[str], cwd: Optional[str] = None,
env: Optional[Dict[str, str]] = None, timeout: Optional[float] = None) -> CommandResult:
try:
proc = subprocess.Popen(
cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
text=True, bufsize=1, env=env or os.environ.copy(),
encoding="utf-8", errors="replace",
)
except Exception as e:
self.log_debug.emit(f"[ERROR] start failed: {e}\n")
return CommandResult(-1, "", str(e))
self._current_proc = proc
stdout_lines: List[str] = []
stderr_lines: List[str] = []
stop_time = time.time() + timeout if timeout else None
def reader(pipe, collector, prefix):
try:
buffer = ""
while True:
char = pipe.read(1)
if not char:
if proc.poll() is not None or self._stop_requested:
break
if stop_time and time.time() > stop_time:
break
time.sleep(0.01)
continue
buffer += char
# Process on newline or carriage return
if char in ('\n', '\r'):
if buffer.strip():
line = buffer
collector.append(line)
self.log_debug.emit(prefix + line)
# Extract percentage
m = PCT_RE.search(line)
if m:
try:
pct = int(m.group(1))
if 0 <= pct <= 100:
self.current_progress_changed.emit(pct)
except Exception:
pass
buffer = ""
except Exception:
pass
t_out = threading.Thread(target=reader, args=(proc.stdout, stdout_lines, ""))
t_err = threading.Thread(target=reader, args=(proc.stderr, stderr_lines, "[ERR] "))
t_out.daemon = True
t_err.daemon = True
t_out.start()
t_err.start()
self._reader_threads = [t_out, t_err]
try:
while proc.poll() is None:
if self._stop_requested:
try:
proc.kill()
except Exception:
pass
try:
subprocess.run(["taskkill", "/PID", str(proc.pid), "/T", "/F"],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
except Exception:
pass
break
if stop_time and time.time() > stop_time:
try:
proc.kill()
except Exception:
pass
try:
subprocess.run(["taskkill", "/PID", str(proc.pid), "/T", "/F"],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
except Exception:
pass
break
time.sleep(0.1)
except Exception:
pass
try:
rc = proc.wait(timeout=2)
except Exception:
try:
proc.kill()
except Exception:
pass
try:
rc = proc.wait(timeout=1)
except Exception:
rc = -1
try:
if proc.stdout:
proc.stdout.close()
if proc.stderr:
proc.stderr.close()
except Exception:
pass
for t in self._reader_threads:
if t.is_alive():
t.join(timeout=3)
self._reader_threads = []
self._current_proc = None
return CommandResult(rc, "".join(stdout_lines), "".join(stderr_lines))
def _download_with_progress(self, url: str, dest: Path, timeout: Optional[float] = None) -> Tuple[bool, str]:
self.log_debug.emit(f"[DL] Starting download: {url}\n")
try:
req = urllib.request.Request(url, headers={"User-Agent": "mtkclient-installer/1.0"})
with urllib.request.urlopen(req, timeout=timeout) as resp:
status = getattr(resp, "status", None) or getattr(resp, "getcode", lambda: None)()
if status and status >= 400:
body = resp.read(1024).decode(errors="replace")
self.log_debug.emit(f"[DL] HTTP error {status}: {body}\n")
return False, f"HTTP {status}"
length = resp.getheader("Content-Length")
if length:
total = int(length)
self.current_progress_changed.emit(0)
self.set_indeterminate.emit(False)
downloaded = 0
chunk = 64 * 1024
with open(dest, "wb") as f:
while True:
if self._stop_requested:
return False, "Cancelled"
data = resp.read(chunk)
if not data:
break
f.write(data)
downloaded += len(data)
pct = int(downloaded * 100 / total) if total > 0 else -1
if pct >= 0:
self.current_progress_changed.emit(min(100, pct))
self.current_progress_changed.emit(100)
self.log_debug.emit(f"[DL] Downloaded {downloaded} bytes (expected {total})\n")
return True, "Downloaded"
else:
self.set_indeterminate.emit(True)
with open(dest, "wb") as f:
while True:
if self._stop_requested:
return False, "Cancelled"
data = resp.read(64 * 1024)
if not data:
break
f.write(data)
self.set_indeterminate.emit(False)
self.current_progress_changed.emit(100)
return True, "Downloaded (unknown length)"
except urllib.error.HTTPError as e:
body = ""
try:
body = e.read(1024).decode(errors="replace")
except Exception:
pass
self.log_debug.emit(f"[DL] HTTPError {e.code}: {body}\n")
return False, f"HTTP {e.code}"
except Exception as e:
self.log_debug.emit(f"[DL] download failed: {e}\n")
return False, str(e)
def run(self):
total = len(self.steps)
for idx, (label, fn) in enumerate(self.steps, start=1):
if idx - 1 < self._start_from_step:
continue
if self._stop_requested:
self.log_summary.emit("Operation cancelled by user.\n")
return
self.progress_changed.emit(int((idx - 1) / total * 100))
self.current_progress_changed.emit(-1)
self.set_indeterminate.emit(True)
self.status_changed.emit(f"[{idx}/{total}] {label}")
summary_msg = f"\n=== Step {idx}/{total}: {label} ===\n"
self.log_summary.emit(summary_msg)
log_to_file(summary_msg)
ok, msg = fn()
self.set_indeterminate.emit(False)
if ok:
ok_msg = f"[OK] {msg}\n"
self.log_summary.emit(ok_msg)
log_to_file(ok_msg)
self.step_succeeded.emit(label, idx - 1)
self.progress_changed.emit(int((idx) / total * 100))
else:
fail_msg = f"[FAILED] {msg}\n"
self.log_summary.emit(fail_msg)
log_to_file(fail_msg)
self.step_failed.emit(label, idx - 1)
return
if self._needs_reboot:
self.reboot_required.emit()
self.progress_changed.emit(100)
self.finished_all.emit()
def step_ensure_winget(self) -> Tuple[bool, str]:
if shutil.which("winget"):
return True, "winget found"
self.log_summary.emit("winget not found. Installing required dependencies...\n")
temp_dir = Path(os.getenv("TEMP") or tempfile.gettempdir())
self.log_summary.emit("Step 1/3: Installing VCLibs dependency...\n")
vclibs_url = "https://aka.ms/Microsoft.VCLibs.x64.14.00.Desktop.appx"
vclibs = temp_dir / "Microsoft.VCLibs.x64.14.00.Desktop.appx"
def attempt_vclibs_download():
return self._download_with_progress(vclibs_url, vclibs, timeout=TIMEOUT_DOWNLOAD)
success, msg = _download_with_retry(attempt_vclibs_download, max_attempts=3, base_delay=1.5)
if success:
self.log_summary.emit(f"VCLibs downloaded ({vclibs.stat().st_size / 1024:.0f} KB)\n")
vclibs_q = _ps_single_quote_escape(str(vclibs))
ps_script = f"Add-AppxPackage -Path '{vclibs_q}' -ErrorAction SilentlyContinue"
encoded_ps = _ps_encode_command(ps_script)
res_install = self._run_proc(
["powershell", "-NoProfile", "-ExecutionPolicy", "Bypass", "-EncodedCommand", encoded_ps],
None, timeout=60
)
if res_install.exitcode == 0:
self.log_summary.emit("VCLibs installed successfully\n")
else:
self.log_summary.emit("VCLibs may already be installed (continuing)\n")
try:
vclibs.unlink()
except:
pass
else:
self.log_summary.emit(f"VCLibs download failed: {msg} (may already be present, continuing)\n")
self.log_summary.emit("Step 2/3: Installing UI.Xaml dependency...\n")
xaml_url = "https://github.com/microsoft/microsoft-ui-xaml/releases/download/v2.8.6/Microsoft.UI.Xaml.2.8.x64.appx"
xaml = temp_dir / "Microsoft.UI.Xaml.2.8.x64.appx"
def attempt_xaml_download():
return self._download_with_progress(xaml_url, xaml, timeout=TIMEOUT_DOWNLOAD)
success, msg = _download_with_retry(attempt_xaml_download, max_attempts=3, base_delay=1.5)
if success:
self.log_summary.emit(f"UI.Xaml downloaded ({xaml.stat().st_size / 1024:.0f} KB)\n")
xaml_q = _ps_single_quote_escape(str(xaml))
ps_script = f"Add-AppxPackage -Path '{xaml_q}' -ErrorAction SilentlyContinue"
encoded_ps = _ps_encode_command(ps_script)
res_install = self._run_proc(
["powershell", "-NoProfile", "-ExecutionPolicy", "Bypass", "-EncodedCommand", encoded_ps],
None, timeout=60
)
if res_install.exitcode == 0:
self.log_summary.emit("UI.Xaml installed successfully\n")
else:
self.log_summary.emit("UI.Xaml may already be installed (continuing)\n")
try:
xaml.unlink()
except:
pass
else:
self.log_summary.emit(f"UI.Xaml download failed: {msg} (may already be present, continuing)\n")
self.log_summary.emit("Step 3/3: Installing App Installer (winget)...\n")
msix = temp_dir / "Microsoft.DesktopAppInstaller.msixbundle"
urls = [
"https://aka.ms/getwinget",
"https://github.com/microsoft/winget-cli/releases/download/v1.7.10861/Microsoft.DesktopAppInstaller_8wekyb3d8bbwe.msixbundle",
]
self.log_summary.emit("Cleaning up any conflicting installations...\n")
ps_script = "Get-AppxPackage Microsoft.DesktopAppInstaller | Remove-AppxPackage -ErrorAction SilentlyContinue"
encoded_ps = _ps_encode_command(ps_script)
self._run_proc(
["powershell", "-NoProfile", "-ExecutionPolicy", "Bypass", "-EncodedCommand", encoded_ps],
None, timeout=30
)
download_success = False
res2 = None
for url_idx, url in enumerate(urls):
self.log_summary.emit(f"Download source {url_idx + 1}/{len(urls)}: {url}\n")
try:
if msix.exists():
msix.unlink()
except:
pass
def attempt_winget_download():
# Use the progress-tracking download method
success, msg = self._download_with_progress(url, msix, timeout=TIMEOUT_DOWNLOAD)
if not success:
return False, msg
# Validate download
if not msix.exists():
return False, "File not found after download"
file_size_mb = msix.stat().st_size / (1024 * 1024)
self.log_summary.emit(f"Downloaded {file_size_mb:.2f} MB\n")
# Safety check
if file_size_mb < 100:
self.log_summary.emit(f"[WARNING] File too small ({file_size_mb:.2f} MB), likely corrupted (should be ~200MB)\n")
try:
msix.unlink()
except:
pass
return False, f"File too small ({file_size_mb:.2f} MB)"
# Validate file format
try:
with open(msix, 'rb') as f:
header = f.read(4)
if header[:2] != b'PK':
self.log_summary.emit("[WARNING] Invalid file format (not a valid bundle)\n")
try:
msix.unlink()
except:
pass
return False, "Invalid file format"
except Exception as e:
return False, f"Cannot validate file: {e}"
return True, "Downloaded and validated"
success, msg = _download_with_retry(attempt_winget_download, max_attempts=3, base_delay=2.0)
if not success:
self.log_summary.emit(f"Source {url_idx + 1} failed: {msg}\n")
continue
# Installation attempts
self.log_summary.emit("Installing App Installer package...\n")
msix_q = _ps_single_quote_escape(str(msix))
for attempt in range(2):
ps_script = f"Add-AppxPackage -Path '{msix_q}' -ErrorAction Stop"
encoded_ps = _ps_encode_command(ps_script)
res2 = self._run_proc(
["powershell", "-NoProfile", "-ExecutionPolicy", "Bypass", "-EncodedCommand", encoded_ps],
None, timeout=TIMEOUT_WINGET
)
self.log_summary.emit(f"Installation attempt {attempt + 1} exit code: {res2.exitcode}\n")
if res2.exitcode == 0:
download_success = True
break
if "0x80073CF0" in (res2.stderr or "") or "0x80070570" in (res2.stderr or ""):
self.log_summary.emit("[ERROR] Package corrupted, trying next source...\n")
try:
msix.unlink()
except:
pass
break
if res2.stderr:
self.log_summary.emit(f"Error: {res2.stderr[:500]}\n")
if attempt == 0:
self.log_summary.emit("Retrying after cleanup...\n")
time.sleep(2)
if download_success:
break
try:
if msix.exists():
os.remove(msix)
except:
pass
if not download_success or (res2 and res2.exitcode != 0):
if res2:
if "sideload" in (res2.stderr or "").lower() or "policy" in (res2.stderr or "").lower():
return False, "Enable app sideloading in Settings > Update & Security > For Developers."
if "0x80073CF3" in (res2.stderr or ""):
return False, "Uninstall 'App Installer' from Settings > Apps, then retry."
if "0x80073CF0" in (res2.stderr or "") or "0x80070570" in (res2.stderr or ""):
return False, "All sources corrupted. Check disk health or download manually from https://aka.ms/getwinget"
return False, "All attempts failed. Try manual installation from https://aka.ms/getwinget"
self.log_summary.emit("Waiting for package registration...\n")
time.sleep(3)
refresh_environment_path()
for attempt in range(3):
if shutil.which("winget"):
self.log_summary.emit("winget found in PATH\n")
return True, "winget installed successfully"
if attempt < 2:
self.log_summary.emit(f"Waiting for PATH update (attempt {attempt + 1}/3)...\n")
time.sleep(2)
refresh_environment_path()
winget_paths = [
Path(os.environ.get("LOCALAPPDATA", "")) / "Microsoft" / "WindowsApps" / "winget.exe",
Path(os.environ.get("ProgramFiles", "")) / "WindowsApps" / "Microsoft.DesktopAppInstaller_8wekyb3d8bbwe" / "winget.exe"
]
for wp in winget_paths:
if wp.exists():
self.log_summary.emit(f"winget found at {wp}, adding to PATH...\n")
try:
windows_apps = str(wp.parent)
if windows_apps not in os.environ.get("PATH", ""):
os.environ["PATH"] = os.environ.get("PATH", "") + ";" + windows_apps
if shutil.which("winget"):
return True, "winget found and added to PATH"
except Exception as e:
self.log_summary.emit(f"Failed to add to PATH: {e}\n")
return False, "winget installed but not accessible. A system restart may be required."
def step_install_git_python(self) -> Tuple[bool, str]:
# Install Git/Python and verify functionality
def get_ver(cmd_list): # version string helper
try:
res = subprocess.run(cmd_list, capture_output=True, text=True, timeout=5)
if res.returncode == 0:
return res.stdout.strip()
except Exception: pass
return None
git_path = shutil.which("git")
git_ver = get_ver([git_path, "--version"]) if git_path else None
py_exec = find_python_executable()
py_ver_raw = get_ver([str(py_exec), "--version"]) if py_exec else None
# Verify it's not a Windows Store stub
py_ok = py_ver_raw and "Python 3" in py_ver_raw
if py_ok:
try:
# py_ver_raw is usually "Python 3.xx.x"
ver_num = py_ver_raw.split(" ")[1]
minor_ver = int(ver_num.split(".")[1])
if minor_ver >= 14:
return False, (
f"Detected installed Python {ver_num}. Dependencies like scrypt will throw build errors on >3.13 and MTKClient won't work. Please uninstall the current Python version and retry the step to install a compatible version."
)
except (IndexError, ValueError):
self.log_summary.emit("Warning: Could not parse Python version string.\n")
if git_ver and py_ok:
self.log_summary.emit(f"Found existing Git: {git_ver}\n")
self.log_summary.emit(f"Found active Python: {py_ver_raw}\n")
return True, "Git and Python already installed"
if not shutil.which("winget"):
return False, "winget not available"
# Refresh sources
self.log_summary.emit("Refreshing winget sources...\n")
self._run_proc(["winget", "source", "update"], None, timeout=120)
if not git_ver:
self.log_summary.emit("Installing Git...\n")
res = self._run_proc(["winget", "install", "--id", "Git.Git", "--source", "winget", "-e",
"--accept-package-agreements", "--accept-source-agreements"],
None, timeout=TIMEOUT_WINGET)
if res.exitcode not in (0, 3010):
return False, f"Git install failed (Exit: {res.exitcode})"
# Install Python if missing/stubbed
if not py_ok:
candidates = [("Python.Python.3.13", True), ("Python.Python.3.12", True), ("Python.Python.3", False)]
installed = False
for py_id, use_exact in candidates:
self.log_summary.emit(f"Attempting to install {py_id}...\n")
cmd = ["winget", "install", "--id", py_id, "--source", "winget"]
if use_exact: cmd.append("-e")
cmd.extend(["--scope", "machine", "--accept-package-agreements", "--accept-source-agreements",
"--override", '/passive PrependPath=1 Include_test=0'])
res = self._run_proc(cmd, None, timeout=TIMEOUT_WINGET)
if res.exitcode in (0, 3010):
if res.exitcode == 3010: self._needs_reboot = True
installed = True; break
if not installed:
return False, "Python installation failed."
# re-query the system to ensure the PATH was updated
self.log_summary.emit("Verifying installations...\n")
# Verify Git again
new_git_path = shutil.which("git")
new_git_ver = get_ver([new_git_path, "--version"]) if new_git_path else None
if new_git_ver:
self.log_summary.emit(f"Verified Git: {new_git_ver}\n")
else:
self.log_summary.emit("[WARNING] Git installed but not found in PATH yet.\n")
# Verify Python again
new_py_exec = find_python_executable()
new_py_ver = get_ver([str(new_py_exec), "--version"]) if new_py_exec else None
if new_py_ver and "Python 3" in new_py_ver:
self.log_summary.emit(f"Verified Python: {new_py_ver}\n")
else:
# If winget succeeded but we can't find it, it's a PATH refresh issue
refresh_environment_path()
find_python_executable() # last attempt. Won't change the result but may help with debugging
return False, "Python installed but isn't in PATH, please retry step or reboot."
return True, "Git and Python setup successful"
def step_refresh_path(self) -> Tuple[bool, str]:
self.log_summary.emit("Reloading environment variables...\n")
if refresh_environment_path():
git_v = shutil.which("git")
py_v = shutil.which("python")
return True, f"PATH refreshed. Git: {git_v}, Python: {py_v}"
return False, "Failed to refresh PATH."
def step_install_winfsp_usbdk(self) -> Tuple[bool, str]:
if not shutil.which("winget"):
return False, "winget missing"
pf = os.environ.get("ProgramFiles", r"C:\Program Files")
if (Path(pf) / "UsbDk" / "UsbDkController.exe").exists():
self.log_summary.emit("UsbDk already installed.\n")
else:
res = self._run_proc(["winget", "install", "--id", "daynix.UsbDk", "--source", "winget", "-e", "--accept-package-agreements", "--accept-source-agreements"], None, timeout=TIMEOUT_WINGET)
if res.exitcode == 3010:
self._needs_reboot = True
elif res.exitcode not in [0]:
self.log_summary.emit(f"Warning: UsbDk install returned {res.exitcode}\n")
if (Path(pf) / "WinFsp").exists() or (Path(pf) / "WinFsp (x86)").exists():
self.log_summary.emit("WinFsp already installed.\n")
else:
res = self._run_proc(["winget", "install", "--id", "WinFsp.WinFsp", "--source", "winget", "-e", "--accept-package-agreements", "--accept-source-agreements"], None, timeout=TIMEOUT_WINGET)
if res.exitcode == 3010:
self._needs_reboot = True
elif res.exitcode not in [0]:
self.log_summary.emit(f"Warning: WinFsp install returned {res.exitcode}\n")
return True, "WinFsp/UsbDk step completed"
def step_install_build_tools(self) -> Tuple[bool, str]:
# check vcvars64.bat presence
pf_x86 = os.environ.get("ProgramFiles(x86)", r"C:\Program Files (x86)")
vcvars = (
Path(pf_x86)
/ "Microsoft Visual Studio"
/ "2022"
/ "BuildTools"
/ "VC"
/ "Auxiliary"
/ "Build"
/ "vcvars64.bat"
)
if vcvars.exists():
self.log_summary.emit("VS Build Tools (C++ Workload) detected.\n")
return True, "VS Build Tools already installed"
# Proceed with installation
self.set_indeterminate.emit(True)
self.log_summary.emit("Checking disk space and VS Build Tools requirements...\n")
try:
total, used, free = shutil.disk_usage(os.environ.get("SystemDrive", "C:"))
if free < 3 * (1024 ** 3):
return False, (
f"Insufficient disk space. Need ~4GB, "
f"have {free / (1024 ** 3):.1f} GB free."
)
except Exception:
self.log_summary.emit("Warning: Could not verify disk space.\n")
if not shutil.which("winget"):
return False, "winget not present"
self.log_summary.emit("Ensuring Winget health...\n")
subprocess.run(["winget", "source", "reset", "--force"], capture_output=True)
subprocess.run(["winget", "source", "update"], capture_output=True)
self.log_summary.emit(
"Installing Visual Studio Build Tools (Desktop C++ workload).\n"
)
cmd = [
"winget",
"install",
"--id",
"Microsoft.VisualStudio.2022.BuildTools",
"--source",
"winget",
"-e",
"--accept-package-agreements",
"--accept-source-agreements",
"--override=--quiet --wait --norestart --add Microsoft.VisualStudio.Workload.VCTools",
]
res = self._run_proc(cmd, None, timeout=TIMEOUT_VS)
# Re-verify system state after installer exits
if vcvars.exists():
self.log_summary.emit("VS Build Tools detected after installer run.\n")
return True, "VS Build Tools already installed"
# Reboot-required success
if res.exitcode == 3010:
self._needs_reboot = True
self.log_summary.emit(
"[NOTICE] VS Build Tools installation requires reboot.\n"
)
return True, "VS Build Tools installed (REBOOT REQUIRED)"
# Known Visual Studio no-op / already-installed HRESULT
if res.exitcode == 2316632107:
return True, "VS Build Tools already present (no changes needed)"
# Zero exit but no files detected → defer to reboot
if res.exitcode == 0:
self._needs_reboot = True
return True, "VS Build Tools install finished (verify after reboot)"
return False, f"VS Build Tools failed (exit {res.exitcode})"
def step_clone_repo(self) -> Tuple[bool, str]:
pf = os.environ.get("ProgramFiles", r"C:\Program Files")
target = Path(pf) / "mtkclient"
if not shutil.which("git"):
return False, "git not found in PATH"
# Enable indeterminate progress for git
self.set_indeterminate.emit(True)
# clone with verification and retry
env = os.environ.copy()
env["GIT_TERMINAL_PROMPT"] = "0"
target.mkdir(parents=True, exist_ok=True)
def verify_repo_ok(t: Path) -> bool:
# Check presence of core files
return (t / "mtk_gui.py").exists() or (t / "mtkclient" / "mtk_main.py").exists()
# If .git exists, verify it's valid
is_valid_repo = False
if (target / ".git").exists():
check = self._run_proc(["git", "rev-parse", "--git-dir"], str(target), timeout=10)
if check.exitcode == 0 and verify_repo_ok(target):
is_valid_repo = True
else:
self.log_summary.emit("Incomplete repository detected, cleaning up .git for fresh clone...\n")
try:
shutil.rmtree(target / ".git", ignore_errors=True)
except Exception as e:
self.log_summary.emit(f"Warning: could not remove .git: {e}\n")
is_valid_repo = False
if is_valid_repo:
self.log_summary.emit("Repository exists and valid; pulling latest changes...\n")
res = self._run_proc(["git", "pull", "--progress"], str(target), env=env, timeout=300)
if res.exitcode != 0:
return False, f"Git pull failed (code {res.exitcode})"
else:
# Attempt shallow clone first, then full clone if shallow fails
self.log_summary.emit(f"Cloning mtkclient repository to {target}...\n")
self.log_summary.emit("This may take 2-5 minutes depending on connection speed...\n")
for attempt, cmd in enumerate([
["git", "clone", "--progress", "--depth", "1", "https://github.com/bkerler/mtkclient.git", str(target)],
["git", "clone", "--progress", "https://github.com/bkerler/mtkclient.git", str(target)]
], start=1):
self.log_summary.emit(f"Git clone attempt {attempt}...\n")
# Ensure target is clean
try:
shutil.rmtree(target, ignore_errors=True)
target.mkdir(parents=True, exist_ok=True)
except Exception:
pass
res = self._run_proc(cmd, None, env=env, timeout=600)
if res.exitcode == 0 and verify_repo_ok(target):
self.log_summary.emit("Repository cloned successfully.\n")
break
else:
self.log_debug.emit(f"[GIT] clone attempt {attempt} exit {res.exitcode}\n")
else:
return False, f"Git clone failed (last exit code {res.exitcode})"
# Configure git safe.directory
self.log_summary.emit("Configuring git safe.directory...\n")
path_str = str(target).replace("\\", "/")
self._run_proc(
["git", "config", "--system", "--add", "safe.directory", path_str],
None, timeout=10
)
# Grant write permissions to current user and Administrators only
# MTKClient needs to create logs/ and config files
self.log_summary.emit("Setting folder permissions for current user...\n")
try:
# Get current username
current_user = os.environ.get("USERNAME", "")
if not current_user:
self.log_summary.emit("Warning: Could not determine current user.\n")
else:
# Grant Modify to current user, Full Control to Administrators
res1 = self._run_proc(
["icacls", str(target), "/grant", f"{current_user}:(OI)(CI)M", "/T"],
None, timeout=120
)
res2 = self._run_proc(
["icacls", str(target), "/grant", "Administrators:(OI)(CI)F", "/T"],
None, timeout=120
)
if res1.exitcode == 0 and res2.exitcode == 0:
self.log_summary.emit("Folder permissions configured for current user.\n")
else:
self.log_summary.emit(f"Warning: Permission setup returned codes {res1.exitcode}/{res2.exitcode}.\n")
except Exception as e:
self.log_summary.emit(f"Warning: Could not set folder permissions: {e}\n")
self.set_indeterminate.emit(False)
return True, "Repository cloned and configured with proper permissions"
def step_pip_install_requirements(self) -> Tuple[bool, str]:
# Guard for empty Python executable
py_exec = find_python_executable()
if not py_exec:
return False, "Python executable not found after install. Please reboot and retry."
pf = os.environ.get("ProgramFiles", r"C:\Program Files")
reqs = Path(pf) / "mtkclient" / "requirements.txt"
if not reqs.exists():