63 lines
1.8 KiB
Python
63 lines
1.8 KiB
Python
import json
|
|
from pathlib import Path
|
|
from typing import Any
|
|
|
|
from config import CONFIG_FILE, DEFAULT_CONFIG, DEFAULT_STATS, PROXIES_FILE, STATS_FILE
|
|
from models.config import BotConfig
|
|
from models.stats import BotStats
|
|
|
|
|
|
def _load_json(path: Path) -> dict[str, Any] | None:
|
|
if not path.exists():
|
|
return None
|
|
try:
|
|
with path.open("r", encoding="utf-8") as fh:
|
|
return json.load(fh)
|
|
except Exception:
|
|
return None
|
|
|
|
|
|
def _save_json(path: Path, data: dict[str, Any]) -> None:
|
|
with path.open("w", encoding="utf-8") as fh:
|
|
json.dump(data, fh, indent=4, ensure_ascii=False)
|
|
|
|
|
|
def load_config() -> BotConfig:
|
|
data = _load_json(CONFIG_FILE)
|
|
if data is None:
|
|
config = DEFAULT_CONFIG
|
|
save_config(config)
|
|
return config
|
|
defaults = DEFAULT_CONFIG.to_dict()
|
|
defaults.update(data)
|
|
default_rates = defaults["rates"]
|
|
default_rates.update(data.get("rates") or {})
|
|
defaults["rates"] = default_rates
|
|
return BotConfig.from_dict(defaults)
|
|
|
|
|
|
def save_config(cfg: BotConfig | dict[str, Any]) -> None:
|
|
config = cfg if isinstance(cfg, BotConfig) else BotConfig.from_dict(cfg)
|
|
_save_json(CONFIG_FILE, config.to_dict())
|
|
|
|
|
|
def load_stats() -> BotStats:
|
|
data = _load_json(STATS_FILE)
|
|
if data is None:
|
|
stats = DEFAULT_STATS
|
|
save_stats(stats)
|
|
return stats
|
|
return BotStats.from_dict(data)
|
|
|
|
|
|
def save_stats(stats: BotStats | dict[str, Any]) -> None:
|
|
model = stats if isinstance(stats, BotStats) else BotStats.from_dict(stats)
|
|
_save_json(STATS_FILE, model.to_dict())
|
|
|
|
|
|
def load_proxies() -> list[str]:
|
|
if not PROXIES_FILE.exists():
|
|
return []
|
|
with PROXIES_FILE.open("r", encoding="utf-8", errors="ignore") as fh:
|
|
return [line.strip() for line in fh if line.strip()]
|