Repository navigation
Expand file tree
/
Copy pathsystem_controller.py
More file actions
2988 lines (2682 loc) · 124 KB
/
Copy pathsystem_controller.py
File metadata and controls
2988 lines (2682 loc) · 124 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
"""
System Controller Module for PC Remote Sentinel
Handles OS hardware metrics, webcam, screen capture/recording, power, and audio controls.
"""
import os
import sys
import gc
import time
import math
import re
import socket
import threading
import ctypes
try:
import ctypes.wintypes
except Exception:
pass
import subprocess
try:
import winsound
except ImportError:
winsound = None
from datetime import datetime, timezone, timedelta
from pathlib import Path
from typing import Dict, Any, List, Optional, Tuple
IS_WINDOWS = sys.platform == "win32"
IS_MAC = sys.platform == "darwin"
IS_LINUX = sys.platform.startswith("linux")
import psutil
from PIL import ImageGrab
from loguru import logger
try:
import cv2
except ImportError:
cv2 = None
class SystemController:
"""Universal OS Controller for remote administration (Windows & macOS)."""
_last_desktop_attach_time: float = 0.0
_dpi_initialized: bool = False
@staticmethod
def get_system_stats() -> Dict[str, Any]:
"""Collect real-time CPU, RAM, Disk, Battery, and Uptime diagnostics."""
cpu_pct = psutil.cpu_percent(interval=0.5)
per_core = psutil.cpu_percent(percpu=True)
mem = psutil.virtual_memory()
disk_target = "C:\\" if IS_WINDOWS else "/"
disk = psutil.disk_usage(disk_target)
# Battery / Power status
battery = psutil.sensors_battery()
battery_info = "N/A (Desktop/AC)"
if battery:
plugged = "🔌 Plugged In" if battery.power_plugged else "🔋 On Battery"
battery_info = f"{battery.percent:.0f}% ({plugged})"
# Uptime
boot_time = datetime.fromtimestamp(psutil.boot_time())
uptime_delta = datetime.now() - boot_time
hours, remainder = divmod(int(uptime_delta.total_seconds()), 3600)
minutes, seconds = divmod(remainder, 60)
uptime_str = f"{hours}h {minutes}m {seconds}s"
return {
"cpu_percent": cpu_pct,
"per_core": per_core,
"memory_percent": mem.percent,
"memory_used_gb": round(mem.used / (1024 ** 3), 2),
"memory_total_gb": round(mem.total / (1024 ** 3), 2),
"disk_percent": disk.percent,
"disk_free_gb": round(disk.free / (1024 ** 3), 2),
"disk_total_gb": round(disk.total / (1024 ** 3), 2),
"battery": battery_info,
"uptime": uptime_str,
"boot_time": boot_time.strftime("%Y-%m-%d %H:%M:%S"),
"session_state": SystemController.get_session_state(),
}
@classmethod
def ensure_desktop_access(cls, force: bool = False) -> bool:
"""Attach thread to active Windows input desktop with 3.0s cache to eliminate input stutters."""
if not IS_WINDOWS:
return True
now = time.time()
if not force and (now - cls._last_desktop_attach_time < 3.0):
return True
try:
if not cls._dpi_initialized:
try:
ctypes.windll.shcore.SetProcessDpiAwareness(2)
except Exception:
pass
cls._dpi_initialized = True
hdesk = ctypes.windll.user32.OpenInputDesktop(0, False, 0x01FF)
if hdesk:
ctypes.windll.user32.SetThreadDesktop(hdesk)
cls._last_desktop_attach_time = now
return True
except Exception:
pass
return False
@staticmethod
def get_session_state() -> str:
"""Detect if OS is at interactive desktop, lock screen, or Session 0."""
if IS_MAC:
try:
out = subprocess.run(["ioreg", "-n", "Root", "-d1"], capture_output=True, text=True, timeout=1.0).stdout
if re.search(r'["\']?(?:CGSSessionScreenIsLocked|kCGSessionScreenIsLocked)["\']?\s*=\s*(?:1|yes|true|<true>)', out, re.IGNORECASE):
return "macOS Lock Screen 🔒"
return "macOS Desktop (Unlocked) 🟢"
except Exception:
return "macOS Desktop 🟢"
try:
hdesk = ctypes.windll.user32.OpenInputDesktop(0, False, 0x0100)
if hdesk:
buf = ctypes.create_unicode_buffer(256)
size = ctypes.c_uint(0)
ctypes.windll.user32.GetUserObjectInformationW(hdesk, 2, buf, 256, ctypes.byref(size))
desk = buf.value.lower()
if desk == "default":
return "Interactive Desktop (Unlocked) 🟢"
elif desk == "winlogon":
return "Windows Login / Lock Screen 🔒"
return f"{buf.value} 🖥️"
except Exception:
pass
return "Pre-Login / Session 0 🔒"
@staticmethod
def take_screenshot(output_path: Path) -> Tuple[bool, str]:
"""Capture full desktop screenshot with graceful pre-login detection."""
if IS_MAC:
try:
res = subprocess.run(["/usr/sbin/screencapture", "-x", str(output_path)], capture_output=True, timeout=5.0)
if res.returncode == 0 and output_path.exists() and output_path.stat().st_size > 0:
return True, "Screenshot captured"
except Exception as se:
logger.debug(f"macOS screencapture error: {se}, falling back to ImageGrab")
try:
SystemController.ensure_desktop_access()
screenshot = ImageGrab.grab(all_screens=True)
screenshot.save(output_path, "PNG")
return True, "Screenshot captured"
except Exception as e:
err = str(e)
logger.error(f"Screenshot error: {err}")
if "screen grab failed" in err.lower():
return False, "⚠️ Screen capture unavailable: PC is currently at the pre-login lock screen (Session 0). Please log into Windows to view active desktop."
return False, f"Screenshot error: {err}"
@staticmethod
def take_webcam_photo(output_path: Path, camera_index: int = 0) -> Tuple[bool, str]:
"""Capture a single photo from webcam."""
if cv2 is None:
return False, "OpenCV (cv2) is not installed."
backend = cv2.CAP_AVFOUNDATION if IS_MAC else cv2.CAP_DSHOW
cap = cv2.VideoCapture(camera_index, backend)
if not cap.isOpened():
cap = cv2.VideoCapture(camera_index)
if not cap.isOpened():
return False, "Could not access webcam device."
try:
# Let sensor adjust for 3 frames
for _ in range(5):
cap.read()
ret, frame = cap.read()
if ret and frame is not None:
cv2.imwrite(str(output_path), frame)
return True, "Photo captured"
return False, "Failed to grab webcam frame"
except Exception as e:
return False, f"Webcam error: {e}"
finally:
cap.release()
@staticmethod
def record_webcam_video(output_path: Path, duration_sec: int = 10, camera_index: int = 0) -> Tuple[bool, str]:
"""Record video clip from webcam for specified seconds."""
if cv2 is None:
return False, "OpenCV is not installed."
backend = cv2.CAP_AVFOUNDATION if IS_MAC else cv2.CAP_DSHOW
cap = cv2.VideoCapture(camera_index, backend)
if not cap.isOpened():
cap = cv2.VideoCapture(camera_index)
if not cap.isOpened():
return False, "Could not open webcam."
try:
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH) or 640)
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT) or 480)
fps = 20.0
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
out = cv2.VideoWriter(str(output_path), fourcc, fps, (width, height))
end_time = time.time() + duration_sec
while time.time() < end_time:
ret, frame = cap.read()
if ret and frame is not None:
out.write(frame)
time.sleep(0.04)
out.release()
return True, f"Recorded {duration_sec}s webcam clip"
except Exception as e:
return False, f"Webcam recording failed: {e}"
finally:
cap.release()
@staticmethod
def record_screen_video(output_path: Path, duration_sec: int = 10) -> Tuple[bool, str]:
"""Record desktop screen video for specified seconds (up to 120s)."""
if IS_MAC:
try:
res = subprocess.run(
["/usr/sbin/screencapture", "-V", str(duration_sec), str(output_path)],
capture_output=True,
timeout=duration_sec + 10
)
if res.returncode == 0 and output_path.exists() and output_path.stat().st_size > 0:
return True, f"Recorded {duration_sec}s screen video"
except Exception as se:
logger.debug(f"macOS native video recording error: {se}, falling back to frame loop")
if cv2 is None:
return False, "OpenCV is not installed."
try:
import numpy as np
screen = ImageGrab.grab()
width, height = screen.size
scale = 1.0
if width > 1920:
scale = 1920.0 / width
width = 1920
height = int(height * scale)
if width % 2 != 0:
width -= 1
if height % 2 != 0:
height -= 1
fps = 10.0
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
out = cv2.VideoWriter(str(output_path), fourcc, fps, (width, height))
end_time = time.time() + duration_sec
frame_delay = 1.0 / fps
while time.time() < end_time:
t0 = time.time()
img = None
frame = None
try:
img = ImageGrab.grab()
frame = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)
if scale != 1.0:
frame = cv2.resize(frame, (width, height))
out.write(frame)
finally:
if img is not None:
del img
if frame is not None:
del frame
elapsed = time.time() - t0
if elapsed < frame_delay:
time.sleep(frame_delay - elapsed)
out.release()
gc.collect()
return True, f"Recorded {duration_sec}s screen video"
except Exception as e:
return False, f"Screen recording failed: {e}"
# ── Power & Session Management ──────────────────────────────────────
@staticmethod
def lock_workstation() -> bool:
"""Lock PC/Mac instantly using OS native APIs."""
if IS_MAC:
# 1. Try SACLockScreenImmediate via login framework
try:
for lib_name in (
"/System/Library/PrivateFrameworks/login.framework/Versions/Current/login",
"/System/Library/PrivateFrameworks/login.framework/login",
"login",
):
try:
lf = ctypes.CDLL(lib_name)
lf.SACLockScreenImmediate()
logger.info("macOS workstation locked via SACLockScreenImmediate.")
return True
except Exception:
continue
except Exception:
pass
# 2. Try keyboard shortcut Ctrl+Cmd+Q via AppleScript
try:
subprocess.run(["osascript", "-e", 'tell application "System Events" to key code 12 using {control down, command down}'], check=True, timeout=3.0)
return True
except Exception:
pass
# 3. Fallback to displaysleepnow
try:
subprocess.run(["pmset", "displaysleepnow"], check=True, timeout=3.0)
return True
except Exception as e:
logger.error(f"macOS lock error: {e}")
return False
try:
res = ctypes.windll.user32.LockWorkStation()
if res != 0:
logger.info("Workstation locked via ctypes user32.LockWorkStation.")
return True
except Exception as e:
logger.debug(f"Direct LockWorkStation failed: {e}")
try:
res = subprocess.run(["rundll32.exe", "user32.dll,LockWorkStation"], shell=False, timeout=3)
if res.returncode == 0:
logger.info("Workstation locked via rundll32.")
return True
except Exception as e:
logger.debug(f"rundll32 LockWorkStation failed: {e}")
try:
res = subprocess.run(["tsdiscon"], shell=False, timeout=3)
if res.returncode == 0:
logger.info("Workstation locked via tsdiscon.")
return True
except Exception as e:
logger.error(f"All workstation lock strategies failed: {e}")
return False
return False
@staticmethod
def sleep_pc() -> bool:
"""Put PC or Mac into sleep state."""
if IS_MAC:
try:
subprocess.run(["pmset", "sleepnow"], check=True)
return True
except Exception:
try:
subprocess.run(["osascript", "-e", 'tell application "System Events" to sleep'], check=True)
return True
except Exception as e:
logger.error(f"macOS sleep error: {e}")
return False
try:
res = subprocess.run(["rundll32.exe", "powrprof.dll,SetSuspendState", "0,1,0"], shell=False, timeout=5)
if res.returncode == 0:
return True
except Exception as e:
logger.debug(f"rundll32 SetSuspendState failed: {e}")
try:
res = subprocess.run(
["powershell", "-NoProfile", "-Command", "Add-Type -Assembly System.Windows.Forms; [System.Windows.Forms.Application]::SetSuspendState([System.Windows.Forms.PowerState]::Suspend, $false, $false)"],
capture_output=True,
timeout=5
)
return res.returncode == 0
except Exception as e:
logger.error(f"Sleep error: {e}")
return False
@staticmethod
def shutdown_pc(seconds: int = 0) -> bool:
"""Shutdown PC or Mac now or with timer."""
if IS_MAC:
try:
if seconds > 0:
def _delayed_shut():
time.sleep(seconds)
subprocess.run(["osascript", "-e", 'tell application "System Events" to shut down'])
threading.Thread(target=_delayed_shut, daemon=True, name="MacDelayedShutdown").start()
return True
subprocess.run(["osascript", "-e", 'tell application "System Events" to shut down'], check=True)
return True
except Exception as e:
logger.error(f"macOS shutdown error: {e}")
return False
try:
subprocess.run(["shutdown", "/s", "/t", str(seconds)], check=True)
return True
except Exception as e:
logger.error(f"Shutdown error: {e}")
return False
@staticmethod
def restart_pc(seconds: int = 0) -> bool:
"""Restart PC or Mac now or with timer."""
if IS_MAC:
try:
if seconds > 0:
def _delayed_rst():
time.sleep(seconds)
subprocess.run(["osascript", "-e", 'tell application "System Events" to restart'])
threading.Thread(target=_delayed_rst, daemon=True, name="MacDelayedRestart").start()
return True
subprocess.run(["osascript", "-e", 'tell application "System Events" to restart'], check=True)
return True
except Exception as e:
logger.error(f"macOS restart error: {e}")
return False
try:
subprocess.run(["shutdown", "/r", "/t", str(seconds)], check=True)
return True
except Exception as e:
logger.error(f"Restart error: {e}")
return False
@staticmethod
def cancel_shutdown() -> bool:
"""Cancel any pending shutdown timer."""
if IS_MAC:
return True
try:
subprocess.run(["shutdown", "/a"], check=True)
return True
except Exception:
return False
@staticmethod
def turn_off_monitors() -> bool:
"""Put monitors to sleep immediately (wakes up on mouse move/key press)."""
if IS_MAC:
try:
subprocess.run(["pmset", "displaysleepnow"], check=True)
return True
except Exception as e:
logger.error(f"macOS display sleep error: {e}")
return False
try:
HWND_BROADCAST = 0xFFFF
WM_SYSCOMMAND = 0x0112
SC_MONITORPOWER = 0xF170
MONITOR_OFF = 2
ctypes.windll.user32.SendMessageW(HWND_BROADCAST, WM_SYSCOMMAND, SC_MONITORPOWER, MONITOR_OFF)
return True
except Exception as e:
logger.debug(f"Direct SendMessageW monitor off failed: {e}")
try:
cmd = "Add-Type -TypeDefinition 'using System; using System.Runtime.InteropServices; public class M { [DllImport(\"user32.dll\")] public static extern int SendMessage(int hWnd, int hMsg, int wParam, int lParam); }'; [M]::SendMessage(0xffff, 0x0112, 0xf170, 2)"
res = subprocess.run(["powershell", "-NoProfile", "-Command", cmd], capture_output=True, timeout=5)
return res.returncode == 0
except Exception as e:
logger.error(f"Monitor off error: {e}")
return False
@staticmethod
def turn_on_monitors() -> bool:
"""Wake up and power on monitors immediately."""
if IS_MAC:
try:
subprocess.run(["caffeinate", "-u", "-t", "2"], check=True)
return True
except Exception as e:
logger.error(f"macOS display wake error: {e}")
return False
try:
HWND_BROADCAST = 0xFFFF
WM_SYSCOMMAND = 0x0112
SC_MONITORPOWER = 0xF170
MONITOR_ON = -1
# 1. Broadcast WM_SYSCOMMAND to power on display
ctypes.windll.user32.SendMessageW(HWND_BROADCAST, WM_SYSCOMMAND, SC_MONITORPOWER, MONITOR_ON)
# 2. Inform power subsystem that display is required (resets idle timers)
ES_SYSTEM_REQUIRED = 0x00000001
ES_DISPLAY_REQUIRED = 0x00000002
ctypes.windll.kernel32.SetThreadExecutionState(ES_SYSTEM_REQUIRED | ES_DISPLAY_REQUIRED)
# 3. Simulate relative hardware mouse movement to wake physical display controller
MOUSEEVENTF_MOVE = 0x0001
ctypes.windll.user32.mouse_event(MOUSEEVENTF_MOVE, 1, 0, 0, 0)
time.sleep(0.02)
ctypes.windll.user32.mouse_event(MOUSEEVENTF_MOVE, -1, 0, 0, 0)
return True
except Exception as e:
logger.error(f"Monitor on error: {e}")
return False
# ── Laptop Tracking & Geolocation ───────────────────────────────────
@staticmethod
def get_battery_status() -> Dict[str, Any]:
"""Fetch laptop battery level, charging state, and remaining life."""
try:
battery = psutil.sensors_battery()
if not battery:
return {
"has_battery": False,
"percent": 100,
"power_plugged": True,
"secsleft": -1,
"status_str": "AC Desktop Power (No Battery)",
}
pct = round(battery.percent, 1)
plugged = bool(battery.power_plugged) if battery.power_plugged is not None else False
secs = battery.secsleft
if plugged:
status_str = f"🔌 {pct:.0f}% [Charging / AC Power]" if pct < 100 else "🔌 100% [Fully Charged]"
else:
if secs is not None and secs > 0 and secs != getattr(psutil, "POWER_TIME_UNLIMITED", -2) and secs != getattr(psutil, "POWER_TIME_UNKNOWN", -1):
hrs = int(secs) // 3600
mins = (int(secs) % 3600) // 60
time_left = f"{hrs}h {mins}m remaining"
else:
time_left = "Calculating..."
status_str = f"🔋 {pct:.0f}% [On Battery — {time_left}]"
return {
"has_battery": True,
"percent": pct,
"power_plugged": plugged,
"secsleft": secs if secs is not None else -1,
"status_str": status_str,
}
except Exception as e:
logger.debug(f"Error reading battery status: {e}")
return {
"has_battery": False,
"percent": 100,
"power_plugged": True,
"secsleft": -1,
"status_str": "N/A",
}
@staticmethod
def get_wifi_details() -> Dict[str, Any]:
"""Fetch current Wi-Fi connection parameters and nearby visible networks."""
result: Dict[str, Any] = {
"connected": False,
"ssid": "",
"bssid": "",
"signal": "",
"radio_type": "",
"channel": "",
"visible_networks": [],
}
if IS_WINDOWS:
try:
out = subprocess.run(
["netsh", "wlan", "show", "interfaces"],
capture_output=True,
text=True,
timeout=2.0,
).stdout
for line in out.splitlines():
line = line.strip()
if ":" in line:
k, v = [x.strip() for x in line.split(":", 1)]
k_lower = k.lower()
if k_lower == "state" and "connected" in v.lower():
result["connected"] = True
elif k_lower == "ssid":
result["ssid"] = v
elif k_lower in ("ap bssid", "bssid"):
result["bssid"] = v
elif k_lower == "signal":
result["signal"] = v
elif k_lower == "radio type":
result["radio_type"] = v
elif k_lower == "channel":
result["channel"] = v
except Exception as e:
logger.debug(f"Error querying netsh wlan interfaces: {e}")
try:
out_net = subprocess.run(
["netsh", "wlan", "show", "networks", "mode=bssid"],
capture_output=True,
text=True,
timeout=3.0,
).stdout
current_ssid = ""
current_net: Optional[Dict[str, str]] = None
for line in out_net.splitlines():
line = line.strip()
if line.startswith("SSID") and ":" in line:
current_ssid = line.split(":", 1)[1].strip()
elif line.startswith("BSSID") and ":" in line:
bssid_val = line.split(":", 1)[1].strip()
current_net = {
"ssid": current_ssid or "<Hidden>",
"bssid": bssid_val,
"signal": "",
"channel": "",
}
result["visible_networks"].append(current_net)
elif current_net and line.startswith("Signal") and ":" in line:
current_net["signal"] = line.split(":", 1)[1].strip()
elif current_net and line.startswith("Channel") and ":" in line:
current_net["channel"] = line.split(":", 1)[1].strip()
result["visible_networks"] = result["visible_networks"][:5]
except Exception as e:
logger.debug(f"Error querying visible networks: {e}")
elif IS_MAC:
try:
airport_path = "/System/Library/PrivateFrameworks/Apple80211.framework/Resources/airport"
if Path(airport_path).exists():
out = subprocess.run([airport_path, "-I"], capture_output=True, text=True, timeout=2.0).stdout
for line in out.splitlines():
line = line.strip()
if ":" in line:
k, v = [x.strip() for x in line.split(":", 1)]
if k == "SSID":
result["ssid"] = v
result["connected"] = True
elif k == "BSSID":
result["bssid"] = v
elif k == "agrCtlRSSI":
result["signal"] = f"{v} dBm"
elif k == "channel":
result["channel"] = v
except Exception as e:
logger.debug(f"macOS Wi-Fi query error: {e}")
return result
@staticmethod
def get_geolocation() -> Dict[str, Any]:
"""Resolve public IP and geographic coordinates via reliable geolocation APIs."""
import httpx
endpoints = [
("http://ip-api.com/json/?fields=status,message,country,countryCode,regionName,city,zip,lat,lon,isp,org,query", "ip_api"),
("https://ipwhois.app/json/", "ipwhois"),
]
for url, service in endpoints:
try:
resp = httpx.get(url, timeout=3.5)
if resp.status_code == 200:
data = resp.json()
if service == "ip_api" and data.get("status") == "success":
lat = float(data.get("lat", 0.0))
lon = float(data.get("lon", 0.0))
return {
"ok": True,
"ip": data.get("query", ""),
"city": data.get("city", "Unknown"),
"region": data.get("regionName", "Unknown"),
"country": data.get("country", "Unknown"),
"country_code": data.get("countryCode", ""),
"lat": lat,
"lon": lon,
"isp": data.get("isp", data.get("org", "Unknown")),
"google_maps": f"https://www.google.com/maps?q={lat},{lon}",
"osm_maps": f"https://www.openstreetmap.org/?mlat={lat}&mlon={lon}#map=16/{lat}/{lon}",
}
elif service == "ipwhois" and data.get("success", False):
lat = float(data.get("latitude", 0.0))
lon = float(data.get("longitude", 0.0))
return {
"ok": True,
"ip": data.get("ip", ""),
"city": data.get("city", "Unknown"),
"region": data.get("region", "Unknown"),
"country": data.get("country", "Unknown"),
"country_code": data.get("country_code", ""),
"lat": lat,
"lon": lon,
"isp": data.get("isp", data.get("org", "Unknown")),
"google_maps": f"https://www.google.com/maps?q={lat},{lon}",
"osm_maps": f"https://www.openstreetmap.org/?mlat={lat}&mlon={lon}#map=16/{lat}/{lon}",
}
except Exception as e:
logger.debug(f"Geolocation lookup failed via {url}: {e}")
continue
return {
"ok": False,
"error": "Could not determine public IP geolocation (offline or timed out)",
"lat": 0.0,
"lon": 0.0,
}
@staticmethod
def detect_vpn_interfaces() -> Dict[str, Any]:
"""Detect if an active VPN or tunnel adapter is routing network traffic."""
vpn_adapters = []
keywords = [
"vpn", "wireguard", "wintun", "tap-windows", "nordvpn", "expressvpn",
"openvpn", "tailscale", "zerotier", "warp", "cloudflare", "cisco",
"anyconnect", "fortinet", "surfshark", "proton", "mullvad", "ppp"
]
try:
for iface_name, addrs in psutil.net_if_addrs().items():
name_lower = iface_name.lower()
for kw in keywords:
if kw in name_lower:
has_ipv4 = any(a.family == socket.AF_INET for a in addrs)
if has_ipv4:
vpn_adapters.append(iface_name)
break
except Exception as e:
logger.debug(f"Error checking VPN adapters: {e}")
is_active = len(vpn_adapters) > 0
return {
"is_vpn_active": is_active,
"active": is_active,
"adapters": vpn_adapters,
"tunnels": vpn_adapters,
}
@staticmethod
def get_hardware_gateway() -> Dict[str, str]:
"""Extract physical router gateway IP and hardware MAC address."""
result = {"gateway_ip": "", "gateway_mac": "", "interface_ip": "", "physical_interface": ""}
if IS_WINDOWS:
try:
out = subprocess.run(["route", "print", "0.0.0.0"], capture_output=True, text=True, timeout=2.0).stdout
matches = re.findall(r'0\.0\.0\.0\s+0\.0\.0\.0\s+([0-9.]+)\s+([0-9.]+)', out)
if matches:
gw_ip, iface_ip = matches[0]
result["gateway_ip"] = gw_ip
result["interface_ip"] = iface_ip
result["physical_interface"] = iface_ip
# Resolve gateway MAC from ARP table
arp_out = subprocess.run(["arp", "-a", gw_ip], capture_output=True, text=True, timeout=2.0).stdout
mac_match = re.search(r'([0-9a-fA-F]{2}(?:-[0-9a-fA-F]{2}){5})', arp_out)
if mac_match:
result["gateway_mac"] = mac_match.group(1).replace("-", ":").upper()
except Exception as e:
logger.debug(f"Error querying physical gateway: {e}")
elif IS_MAC:
try:
out = subprocess.run(["route", "-n", "get", "default"], capture_output=True, text=True, timeout=2.0).stdout
m = re.search(r'gateway:\s*([0-9.]+)', out)
if m:
gw_ip = m.group(1)
result["gateway_ip"] = gw_ip
arp_out = subprocess.run(["arp", "-n", gw_ip], capture_output=True, text=True, timeout=2.0).stdout
mac_match = re.search(r'([0-9a-fA-F]{1,2}(?::[0-9a-fA-F]{1,2}){5})', arp_out)
if mac_match:
result["gateway_mac"] = mac_match.group(1).upper()
except Exception as e:
logger.debug(f"macOS gateway query error: {e}")
return result
@staticmethod
def query_wifi_bssid_location(bssid: str) -> Optional[Dict[str, Any]]:
"""Query open Wi-Fi BSSID database to resolve physical coordinates bypassing any VPN."""
if not bssid or bssid.count(":") != 5:
return None
import httpx
try:
url = f"https://api.mylnikov.org/geolocation/wifi?bssid={bssid}"
resp = httpx.get(url, timeout=2.5)
if resp.status_code == 200:
data = resp.json()
if data.get("result") == 200 and data.get("data"):
d = data["data"]
lat = float(d.get("lat", 0.0))
lon = float(d.get("lon", 0.0))
if lat != 0.0 or lon != 0.0:
return {
"lat": lat,
"lon": lon,
"range_m": d.get("range", 100),
"source": "Wi-Fi Router BSSID Physical Positioning",
"google_maps": f"https://www.google.com/maps?q={lat},{lon}",
"osm_maps": f"https://www.openstreetmap.org/?mlat={lat}&mlon={lon}#map=16/{lat}/{lon}",
}
except Exception as e:
logger.debug(f"BSSID physical geolocation lookup notice: {e}")
return None
@staticmethod
def get_tracking_info() -> Dict[str, Any]:
"""
Synthesize complete tracking intelligence dossier for remote laptops and PCs,
equipped with Anti-VPN detection and physical Wi-Fi hardware anchoring.
"""
try:
battery = SystemController.get_battery_status()
wifi = SystemController.get_wifi_details()
geo = SystemController.get_geolocation()
session = SystemController.get_session_state()
vpn = SystemController.detect_vpn_interfaces()
gw = SystemController.get_hardware_gateway()
# Attempt physical Wi-Fi BSSID geolocation (bypasses software VPN)
physical_geo = None
if wifi.get("bssid"):
physical_geo = SystemController.query_wifi_bssid_location(wifi["bssid"])
username = os.environ.get("USERNAME") or os.environ.get("USER") or "Unknown"
hostname = os.environ.get("COMPUTERNAME") or socket.gethostname()
uptime_str = "Unknown"
try:
boot_time = datetime.fromtimestamp(psutil.boot_time())
uptime_delta = datetime.now() - boot_time
hours, rem = divmod(int(uptime_delta.total_seconds()), 3600)
mins, _ = divmod(rem, 60)
uptime_str = f"{hours}h {mins}m"
except Exception:
pass
return {
"ok": True,
"hostname": hostname,
"user": username,
"battery": battery,
"wifi": wifi,
"geo": geo,
"physical_geo": physical_geo,
"vpn": vpn,
"gateway": gw,
"hardware_gateway": gw,
"session_state": session,
"uptime": uptime_str,
"timestamp": datetime.now(timezone.utc).isoformat(),
}
except Exception as e:
logger.error(f"Error compiling tracking dossier: {e}")
return {
"ok": False,
"error": str(e),
"hostname": os.environ.get("COMPUTERNAME", "PC"),
"user": os.environ.get("USERNAME", "User"),
"battery": {"has_battery": False, "status_str": "N/A"},
"wifi": {"connected": False, "ssid": "", "bssid": "", "visible_networks": []},
"geo": {"ok": False, "lat": 0.0, "lon": 0.0},
"physical_geo": None,
"vpn": {"is_vpn_active": False, "adapters": []},
"gateway": {"gateway_ip": "", "gateway_mac": ""},
"session_state": "Unknown",
"uptime": "N/A",
"timestamp": datetime.now(timezone.utc).isoformat(),
}
# ── Audio & Speech Controls ─────────────────────────────────────────
@staticmethod
def control_media(action: str) -> bool:
"""
Adjust volume and media playback via OS native keystrokes or AppleScript.
action: 'up', 'down', 'mute', 'play_pause', 'play', 'pause', 'next', 'prev', 'stop'
"""
if IS_MAC:
try:
act = action.lower().strip()
if act in ("up",):
subprocess.run(["osascript", "-e", 'set volume output volume ((output volume of (get volume settings)) + 6)'], check=True)
elif act in ("down",):
subprocess.run(["osascript", "-e", 'set volume output volume ((output volume of (get volume settings)) - 6)'], check=True)
elif act in ("mute",):
subprocess.run(["osascript", "-e", 'set volume output muted (not (output muted of (get volume settings)))'], check=True)
elif act in ("play_pause", "play", "pause"):
subprocess.run(["osascript", "-e", 'tell application "Music" to playpause'], check=True)
elif act in ("next",):
subprocess.run(["osascript", "-e", 'tell application "Music" to next track'], check=True)
elif act in ("prev",):
subprocess.run(["osascript", "-e", 'tell application "Music" to previous track'], check=True)
return True
except Exception as e:
logger.error(f"macOS media control error: {e}")
return False
KEYEVENTF_EXTENDEDKEY = 0x0001
KEYEVENTF_KEYUP = 0x0002
# Mapping: (VK_CODE, SCAN_CODE)
key_map = {
"up": (0xAF, 0x30), # VK_VOLUME_UP
"down": (0xAE, 0x2E), # VK_VOLUME_DOWN
"mute": (0xAD, 0x20), # VK_VOLUME_MUTE
"play_pause": (0xCD, 0x22), # VK_MEDIA_PLAY_PAUSE
"play": (0xCD, 0x22), # VK_MEDIA_PLAY_PAUSE
"pause": (0xCD, 0x22), # VK_MEDIA_PLAY_PAUSE
"next": (0xB0, 0x19), # VK_MEDIA_NEXT_TRACK
"prev": (0xB1, 0x10), # VK_MEDIA_PREV_TRACK
"stop": (0xB2, 0x24), # VK_MEDIA_STOP
}
entry = key_map.get(action.lower())
if not entry:
return False
vk, scan = entry
try:
# Simulate a single genuine extended hardware media key press
ctypes.windll.user32.keybd_event(vk, scan, KEYEVENTF_EXTENDEDKEY, 0)
time.sleep(0.05)
ctypes.windll.user32.keybd_event(vk, scan, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0)
return True
except Exception as e:
logger.error(f"Media control error: {e}")
return False
@staticmethod
def change_volume(action: str) -> bool:
"""Backward-compatible alias for control_media."""
return SystemController.control_media(action)
@staticmethod
def press_media_key(action: str) -> Tuple[bool, str]:
"""Convenience method returning (ok, msg) tuple for media key actions."""
ok = SystemController.control_media(action)
return ok, f"Media key '{action}' triggered" if ok else f"Unknown or failed media key: {action}"
@staticmethod
def get_active_window_title_fast() -> str:
"""Return title of current foreground window quickly without external imports."""
if IS_MAC:
try:
as_cmd = 'tell application "System Events" to get name of first application process whose frontmost is true'
title = subprocess.check_output(["osascript", "-e", as_cmd], timeout=1.5).decode().strip()
return title or "macOS Desktop"
except Exception:
return "macOS Desktop"
try:
SystemController.ensure_desktop_access()
user32 = ctypes.windll.user32
h = user32.GetForegroundWindow()
if h:
length = user32.GetWindowTextLengthW(h)
if length > 0:
buf = ctypes.create_unicode_buffer(length + 1)
user32.GetWindowTextW(h, buf, length + 1)
t = buf.value.strip()
if t:
return t
except Exception:
pass
return "Desktop"
@staticmethod
def switch_virtual_desktop(action: str) -> Tuple[bool, str]:
"""
Switch, create, or navigate Virtual Desktops / Spaces via native OS events.
action: 'next', 'prev', 'new', 'close', 'task_view', 'show_desktop'
"""
action = action.lower().strip()
if IS_MAC:
try:
if action == "next":
subprocess.run(["osascript", "-e", 'tell application "System Events" to key code 124 using {control down}'], check=True)
return True, "Switched to next Space"
elif action == "prev":
subprocess.run(["osascript", "-e", 'tell application "System Events" to key code 123 using {control down}'], check=True)
return True, "Switched to previous Space"
elif action in ("task_view", "mission_control"):
subprocess.run(["osascript", "-e", 'tell application "System Events" to key code 126 using {control down}'], check=True)
return True, "Triggered Mission Control"
elif action == "show_desktop":
subprocess.run(["osascript", "-e", 'tell application "System Events" to key code 103'], check=True)
return True, "Toggled Show Desktop"
return True, f"macOS Space action '{action}' executed"
except Exception as e:
return False, f"macOS Space error: {e}"
SystemController.ensure_desktop_access()
KEYEVENTF_EXTENDEDKEY = 0x0001
KEYEVENTF_KEYUP = 0x0002
VK_LWIN = 0x5B
VK_CONTROL = 0x11
VK_RIGHT = 0x27
VK_LEFT = 0x25
VK_D = 0x44
VK_F4 = 0x73
VK_TAB = 0x09
if action in ("next", "right"):
primary, use_ctrl, ext, label = VK_RIGHT, True, True, "Next Desktop (Win+Ctrl+Right)"
elif action in ("prev", "previous", "left"):
primary, use_ctrl, ext, label = VK_LEFT, True, True, "Previous Desktop (Win+Ctrl+Left)"
elif action in ("new", "create"):