Files

75 lines
1.9 KiB
Python

from __future__ import annotations
import json
import os
from pathlib import Path
from typing import Any
from utils.logger import get_logger
logger = get_logger(__name__)
DATA_DIR = Path(__file__).resolve().parent.parent / "data"
CONFIG_FILE = DATA_DIR / "config.json"
DEFAULT_CONFIG: dict[str, Any] = {
"selected_game_id": None,
"theme": "dark",
"sidebar_collapsed": False,
"telemetry_port": 20777,
"tcp_port": 20778,
"use_unified_port": True,
"game_ports": {},
"ui_test_mode": False,
"market_url": "https://turbosu.yeij.top",
"telemetry_host": "0.0.0.0",
"server_host": "0.0.0.0",
"server_port": 9527,
"forward_targets": [],
}
def load_config() -> dict[str, Any]:
if CONFIG_FILE.exists():
try:
with open(CONFIG_FILE, "r", encoding="utf-8") as f:
cfg = json.load(f)
merged = {**DEFAULT_CONFIG, **cfg}
logger.info("Config loaded from %s", CONFIG_FILE)
return merged
except Exception as e:
logger.error("Failed to load config: %s", e)
logger.info("No config file found, using defaults")
return DEFAULT_CONFIG.copy()
def save_config(cfg: dict[str, Any]) -> None:
DATA_DIR.mkdir(parents=True, exist_ok=True)
try:
with open(CONFIG_FILE, "w", encoding="utf-8") as f:
json.dump(cfg, f, indent=2, ensure_ascii=False)
logger.info("Config saved to %s", CONFIG_FILE)
except Exception as e:
logger.error("Failed to save config: %s", e)
_config_cache: dict[str, Any] | None = None
def get_config() -> dict[str, Any]:
global _config_cache
if _config_cache is None:
_config_cache = load_config()
return _config_cache
def update_config(key: str, value: Any) -> None:
cfg = get_config()
cfg[key] = value
save_config(cfg)
def reload_config() -> None:
global _config_cache
_config_cache = None