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.
- sysmaint/__init__.py +17 -0
- sysmaint/__main__.py +6 -0
- sysmaint/cli.py +637 -0
- sysmaint/config.py +229 -0
- sysmaint/gui/__init__.py +5 -0
- sysmaint/gui/app.py +193 -0
- sysmaint/gui/components/__init__.py +13 -0
- sysmaint/gui/components/cards.py +239 -0
- sysmaint/gui/components/console.py +61 -0
- sysmaint/gui/components/dialogs.py +79 -0
- sysmaint/gui/theme.py +52 -0
- sysmaint/gui/views/__init__.py +25 -0
- sysmaint/gui/views/backup.py +167 -0
- sysmaint/gui/views/cleaner.py +227 -0
- sysmaint/gui/views/dashboard.py +252 -0
- sysmaint/gui/views/diagnostics.py +243 -0
- sysmaint/gui/views/integrity.py +158 -0
- sysmaint/gui/views/malware.py +293 -0
- sysmaint/gui/views/network.py +171 -0
- sysmaint/gui/views/security.py +118 -0
- sysmaint/gui/views/settings.py +211 -0
- sysmaint/gui/views/startup.py +133 -0
- sysmaint/logging_setup.py +62 -0
- sysmaint/modules/__init__.py +41 -0
- sysmaint/modules/backup.py +106 -0
- sysmaint/modules/cleaner.py +249 -0
- sysmaint/modules/disk.py +160 -0
- sysmaint/modules/drivers.py +89 -0
- sysmaint/modules/integrity.py +148 -0
- sysmaint/modules/malware.py +412 -0
- sysmaint/modules/memory.py +105 -0
- sysmaint/modules/network.py +167 -0
- sysmaint/modules/optimizer.py +186 -0
- sysmaint/modules/recovery.py +353 -0
- sysmaint/modules/report.py +232 -0
- sysmaint/modules/restore.py +123 -0
- sysmaint/modules/scheduler.py +137 -0
- sysmaint/modules/security.py +88 -0
- sysmaint/modules/services.py +171 -0
- sysmaint/modules/startup.py +95 -0
- sysmaint/modules/sysinfo.py +112 -0
- sysmaint/service/__init__.py +5 -0
- sysmaint/service/server.py +210 -0
- sysmaint/tui/__init__.py +5 -0
- sysmaint/tui/app.py +830 -0
- sysmaint/tui/modals.py +201 -0
- sysmaint/tui/themes.py +97 -0
- sysmaint/utils/__init__.py +39 -0
- sysmaint/utils/common.py +255 -0
- sysmaint/utils/escalate.py +93 -0
- sysmaint/utils/linux.py +240 -0
- sysmaint/utils/parsers.py +171 -0
- sysmaint/utils/windows.py +308 -0
- sysmaint-0.1.0.dist-info/METADATA +307 -0
- sysmaint-0.1.0.dist-info/RECORD +57 -0
- sysmaint-0.1.0.dist-info/WHEEL +4 -0
- sysmaint-0.1.0.dist-info/entry_points.txt +5 -0
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
# sysmaint/modules/optimizer.py
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from ..config import SysMaintConfig
|
|
9
|
+
from .backup import create_backup
|
|
10
|
+
from .cleaner import clean_junk, scan_junk
|
|
11
|
+
from .disk import get_disk_partitions
|
|
12
|
+
from .memory import check_memory, optimize_memory
|
|
13
|
+
from .network import flush_dns
|
|
14
|
+
from .security import audit_security_posture
|
|
15
|
+
from .services import ensure_expected_services, list_services
|
|
16
|
+
|
|
17
|
+
logger = logging.getLogger("sysmaint.optimizer")
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def run_smart_scan(config: SysMaintConfig) -> dict[str, Any]:
|
|
21
|
+
"""
|
|
22
|
+
Perform a unified, non-destructive Smart Health Scan across all system areas.
|
|
23
|
+
|
|
24
|
+
Returns:
|
|
25
|
+
Comprehensive health report with a 0-100 System Health Score and actionable findings.
|
|
26
|
+
"""
|
|
27
|
+
logger.info("Starting 1-Click Smart System Health Scan")
|
|
28
|
+
findings: list[dict[str, Any]] = []
|
|
29
|
+
score = 100
|
|
30
|
+
|
|
31
|
+
# 1. Disk Space & Partitions
|
|
32
|
+
partitions = get_disk_partitions()
|
|
33
|
+
for part in partitions:
|
|
34
|
+
if part.get("percent", 0) > 90.0:
|
|
35
|
+
findings.append({
|
|
36
|
+
"category": "Disk",
|
|
37
|
+
"severity": "High",
|
|
38
|
+
"title": f"Drive {part.get('device')} is nearly full ({part.get('percent')}%)",
|
|
39
|
+
"fixable": True,
|
|
40
|
+
"action": "clean_junk",
|
|
41
|
+
})
|
|
42
|
+
score -= 15
|
|
43
|
+
elif part.get("percent", 0) > 80.0:
|
|
44
|
+
findings.append({
|
|
45
|
+
"category": "Disk",
|
|
46
|
+
"severity": "Medium",
|
|
47
|
+
"title": f"Drive {part.get('device')} has low storage space ({part.get('percent')}%)",
|
|
48
|
+
"fixable": True,
|
|
49
|
+
"action": "clean_junk",
|
|
50
|
+
})
|
|
51
|
+
score -= 5
|
|
52
|
+
|
|
53
|
+
# 2. Memory Pressure
|
|
54
|
+
mem_info = check_memory()
|
|
55
|
+
if mem_info.get("percent", 0) > 85.0:
|
|
56
|
+
findings.append({
|
|
57
|
+
"category": "Memory",
|
|
58
|
+
"severity": "Medium",
|
|
59
|
+
"title": f"High RAM usage ({mem_info.get('percent')}%) - cache trimming recommended",
|
|
60
|
+
"fixable": True,
|
|
61
|
+
"action": "optimize_memory",
|
|
62
|
+
})
|
|
63
|
+
score -= 10
|
|
64
|
+
|
|
65
|
+
# 3. Junk Files & Temporary Data
|
|
66
|
+
junk_info = scan_junk()
|
|
67
|
+
if junk_info.get("total_bytes", 0) > 500 * 1024 * 1024: # > 500 MB
|
|
68
|
+
findings.append({
|
|
69
|
+
"category": "Cleaner",
|
|
70
|
+
"severity": "Medium",
|
|
71
|
+
"title": f"Found {junk_info.get('total_bytes_formatted')} of junk files ({junk_info.get('total_files')} files)",
|
|
72
|
+
"fixable": True,
|
|
73
|
+
"action": "clean_junk",
|
|
74
|
+
"data": junk_info,
|
|
75
|
+
})
|
|
76
|
+
score -= 10
|
|
77
|
+
elif junk_info.get("total_bytes", 0) > 50 * 1024 * 1024: # > 50 MB
|
|
78
|
+
findings.append({
|
|
79
|
+
"category": "Cleaner",
|
|
80
|
+
"severity": "Low",
|
|
81
|
+
"title": f"Found {junk_info.get('total_bytes_formatted')} of temporary cache files",
|
|
82
|
+
"fixable": True,
|
|
83
|
+
"action": "clean_junk",
|
|
84
|
+
"data": junk_info,
|
|
85
|
+
})
|
|
86
|
+
score -= 5
|
|
87
|
+
|
|
88
|
+
# 4. Services
|
|
89
|
+
services = list_services()
|
|
90
|
+
failed_services = [s for s in services if not s.get("healthy", True)]
|
|
91
|
+
if failed_services:
|
|
92
|
+
findings.append({
|
|
93
|
+
"category": "Services",
|
|
94
|
+
"severity": "High",
|
|
95
|
+
"title": f"Found {len(failed_services)} failed or stopped service(s)",
|
|
96
|
+
"fixable": True,
|
|
97
|
+
"action": "restart_services",
|
|
98
|
+
"details": [s.get("name") for s in failed_services[:5]],
|
|
99
|
+
})
|
|
100
|
+
score -= 15
|
|
101
|
+
|
|
102
|
+
# 5. Security Posture
|
|
103
|
+
sec_info = audit_security_posture()
|
|
104
|
+
for issue in sec_info.get("issues", []):
|
|
105
|
+
findings.append({
|
|
106
|
+
"category": "Security",
|
|
107
|
+
"severity": "High" if "Disabled" in issue or "OFF" in issue else "Medium",
|
|
108
|
+
"title": issue,
|
|
109
|
+
"fixable": False,
|
|
110
|
+
})
|
|
111
|
+
score -= 10
|
|
112
|
+
|
|
113
|
+
# Final Score Normalization
|
|
114
|
+
final_score = max(0, min(100, score))
|
|
115
|
+
if final_score >= 90:
|
|
116
|
+
health_grade = "Excellent"
|
|
117
|
+
elif final_score >= 75:
|
|
118
|
+
health_grade = "Good"
|
|
119
|
+
elif final_score >= 50:
|
|
120
|
+
health_grade = "Fair"
|
|
121
|
+
else:
|
|
122
|
+
health_grade = "Critical"
|
|
123
|
+
|
|
124
|
+
return {
|
|
125
|
+
"health_score": final_score,
|
|
126
|
+
"health_grade": health_grade,
|
|
127
|
+
"total_issues": len(findings),
|
|
128
|
+
"fixable_issues": len([f for f in findings if f.get("fixable")]),
|
|
129
|
+
"findings": findings,
|
|
130
|
+
"memory_summary": {
|
|
131
|
+
"used_formatted": mem_info.get("used_formatted"),
|
|
132
|
+
"total_formatted": mem_info.get("total_formatted"),
|
|
133
|
+
"percent": mem_info.get("percent"),
|
|
134
|
+
},
|
|
135
|
+
"junk_summary": {
|
|
136
|
+
"reclaimable_bytes": junk_info.get("total_bytes"),
|
|
137
|
+
"reclaimable_formatted": junk_info.get("total_bytes_formatted"),
|
|
138
|
+
"file_count": junk_info.get("total_files"),
|
|
139
|
+
},
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def run_auto_fix(
|
|
144
|
+
config: SysMaintConfig,
|
|
145
|
+
create_restore: bool = True,
|
|
146
|
+
) -> dict[str, Any]:
|
|
147
|
+
"""
|
|
148
|
+
Execute 1-Click Auto-Fix for all detected fixable issues.
|
|
149
|
+
|
|
150
|
+
Args:
|
|
151
|
+
config: SysMaintConfig instance.
|
|
152
|
+
create_restore: Whether to create a backup / restore point before fixing.
|
|
153
|
+
|
|
154
|
+
Returns:
|
|
155
|
+
Summary of executed repair operations and updated health state.
|
|
156
|
+
"""
|
|
157
|
+
logger.info("Executing 1-Click Auto-Fix")
|
|
158
|
+
results: dict[str, Any] = {}
|
|
159
|
+
|
|
160
|
+
# 1. Automatic Restore Point Creation
|
|
161
|
+
if create_restore and config.repair.auto_create_restore_point:
|
|
162
|
+
try:
|
|
163
|
+
results["backup"] = create_backup(config, kind="auto", description="SysMaint Pre-Optimization Point")
|
|
164
|
+
except Exception as exc:
|
|
165
|
+
results["backup"] = {"created": False, "error": str(exc)}
|
|
166
|
+
|
|
167
|
+
# 2. Clean Junk Files
|
|
168
|
+
results["cleaner"] = clean_junk(dry_run=False)
|
|
169
|
+
|
|
170
|
+
# 3. Optimize Memory
|
|
171
|
+
results["memory"] = optimize_memory()
|
|
172
|
+
|
|
173
|
+
# 4. Flush DNS Cache
|
|
174
|
+
results["network"] = flush_dns()
|
|
175
|
+
|
|
176
|
+
# 5. Ensure Expected Services
|
|
177
|
+
if config.services.enable and config.services.expected_services:
|
|
178
|
+
results["services"] = ensure_expected_services(config.services.expected_services)
|
|
179
|
+
|
|
180
|
+
# Re-evaluate health score
|
|
181
|
+
new_scan = run_smart_scan(config)
|
|
182
|
+
results["new_health_score"] = new_scan["health_score"]
|
|
183
|
+
results["new_health_grade"] = new_scan["health_grade"]
|
|
184
|
+
results["remaining_issues"] = new_scan["total_issues"]
|
|
185
|
+
|
|
186
|
+
return results
|
|
@@ -0,0 +1,353 @@
|
|
|
1
|
+
# src/sysmaint/modules/recovery.py
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
import os
|
|
7
|
+
import platform
|
|
8
|
+
import re
|
|
9
|
+
import shutil
|
|
10
|
+
from datetime import datetime
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
from ..utils.common import format_bytes, run_command
|
|
15
|
+
|
|
16
|
+
logger = logging.getLogger("sysmaint.recovery")
|
|
17
|
+
|
|
18
|
+
# Magic byte signatures for safe read-only file carving
|
|
19
|
+
FILE_SIGNATURES: dict[str, dict[str, Any]] = {
|
|
20
|
+
"pdf": {
|
|
21
|
+
"header": b"%PDF-",
|
|
22
|
+
"footer": b"%%EOF",
|
|
23
|
+
"ext": ".pdf",
|
|
24
|
+
"max_size": 25 * 1024 * 1024,
|
|
25
|
+
},
|
|
26
|
+
"png": {
|
|
27
|
+
"header": b"\x89PNG\r\n\x1a\n",
|
|
28
|
+
"footer": b"IEND\xaeB`\x82",
|
|
29
|
+
"ext": ".png",
|
|
30
|
+
"max_size": 15 * 1024 * 1024,
|
|
31
|
+
},
|
|
32
|
+
"jpg": {
|
|
33
|
+
"header": b"\xff\xd8\xff",
|
|
34
|
+
"footer": b"\xff\xd9",
|
|
35
|
+
"ext": ".jpg",
|
|
36
|
+
"max_size": 15 * 1024 * 1024,
|
|
37
|
+
},
|
|
38
|
+
"zip": {
|
|
39
|
+
"header": b"PK\x03\x04",
|
|
40
|
+
"footer": None,
|
|
41
|
+
"ext": ".zip",
|
|
42
|
+
"max_size": 25 * 1024 * 1024,
|
|
43
|
+
},
|
|
44
|
+
"sqlite": {
|
|
45
|
+
"header": b"SQLite format 3\x00",
|
|
46
|
+
"footer": None,
|
|
47
|
+
"ext": ".sqlite",
|
|
48
|
+
"max_size": 25 * 1024 * 1024,
|
|
49
|
+
},
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def list_trash_items(limit: int = 50) -> dict[str, Any]:
|
|
54
|
+
"""List recently deleted items in the OS Recycle Bin (Windows) or Trash (Linux)."""
|
|
55
|
+
system = platform.system().lower()
|
|
56
|
+
items: list[dict[str, Any]] = []
|
|
57
|
+
|
|
58
|
+
if system == "windows":
|
|
59
|
+
from ..utils.windows import run_powershell
|
|
60
|
+
|
|
61
|
+
script = (
|
|
62
|
+
"$shell = New-Object -ComObject Shell.Application; "
|
|
63
|
+
"$bin = $shell.NameSpace(10); "
|
|
64
|
+
f"$bin.Items() | Select-Object -First {int(limit)} | ForEach-Object {{ "
|
|
65
|
+
"[PSCustomObject]@{ "
|
|
66
|
+
"Name = $_.Name; "
|
|
67
|
+
"OriginalPath = $bin.GetDetailsOf($_, 1); "
|
|
68
|
+
"DeletedDate = $bin.GetDetailsOf($_, 2); "
|
|
69
|
+
"Size = $_.Size; "
|
|
70
|
+
"Path = $_.Path "
|
|
71
|
+
"} } | ConvertTo-Json"
|
|
72
|
+
)
|
|
73
|
+
data = run_powershell(script, as_json=True)
|
|
74
|
+
if isinstance(data, dict):
|
|
75
|
+
data = [data]
|
|
76
|
+
if isinstance(data, list):
|
|
77
|
+
for entry in data:
|
|
78
|
+
if isinstance(entry, dict):
|
|
79
|
+
size = int(entry.get("Size") or 0)
|
|
80
|
+
items.append(
|
|
81
|
+
{
|
|
82
|
+
"name": entry.get("Name", ""),
|
|
83
|
+
"original_path": entry.get("OriginalPath", ""),
|
|
84
|
+
"deleted_date": entry.get("DeletedDate", ""),
|
|
85
|
+
"size": size,
|
|
86
|
+
"size_formatted": format_bytes(size),
|
|
87
|
+
"trash_path": entry.get("Path", ""),
|
|
88
|
+
}
|
|
89
|
+
)
|
|
90
|
+
return {"platform": "windows", "count": len(items), "items": items}
|
|
91
|
+
|
|
92
|
+
# Linux FreeDesktop Trash (~/.local/share/Trash)
|
|
93
|
+
trash_root = Path.home() / ".local" / "share" / "Trash"
|
|
94
|
+
info_dir = trash_root / "info"
|
|
95
|
+
files_dir = trash_root / "files"
|
|
96
|
+
|
|
97
|
+
if info_dir.is_dir():
|
|
98
|
+
for info_file in sorted(info_dir.glob("*.trashinfo"))[:limit]:
|
|
99
|
+
try:
|
|
100
|
+
content = info_file.read_text(encoding="utf-8", errors="replace")
|
|
101
|
+
orig_match = re.search(r"^Path=(.+)$", content, re.MULTILINE)
|
|
102
|
+
date_match = re.search(r"^DeletionDate=(.+)$", content, re.MULTILINE)
|
|
103
|
+
item_name = info_file.stem
|
|
104
|
+
file_path = files_dir / item_name
|
|
105
|
+
size = file_path.stat().st_size if file_path.is_file() else 0
|
|
106
|
+
items.append(
|
|
107
|
+
{
|
|
108
|
+
"name": item_name,
|
|
109
|
+
"original_path": orig_match.group(1).strip() if orig_match else "",
|
|
110
|
+
"deleted_date": date_match.group(1).strip() if date_match else "",
|
|
111
|
+
"size": size,
|
|
112
|
+
"size_formatted": format_bytes(size),
|
|
113
|
+
"trash_path": str(file_path),
|
|
114
|
+
}
|
|
115
|
+
)
|
|
116
|
+
except OSError as exc:
|
|
117
|
+
logger.debug("Skipping trash info %s: %s", info_file, exc)
|
|
118
|
+
|
|
119
|
+
return {"platform": system, "count": len(items), "items": items}
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def restore_trash_item(
|
|
123
|
+
name: str,
|
|
124
|
+
destination: Path | None = None,
|
|
125
|
+
dry_run: bool = False,
|
|
126
|
+
) -> dict[str, Any]:
|
|
127
|
+
"""Restore a deleted file or folder from Recycle Bin / Trash to its original or custom path."""
|
|
128
|
+
if not name:
|
|
129
|
+
return {"error": "Item name is required for trash recovery."}
|
|
130
|
+
|
|
131
|
+
trash_listing = list_trash_items(limit=200)
|
|
132
|
+
matches = [
|
|
133
|
+
item
|
|
134
|
+
for item in trash_listing.get("items", [])
|
|
135
|
+
if item.get("name", "").lower() == name.lower()
|
|
136
|
+
or Path(item.get("original_path", "")).name.lower() == name.lower()
|
|
137
|
+
]
|
|
138
|
+
|
|
139
|
+
if not matches:
|
|
140
|
+
return {"error": f"No item matching '{name}' found in Recycle Bin / Trash."}
|
|
141
|
+
|
|
142
|
+
target = matches[0]
|
|
143
|
+
src = Path(target["trash_path"])
|
|
144
|
+
if not src.exists():
|
|
145
|
+
return {"error": f"Trash backing file does not exist: {src}"}
|
|
146
|
+
|
|
147
|
+
if destination:
|
|
148
|
+
dest_path = Path(destination) / target["name"] if Path(destination).is_dir() else Path(destination)
|
|
149
|
+
else:
|
|
150
|
+
orig_dir = target.get("original_path") or str(Path.home() / "Recovered")
|
|
151
|
+
dest_path = Path(orig_dir) / target["name"]
|
|
152
|
+
|
|
153
|
+
if dry_run:
|
|
154
|
+
return {
|
|
155
|
+
"dry_run": True,
|
|
156
|
+
"action": "restore_trash_item",
|
|
157
|
+
"source": str(src),
|
|
158
|
+
"destination": str(dest_path),
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
dest_path.parent.mkdir(parents=True, exist_ok=True)
|
|
162
|
+
if src.is_dir():
|
|
163
|
+
shutil.copytree(src, dest_path, dirs_exist_ok=True)
|
|
164
|
+
else:
|
|
165
|
+
shutil.copy2(src, dest_path)
|
|
166
|
+
|
|
167
|
+
return {
|
|
168
|
+
"status": "restored",
|
|
169
|
+
"name": target["name"],
|
|
170
|
+
"restored_to": str(dest_path),
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def list_shadow_copies() -> dict[str, Any]:
|
|
175
|
+
"""List Volume Shadow Copies (Windows) or filesystem snapshots (Linux)."""
|
|
176
|
+
system = platform.system().lower()
|
|
177
|
+
if system == "windows":
|
|
178
|
+
res = run_command(["vssadmin", "list", "shadows"], check=False)
|
|
179
|
+
shadows: list[dict[str, str]] = []
|
|
180
|
+
current: dict[str, str] = {}
|
|
181
|
+
for line in res.stdout.splitlines():
|
|
182
|
+
stripped = line.strip()
|
|
183
|
+
if stripped.startswith("Contents of shadow copy set ID:"):
|
|
184
|
+
if current:
|
|
185
|
+
shadows.append(current)
|
|
186
|
+
current = {}
|
|
187
|
+
current["set_id"] = stripped.split(":", 1)[1].strip()
|
|
188
|
+
elif stripped.startswith("Shadow Copy ID:"):
|
|
189
|
+
current["shadow_id"] = stripped.split(":", 1)[1].strip()
|
|
190
|
+
elif stripped.startswith("Original Volume:"):
|
|
191
|
+
current["volume"] = stripped.split(":", 1)[1].strip()
|
|
192
|
+
elif stripped.startswith("Shadow Copy Volume:"):
|
|
193
|
+
current["shadow_volume"] = stripped.split(":", 1)[1].strip()
|
|
194
|
+
elif stripped.startswith(("Creation Time:", "creation time:")):
|
|
195
|
+
current["created_at"] = stripped.split(":", 1)[1].strip()
|
|
196
|
+
if current:
|
|
197
|
+
shadows.append(current)
|
|
198
|
+
|
|
199
|
+
return {
|
|
200
|
+
"platform": "windows",
|
|
201
|
+
"count": len(shadows),
|
|
202
|
+
"shadows": shadows,
|
|
203
|
+
"raw_returncode": res.returncode,
|
|
204
|
+
"note": (
|
|
205
|
+
"Administrator privileges are required to query VSS."
|
|
206
|
+
if res.returncode != 0 and not shadows
|
|
207
|
+
else "Use mklink /d C:\\ShadowMount <shadow_volume>\\ to browse a shadow copy."
|
|
208
|
+
),
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
# Linux: check timeshift or btrfs
|
|
212
|
+
if shutil.which("timeshift"):
|
|
213
|
+
res = run_command(["timeshift", "--list"], check=False)
|
|
214
|
+
return {"platform": "linux", "tool": "timeshift", "output": res.stdout[:3000]}
|
|
215
|
+
if shutil.which("btrfs"):
|
|
216
|
+
res = run_command(["btrfs", "subvolume", "list", "/"], check=False)
|
|
217
|
+
return {"platform": "linux", "tool": "btrfs", "output": res.stdout[:3000]}
|
|
218
|
+
|
|
219
|
+
return {"platform": system, "count": 0, "shadows": [], "note": "No snapshot tool detected."}
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def scan_recoverable_temp_files(limit: int = 50) -> dict[str, Any]:
|
|
223
|
+
"""Scan common application auto-recovery and temp backup locations for unsaved drafts."""
|
|
224
|
+
candidates: list[Path] = []
|
|
225
|
+
home = Path.home()
|
|
226
|
+
|
|
227
|
+
if platform.system().lower() == "windows":
|
|
228
|
+
appdata = Path(os.environ.get("APPDATA", home / "AppData" / "Roaming"))
|
|
229
|
+
local = Path(os.environ.get("LOCALAPPDATA", home / "AppData" / "Local"))
|
|
230
|
+
candidates.extend(
|
|
231
|
+
[
|
|
232
|
+
appdata / "Microsoft" / "Word",
|
|
233
|
+
appdata / "Microsoft" / "Excel",
|
|
234
|
+
appdata / "Microsoft" / "PowerPoint",
|
|
235
|
+
local / "Microsoft" / "Office" / "UnsavedFiles",
|
|
236
|
+
local / "Temp",
|
|
237
|
+
]
|
|
238
|
+
)
|
|
239
|
+
else:
|
|
240
|
+
candidates.extend(
|
|
241
|
+
[
|
|
242
|
+
home / ".config" / "libreoffice" / "4" / "user" / "backup",
|
|
243
|
+
Path("/tmp"),
|
|
244
|
+
]
|
|
245
|
+
)
|
|
246
|
+
|
|
247
|
+
recovery_exts = {".asd", ".wbk", ".tmp", ".bak", ".autosave", ".swp"}
|
|
248
|
+
found: list[dict[str, Any]] = []
|
|
249
|
+
|
|
250
|
+
for folder in candidates:
|
|
251
|
+
if not folder.is_dir():
|
|
252
|
+
continue
|
|
253
|
+
try:
|
|
254
|
+
for entry in folder.iterdir():
|
|
255
|
+
if len(found) >= limit:
|
|
256
|
+
break
|
|
257
|
+
if entry.is_file() and (
|
|
258
|
+
entry.suffix.lower() in recovery_exts or entry.name.startswith("~$")
|
|
259
|
+
):
|
|
260
|
+
stat = entry.stat()
|
|
261
|
+
found.append(
|
|
262
|
+
{
|
|
263
|
+
"name": entry.name,
|
|
264
|
+
"path": str(entry),
|
|
265
|
+
"size": stat.st_size,
|
|
266
|
+
"size_formatted": format_bytes(stat.st_size),
|
|
267
|
+
"modified": datetime.fromtimestamp(stat.st_mtime).isoformat(
|
|
268
|
+
timespec="seconds"
|
|
269
|
+
),
|
|
270
|
+
}
|
|
271
|
+
)
|
|
272
|
+
except OSError:
|
|
273
|
+
continue
|
|
274
|
+
|
|
275
|
+
return {"count": len(found), "files": found}
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
def carve_recoverable_files(
|
|
279
|
+
source_path: Path,
|
|
280
|
+
output_dir: Path,
|
|
281
|
+
file_types: list[str] | None = None,
|
|
282
|
+
max_files: int = 50,
|
|
283
|
+
dry_run: bool = False,
|
|
284
|
+
) -> dict[str, Any]:
|
|
285
|
+
"""
|
|
286
|
+
Safely scan a binary disk image or raw file for known file signatures and carve them
|
|
287
|
+
into a separate output directory (read-only on source).
|
|
288
|
+
"""
|
|
289
|
+
src = Path(source_path)
|
|
290
|
+
out = Path(output_dir)
|
|
291
|
+
|
|
292
|
+
if not src.exists() or not src.is_file():
|
|
293
|
+
return {"error": f"Source must be an existing file or raw disk image: {src}"}
|
|
294
|
+
|
|
295
|
+
if out.resolve() == src.parent.resolve() and src.suffix.lower() in {".img", ".dd", ".raw"}:
|
|
296
|
+
return {
|
|
297
|
+
"error": "Safety block: output_dir must be in a separate directory from the disk image."
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
selected_types = [t.lower() for t in (file_types or list(FILE_SIGNATURES.keys()))]
|
|
301
|
+
active_sigs = {k: v for k, v in FILE_SIGNATURES.items() if k in selected_types}
|
|
302
|
+
if not active_sigs:
|
|
303
|
+
return {"error": f"No valid file types selected. Choose from: {list(FILE_SIGNATURES)}"}
|
|
304
|
+
|
|
305
|
+
data = src.read_bytes()
|
|
306
|
+
carved: list[dict[str, Any]] = []
|
|
307
|
+
|
|
308
|
+
if not dry_run:
|
|
309
|
+
out.mkdir(parents=True, exist_ok=True)
|
|
310
|
+
|
|
311
|
+
for sig_name, spec in active_sigs.items():
|
|
312
|
+
header: bytes = spec["header"]
|
|
313
|
+
footer: bytes | None = spec["footer"]
|
|
314
|
+
ext: str = spec["ext"]
|
|
315
|
+
max_size: int = spec["max_size"]
|
|
316
|
+
|
|
317
|
+
pos = 0
|
|
318
|
+
while len(carved) < max_files:
|
|
319
|
+
start = data.find(header, pos)
|
|
320
|
+
if start == -1:
|
|
321
|
+
break
|
|
322
|
+
|
|
323
|
+
if footer:
|
|
324
|
+
end_idx = data.find(footer, start + len(header), start + max_size)
|
|
325
|
+
end = (end_idx + len(footer)) if end_idx != -1 else min(len(data), start + max_size)
|
|
326
|
+
else:
|
|
327
|
+
end = min(len(data), start + min(max_size, 1024 * 1024))
|
|
328
|
+
|
|
329
|
+
chunk = data[start:end]
|
|
330
|
+
out_name = f"carved_{sig_name}_{len(carved) + 1:04d}{ext}"
|
|
331
|
+
out_file = out / out_name
|
|
332
|
+
|
|
333
|
+
if not dry_run:
|
|
334
|
+
out_file.write_bytes(chunk)
|
|
335
|
+
|
|
336
|
+
carved.append(
|
|
337
|
+
{
|
|
338
|
+
"type": sig_name,
|
|
339
|
+
"offset": start,
|
|
340
|
+
"size": len(chunk),
|
|
341
|
+
"size_formatted": format_bytes(len(chunk)),
|
|
342
|
+
"output_file": str(out_file),
|
|
343
|
+
}
|
|
344
|
+
)
|
|
345
|
+
pos = end if end > start else start + len(header)
|
|
346
|
+
|
|
347
|
+
return {
|
|
348
|
+
"source": str(src),
|
|
349
|
+
"output_dir": str(out),
|
|
350
|
+
"dry_run": dry_run,
|
|
351
|
+
"carved_count": len(carved),
|
|
352
|
+
"files": carved,
|
|
353
|
+
}
|