This repository has been archived on 2026-11-15. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
WGTools-Extended/app/core/preferences.py
T
asminme f4929c7cac
Wydanie WGTools-Extended / release (push) Successful in 11s
1.0.5 - opisy usług w przekierowaniach
2026-10-30 13:15:39 +01:00

131 lines
5.0 KiB
Python

from __future__ import annotations
import sqlite3
import time
import re
import base64
import json
from pathlib import Path
from typing import Any
from .settings import DATABASE_PATH, ONLINE_THRESHOLD_SECONDS, REFRESH_SECONDS
DEFAULT_BACKUP_RETENTION = 20
def get_service_policy() -> dict[str, Any]:
return json.loads(_get('forward_service_policy', '{"enabled":false,"mode":"list","services":[]}'))
def update_service_policy(enabled: bool, mode: str, services: list[str]) -> dict[str, Any]:
if mode not in {'list', 'custom', 'combo'}:
raise ValueError('Nieprawidłowy tryb usług')
services = list(dict.fromkeys(s.strip() for s in services if s.strip()))
if len(services) > 1000 or any(len(s) > 120 or any(ord(c) < 32 for c in s) or s.casefold() == 'other' for s in services):
raise ValueError('Nieprawidłowa lista usług')
if enabled and mode in {'list', 'combo'} and not services:
raise ValueError('Dodaj co najmniej jedną usługę do listy')
policy = {'enabled': enabled, 'mode': mode, 'services': services}
_set('forward_service_policy', json.dumps(policy, ensure_ascii=True))
return policy
def get_branding() -> dict[str, Any]:
values = _get_many({"brand_name": "WGTools-Extended", "brand_color": "#8f1f27", "brand_logo": ""})
return {"name": values["brand_name"], "color": values["brand_color"], "logo": values["brand_logo"]}
def update_branding(name: str, color: str, logo: str) -> dict[str, Any]:
name = name.strip()
if len(name) > 80 or any(ord(c) < 32 for c in name):
raise ValueError("Nieprawidłowa nazwa marki")
if not re.fullmatch(r"#[0-9a-fA-F]{6}", color):
raise ValueError("Nieprawidłowy kolor")
if logo:
prefix = "data:image/png;base64,"
if not logo.startswith(prefix) or len(logo) > 400000:
raise ValueError("Logo musi być plikiem PNG o rozmiarze do 300 KB")
try:
raw = base64.b64decode(logo[len(prefix):], validate=True)
except ValueError as exc:
raise ValueError("Nieprawidłowy plik logo") from exc
if not raw.startswith(b"\x89PNG\r\n\x1a\n"):
raise ValueError("Logo musi być plikiem PNG")
_set("brand_name", name)
_set("brand_color", color)
_set("brand_logo", logo)
return get_branding()
def _connect() -> sqlite3.Connection:
Path(DATABASE_PATH).parent.mkdir(parents=True, exist_ok=True)
conn = sqlite3.connect(DATABASE_PATH)
conn.row_factory = sqlite3.Row
conn.execute("PRAGMA journal_mode=WAL")
return conn
def init_preferences() -> None:
with _connect() as conn:
conn.execute(
"""
CREATE TABLE IF NOT EXISTS app_settings (
key TEXT PRIMARY KEY,
value TEXT NOT NULL,
updated_at INTEGER NOT NULL
)
"""
)
def _get(key: str, default: str) -> str:
init_preferences()
with _connect() as conn:
row = conn.execute("SELECT value FROM app_settings WHERE key=?", (key,)).fetchone()
return str(row["value"]) if row else default
def _get_many(defaults: dict[str, str]) -> dict[str, str]:
init_preferences()
with _connect() as conn:
placeholders = ",".join("?" for _ in defaults)
rows = conn.execute(f"SELECT key,value FROM app_settings WHERE key IN ({placeholders})", tuple(defaults)).fetchall()
return {**defaults, **{str(row["key"]): str(row["value"]) for row in rows}}
def _set(key: str, value: str) -> None:
init_preferences()
with _connect() as conn:
conn.execute(
"""
INSERT INTO app_settings(key,value,updated_at) VALUES(?,?,?)
ON CONFLICT(key) DO UPDATE SET value=excluded.value, updated_at=excluded.updated_at
""",
(key, value, int(time.time())),
)
def get_preferences() -> dict[str, Any]:
values = _get_many({"refresh_seconds": str(REFRESH_SECONDS), "online_threshold_seconds": str(ONLINE_THRESHOLD_SECONDS), "backup_retention": str(DEFAULT_BACKUP_RETENTION)})
refresh = int(values["refresh_seconds"])
threshold = int(values["online_threshold_seconds"])
retention = int(values["backup_retention"])
return {
"refresh_seconds": max(2, min(refresh, 60)),
"online_threshold_seconds": max(30, min(threshold, 3600)),
"backup_retention": max(1, min(retention, 200)),
}
def update_preferences(*, refresh_seconds: int, online_threshold_seconds: int, backup_retention: int) -> dict[str, Any]:
if not 2 <= int(refresh_seconds) <= 60:
raise ValueError("Refresh interval must be between 2 and 60 seconds")
if not 30 <= int(online_threshold_seconds) <= 3600:
raise ValueError("Online threshold must be between 30 and 3600 seconds")
if not 1 <= int(backup_retention) <= 200:
raise ValueError("Backup retention must be between 1 and 200")
_set("refresh_seconds", str(int(refresh_seconds)))
_set("online_threshold_seconds", str(int(online_threshold_seconds)))
_set("backup_retention", str(int(backup_retention)))
return get_preferences()