-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmain.py
More file actions
9897 lines (8153 loc) · 454 KB
/
main.py
File metadata and controls
9897 lines (8153 loc) · 454 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
import sys
import os
import subprocess
import re
import time
import threading
import shlex
from datetime import datetime
from PyQt6.QtWidgets import (
QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
QTabWidget, QPushButton, QLabel, QLineEdit, QTextEdit, QTextBrowser,
QComboBox, QCheckBox, QGroupBox, QScrollArea, QFileDialog,
QMessageBox, QProgressBar, QListWidget, QTreeWidget, QInputDialog, QProgressDialog, QProgressDialog,
QTreeWidgetItem, QSplitter, QFrame, QMenu, QSystemTrayIcon, QGridLayout, QSpinBox, QStyle, QStyledItemDelegate, QDockWidget,
QFormLayout, QStatusBar, QDialog)
from PyQt6.QtGui import (QIcon, QFont, QPixmap, QColor, QPalette, QAction, QTextDocument,
QTextCursor, QStandardItemModel, QStandardItem)
from PyQt6.QtCore import (Qt, QSize, QTimer, QProcess, QSettings, QThread,
pyqtSignal, QObject, QByteArray, QDateTime, QStandardPaths)
from androguard_tab import AndroguardTab
from functools import partial
import webbrowser
import json
import zipfile
import tempfile
import requests
import shutil
import xml.etree.ElementTree as ET
from packaging import version
import traceback
import requests
import shutil
import zipfile
import tempfile
# Set ANDROID_SDK_ROOT if not already set
# Prioritize existing ANDROID_SDK_ROOT environment variable if it points to a valid SDK.
# A valid SDK is considered to have a 'platform-tools' subdirectory.
# If you have a full Android SDK installed elsewhere, set the ANDROID_SDK_ROOT
# environment variable to its path (e.g., C:\Users\YourUser\AppData\Local\Android\Sdk).
# This will allow the application to use your existing SDK.
sdk_root_path = None
if "ANDROID_SDK_ROOT" in os.environ:
existing_sdk_root = os.environ["ANDROID_SDK_ROOT"]
if os.path.isdir(os.path.join(existing_sdk_root, "platform-tools")):
sdk_root_path = existing_sdk_root
print(f"INFO: Using existing ANDROID_SDK_ROOT from environment: {sdk_root_path}")
else:
print(f"WARNING: Existing ANDROID_SDK_ROOT environment variable points to an invalid SDK: {existing_sdk_root}. Falling back to local tools/sdk.")
if sdk_root_path is None:
sdk_root_path = os.path.join(os.getcwd(), "tools", "sdk")
if not os.path.isdir(os.path.join(sdk_root_path, "platform-tools")):
print(f"WARNING: Local SDK path {sdk_root_path} does not contain platform-tools. Emulator might not function correctly.")
os.environ["ANDROID_SDK_ROOT"] = sdk_root_path
print(f"INFO: ANDROID_SDK_ROOT set to local path: {sdk_root_path}")
import logging
# Constants
VERSION = "2.1.1"
APP_NAME = "Android Control Tool"
DEVELOPER = "fzer0x"
SUPPORTED_ANDROID_VERSIONS = ["4.0", "5.0", "6.0", "7.0", "8.0", "9.0", "10", "11", "12", "13", "14", "15", "16"]
DEFAULT_ADB_PATH = "adb" if sys.platform != "win32" else "adb.exe"
DEFAULT_FASTBOOT_PATH = "fastboot" if sys.platform != "win32" else "fastboot.exe"
# Global settings with thread-safe access
settings = QSettings("AndroidToolMaster", "UACT")
settings_lock = threading.Lock()
def setup_logging():
"""Set up centralized logging to a file."""
log_dir = QStandardPaths.writableLocation(QStandardPaths.StandardLocation.AppDataLocation)
if not os.path.exists(log_dir):
os.makedirs(log_dir)
log_file = os.path.join(log_dir, "android_control_tool.log")
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(module)s - %(message)s',
handlers=[
logging.FileHandler(log_file, mode='w', encoding='utf-8'),
logging.StreamHandler() # Also log to console for debugging
]
)
logging.info("Application started.")
return log_file
def global_exception_hook(exctype, value, tb):
"""Global exception handler to log unhandled exceptions."""
error_msg = "".join(traceback.format_exception(exctype, value, tb))
logging.critical(f"Unhandled exception caught:\n{error_msg}")
QMessageBox.critical(None, "Critical Error", f"A critical error occurred. Please check the log file for details.\n\n{error_msg}")
sys.exit(1)
class Worker(QObject):
finished = pyqtSignal(object)
error = pyqtSignal(Exception)
progress_update = pyqtSignal(int, str)
def __init__(self, fn, *args, **kwargs):
super().__init__()
self.fn = fn
self.args = args
self.kwargs = kwargs
def run(self):
try:
result = self.fn(self, *self.args, **self.kwargs)
self.finished.emit(result)
except Exception as e:
self.error.emit(e)
class CopyableMessageBox(QMessageBox):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse)
# Finde das interne QTextEdit, um es ebenfalls auswählbar zu machen
# Dies ist ein kleiner Workaround, da Qt das nicht direkt unterstützt.
for child in self.findChildren(QTextEdit):
child.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse)
@staticmethod
def critical(parent, title, text):
msg = CopyableMessageBox(parent)
msg.setIcon(QMessageBox.Icon.Critical)
msg.setWindowTitle(title)
msg.setText(text)
return msg.exec()
@staticmethod
def warning(parent, title, text):
msg = CopyableMessageBox(parent)
msg.setIcon(QMessageBox.Icon.Warning)
msg.setWindowTitle(title)
msg.setText(text)
return msg.exec()
@staticmethod
def information(parent, title, text):
msg = CopyableMessageBox(parent)
msg.setIcon(QMessageBox.Icon.Information)
msg.setWindowTitle(title)
msg.setText(text)
return msg.exec()
class CommandWorker(QObject):
command_output = pyqtSignal(str)
command_finished = pyqtSignal(int, str)
progress_update = pyqtSignal(int, str)
def __init__(self):
super().__init__()
self.process = None
self.is_running = False
self.timeout = 30 # Default timeout in seconds
self._command_queue = []
self._queue_lock = threading.Lock()
self._current_process = None
self.process_timer = QTimer()
self.process_timer.timeout.connect(self.process_command_queue)
self.process_timer.start(50) # Check queue every 50ms
def run_command(self, command, cwd=None, timeout=None):
if isinstance(command, str):
command = shlex.split(command) if sys.platform != "win32" else command
with self._queue_lock:
self._command_queue.append((command, cwd, timeout))
def process_command_queue(self):
if self._current_process is not None and self._current_process.state() != QProcess.NotRunning:
return # Still processing previous command
with self._queue_lock:
if not self._command_queue:
return # No commands to process
command, cwd, timeout = self._command_queue.pop(0)
self.is_running = True
actual_timeout = timeout if timeout is not None else self.timeout
try:
self._current_process = QProcess()
if cwd:
self._current_process.setWorkingDirectory(cwd)
self._current_process.setProcessChannelMode(QProcess.ProcessChannelMode.MergedChannels)
self._current_process.readyRead.connect(self._handle_output)
self._current_process.finished.connect(self._handle_finished)
timer = QTimer()
timer.setSingleShot(True)
timer.timeout.connect(lambda: self._handle_timeout(command, actual_timeout))
timer.start(actual_timeout * 1000)
if isinstance(command, list):
program = command[0]
args = command[1:]
else:
program = command
args = []
self._current_process.start(program, args)
except Exception as e:
error_msg = f"Error executing command: {str(e)}\n{traceback.format_exc()}"
self.command_output.emit(error_msg)
self.command_finished.emit(-1, error_msg)
def _handle_output(self):
"""Handle process output in real-time"""
if self._current_process:
data = self._current_process.readAll().data().decode(errors='replace')
if data:
self.command_output.emit(data.strip())
def _handle_finished(self, exit_code, exit_status):
"""Handle process completion"""
if self._current_process:
self._handle_output()
error = ""
if exit_code != 0:
error = self._current_process.readAllStandardError().data().decode(errors='replace').strip()
self._current_process.deleteLater()
self._current_process = None
self.is_running = False
self.command_finished.emit(exit_code, error)
def _handle_timeout(self, command, timeout):
"""Handle command timeout"""
if self._current_process and self._current_process.state() != QProcess.NotRunning:
error_msg = f"Command timed out after {timeout} seconds"
self.command_output.emit(error_msg)
self.command_finished.emit(-2, error_msg)
self.cleanup_process()
def cleanup_process(self):
"""Clean up the current process"""
if self._current_process:
if self._current_process.state() != QProcess.NotRunning:
self._current_process.kill()
self._current_process.waitForFinished(2000)
self._current_process.deleteLater()
self._current_process = None
self.is_running = False
def stop(self):
"""Stop all command processing and cleanup"""
self.is_running = False
self.cleanup_process()
class DeviceManager(QObject):
devices_updated = pyqtSignal(list)
device_details_updated = pyqtSignal(dict)
connection_status_changed = pyqtSignal(bool)
def __init__(self):
super().__init__()
with settings_lock:
self.adb_path = settings.value("adb_path", DEFAULT_ADB_PATH)
self.fastboot_path = settings.value("fastboot_path", DEFAULT_FASTBOOT_PATH)
self.connected_devices = []
self.current_device = None
self.device_details = {}
self.device_initialized = False
self.last_device_check = 0
self.last_details_check = 0
self.device_check_interval = 60000 # Check devices every 60 seconds
self.details_check_interval = 58000 # Update details every 58 seconds
self.is_updating_devices = False
self.worker_thread = QThread()
self.worker_thread.start()
self.command_worker = CommandWorker()
self.command_worker.moveToThread(self.worker_thread)
self.timer = QTimer()
self.timer.timeout.connect(self.check_updates)
self.timer.start(1000) # Timer ticks every second but checks intervals
self.lock = threading.Lock()
self.update_queue = [] # Queue for pending updates
self.start_adb_server()
def start_adb_server(self):
"""Starts the ADB server to ensure it's running and can prompt for authorization."""
try:
logging.info("Attempting to start ADB server...")
subprocess.run([self.adb_path, "start-server"], capture_output=True, text=True, timeout=10, check=False)
logging.info("ADB 'start-server' command issued.")
except (subprocess.TimeoutExpired, FileNotFoundError, Exception) as e:
logging.error(f"Failed to start ADB server: {e}")
def check_updates(self):
"""Check if we need to update devices or details based on intervals"""
current_time = QDateTime.currentMSecsSinceEpoch()
if current_time - self.last_device_check >= self.device_check_interval:
if not self.is_updating_devices:
self.update_devices()
if self.current_device and current_time - self.last_details_check >= self.details_check_interval:
self.last_details_check = current_time
QTimer.singleShot(0, self.update_device_details)
def update_devices(self):
"""Starts the device update process in a background thread."""
if self.is_updating_devices:
return
self.is_updating_devices = True
self.last_device_check = QDateTime.currentMSecsSinceEpoch()
self.thread = QThread()
self.worker = Worker(self._get_devices_sync)
self.worker.moveToThread(self.thread)
self.thread.started.connect(self.worker.run)
self.worker.finished.connect(self._on_devices_updated)
self.worker.error.connect(self._on_update_error)
self.worker.finished.connect(self.thread.quit)
self.worker.finished.connect(self.worker.deleteLater)
self.thread.finished.connect(self.thread.deleteLater)
self.thread.start()
def _get_devices_sync(self, worker_instance=None):
"""Synchronous part of device update, runs in a worker thread. Accepts optional worker instance."""
adb_devices = []
try:
adb_output = subprocess.check_output([self.adb_path, "devices"], text=True, timeout=2)
for line in adb_output.splitlines()[1:]:
if "\t" in line:
device_id, status = line.strip().split("\t")
if status == "device":
model_name = "Unknown"
try:
model_output = subprocess.check_output(
[self.adb_path, "-s", device_id, "shell", "getprop", "ro.product.model"],
text=True, timeout=2, encoding='utf-8', errors='replace'
).strip()
if model_output:
model_name = model_output
except (subprocess.CalledProcessError, subprocess.TimeoutExpired, FileNotFoundError):
pass # Ignore if model name can't be fetched
adb_devices.append({"id": device_id, "type": "adb", "status": status, "model": model_name})
except (subprocess.CalledProcessError, subprocess.TimeoutExpired, FileNotFoundError):
pass # Ignore errors, e.g. if adb is not running
fastboot_devices = []
try:
fastboot_output = subprocess.check_output([self.fastboot_path, "devices"], text=True, timeout=2)
for line in fastboot_output.splitlines():
if "\t" in line:
device_id, _ = line.strip().split("\t")
fastboot_devices.append({"id": device_id, "type": "fastboot", "status": "fastboot"})
except (subprocess.CalledProcessError, subprocess.TimeoutExpired, FileNotFoundError):
pass # Ignore errors
return adb_devices + fastboot_devices
def _on_devices_updated(self, new_devices):
"""Handles the result from the background device scan."""
self.connected_devices = new_devices
self.devices_updated.emit(self.connected_devices)
if self.connected_devices:
self.connection_status_changed.emit(True)
if not self.device_initialized or self.current_device not in [d["id"] for d in self.connected_devices]:
self.device_initialized = True
self.set_current_device(self.connected_devices[0]["id"])
else:
self.connection_status_changed.emit(False)
self.current_device = None
self.device_details = {}
self.device_details_updated.emit({})
self.is_updating_devices = False
def _on_update_error(self, e):
logging.error(f"Error updating devices: {e}\n{traceback.format_exc()}")
self.is_updating_devices = False
def set_current_device(self, device_id):
with self.lock:
self.current_device = device_id
self.update_device_details()
def update_device_details(self):
"""Update device details in background"""
if not self.current_device:
return
details = {}
device_type = next((d["type"] for d in self.connected_devices if d["id"] == self.current_device), None)
if device_type == "adb":
try:
details["serial"] = self.current_device
details["type"] = "adb"
# Get all properties at once for efficiency.
prop_output = subprocess.check_output(
[self.adb_path, "-s", self.current_device, "shell", "getprop"],
text=True, timeout=5, encoding='utf-8', errors='replace'
).strip()
prop_dict = {}
for line in prop_output.splitlines():
match = re.match(r'\[([^\]]+)\]: \[([^\]]*)\]', line)
if match:
key, value = match.groups()
prop_dict[key] = value
details["model"] = prop_dict.get("ro.product.model", "Unbekannt")
details["brand"] = prop_dict.get("ro.product.brand", "Unbekannt")
details["android_version"] = prop_dict.get("ro.build.version.release", "Unbekannt")
details["build_number"] = prop_dict.get("ro.build.display.id", "Unbekannt")
details["build_id"] = prop_dict.get("ro.build.display.id", "Unknown") # Alias for build_number
# Get root status using multiple methods for reliability.
root_methods = [
["su", "-c", "echo Root check"],
["which", "su"],
]
details["root"] = False
for method_args in root_methods:
result = subprocess.run(
[self.adb_path, "-s", self.current_device, "shell"] + method_args,
capture_output=True, text=True, timeout=2, encoding='utf-8', errors='replace'
)
if result.returncode == 0:
details["root"] = True
break
result = subprocess.run(
[self.adb_path, "-s", self.current_device, "get-state"],
capture_output=True, text=True, timeout=5, encoding='utf-8', errors='replace'
)
details["state"] = result.stdout.strip() or "unknown"
result = subprocess.run(
[self.adb_path, "-s", self.current_device, "shell", "dumpsys", "battery"],
capture_output=True, text=True, timeout=5, encoding='utf-8', errors='replace'
)
battery_info = result.stdout.strip()
details["battery_level"] = "Unbekannt"
match = re.search(r"level:\s*(\d+)", battery_info)
if match:
details["battery_level"] = f"{match.group(1)}%"
result = subprocess.run(
[self.adb_path, "-s", self.current_device, "shell", "df", "/data"],
capture_output=True, text=True, timeout=5, encoding='utf-8', errors='replace'
)
storage_info = result.stdout.strip()
if len(storage_info.splitlines()) > 1:
parts = storage_info.splitlines()[1].split()
if len(parts) >= 4:
try:
# df usually outputs in 1K-blocks. Convert to GB.
total_kb = int(parts[1])
used_kb = int(parts[2])
details["storage_total_gb"] = f"{total_kb / (1024*1024):.2f}"
details["storage_used_gb"] = f"{used_kb / (1024*1024):.2f}"
details["storage_percent"] = parts[4] if len(parts) >= 5 else f"{int(used_kb/total_kb*100)}%"
except (ValueError, IndexError, ZeroDivisionError):
pass # Ignore parsing errors
except (subprocess.TimeoutExpired, subprocess.CalledProcessError, FileNotFoundError) as e:
logging.warning(f"Error getting device details for {self.current_device}: {e}")
elif device_type == "fastboot":
try:
details["serial"] = self.current_device
details["type"] = "fastboot"
result = subprocess.run(
[self.fastboot_path, "-s", self.current_device, "getvar", "all"],
capture_output=True, text=True, timeout=10, encoding='utf-8', errors='replace'
)
# Fastboot getvar all sends output to stderr
output = result.stderr.strip()
for line in output.splitlines():
if ":" in line:
key_val_part = line.split(":", 1)
key = key_val_part[0].replace("(bootloader)", "").strip()
value = key_val_part[1].strip()
details[key] = value
details["unlocked"] = details.get("unlocked", "no").lower() == "yes"
except (subprocess.TimeoutExpired, subprocess.CalledProcessError, FileNotFoundError) as e:
logging.warning(f"Error getting fastboot details for {self.current_device}: {e}")
self.device_details = details
self.device_details_updated.emit(details)
def execute_adb_command(self, command, device_specific=True, timeout=30):
if not self.current_device:
return None, "No device selected #001"
full_command = [self.adb_path]
if device_specific:
full_command.extend(["-s", self.current_device])
if isinstance(command, str):
full_command.extend(shlex.split(command))
else:
full_command.extend(command)
try:
result = subprocess.run(full_command,
capture_output=True,
text=True,
encoding='utf-8', errors='replace',
timeout=timeout)
output = (result.stdout or "").strip() + "\n" + (result.stderr or "").strip()
return result.returncode, output.strip()
except subprocess.TimeoutExpired:
return -1, "Command timed out"
except Exception as e:
return -1, f"Error executing ADB command: {str(e)}"
def execute_fastboot_command(self, command, device_specific=True, timeout=30):
if not self.current_device:
return None, "No device selected #002"
full_command = [self.fastboot_path]
if device_specific:
full_command.extend(["-s", self.current_device])
if isinstance(command, str):
full_command.extend(shlex.split(command))
else:
full_command.extend(command)
try:
result = subprocess.run(full_command,
capture_output=True,
text=True,
timeout=timeout,
encoding='utf-8', errors='replace')
return result.returncode, result.stdout.strip()
except subprocess.TimeoutExpired:
return -1, "Command timed out"
except Exception as e:
return -1, f"Error executing Fastboot command: {str(e)}"
def reboot_device(self, mode="system"):
if not self.current_device:
return False, "No device selected #003"
device_type = next((d["type"] for d in self.connected_devices if d["id"] == self.current_device), None)
if device_type == "adb":
valid_modes = ["recovery", "bootloader", "sideload", "download"]
cmd_list = ["reboot"]
if mode.lower() in valid_modes:
cmd_list.append(mode.lower())
return_code, output = self.execute_adb_command(cmd_list)
return return_code == 0, output
elif device_type == "fastboot":
valid_modes = ["recovery", "bootloader", "system"]
cmd_list = ["reboot"]
if mode.lower() in valid_modes:
cmd_list = [f"reboot-{mode.lower()}"]
return_code, output = self.execute_fastboot_command(cmd_list)
return return_code == 0, output
else:
return False, "Unknown device type"
def wait_for_disconnect(self, device_id, timeout=30):
"""Waits for a specific device to disconnect from ADB."""
start_time = time.time()
while time.time() - start_time < timeout:
try:
result = subprocess.run([self.adb_path, "devices"], capture_output=True, text=True, timeout=5)
if device_id not in result.stdout:
logging.info(f"Device {device_id} successfully disconnected.")
return True
except (subprocess.TimeoutExpired, subprocess.CalledProcessError):
# ADB server might be down during reboot, which is expected.
pass
time.sleep(1)
logging.warning(f"Timeout waiting for device {device_id} to disconnect.")
return False
def wait_for_connect(self, timeout=60):
"""Waits for any device to connect via ADB."""
start_time = time.time()
logging.info("Waiting for a device to connect...")
while time.time() - start_time < timeout:
try:
result = subprocess.run([self.adb_path, "devices"], capture_output=True, text=True, timeout=5)
lines = result.stdout.strip().splitlines()
# Check if there is at least one device listed that is not offline
for line in lines[1:]:
if "\t" in line and "offline" not in line:
device_id = line.split('\t')[0]
logging.info(f"Device {device_id} connected.")
return True
except (subprocess.TimeoutExpired, subprocess.CalledProcessError):
pass
time.sleep(2)
logging.warning("Timeout waiting for a device to connect.")
return False
class FileManager(QObject):
file_transfer_progress = pyqtSignal(int, str)
file_operation_complete = pyqtSignal(bool, str)
file_operation_started = pyqtSignal(str)
def __init__(self, device_manager):
super().__init__()
self.device_manager = device_manager
self.lock = threading.Lock()
self.active_transfers = {}
def push_file(self, local_path, remote_path):
if not self.device_manager.current_device and not getattr(self.device_manager, "suppress_no_device_warning", False):
QMessageBox.warning(None, "Error", "No device selected #004")
return
local_path = os.path.normpath(local_path)
if not os.path.exists(local_path):
self.file_operation_complete.emit(False, f"Local file does not exist: {local_path}")
return
transfer_id = f"push_{time.time()}"
self.active_transfers[transfer_id] = {
"type": "push",
"local_path": local_path,
"remote_path": remote_path,
"cancelled": False
}
def run_push():
try:
self.file_operation_started.emit(f"Pushing {local_path} to {remote_path}")
total_size = os.path.getsize(local_path)
if total_size == 0:
total_size = 1 # Avoid division by zero
remote_dir = os.path.dirname(remote_path.replace("\\", "/"))
if remote_dir:
self.device_manager.execute_adb_command(["shell", "mkdir", "-p", remote_dir])
command = [
self.device_manager.adb_path,
"-s", self.device_manager.current_device,
"push", local_path, remote_path
]
process = subprocess.Popen(
command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True,
encoding='utf-8',
errors='replace'
)
transferred = 0
last_progress = 0
start_time = time.time()
while True:
if self.active_transfers.get(transfer_id, {}).get("cancelled", False):
process.terminate()
self.file_operation_complete.emit(False, "Transfer cancelled by user")
break
output = process.stdout.readline()
if output == '' and process.poll() is not None:
break
if output:
match = re.search(r'(\d+)%', output)
if match:
progress = int(match.group(1))
if progress != last_progress:
self.file_transfer_progress.emit(progress, f"Uploading: {progress}%")
last_progress = progress
else:
elapsed = time.time() - start_time
if elapsed > 0:
transferred = min(total_size, transferred + 1024) # Simulate progress for commands that don't report it.
progress = min(99, int((transferred / total_size) * 100))
self.file_transfer_progress.emit(
progress,
f"Uploading: {progress}%"
)
return_code = process.poll()
stderr_output = process.stderr.read()
if return_code == 0:
self.file_operation_complete.emit(True, f"File transfer completed: {local_path} -> {remote_path}")
else:
error_msg = f"File transfer failed: {stderr_output.strip()}" if stderr_output else "File transfer failed"
self.file_operation_complete.emit(False, error_msg)
except Exception as e:
error_msg = f"Error during file push: {str(e)}\n{traceback.format_exc()}"
self.file_operation_complete.emit(False, error_msg)
finally:
self.active_transfers.pop(transfer_id, None)
thread = threading.Thread(target=run_push, daemon=True)
thread.start()
return transfer_id
def pull_file(self, remote_path, local_path):
if not self.device_manager.current_device:
self.file_operation_complete.emit(False, "No device selected #005")
return
local_path = os.path.normpath(local_path)
if os.path.exists(local_path):
self.file_operation_complete.emit(False, f"File already exists: {local_path}")
return
transfer_id = f"pull_{time.time()}"
self.active_transfers[transfer_id] = {
"type": "pull",
"local_path": local_path,
"remote_path": remote_path,
"cancelled": False
}
def run_pull():
try:
self.file_operation_started.emit(f"Pulling {remote_path} to {local_path}")
cleaned_path = remote_path.replace('\\', '/')
size_cmd = ["shell", "stat", "-c", "%s", cleaned_path]
return_code, size_output = self.device_manager.execute_adb_command(size_cmd)
if return_code != 0:
self.file_operation_complete.emit(False, f"Failed to get remote file size: {size_output}")
return
try:
total_size = int(size_output.strip())
except ValueError:
total_size = 0
if total_size == 0:
total_size = 1 # Avoid division by zero
command = [
self.device_manager.adb_path,
"-s", self.device_manager.current_device,
"pull", remote_path, local_path
]
process = subprocess.Popen(
command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True,
encoding='utf-8',
errors='replace'
)
start_time = time.time()
last_update = start_time
last_size = 0
while True:
if self.active_transfers.get(transfer_id, {}).get("cancelled", False):
process.terminate()
self.file_operation_complete.emit(False, "Transfer cancelled by user")
break
if not os.path.exists(local_path):
time.sleep(0.1)
continue
current_size = os.path.getsize(local_path)
now = time.time()
if now - last_update > 0.5:
progress = min(99, int((current_size / total_size) * 100))
transferred = current_size - last_size
elapsed = now - last_update
speed = transferred / elapsed if elapsed > 0 else 0
remaining = (total_size - current_size) / speed if speed > 0 else 0
self.file_transfer_progress.emit(
progress,
f"Downloading: {progress}% ({(speed/1024):.1f} KB/s, {remaining:.1f}s remaining)"
)
last_update = now
last_size = current_size
if process.poll() is not None:
break
time.sleep(0.1)
return_code = process.poll()
stderr_output = process.stderr.read()
if return_code == 0:
if os.path.exists(local_path) and os.path.getsize(local_path) > 0:
self.file_operation_complete.emit(True, f"File transfer completed: {remote_path} -> {local_path}")
else:
self.file_operation_complete.emit(False, "File transfer failed: empty or missing file")
else:
error_msg = f"File transfer failed: {stderr_output.strip()}" if stderr_output else "File transfer failed"
self.file_operation_complete.emit(False, error_msg)
if os.path.exists(local_path):
try:
os.remove(local_path)
except:
pass
except Exception as e:
error_msg = f"Error during file pull: {str(e)}\n{traceback.format_exc()}"
self.file_operation_complete.emit(False, error_msg)
if os.path.exists(local_path):
try:
os.remove(local_path)
except:
pass
finally:
self.active_transfers.pop(transfer_id, None)
thread = threading.Thread(target=run_pull, daemon=True)
thread.start()
return transfer_id
def cancel_transfer(self, transfer_id):
if transfer_id in self.active_transfers:
self.active_transfers[transfer_id]["cancelled"] = True
class PackageManager(QObject):
package_operation_complete = pyqtSignal(bool, str)
package_list_updated = pyqtSignal(list)
package_info_updated = pyqtSignal(dict)
def __init__(self, device_manager):
super().__init__()
self.device_manager = device_manager
self.lock = threading.Lock()
def get_installed_packages(self, system_only=False, third_party_only=False, enabled_only=False, disabled_only=False):
if not self.device_manager.current_device:
self.package_operation_complete.emit(False, "No device selected #006")
return False, "No device selected #006"
try:
command = [self.device_manager.adb_path, "-s", self.device_manager.current_device, "shell", "pm", "list", "packages"]
if system_only:
command.append("-s")
elif third_party_only:
command.append("-3")
if enabled_only:
command.extend(["-e"])
elif disabled_only:
command.extend(["-d"])
result = subprocess.run(command, capture_output=True, text=True, timeout=30)
packages = []
for line in result.stdout.splitlines():
if line.startswith("package:"):
package_name = line[8:].strip()
if package_name:
packages.append(package_name)
self.package_list_updated.emit(packages)
return True, "Package list retrieved"
except subprocess.TimeoutExpired:
error_msg = "Timeout while getting package list"
self.package_operation_complete.emit(False, error_msg)
return False, error_msg
except Exception as e:
error_msg = f"Error getting package list: {str(e)}"
self.package_operation_complete.emit(False, error_msg)
return False, error_msg
def get_package_info(self, package_name):
if not self.device_manager.current_device:
return False, "No device selected #007"
if not package_name or not isinstance(package_name, str):
return False, "Invalid package name"
try:
command = [self.device_manager.adb_path, "-s", self.device_manager.current_device, "shell", "dumpsys", "package", package_name]
result = subprocess.run(command, capture_output=True, text=True, timeout=30)
output = result.stdout
info = {
"name": package_name,
"version": "Unknown",
"uid": "Unknown",
"path": "Unknown",
"enabled": True,
"target_sdk": "Unknown",
"min_sdk": "Unknown",
"installer": "Unknown",
"data_dir": "Unknown",
"signature": "Unknown",
"cpu_abi": "Unknown",
"permissions": []
}
version_match = re.search(r"versionName=([^\s]+)", output)
if version_match:
info["version"] = version_match.group(1).strip('"\'')
target_sdk_match = re.search(r"targetSdk=(\d+)", output)
if target_sdk_match:
info["target_sdk"] = target_sdk_match.group(1)
min_sdk_match = re.search(r"minSdk=(\d+)", output)
if min_sdk_match:
info["min_sdk"] = min_sdk_match.group(1)
installer_match = re.search(r"installerPackageName=([^\s]+)", output)
if installer_match:
info["installer"] = installer_match.group(1)
data_dir_match = re.search(r"dataDir=([^\s]+)", output)
if data_dir_match:
info["data_dir"] = data_dir_match.group(1)
uid_match = re.search(r"userId=(\d+)", output)
if uid_match:
info["uid"] = uid_match.group(1)
path_match = re.search(r"codePath=([^\s]+)", output)
if path_match:
info["path"] = path_match.group(1).strip('"\'')
enabled_match = re.search(r"enabled=(\d+)", output)
if enabled_match:
info["enabled"] = enabled_match.group(1) == "1"
cpu_abi_match = re.search(r"primaryCpuAbi=([^\s]+)", output)
if cpu_abi_match:
info["cpu_abi"] = cpu_abi_match.group(1)
# Signature parsing
signatures_block_match = re.search(r"signatures:\[(.*?)\]", output, re.DOTALL)
if signatures_block_match:
sig_hash_match = re.search(r'([a-fA-F0-9]{8,})', signatures_block_match.group(1))
if sig_hash_match:
info["signature"] = sig_hash_match.group(1)
permissions_section = re.search(r"requested permissions:(.*?)install permissions:", output, re.DOTALL)
if not permissions_section:
permissions_section = re.search(r"requested permissions:(.*)", output, re.DOTALL)
if permissions_section:
permissions = re.findall(r"(\w+): granted=(\w+)", permissions_section.group(1))
info["permissions"] = [f"{p[0]} ({'granted' if p[1] == 'true' else 'denied'})" for p in permissions]
install_time_match = re.search(r"firstInstallTime=(\d+)", output)
if install_time_match:
try:
timestamp = int(install_time_match.group(1))
info["install_time"] = datetime.fromtimestamp(timestamp/1000).strftime("%Y-%m-%d %H:%M:%S")
except:
pass
update_time_match = re.search(r"lastUpdateTime=(\d+)", output)
if update_time_match:
try:
timestamp = int(update_time_match.group(1))
info["update_time"] = datetime.fromtimestamp(timestamp/1000).strftime("%Y-%m-%d %H:%M:%S")
except:
pass
size_match = re.search(r"codeSize=(\d+)", output)
if size_match:
try:
size_bytes = int(size_match.group(1))