sysmaint 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. sysmaint/__init__.py +17 -0
  2. sysmaint/__main__.py +6 -0
  3. sysmaint/cli.py +637 -0
  4. sysmaint/config.py +229 -0
  5. sysmaint/gui/__init__.py +5 -0
  6. sysmaint/gui/app.py +193 -0
  7. sysmaint/gui/components/__init__.py +13 -0
  8. sysmaint/gui/components/cards.py +239 -0
  9. sysmaint/gui/components/console.py +61 -0
  10. sysmaint/gui/components/dialogs.py +79 -0
  11. sysmaint/gui/theme.py +52 -0
  12. sysmaint/gui/views/__init__.py +25 -0
  13. sysmaint/gui/views/backup.py +167 -0
  14. sysmaint/gui/views/cleaner.py +227 -0
  15. sysmaint/gui/views/dashboard.py +252 -0
  16. sysmaint/gui/views/diagnostics.py +243 -0
  17. sysmaint/gui/views/integrity.py +158 -0
  18. sysmaint/gui/views/malware.py +293 -0
  19. sysmaint/gui/views/network.py +171 -0
  20. sysmaint/gui/views/security.py +118 -0
  21. sysmaint/gui/views/settings.py +211 -0
  22. sysmaint/gui/views/startup.py +133 -0
  23. sysmaint/logging_setup.py +62 -0
  24. sysmaint/modules/__init__.py +41 -0
  25. sysmaint/modules/backup.py +106 -0
  26. sysmaint/modules/cleaner.py +249 -0
  27. sysmaint/modules/disk.py +160 -0
  28. sysmaint/modules/drivers.py +89 -0
  29. sysmaint/modules/integrity.py +148 -0
  30. sysmaint/modules/malware.py +412 -0
  31. sysmaint/modules/memory.py +105 -0
  32. sysmaint/modules/network.py +167 -0
  33. sysmaint/modules/optimizer.py +186 -0
  34. sysmaint/modules/recovery.py +353 -0
  35. sysmaint/modules/report.py +232 -0
  36. sysmaint/modules/restore.py +123 -0
  37. sysmaint/modules/scheduler.py +137 -0
  38. sysmaint/modules/security.py +88 -0
  39. sysmaint/modules/services.py +171 -0
  40. sysmaint/modules/startup.py +95 -0
  41. sysmaint/modules/sysinfo.py +112 -0
  42. sysmaint/service/__init__.py +5 -0
  43. sysmaint/service/server.py +210 -0
  44. sysmaint/tui/__init__.py +5 -0
  45. sysmaint/tui/app.py +830 -0
  46. sysmaint/tui/modals.py +201 -0
  47. sysmaint/tui/themes.py +97 -0
  48. sysmaint/utils/__init__.py +39 -0
  49. sysmaint/utils/common.py +255 -0
  50. sysmaint/utils/escalate.py +93 -0
  51. sysmaint/utils/linux.py +240 -0
  52. sysmaint/utils/parsers.py +171 -0
  53. sysmaint/utils/windows.py +308 -0
  54. sysmaint-0.1.0.dist-info/METADATA +307 -0
  55. sysmaint-0.1.0.dist-info/RECORD +57 -0
  56. sysmaint-0.1.0.dist-info/WHEEL +4 -0
  57. sysmaint-0.1.0.dist-info/entry_points.txt +5 -0
