pyegclamui 3.2.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.
- pyegclamui/__init__.py +10 -0
- pyegclamui/__main__.py +9 -0
- pyegclamui/assets/egav.ico +0 -0
- pyegclamui/assets/egav.png +0 -0
- pyegclamui/assets/pyegclamui.desktop +22 -0
- pyegclamui/core/__init__.py +4 -0
- pyegclamui/core/autostart.py +188 -0
- pyegclamui/core/config.py +256 -0
- pyegclamui/core/daemon.py +296 -0
- pyegclamui/core/desktop_integration.py +173 -0
- pyegclamui/core/detector.py +263 -0
- pyegclamui/core/logger.py +260 -0
- pyegclamui/core/monitor.py +281 -0
- pyegclamui/core/process.py +124 -0
- pyegclamui/core/quarantine.py +207 -0
- pyegclamui/core/scanner.py +589 -0
- pyegclamui/core/service_manager.py +304 -0
- pyegclamui/core/setup_engine.py +387 -0
- pyegclamui/core/system_capability.py +149 -0
- pyegclamui/core/telemetry.py +391 -0
- pyegclamui/core/updater.py +430 -0
- pyegclamui/gui/__init__.py +3 -0
- pyegclamui/gui/app.py +260 -0
- pyegclamui/gui/icons.py +434 -0
- pyegclamui/gui/issue_dialog.py +292 -0
- pyegclamui/gui/main_window.py +1850 -0
- pyegclamui/gui/platform_theme.py +81 -0
- pyegclamui/gui/scan_dialog.py +257 -0
- pyegclamui/gui/setup_dialog.py +352 -0
- pyegclamui/gui/styles.py +358 -0
- pyegclamui/gui/tk_app.py +743 -0
- pyegclamui/gui/tray.py +106 -0
- pyegclamui/gui/update_dialog.py +420 -0
- pyegclamui/gui/welcome_dialog.py +191 -0
- pyegclamui-3.2.0.dist-info/METADATA +233 -0
- pyegclamui-3.2.0.dist-info/RECORD +40 -0
- pyegclamui-3.2.0.dist-info/WHEEL +5 -0
- pyegclamui-3.2.0.dist-info/entry_points.txt +15 -0
- pyegclamui-3.2.0.dist-info/licenses/LICENSE +692 -0
- pyegclamui-3.2.0.dist-info/top_level.txt +1 -0
pyegclamui/__init__.py
ADDED
pyegclamui/__main__.py
ADDED
|
Binary file
|
|
Binary file
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
[Desktop Entry]
|
|
2
|
+
Version=1.0
|
|
3
|
+
Type=Application
|
|
4
|
+
Name=pyEGClamUI
|
|
5
|
+
GenericName=Antivirus GUI
|
|
6
|
+
Comment=An open-source, cross-platform desktop GUI for ClamAV
|
|
7
|
+
Exec=pyegclamui %F
|
|
8
|
+
Icon=pyegclamui
|
|
9
|
+
Terminal=false
|
|
10
|
+
StartupNotify=true
|
|
11
|
+
Categories=Utility;System;Security;
|
|
12
|
+
Keywords=clamav;antivirus;scanner;security;protection;malware;virus;
|
|
13
|
+
MimeType=inode/directory;application/x-executable;application/x-ms-dos-executable;application/zip;application/x-tar;application/x-compressed-tar;application/x-bzip;application/x-7z-compressed;
|
|
14
|
+
Actions=QuickScan;QuarantineVault;
|
|
15
|
+
|
|
16
|
+
[Desktop Action QuickScan]
|
|
17
|
+
Name=Run Quick Scan
|
|
18
|
+
Exec=pyegclamui-scan --quick
|
|
19
|
+
|
|
20
|
+
[Desktop Action QuarantineVault]
|
|
21
|
+
Name=Open Quarantine Vault
|
|
22
|
+
Exec=pyegclamui --quarantine
|
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Cross-platform system startup manager for pyEGClamUI.
|
|
3
|
+
Enables or disables launching pyEGClamUI minimized to tray on system login.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
import os
|
|
7
|
+
import sys
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class AutoStartManager:
|
|
12
|
+
"""Manages OS startup auto-launch entries (Windows Registry / Linux XDG Autostart)."""
|
|
13
|
+
|
|
14
|
+
APP_KEY = "pyEGClamUI"
|
|
15
|
+
|
|
16
|
+
@classmethod
|
|
17
|
+
def is_supported(cls) -> bool:
|
|
18
|
+
"""Returns True if auto-start is supported on the current platform."""
|
|
19
|
+
return sys.platform in ("win32", "linux", "darwin")
|
|
20
|
+
|
|
21
|
+
@classmethod
|
|
22
|
+
def get_launch_command(cls) -> str:
|
|
23
|
+
"""Constructs the command to launch pyEGClamUI minimized to system tray."""
|
|
24
|
+
if getattr(sys, "frozen", False):
|
|
25
|
+
return f'"{sys.executable}" --minimized'
|
|
26
|
+
|
|
27
|
+
# Prefer pythonw.exe on Windows to prevent showing a console window
|
|
28
|
+
python_exec = sys.executable
|
|
29
|
+
if sys.platform == "win32":
|
|
30
|
+
candidate = Path(python_exec).parent / "pythonw.exe"
|
|
31
|
+
if candidate.exists():
|
|
32
|
+
python_exec = str(candidate)
|
|
33
|
+
|
|
34
|
+
return f'"{python_exec}" -m pyegclamui.gui.app --minimized'
|
|
35
|
+
|
|
36
|
+
@classmethod
|
|
37
|
+
def is_enabled(cls) -> bool:
|
|
38
|
+
"""Checks if pyEGClamUI is configured to launch at system startup."""
|
|
39
|
+
if sys.platform == "win32":
|
|
40
|
+
return cls._is_enabled_windows()
|
|
41
|
+
elif sys.platform == "linux":
|
|
42
|
+
return cls._is_enabled_linux()
|
|
43
|
+
elif sys.platform == "darwin":
|
|
44
|
+
return cls._is_enabled_macos()
|
|
45
|
+
return False
|
|
46
|
+
|
|
47
|
+
@classmethod
|
|
48
|
+
def set_enabled(cls, enable: bool) -> bool:
|
|
49
|
+
"""Enables or disables system startup auto-launch."""
|
|
50
|
+
if sys.platform == "win32":
|
|
51
|
+
return cls._set_enabled_windows(enable)
|
|
52
|
+
elif sys.platform == "linux":
|
|
53
|
+
return cls._set_enabled_linux(enable)
|
|
54
|
+
elif sys.platform == "darwin":
|
|
55
|
+
return cls._set_enabled_macos(enable)
|
|
56
|
+
return False
|
|
57
|
+
|
|
58
|
+
# --- Windows Registry (HKCU\...\Run) ---
|
|
59
|
+
@classmethod
|
|
60
|
+
def _is_enabled_windows(cls) -> bool:
|
|
61
|
+
try:
|
|
62
|
+
import winreg
|
|
63
|
+
|
|
64
|
+
key = winreg.OpenKey(
|
|
65
|
+
winreg.HKEY_CURRENT_USER,
|
|
66
|
+
r"Software\Microsoft\Windows\CurrentVersion\Run",
|
|
67
|
+
0,
|
|
68
|
+
winreg.KEY_READ,
|
|
69
|
+
)
|
|
70
|
+
try:
|
|
71
|
+
val, _ = winreg.QueryValueEx(key, cls.APP_KEY)
|
|
72
|
+
return bool(val)
|
|
73
|
+
except FileNotFoundError:
|
|
74
|
+
return False
|
|
75
|
+
finally:
|
|
76
|
+
winreg.CloseKey(key)
|
|
77
|
+
except Exception:
|
|
78
|
+
return False
|
|
79
|
+
|
|
80
|
+
@classmethod
|
|
81
|
+
def _set_enabled_windows(cls, enable: bool) -> bool:
|
|
82
|
+
try:
|
|
83
|
+
import winreg
|
|
84
|
+
|
|
85
|
+
key = winreg.CreateKeyEx(
|
|
86
|
+
winreg.HKEY_CURRENT_USER,
|
|
87
|
+
r"Software\Microsoft\Windows\CurrentVersion\Run",
|
|
88
|
+
0,
|
|
89
|
+
winreg.KEY_SET_VALUE,
|
|
90
|
+
)
|
|
91
|
+
try:
|
|
92
|
+
if enable:
|
|
93
|
+
cmd = cls.get_launch_command()
|
|
94
|
+
winreg.SetValueEx(key, cls.APP_KEY, 0, winreg.REG_SZ, cmd)
|
|
95
|
+
else:
|
|
96
|
+
try:
|
|
97
|
+
winreg.DeleteValue(key, cls.APP_KEY)
|
|
98
|
+
except FileNotFoundError:
|
|
99
|
+
pass
|
|
100
|
+
return True
|
|
101
|
+
finally:
|
|
102
|
+
winreg.CloseKey(key)
|
|
103
|
+
except Exception as e:
|
|
104
|
+
print(f"[AutoStartManager] Windows registry error: {e}")
|
|
105
|
+
return False
|
|
106
|
+
|
|
107
|
+
# --- Linux XDG Autostart (~/.config/autostart/) ---
|
|
108
|
+
@classmethod
|
|
109
|
+
def _get_linux_desktop_file(cls) -> Path:
|
|
110
|
+
base = os.getenv("XDG_CONFIG_HOME", str(Path.home() / ".config"))
|
|
111
|
+
return Path(base) / "autostart" / "pyegclamui.desktop"
|
|
112
|
+
|
|
113
|
+
@classmethod
|
|
114
|
+
def _is_enabled_linux(cls) -> bool:
|
|
115
|
+
return cls._get_linux_desktop_file().exists()
|
|
116
|
+
|
|
117
|
+
@classmethod
|
|
118
|
+
def _set_enabled_linux(cls, enable: bool) -> bool:
|
|
119
|
+
try:
|
|
120
|
+
desktop_file = cls._get_linux_desktop_file()
|
|
121
|
+
if enable:
|
|
122
|
+
desktop_file.parent.mkdir(parents=True, exist_ok=True)
|
|
123
|
+
content = (
|
|
124
|
+
"[Desktop Entry]\n"
|
|
125
|
+
"Type=Application\n"
|
|
126
|
+
"Name=pyEGClamUI\n"
|
|
127
|
+
"Comment=ClamAV Antivirus Desktop Guard\n"
|
|
128
|
+
"Exec=pyegclamui --minimized\n"
|
|
129
|
+
"Terminal=false\n"
|
|
130
|
+
"Icon=pyegclamui\n"
|
|
131
|
+
"Categories=Utility;Security;\n"
|
|
132
|
+
)
|
|
133
|
+
desktop_file.write_text(content, encoding="utf-8")
|
|
134
|
+
else:
|
|
135
|
+
if desktop_file.exists():
|
|
136
|
+
desktop_file.unlink()
|
|
137
|
+
return True
|
|
138
|
+
except Exception as e:
|
|
139
|
+
print(f"[AutoStartManager] Linux autostart error: {e}")
|
|
140
|
+
return False
|
|
141
|
+
|
|
142
|
+
# --- macOS LaunchAgent (~/Library/LaunchAgents/) ---
|
|
143
|
+
@classmethod
|
|
144
|
+
def _get_macos_plist_file(cls) -> Path:
|
|
145
|
+
return Path.home() / "Library" / "LaunchAgents" / "in.eg1.pyegclamui.plist"
|
|
146
|
+
|
|
147
|
+
@classmethod
|
|
148
|
+
def _is_enabled_macos(cls) -> bool:
|
|
149
|
+
return cls._get_macos_plist_file().exists()
|
|
150
|
+
|
|
151
|
+
@classmethod
|
|
152
|
+
def _set_enabled_macos(cls, enable: bool) -> bool:
|
|
153
|
+
try:
|
|
154
|
+
plist_file = cls._get_macos_plist_file()
|
|
155
|
+
if enable:
|
|
156
|
+
plist_file.parent.mkdir(parents=True, exist_ok=True)
|
|
157
|
+
python_exec = sys.executable
|
|
158
|
+
content = (
|
|
159
|
+
'<?xml version="1.0" encoding="UTF-8"?>\n'
|
|
160
|
+
'<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" '
|
|
161
|
+
'"http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n'
|
|
162
|
+
'<plist version="1.0">\n'
|
|
163
|
+
'<dict>\n'
|
|
164
|
+
' <key>Label</key>\n'
|
|
165
|
+
' <string>in.eg1.pyegclamui</string>\n'
|
|
166
|
+
' <key>ProgramArguments</key>\n'
|
|
167
|
+
' <array>\n'
|
|
168
|
+
f' <string>{python_exec}</string>\n'
|
|
169
|
+
' <string>-m</string>\n'
|
|
170
|
+
' <string>pyegclamui.gui.app</string>\n'
|
|
171
|
+
' <string>--minimized</string>\n'
|
|
172
|
+
' </array>\n'
|
|
173
|
+
' <key>RunAtLoad</key>\n'
|
|
174
|
+
' <true/>\n'
|
|
175
|
+
' <key>KeepAlive</key>\n'
|
|
176
|
+
' <false/>\n'
|
|
177
|
+
'</dict>\n'
|
|
178
|
+
'</plist>\n'
|
|
179
|
+
)
|
|
180
|
+
plist_file.write_text(content, encoding="utf-8")
|
|
181
|
+
else:
|
|
182
|
+
if plist_file.exists():
|
|
183
|
+
plist_file.unlink()
|
|
184
|
+
return True
|
|
185
|
+
except Exception as e:
|
|
186
|
+
print(f"[AutoStartManager] macOS launchd error: {e}")
|
|
187
|
+
return False
|
|
188
|
+
|
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Configuration manager for pyEGClamUI.
|
|
3
|
+
Stores user settings and state in standard, human-readable JSON files.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
import sys
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import Any, Dict, List
|
|
11
|
+
|
|
12
|
+
from pyegclamui import __version__
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class AppPaths:
|
|
16
|
+
"""Manages cross-platform standard directories for pyEGClamUI."""
|
|
17
|
+
|
|
18
|
+
@staticmethod
|
|
19
|
+
def _safe_mkdir(path: Path) -> Path:
|
|
20
|
+
"""Safely attempts to create directories without crashing on read-only environments."""
|
|
21
|
+
try:
|
|
22
|
+
path.mkdir(parents=True, exist_ok=True)
|
|
23
|
+
except OSError:
|
|
24
|
+
pass
|
|
25
|
+
return path
|
|
26
|
+
|
|
27
|
+
@staticmethod
|
|
28
|
+
def get_config_dir() -> Path:
|
|
29
|
+
"""Returns standard user configuration directory."""
|
|
30
|
+
if sys.platform == "win32":
|
|
31
|
+
base = os.getenv("APPDATA", str(Path.home() / "AppData" / "Roaming"))
|
|
32
|
+
path = Path(base) / "pyEGClamUI"
|
|
33
|
+
elif sys.platform == "darwin":
|
|
34
|
+
path = Path.home() / "Library" / "Application Support" / "pyEGClamUI"
|
|
35
|
+
else:
|
|
36
|
+
base = os.getenv("XDG_CONFIG_HOME", str(Path.home() / ".config"))
|
|
37
|
+
path = Path(base) / "pyegclamui"
|
|
38
|
+
return AppPaths._safe_mkdir(path)
|
|
39
|
+
|
|
40
|
+
@staticmethod
|
|
41
|
+
def get_data_dir() -> Path:
|
|
42
|
+
"""Returns standard user application data directory."""
|
|
43
|
+
if sys.platform == "win32":
|
|
44
|
+
base = os.getenv("LOCALAPPDATA", str(Path.home() / "AppData" / "Local"))
|
|
45
|
+
path = Path(base) / "pyEGClamUI"
|
|
46
|
+
elif sys.platform == "darwin":
|
|
47
|
+
path = Path.home() / "Library" / "Application Support" / "pyEGClamUI"
|
|
48
|
+
else:
|
|
49
|
+
base = os.getenv("XDG_DATA_HOME", str(Path.home() / ".local" / "share"))
|
|
50
|
+
path = Path(base) / "pyegclamui"
|
|
51
|
+
return AppPaths._safe_mkdir(path)
|
|
52
|
+
|
|
53
|
+
@staticmethod
|
|
54
|
+
def get_database_dir() -> Path:
|
|
55
|
+
"""Returns active virus database directory (ProgramData on Windows if present, else user data dir)."""
|
|
56
|
+
if sys.platform == "win32":
|
|
57
|
+
prog_data = os.getenv("ProgramData", "C:/ProgramData")
|
|
58
|
+
shared_db = Path(prog_data) / "ClamAV" / "database"
|
|
59
|
+
if shared_db.is_dir() and any(shared_db.glob("*.c*d")):
|
|
60
|
+
return shared_db
|
|
61
|
+
user_db = AppPaths.get_data_dir() / "database"
|
|
62
|
+
return AppPaths._safe_mkdir(user_db)
|
|
63
|
+
|
|
64
|
+
@staticmethod
|
|
65
|
+
def get_quarantine_dir() -> Path:
|
|
66
|
+
"""Returns directory where quarantined threats are safely stored."""
|
|
67
|
+
path = AppPaths.get_data_dir() / "quarantine"
|
|
68
|
+
return AppPaths._safe_mkdir(path)
|
|
69
|
+
|
|
70
|
+
@staticmethod
|
|
71
|
+
def get_logs_dir() -> Path:
|
|
72
|
+
"""Returns directory where application and scan logs are written."""
|
|
73
|
+
if sys.platform == "win32":
|
|
74
|
+
path = AppPaths.get_data_dir() / "logs"
|
|
75
|
+
elif sys.platform == "darwin":
|
|
76
|
+
path = Path.home() / "Library" / "Logs" / "pyEGClamUI"
|
|
77
|
+
else:
|
|
78
|
+
base = os.getenv("XDG_STATE_HOME", str(Path.home() / ".local" / "state"))
|
|
79
|
+
path = Path(base) / "pyegclamui" / "logs"
|
|
80
|
+
return AppPaths._safe_mkdir(path)
|
|
81
|
+
|
|
82
|
+
@staticmethod
|
|
83
|
+
def get_package_root() -> Path:
|
|
84
|
+
"""Returns root directory of the installed pyegclamui package."""
|
|
85
|
+
if getattr(sys, "frozen", False) and hasattr(sys, "_MEIPASS"):
|
|
86
|
+
meipass = Path(sys._MEIPASS)
|
|
87
|
+
if (meipass / "pyegclamui").exists():
|
|
88
|
+
return meipass / "pyegclamui"
|
|
89
|
+
return meipass
|
|
90
|
+
return Path(__file__).resolve().parent.parent
|
|
91
|
+
|
|
92
|
+
@staticmethod
|
|
93
|
+
def get_asset_path(*subpaths: str) -> Path:
|
|
94
|
+
"""Returns absolute path to a bundled asset file."""
|
|
95
|
+
pkg_asset = AppPaths.get_package_root() / "assets" / Path(*subpaths)
|
|
96
|
+
if pkg_asset.exists():
|
|
97
|
+
return pkg_asset
|
|
98
|
+
if getattr(sys, "frozen", False) and hasattr(sys, "_MEIPASS"):
|
|
99
|
+
alt = Path(sys._MEIPASS) / "assets" / Path(*subpaths)
|
|
100
|
+
if alt.exists():
|
|
101
|
+
return alt
|
|
102
|
+
return pkg_asset
|
|
103
|
+
|
|
104
|
+
@staticmethod
|
|
105
|
+
def get_app_icon_path() -> Path:
|
|
106
|
+
"""Returns the best available icon file for the current operating system."""
|
|
107
|
+
if sys.platform in ("linux", "darwin"):
|
|
108
|
+
for candidate in ["egav.png", "egav.ico"]:
|
|
109
|
+
p = AppPaths.get_asset_path(candidate)
|
|
110
|
+
if p.exists():
|
|
111
|
+
return p
|
|
112
|
+
else:
|
|
113
|
+
for candidate in ["egav.ico", "egav.png"]:
|
|
114
|
+
p = AppPaths.get_asset_path(candidate)
|
|
115
|
+
if p.exists():
|
|
116
|
+
return p
|
|
117
|
+
return AppPaths.get_asset_path("egav.png")
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
class Config:
|
|
121
|
+
"""Manages application settings and preferences."""
|
|
122
|
+
|
|
123
|
+
_instance = None
|
|
124
|
+
|
|
125
|
+
DEFAULT_CONFIG: Dict[str, Any] = {
|
|
126
|
+
"preferences": {
|
|
127
|
+
"real_time_protection": False,
|
|
128
|
+
"auto_updates": True,
|
|
129
|
+
"action_on_threat": 3, # 1: Report, 2: Delete/Trash, 3: Quarantine
|
|
130
|
+
"notifications": True,
|
|
131
|
+
"theme": "dark", # "dark" or "light"
|
|
132
|
+
"close_to_tray": True,
|
|
133
|
+
"confirm_exit_from_tray": True,
|
|
134
|
+
"start_with_system": False,
|
|
135
|
+
"first_run_completed": False,
|
|
136
|
+
},
|
|
137
|
+
"scan_settings": {
|
|
138
|
+
"max_file_size_mb": 50,
|
|
139
|
+
"extract_archives": True,
|
|
140
|
+
"max_extract_size_mb": 100,
|
|
141
|
+
"max_extract_files": 1000,
|
|
142
|
+
"max_recursion": 15,
|
|
143
|
+
"monitor_dirs": [],
|
|
144
|
+
"exclude_extensions": [
|
|
145
|
+
"jpg", "jpeg", "gif", "png", "bmp", "tiff", "webp",
|
|
146
|
+
"mp3", "wav", "flac", "ogg", "m4a",
|
|
147
|
+
"mp4", "mkv", "avi", "mov", "wmv", "flv", "webm"
|
|
148
|
+
],
|
|
149
|
+
"include_only_extensions": [],
|
|
150
|
+
"prefer_daemon": True,
|
|
151
|
+
"custom_clamscan_path": "",
|
|
152
|
+
"custom_clamdscan_path": "",
|
|
153
|
+
"custom_clamd_path": "",
|
|
154
|
+
"custom_freshclam_path": "",
|
|
155
|
+
"clamd_tcp_port": 3310,
|
|
156
|
+
"clamd_tcp_host": "127.0.0.1",
|
|
157
|
+
"clamd_unix_socket": "/var/run/clamav/clamd.ctl",
|
|
158
|
+
},
|
|
159
|
+
"user_profile": {
|
|
160
|
+
"user_id": "",
|
|
161
|
+
"display_name": "",
|
|
162
|
+
"email": "",
|
|
163
|
+
"is_anonymous": True,
|
|
164
|
+
},
|
|
165
|
+
"telemetry": {
|
|
166
|
+
"enabled": False,
|
|
167
|
+
"firebase_project_id": "eg1-pyegclamui",
|
|
168
|
+
"share_os_info": True,
|
|
169
|
+
"share_clamav_version": True,
|
|
170
|
+
"share_scan_stats": True,
|
|
171
|
+
"last_active_heartbeat": "",
|
|
172
|
+
"install_reported": False,
|
|
173
|
+
},
|
|
174
|
+
"last_update_check": "",
|
|
175
|
+
"version": __version__
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
def __init__(self):
|
|
179
|
+
self.config_file = AppPaths.get_config_dir() / "config.json"
|
|
180
|
+
self.data: Dict[str, Any] = {}
|
|
181
|
+
self.load()
|
|
182
|
+
|
|
183
|
+
@classmethod
|
|
184
|
+
def get_instance(cls) -> "Config":
|
|
185
|
+
if cls._instance is None:
|
|
186
|
+
cls._instance = Config()
|
|
187
|
+
return cls._instance
|
|
188
|
+
|
|
189
|
+
def load(self) -> None:
|
|
190
|
+
"""Loads configuration from JSON file or populates defaults if missing."""
|
|
191
|
+
if self.config_file.exists():
|
|
192
|
+
try:
|
|
193
|
+
with open(self.config_file, "r", encoding="utf-8") as f:
|
|
194
|
+
loaded = json.load(f)
|
|
195
|
+
self.data = self._deep_merge(self.DEFAULT_CONFIG, loaded)
|
|
196
|
+
self._ensure_user_id()
|
|
197
|
+
return
|
|
198
|
+
except Exception as e:
|
|
199
|
+
print(f"[Config] Error reading {self.config_file}: {e}, using defaults.")
|
|
200
|
+
self.data = json.loads(json.dumps(self.DEFAULT_CONFIG))
|
|
201
|
+
self._ensure_user_id()
|
|
202
|
+
self.save()
|
|
203
|
+
|
|
204
|
+
def _ensure_user_id(self):
|
|
205
|
+
"""Generates an anonymous user ID if none exists."""
|
|
206
|
+
profile = self.data.setdefault("user_profile", {})
|
|
207
|
+
if not profile.get("user_id"):
|
|
208
|
+
import random
|
|
209
|
+
profile["user_id"] = f"Guest{random.randint(10000000, 99999999)}"
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def save(self) -> None:
|
|
213
|
+
"""Persists current configuration to JSON file."""
|
|
214
|
+
try:
|
|
215
|
+
with open(self.config_file, "w", encoding="utf-8") as f:
|
|
216
|
+
json.dump(self.data, f, indent=4, ensure_ascii=False)
|
|
217
|
+
except Exception as e:
|
|
218
|
+
print(f"[Config] Failed to save {self.config_file}: {e}")
|
|
219
|
+
|
|
220
|
+
def get(self, *keys: str, default: Any = None) -> Any:
|
|
221
|
+
"""Navigates hierarchical keys: config.get('preferences', 'theme')."""
|
|
222
|
+
curr = self.data
|
|
223
|
+
for key in keys:
|
|
224
|
+
if isinstance(curr, dict) and key in curr:
|
|
225
|
+
curr = curr[key]
|
|
226
|
+
else:
|
|
227
|
+
return default
|
|
228
|
+
return curr
|
|
229
|
+
|
|
230
|
+
def set(self, *keys_and_value: Any) -> None:
|
|
231
|
+
"""Sets a value: config.set('preferences', 'theme', 'light')."""
|
|
232
|
+
if len(keys_and_value) < 2:
|
|
233
|
+
raise ValueError("set() requires at least one key and a value")
|
|
234
|
+
keys = keys_and_value[:-1]
|
|
235
|
+
value = keys_and_value[-1]
|
|
236
|
+
|
|
237
|
+
curr = self.data
|
|
238
|
+
for key in keys[:-1]:
|
|
239
|
+
curr = curr.setdefault(key, {})
|
|
240
|
+
curr[keys[-1]] = value
|
|
241
|
+
self.save()
|
|
242
|
+
|
|
243
|
+
def reset_defaults(self) -> None:
|
|
244
|
+
"""Resets all configuration values to defaults."""
|
|
245
|
+
self.data = json.loads(json.dumps(self.DEFAULT_CONFIG))
|
|
246
|
+
self.save()
|
|
247
|
+
|
|
248
|
+
@staticmethod
|
|
249
|
+
def _deep_merge(default: dict, override: dict) -> dict:
|
|
250
|
+
result = dict(default)
|
|
251
|
+
for k, v in override.items():
|
|
252
|
+
if k in result and isinstance(result[k], dict) and isinstance(v, dict):
|
|
253
|
+
result[k] = Config._deep_merge(result[k], v)
|
|
254
|
+
else:
|
|
255
|
+
result[k] = v
|
|
256
|
+
return result
|