sysmaint/tui/app.py ADDED
@@ -0,0 +1,830 @@
1
+ # src/sysmaint/tui/app.py
2
+
3
+ from __future__ import annotations
4
+
5
+ import platform
6
+ from collections.abc import Callable
7
+ from typing import Any, ClassVar
8
+
9
+ import httpx
10
+ import psutil
11
+ from rich.table import Table
12
+ from textual import work
13
+ from textual.app import App, ComposeResult
14
+ from textual.binding import Binding
15
+ from textual.containers import Horizontal, Vertical
16
+ from textual.widgets import (
17
+ Button,
18
+ ContentSwitcher,
19
+ Footer,
20
+ Header,
21
+ Input,
22
+ Label,
23
+ LoadingIndicator,
24
+ ProgressBar,
25
+ Static,
26
+ Tab,
27
+ Tabs,
28
+ )
29
+
30
+ from .. import __brand__, __codename__, __version__
31
+ from ..config import SysMaintConfig, load_config
32
+ from ..modules import (
33
+ disk,
34
+ integrity,
35
+ malware,
36
+ memory,
37
+ network,
38
+ optimizer,
39
+ recovery,
40
+ security,
41
+ )
42
+ from ..utils.escalate import is_elevated, request_elevation
43
+ from .modals import ConfirmLongTaskModal, ElevationModal, TechnicalLogModal
44
+ from .themes import CUSTOM_THEMES, THEME_CYCLE
45
+
46
+
47
+ class SysMaintTUI(App):
48
+ """User-friendly, btop-inspired Terminal Client UI for SysMaint."""
49
+
50
+ TITLE = f"SysMaint v{__version__} ({__codename__})"
51
+ SUB_TITLE = __brand__
52
+
53
+ CSS = """
54
+ Screen {
55
+ background: $background;
56
+ color: $text;
57
+ }
58
+
59
+ #workspace-pane {
60
+ height: 1fr;
61
+ padding: 0 1;
62
+ }
63
+
64
+ #nav-tabs {
65
+ width: 100%;
66
+ height: 3;
67
+ background: $surface;
68
+ border-bottom: solid $primary;
69
+ }
70
+
71
+ #nav-tabs Tab {
72
+ width: 1fr;
73
+ height: 3;
74
+ padding: 1 1;
75
+ content-align: center middle;
76
+ text-style: bold;
77
+ color: $text-muted;
78
+ }
79
+
80
+ #nav-tabs Tab.-active {
81
+ color: $primary;
82
+ background: $panel;
83
+ text-style: bold;
84
+ }
85
+
86
+ .telemetry-grid {
87
+ layout: grid;
88
+ grid-size: 3;
89
+ grid-gutter: 1;
90
+ height: 5;
91
+ margin: 1 0 0 0;
92
+ }
93
+
94
+ .metric-card {
95
+ background: $panel;
96
+ border: round $primary;
97
+ padding: 0 1;
98
+ height: 5;
99
+ }
100
+
101
+ #device-strip {
102
+ background: $panel;
103
+ border: round $secondary;
104
+ padding: 0 2;
105
+ height: 3;
106
+ margin: 0;
107
+ content-align: left middle;
108
+ }
109
+
110
+ #sysinfo-summary {
111
+ height: 1;
112
+ }
113
+
114
+ #page-switcher {
115
+ height: 1fr;
116
+ margin-top: 1;
117
+ }
118
+
119
+ .tab-body {
120
+ height: 1fr;
121
+ }
122
+
123
+ .card {
124
+ background: $panel;
125
+ border: round $secondary;
126
+ padding: 1 2;
127
+ margin: 0 0 1 0;
128
+ height: auto;
129
+ }
130
+
131
+ .card-title {
132
+ color: $primary;
133
+ text-style: bold;
134
+ margin-bottom: 0;
135
+ }
136
+
137
+ .action-item {
138
+ height: auto;
139
+ margin: 1 0 0 0;
140
+ }
141
+
142
+ /* Radiant outline buttons on dark background (default for obsidian-gold & dark themes) */
143
+ Button {
144
+ background: $surface;
145
+ color: $primary;
146
+ border: round $primary;
147
+ text-style: bold;
148
+ }
149
+
150
+ Button:hover, Button:focus {
151
+ background: $panel;
152
+ color: $accent;
153
+ border: heavy $accent;
154
+ }
155
+
156
+ /* Solid dark-yellow / golden buttons for amber-slate theme */
157
+ Screen.solid-gold-buttons Button {
158
+ background: #a16207;
159
+ color: #fefce8;
160
+ border: round #eab308;
161
+ }
162
+
163
+ Screen.solid-gold-buttons Button:hover,
164
+ Screen.solid-gold-buttons Button:focus {
165
+ background: #ca8a04;
166
+ color: #090b10;
167
+ border: heavy #fde047;
168
+ }
169
+
170
+ .action-item Button {
171
+ width: 1fr;
172
+ margin-right: 1;
173
+ }
174
+
175
+ .action-desc {
176
+ color: $text-muted;
177
+ padding-left: 1;
178
+ margin-top: 1;
179
+ }
180
+
181
+ .result-box {
182
+ background: $surface;
183
+ border: round $accent;
184
+ padding: 1 2;
185
+ margin: 0 0 1 0;
186
+ height: 1fr;
187
+ overflow-y: auto;
188
+ }
189
+
190
+ Footer {
191
+ height: 3;
192
+ border-top: solid $panel;
193
+ padding: 0 2;
194
+ content-align: left middle;
195
+ }
196
+
197
+ #activity-bar {
198
+ height: auto;
199
+ background: $surface;
200
+ border-top: solid $primary;
201
+ padding: 0 2;
202
+ display: none;
203
+ }
204
+
205
+ #activity-bar.active {
206
+ display: block;
207
+ }
208
+
209
+ #activity-top-row {
210
+ height: auto;
211
+ align: left middle;
212
+ }
213
+
214
+ #activity-spinner {
215
+ width: 4;
216
+ height: 1;
217
+ display: none;
218
+ }
219
+
220
+ #activity-spinner.active {
221
+ display: block;
222
+ }
223
+
224
+ #activity-status {
225
+ width: 1fr;
226
+ padding: 0 1;
227
+ color: $text;
228
+ text-style: bold;
229
+ }
230
+
231
+ #activity-percent {
232
+ width: 10;
233
+ text-align: right;
234
+ color: $accent;
235
+ text-style: bold;
236
+ }
237
+
238
+ #activity-progress {
239
+ width: 100%;
240
+ height: auto;
241
+ margin-top: 1;
242
+ padding: 0 1;
243
+ border: round $primary;
244
+ background: $background;
245
+ display: none;
246
+ }
247
+
248
+ #activity-progress.active {
249
+ display: block;
250
+ }
251
+
252
+ ProgressBar {
253
+ width: 100%;
254
+ }
255
+
256
+ ProgressBar > Bar {
257
+ width: 1fr;
258
+ }
259
+
260
+ ProgressBar > Bar > .bar--bar {
261
+ color: $primary;
262
+ background: #334155;
263
+ }
264
+
265
+ ProgressBar > Bar > .bar--complete {
266
+ color: $success;
267
+ background: #334155;
268
+ }
269
+
270
+ ProgressBar > Bar > .bar--indeterminate {
271
+ color: $accent;
272
+ background: #334155;
273
+ }
274
+
275
+ #activity-live-line {
276
+ color: $text-muted;
277
+ margin-top: 0;
278
+ }
279
+
280
+ Input {
281
+ margin: 1 0 0 0;
282
+ }
283
+ """
284
+
285
+ BINDINGS: ClassVar[list[Binding]] = [
286
+ Binding("q", "quit", "Quit"),
287
+ Binding("r", "refresh_metrics", "Refresh"),
288
+ Binding("l", "open_log", "View Technical Log"),
289
+ Binding("t", "toggle_theme", "Switch Theme"),
290
+ ]
291
+
292
+ def __init__(
293
+ self,
294
+ config: SysMaintConfig | None = None,
295
+ server_url: str | None = None,
296
+ ) -> None:
297
+ super().__init__()
298
+ self.cfg = config or load_config()
299
+ self.server_url = server_url.rstrip("/") if server_url else None
300
+ self._busy = False
301
+ self._log_entries: list[tuple[str, Any]] = []
302
+
303
+ def compose(self) -> ComposeResult:
304
+ yield Header(show_clock=True)
305
+ with Vertical(id="workspace-pane"):
306
+ yield Tabs(
307
+ Tab("Overview", id="tab-overview"),
308
+ Tab("System Repair", id="tab-repair"),
309
+ Tab("Security & Malware", id="tab-security"),
310
+ Tab("Data Recovery", id="tab-recovery"),
311
+ Tab("Background Service", id="tab-service"),
312
+ id="nav-tabs",
313
+ )
314
+
315
+ with Horizontal(classes="telemetry-grid"):
316
+ with Vertical(classes="metric-card"):
317
+ yield Label("Processor (CPU)", classes="card-title")
318
+ yield ProgressBar(total=100, show_eta=False, id="bar-cpu")
319
+ yield Static("0.0%", id="val-cpu")
320
+ with Vertical(classes="metric-card"):
321
+ yield Label("Memory (RAM)", classes="card-title")
322
+ yield ProgressBar(total=100, show_eta=False, id="bar-ram")
323
+ yield Static("0.0%", id="val-ram")
324
+ with Vertical(classes="metric-card"):
325
+ yield Label("Main Storage", classes="card-title")
326
+ yield ProgressBar(total=100, show_eta=False, id="bar-disk")
327
+ yield Static("0.0%", id="val-disk")
328
+
329
+ with Vertical(id="device-strip"):
330
+ yield Static("", id="sysinfo-summary")
331
+
332
+ with ContentSwitcher(initial="tab-overview", id="page-switcher"):
333
+ with Vertical(id="tab-overview", classes="tab-body"):
334
+ with Vertical(classes="card"):
335
+ yield Label("Quick Actions", classes="card-title")
336
+ with Horizontal(classes="action-item"):
337
+ yield Button("Quick Scan", id="btn-quick-scan")
338
+ yield Button("Refresh Stats", id="btn-refresh")
339
+ yield Button("View Technical Log (L)", id="btn-open-log")
340
+ yield Label(
341
+ "Note: Quick Scan safely checks storage, memory, and system health without changing files.",
342
+ classes="action-desc",
343
+ )
344
+ yield Static(
345
+ "Press Quick Scan to see a plain-English health summary.",
346
+ id="res-overview",
347
+ classes="result-box",
348
+ )
349
+
350
+ with Vertical(id="tab-repair", classes="tab-body"):
351
+ with Vertical(classes="card"):
352
+ yield Label("Health Checks & Repair Tools", classes="card-title")
353
+ with Horizontal(classes="action-item"):
354
+ yield Button("Check System Files", id="btn-integrity")
355
+ yield Button("Fix System Files", id="btn-integrity-fix")
356
+ yield Button("Preview System Fixes", id="btn-repair-dry")
357
+ yield Button("Test & Fix Network", id="btn-net-check")
358
+ yield Label(
359
+ "Note: 'Check/Fix System Files' uses Windows DISM & SFC (or Linux package verify) and requires Administrator/root privileges.",
360
+ classes="action-desc",
361
+ )
362
+ yield Static(
363
+ "Select a check or repair above to inspect your system.",
364
+ id="res-repair",
365
+ classes="result-box",
366
+ )
367
+
368
+ with Vertical(id="tab-security", classes="tab-body"):
369
+ with Vertical(classes="card"):
370
+ yield Label("Protection Audit & Threat Scanner", classes="card-title")
371
+ with Horizontal(classes="action-item"):
372
+ yield Button("Check System Protection", id="btn-sec-audit")
373
+ yield Button("Scan for Viruses & Malware", id="btn-malware-scan")
374
+ yield Label(
375
+ "Note: Scans Downloads, Temp, and Startup folders offline using built-in YARA rules and ClamAV (if installed).",
376
+ classes="action-desc",
377
+ )
378
+ yield Static(
379
+ "Run a protection check or malware scan to see results here.",
380
+ id="res-security",
381
+ classes="result-box",
382
+ )
383
+
384
+ with Vertical(id="tab-recovery", classes="tab-body"):
385
+ with Vertical(classes="card"):
386
+ yield Label("Recover Deleted & Unsaved Files", classes="card-title")
387
+ with Horizontal(classes="action-item"):
388
+ yield Button("View Deleted Files", id="btn-trash-list")
389
+ yield Button("Find Unsaved Documents", id="btn-temp-rec")
390
+ yield Button("View Restore Snapshots", id="btn-shadows")
391
+ yield Label(
392
+ "Note: Inspects your Recycle Bin / Trash, Office & LibreOffice auto-recovery drafts, and OS restore snapshots.",
393
+ classes="action-desc",
394
+ )
395
+ yield Static(
396
+ "Choose a recovery option above to search for lost files.",
397
+ id="res-recovery",
398
+ classes="result-box",
399
+ )
400
+
401
+ with Vertical(id="tab-service", classes="tab-body"):
402
+ with Vertical(classes="card"):
403
+ yield Label("Microservice Connection", classes="card-title")
404
+ yield Input(
405
+ value=self.server_url or "http://127.0.0.1:8765",
406
+ placeholder="http://127.0.0.1:8765",
407
+ id="input-server-url",
408
+ )
409
+ with Horizontal(classes="action-item"):
410
+ yield Button("Check Service Health", id="btn-svc-health")
411
+ yield Button("Fetch System Profile", id="btn-svc-sysinfo")
412
+ yield Label(
413
+ "Note: Start the background service anytime by running 'sysmaint serve' in a terminal.",
414
+ classes="action-desc",
415
+ )
416
+ yield Static(
417
+ "Check whether the local SysMaint microservice is running.",
418
+ id="res-service",
419
+ classes="result-box",
420
+ )
421
+
422
+ with Vertical(id="activity-bar"):
423
+ with Horizontal(id="activity-top-row"):
424
+ yield LoadingIndicator(id="activity-spinner")
425
+ yield Static("Ready.", id="activity-status")
426
+ yield Static("", id="activity-percent")
427
+ yield ProgressBar(total=100, show_eta=False, id="activity-progress")
428
+ yield Static("", id="activity-live-line")
429
+
430
+ yield Footer()
431
+
432
+ def on_mount(self) -> None:
433
+ for theme_obj in CUSTOM_THEMES:
434
+ self.register_theme(theme_obj)
435
+ self._apply_theme("obsidian-gold")
436
+ self.action_refresh_metrics()
437
+ self.set_interval(5.0, self.action_refresh_metrics)
438
+
439
+ def _apply_theme(self, theme_name: str) -> None:
440
+ self.theme = theme_name
441
+ if theme_name == "amber-slate":
442
+ self.screen.add_class("solid-gold-buttons")
443
+ else:
444
+ self.screen.remove_class("solid-gold-buttons")
445
+
446
+ def on_tabs_tab_activated(self, event: Tabs.TabActivated) -> None:
447
+ if event.tab and event.tab.id:
448
+ self.query_one("#page-switcher", ContentSwitcher).current = event.tab.id
449
+
450
+ def action_open_log(self) -> None:
451
+ self.push_screen(TechnicalLogModal(self._log_entries))
452
+
453
+ def action_toggle_theme(self) -> None:
454
+ try:
455
+ idx = THEME_CYCLE.index(self.theme)
456
+ next_theme = THEME_CYCLE[(idx + 1) % len(THEME_CYCLE)]
457
+ except ValueError:
458
+ next_theme = THEME_CYCLE[0]
459
+ self._apply_theme(next_theme)
460
+ self.notify(f"Theme switched to: {next_theme}", title="Theme")
461
+
462
+ def _set_busy(self, busy: bool, message: str, live_line: str = "") -> None:
463
+ self._busy = busy
464
+ bar = self.query_one("#activity-bar", Vertical)
465
+ spinner = self.query_one("#activity-spinner", LoadingIndicator)
466
+ progress = self.query_one("#activity-progress", ProgressBar)
467
+ status = self.query_one("#activity-status", Static)
468
+ pct_lbl = self.query_one("#activity-percent", Static)
469
+ live = self.query_one("#activity-live-line", Static)
470
+
471
+ if busy:
472
+ bar.add_class("active")
473
+ spinner.add_class("active")
474
+ progress.add_class("active")
475
+ progress.update(total=None, progress=0)
476
+ pct_lbl.update("Running...")
477
+ else:
478
+ bar.remove_class("active")
479
+ spinner.remove_class("active")
480
+ progress.remove_class("active")
481
+ pct_lbl.update("")
482
+
483
+ status.update(message)
484
+ live.update(live_line)
485
+
486
+ def _update_live_progress(self, line: str, percent: float | None) -> None:
487
+ progress = self.query_one("#activity-progress", ProgressBar)
488
+ pct_lbl = self.query_one("#activity-percent", Static)
489
+ live = self.query_one("#activity-live-line", Static)
490
+ if percent is not None:
491
+ progress.update(total=100, progress=percent)
492
+ pct_lbl.update(f"{percent:.1f}%")
493
+ live.update(f"Live output: {line[:110]}")
494
+
495
+ def action_refresh_metrics(self) -> None:
496
+ cpu = psutil.cpu_percent(interval=None)
497
+ ram = psutil.virtual_memory().percent
498
+ root = "C:\\" if platform.system().lower() == "windows" else "/"
499
+ try:
500
+ dsk = psutil.disk_usage(root).percent
501
+ except OSError:
502
+ dsk = 0.0
503
+
504
+ priv = "Administrator / Root" if is_elevated() else "Standard User"
505
+ engine = self.server_url or "Local Standalone"
506
+ self.query_one("#bar-cpu", ProgressBar).update(progress=cpu)
507
+ self.query_one("#bar-ram", ProgressBar).update(progress=ram)
508
+ self.query_one("#bar-disk", ProgressBar).update(progress=dsk)
509
+ self.query_one("#val-cpu", Static).update(f"{cpu:.1f}% used")
510
+ self.query_one("#val-ram", Static).update(f"{ram:.1f}% used")
511
+ self.query_one("#val-disk", Static).update(f"{dsk:.1f}% used")
512
+ self.query_one("#sysinfo-summary", Static).update(
513
+ f"Device: {platform.node()} | OS: {platform.system()} {platform.release()} | "
514
+ f"Privileges: {priv} | Engine: {engine}"
515
+ )
516
+
517
+ def _finish_task(self, target_id: str, title: str, summary_renderable: Any, raw_data: Any) -> None:
518
+ self.query_one(f"#{target_id}", Static).update(summary_renderable)
519
+ self._log_entries.append((title, raw_data))
520
+ self._set_busy(False, "", "")
521
+ self.notify(f"Completed: {title} (press L for technical log)", title="Done")
522
+
523
+ def _launch_guarded_task(
524
+ self,
525
+ *,
526
+ title: str,
527
+ status_msg: str,
528
+ target_id: str,
529
+ fn: Callable[[Callable[[str, float | None], None]], tuple[Any, Any]],
530
+ requires_admin: bool = False,
531
+ long_estimate: str | None = None,
532
+ long_details: str = "",
533
+ ) -> None:
534
+ if self._busy:
535
+ self.notify(
536
+ "A background task is already running. Please wait for it to finish.",
537
+ title="Task in Progress",
538
+ severity="warning",
539
+ )
540
+ return
541
+
542
+ def start_after_confirm(confirmed: bool) -> None:
543
+ if not confirmed:
544
+ return
545
+ self._set_busy(True, status_msg, "Starting command...")
546
+ self._worker_exec(target_id, title, fn)
547
+
548
+ def check_long_or_run() -> None:
549
+ if long_estimate:
550
+ self.push_screen(
551
+ ConfirmLongTaskModal(title, long_estimate, long_details),
552
+ start_after_confirm,
553
+ )
554
+ else:
555
+ start_after_confirm(True)
556
+
557
+ if requires_admin and not is_elevated():
558
+ def on_elev_choice(choice: str) -> None:
559
+ if choice == "elevate":
560
+ ok = request_elevation(["tui"], exit_on_relaunch=True)
561
+ if not ok:
562
+ self.notify("Administrator elevation was cancelled.", severity="warning")
563
+ self.push_screen(ElevationModal(title), on_elev_choice)
564
+ return
565
+
566
+ check_long_or_run()
567
+
568
+ @work(thread=True)
569
+ def _worker_exec(
570
+ self,
571
+ target_id: str,
572
+ title: str,
573
+ fn: Callable[[Callable[[str, float | None], None]], tuple[Any, Any]],
574
+ ) -> None:
575
+ def report_progress(line: str, pct: float | None) -> None:
576
+ self.call_from_thread(self._update_live_progress, line, pct)
577
+
578
+ try:
579
+ summary, raw = fn(report_progress)
580
+ except Exception as exc:
581
+ summary = f"[red]Could not complete {title}:[/red] {exc}"
582
+ raw = {"error": str(exc)}
583
+ self.call_from_thread(self._finish_task, target_id, title, summary, raw)
584
+
585
+ def on_button_pressed(self, event: Button.Pressed) -> None:
586
+ bid = event.button.id
587
+ if bid == "btn-refresh":
588
+ self.action_refresh_metrics()
589
+ if not self._busy:
590
+ self.notify("Live telemetry refreshed.", title="Refreshed")
591
+ elif bid == "btn-open-log":
592
+ self.action_open_log()
593
+ elif bid == "btn-quick-scan":
594
+ self._launch_guarded_task(
595
+ title="Quick Scan",
596
+ status_msg="Running Quick Scan (checking disk, memory, and system health)...",
597
+ target_id="res-overview",
598
+ fn=self._task_quick_scan,
599
+ )
600
+ elif bid == "btn-integrity":
601
+ self._launch_guarded_task(
602
+ title="Check System Files",
603
+ status_msg="Checking core OS files (DISM & SFC)...",
604
+ target_id="res-repair",
605
+ fn=lambda cb: self._task_integrity(repair=False, cb=cb),
606
+ requires_admin=True,
607
+ long_estimate="5 to 25 minutes depending on disk speed",
608
+ long_details="Runs Windows DISM /ScanHealth and SFC /verifyonly (or Linux package verification) to check OS files without modifying them.",
609
+ )
610
+ elif bid == "btn-integrity-fix":
611
+ self._launch_guarded_task(
612
+ title="Fix System Files",
613
+ status_msg="Repairing corrupted OS files (DISM /RestoreHealth & SFC /scannow)...",
614
+ target_id="res-repair",
615
+ fn=lambda cb: self._task_integrity(repair=True, cb=cb),
616
+ requires_admin=True,
617
+ long_estimate="10 to 40 minutes depending on disk and network speed",
618
+ long_details="Runs Windows DISM /RestoreHealth and sfc /scannow to repair corrupted operating system files.",
619
+ )
620
+ elif bid == "btn-repair-dry":
621
+ self._launch_guarded_task(
622
+ title="Preview System Fixes",
623
+ status_msg="Preparing safe preview of system repairs...",
624
+ target_id="res-repair",
625
+ fn=self._task_repair_preview,
626
+ )
627
+ elif bid == "btn-net-check":
628
+ self._launch_guarded_task(
629
+ title="Test & Fix Network",
630
+ status_msg="Testing connectivity and flushing DNS cache...",
631
+ target_id="res-repair",
632
+ fn=self._task_net_check,
633
+ )
634
+ elif bid == "btn-sec-audit":
635
+ self._launch_guarded_task(
636
+ title="Check System Protection",
637
+ status_msg="Auditing firewall, antivirus, and protection status...",
638
+ target_id="res-security",
639
+ fn=self._task_sec_audit,
640
+ )
641
+ elif bid == "btn-malware-scan":
642
+ self._launch_guarded_task(
643
+ title="Scan for Viruses & Malware",
644
+ status_msg="Scanning Downloads, Temp, and Startup folders for threats...",
645
+ target_id="res-security",
646
+ fn=self._task_malware_scan,
647
+ long_estimate="2 to 15 minutes depending on Downloads/Temp folder size",
648
+ long_details="Scans high-risk folders offline using YARA threat rules and ClamAV (if installed).",
649
+ )
650
+ elif bid == "btn-trash-list":
651
+ self._launch_guarded_task(
652
+ title="View Deleted Files",
653
+ status_msg="Reading Recycle Bin / Trash contents...",
654
+ target_id="res-recovery",
655
+ fn=self._task_trash_list,
656
+ )
657
+ elif bid == "btn-temp-rec":
658
+ self._launch_guarded_task(
659
+ title="Find Unsaved Documents",
660
+ status_msg="Searching for unsaved Office, LibreOffice, and temp documents...",
661
+ target_id="res-recovery",
662
+ fn=self._task_temp_rec,
663
+ )
664
+ elif bid == "btn-shadows":
665
+ self._launch_guarded_task(
666
+ title="View Restore Snapshots",
667
+ status_msg="Checking available system restore snapshots...",
668
+ target_id="res-recovery",
669
+ fn=self._task_shadows,
670
+ requires_admin=True,
671
+ )
672
+ elif bid == "btn-svc-health":
673
+ url = self.query_one("#input-server-url", Input).value.strip().rstrip("/")
674
+ self._launch_guarded_task(
675
+ title="Check Service Health",
676
+ status_msg=f"Connecting to {url}/health...",
677
+ target_id="res-service",
678
+ fn=lambda cb: self._task_svc_get(url, "/health", cb),
679
+ )
680
+ elif bid == "btn-svc-sysinfo":
681
+ url = self.query_one("#input-server-url", Input).value.strip().rstrip("/")
682
+ self._launch_guarded_task(
683
+ title="Fetch System Profile",
684
+ status_msg=f"Fetching system profile from {url}/v1/sysinfo...",
685
+ target_id="res-service",
686
+ fn=lambda cb: self._task_svc_get(url, "/v1/sysinfo", cb),
687
+ )
688
+
689
+ def _task_quick_scan(self, cb: Callable[[str, float | None], None]) -> tuple[Any, Any]:
690
+ cb("Step 1/3: Checking memory usage...", 25.0)
691
+ mem = memory.check_memory()
692
+ cb("Step 2/3: Checking disk partitions...", 60.0)
693
+ dsk = disk.check_disk(repair=False)
694
+ cb("Step 3/3: Running smart health summary...", 90.0)
695
+ if self.server_url:
696
+ data = httpx.get(f"{self.server_url}/v1/smart-scan", timeout=30.0).json()
697
+ else:
698
+ data = optimizer.run_smart_scan(self.cfg)
699
+ cb("Quick Scan complete.", 100.0)
700
+ table = Table(title="Quick Scan Summary", expand=True)
701
+ table.add_column("Area", style="cyan")
702
+ table.add_column("Status", style="green")
703
+ table.add_row("Memory Usage", f"{mem.get('percent_used', 'N/A')}% used")
704
+ table.add_row("Disk Check", str(dsk.get("status", dsk.get("tool", "Checked"))))
705
+ table.add_row("Overall Scan", "Completed safely (no files modified)")
706
+ return table, {"smart_scan": data, "memory": mem, "disk": dsk}
707
+
708
+ def _task_integrity(self, repair: bool, cb: Callable[[str, float | None], None]) -> tuple[Any, Any]:
709
+ res = integrity.check_integrity(repair=repair, progress_cb=cb)
710
+ status = res.get("status", "Checked")
711
+ msg = f"[bold cyan]System File Status:[/bold cyan] {status}\nPress [bold]L[/bold] (View Technical Log) for full DISM/SFC output."
712
+ return msg, res
713
+
714
+ def _task_repair_preview(self, cb: Callable[[str, float | None], None]) -> tuple[Any, Any]:
715
+ cb("Generating dry-run repair plan...", 50.0)
716
+ net_preview = network.reset_network_stack(dry_run=True)
717
+ res = {
718
+ "dry_run": True,
719
+ "disk": "chkdsk /scan (Windows) or fsck -n (Linux)",
720
+ "system_files": "DISM /RestoreHealth + sfc /scannow",
721
+ "network": net_preview,
722
+ }
723
+ cb("Preview ready.", 100.0)
724
+ table = Table(title="Planned Repairs (Preview Only — Nothing Changed)", expand=True)
725
+ table.add_column("Repair Step", style="yellow")
726
+ table.add_column("Action")
727
+ table.add_row("Disk Check", res["disk"])
728
+ table.add_row("System Files", res["system_files"])
729
+ table.add_row("Network Reset", ", ".join(net_preview.get("commands", ["NetworkManager restart"])))
730
+ return table, res
731
+
732
+ def _task_net_check(self, cb: Callable[[str, float | None], None]) -> tuple[Any, Any]:
733
+ cb("Step 1/2: Pinging 1.1.1.1...", 40.0)
734
+ ping_res = network.test_connectivity("1.1.1.1")
735
+ cb("Step 2/2: Flushing DNS resolver cache...", 85.0)
736
+ dns_res = network.flush_dns()
737
+ cb("Network check complete.", 100.0)
738
+ msg = (
739
+ f"[bold cyan]Internet Ping (1.1.1.1):[/bold cyan] "
740
+ f"{'Reachable' if ping_res.get('reachable', True) else 'Unreachable'}\n"
741
+ f"[bold cyan]DNS Cache:[/bold cyan] {dns_res.get('message', 'Flushed')}"
742
+ )
743
+ return msg, {"ping": ping_res, "dns_flush": dns_res}
744
+
745
+ def _task_sec_audit(self, cb: Callable[[str, float | None], None]) -> tuple[Any, Any]:
746
+ cb("Inspecting firewall, antivirus, and privilege state...", 50.0)
747
+ res = security.audit_security_posture()
748
+ cb("Audit complete.", 100.0)
749
+ table = Table(title="System Protection Status", expand=True)
750
+ table.add_column("Check", style="cyan")
751
+ table.add_column("Result")
752
+ for key, val in res.items():
753
+ table.add_row(str(key).replace("_", " ").title(), str(val))
754
+ return table, res
755
+
756
+ def _task_malware_scan(self, cb: Callable[[str, float | None], None]) -> tuple[Any, Any]:
757
+ cb("Scanning Downloads, Temp, and Startup folders offline...", None)
758
+ res = malware.scan(self.cfg.malware, offline=True, quick_scan=True)
759
+ threats = res.get("threats_found", res.get("infected_count", 0))
760
+ cb("Malware scan complete.", 100.0)
761
+ msg = (
762
+ f"[bold cyan]Scan Finished:[/bold cyan] {threats} potential threat(s) flagged.\n"
763
+ "Press [bold]L[/bold] to inspect scanned paths and engine details."
764
+ )
765
+ return msg, res
766
+
767
+ def _task_trash_list(self, cb: Callable[[str, float | None], None]) -> tuple[Any, Any]:
768
+ cb("Listing Recycle Bin / Trash items...", 50.0)
769
+ res = recovery.list_trash_items(limit=25)
770
+ items = res.get("items", [])
771
+ cb("Done.", 100.0)
772
+ if not items:
773
+ return "Your Recycle Bin / Trash is currently empty.", res
774
+ table = Table(title=f"Deleted Files Found ({len(items)})", expand=True)
775
+ table.add_column("Name", style="cyan")
776
+ table.add_column("Size")
777
+ table.add_column("Deleted Date")
778
+ for item in items[:15]:
779
+ table.add_row(item.get("name", ""), item.get("size_formatted", ""), item.get("deleted_date", ""))
780
+ return table, res
781
+
782
+ def _task_temp_rec(self, cb: Callable[[str, float | None], None]) -> tuple[Any, Any]:
783
+ cb("Scanning Office, LibreOffice, and temp auto-recovery folders...", 50.0)
784
+ res = recovery.scan_recoverable_temp_files(limit=25)
785
+ files = res.get("files", [])
786
+ cb("Done.", 100.0)
787
+ if not files:
788
+ return "No unsaved Office or temp draft files were found.", res
789
+ table = Table(title=f"Recoverable Drafts Found ({len(files)})", expand=True)
790
+ table.add_column("File", style="cyan")
791
+ table.add_column("Size")
792
+ table.add_column("Modified")
793
+ for f in files[:15]:
794
+ table.add_row(f.get("name", ""), f.get("size_formatted", ""), f.get("modified", ""))
795
+ return table, res
796
+
797
+ def _task_shadows(self, cb: Callable[[str, float | None], None]) -> tuple[Any, Any]:
798
+ cb("Querying system restore snapshots...", 50.0)
799
+ res = recovery.list_shadow_copies()
800
+ count = res.get("count", 0)
801
+ note = res.get("note", "")
802
+ cb("Done.", 100.0)
803
+ msg = f"[bold cyan]Restore Snapshots Found:[/bold cyan] {count}\n{note}"
804
+ return msg, res
805
+
806
+ def _task_svc_get(
807
+ self,
808
+ base_url: str,
809
+ path: str,
810
+ cb: Callable[[str, float | None], None],
811
+ ) -> tuple[Any, Any]:
812
+ cb(f"Requesting {base_url}{path}...", 50.0)
813
+ try:
814
+ resp = httpx.get(f"{base_url}{path}", timeout=5.0)
815
+ data = resp.json()
816
+ cb("Connected.", 100.0)
817
+ return f"[green]Connected to {base_url}{path}[/green] (HTTP {resp.status_code}). Press L for JSON payload.", data
818
+ except Exception as exc:
819
+ err = {
820
+ "error": f"Could not reach {base_url}{path}: {exc}",
821
+ "hint": "Start the background service with: sysmaint serve",
822
+ }
823
+ cb("Service unreachable.", 100.0)
824
+ return f"[yellow]Service is not running at {base_url}.[/yellow]\nStart it in a terminal with: [bold]sysmaint serve[/bold]", err
825
+
826
+
827
+ def launch_tui(config: SysMaintConfig | None = None, server_url: str | None = None) -> None:
828
+ """Launch the SysMaint Terminal Client UI."""
829
+ app = SysMaintTUI(config=config, server_url=server_url)
830
+ app.run()