Files
push_fenxiangfengshi/fengxiang/config.py
T

295 lines
9.1 KiB
Python

"""配置加载。
优先级:环境变量 > config.yaml > 内置默认值。
之所以做三级覆盖,是为了让同一个镜像在本地、测试、生产三种环境复用,
而密钥(企业微信 webhook、管理接口 token)永远不进代码库。
"""
from __future__ import annotations
import os
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Dict, List, Tuple
import yaml
# ---------------------------------------------------------------------------
# 默认值:一份可直接跑起来的基线配置
# ---------------------------------------------------------------------------
DEFAULT_LOGIN_URL = (
"https://fspass.szfx.com/ucenter/userlogin"
"?platform=saas&redirect_url=https%3A%2F%2Ffs.szfx.com%2FMMS%23%2F"
"&return_url=https%3A%2F%2Ffs.szfx.com%2Fsaasmerchant%2Fsetstoken"
)
DEFAULTS: Dict[str, Any] = {
"shop_id": "20434543575189",
"timezone": "Asia/Shanghai",
"api": {
"base_url": "https://fs.szfx.com",
"order_path": "/saasmerchant/pcweb/order/quickpayorder/list",
"login_url": DEFAULT_LOGIN_URL,
"timeout": 20,
"max_retries": 2,
},
"notify": {
# 服务器上只开企业微信;feishu 保留配置位,默认关闭
"channels": ["wecom"],
"alert_cooldown_sec": 1800,
"wecom": {"webhook": ""},
"feishu": {"webhook": "", "enabled": False},
},
"polling": {
"peak_hours": [[11, 13], [17, 19]],
"interval_min": 5,
"interval_max": 10,
"peak_page_size": 20,
"idle_page_size": 5,
"night_start": "21:00",
"night_end": "07:40",
"night_check_sec": 60,
"keepalive_sec": 300,
# 一次补推超过该条数就不再逐条推送,改发汇总,防止恢复后刷屏
"bulk_summary_threshold": 5,
},
"paths": {
"cookies": "data/cookies.json",
"state": "data/state.json",
"logs": "data/logs",
},
"admin": {
"enabled": True,
"host": "0.0.0.0",
"port": 8089,
"token": "",
},
"log": {"level": "INFO", "max_bytes": 5242880, "backup_count": 5},
"tts": {"enabled": False, "voice_prompt": ""},
}
def _deep_merge(base: Dict[str, Any], override: Dict[str, Any]) -> Dict[str, Any]:
"""递归合并字典,override 覆盖 base。"""
out = dict(base)
for key, value in (override or {}).items():
if isinstance(value, dict) and isinstance(out.get(key), dict):
out[key] = _deep_merge(out[key], value)
else:
out[key] = value
return out
def _as_bool(value: Any) -> bool:
if isinstance(value, bool):
return value
return str(value).strip().lower() in ("1", "true", "yes", "on", "y")
def parse_hhmm(text: str) -> int:
"""'21:00' -> 1260(当天分钟数)。"""
hh, mm = str(text).split(":")[:2]
return int(hh) * 60 + int(mm)
# ---------------------------------------------------------------------------
# 强类型配置对象
# ---------------------------------------------------------------------------
@dataclass
class ApiCfg:
base_url: str
order_path: str
login_url: str
timeout: int
max_retries: int
@property
def order_url(self) -> str:
return self.base_url.rstrip("/") + self.order_path
@dataclass
class NotifyCfg:
channels: List[str]
alert_cooldown_sec: int
wecom_webhook: str
feishu_webhook: str
feishu_enabled: bool
@dataclass
class PollingCfg:
peak_hours: List[Tuple[int, int]]
interval_min: int
interval_max: int
peak_page_size: int
idle_page_size: int
night_start_min: int
night_end_min: int
night_check_sec: int
keepalive_sec: int
bulk_summary_threshold: int
@dataclass
class PathsCfg:
cookies: Path
state: Path
logs: Path
@dataclass
class AdminCfg:
enabled: bool
host: str
port: int
token: str
@dataclass
class LogCfg:
level: str
max_bytes: int
backup_count: int
@dataclass
class TtsCfg:
enabled: bool
voice_prompt: str
@dataclass
class Config:
shop_id: str
timezone: str
api: ApiCfg
notify: NotifyCfg
polling: PollingCfg
paths: PathsCfg
admin: AdminCfg
log: LogCfg
tts: TtsCfg
raw: Dict[str, Any] = field(default_factory=dict, repr=False)
def ensure_dirs(self) -> None:
self.paths.cookies.parent.mkdir(parents=True, exist_ok=True)
self.paths.state.parent.mkdir(parents=True, exist_ok=True)
self.paths.logs.mkdir(parents=True, exist_ok=True)
def _apply_env(data: Dict[str, Any]) -> Dict[str, Any]:
"""环境变量覆盖。命名约定:FX_<段>_<键>。"""
env = os.environ
if env.get("FX_SHOP_ID"):
data["shop_id"] = env["FX_SHOP_ID"]
if env.get("FX_WECOM_WEBHOOK"):
data["notify"]["wecom"]["webhook"] = env["FX_WECOM_WEBHOOK"]
if env.get("FX_FEISHU_WEBHOOK"):
data["notify"]["feishu"]["webhook"] = env["FX_FEISHU_WEBHOOK"]
if env.get("FX_FEISHU_ENABLED"):
data["notify"]["feishu"]["enabled"] = _as_bool(env["FX_FEISHU_ENABLED"])
if env.get("FX_CHANNELS"):
data["notify"]["channels"] = [
c.strip() for c in env["FX_CHANNELS"].split(",") if c.strip()
]
if env.get("FX_ADMIN_TOKEN"):
data["admin"]["token"] = env["FX_ADMIN_TOKEN"]
if env.get("FX_ADMIN_PORT"):
data["admin"]["port"] = int(env["FX_ADMIN_PORT"])
if env.get("FX_ADMIN_ENABLED"):
data["admin"]["enabled"] = _as_bool(env["FX_ADMIN_ENABLED"])
if env.get("FX_DATA_DIR"):
base = Path(env["FX_DATA_DIR"])
data["paths"]["cookies"] = str(base / "cookies.json")
data["paths"]["state"] = str(base / "state.json")
data["paths"]["logs"] = str(base / "logs")
if env.get("FX_LOG_LEVEL"):
data["log"]["level"] = env["FX_LOG_LEVEL"]
if env.get("FX_TTS_ENABLED"):
data["tts"]["enabled"] = _as_bool(env["FX_TTS_ENABLED"])
return data
def load_config(path: str | os.PathLike | None = None) -> Config:
"""加载配置。path 为 None 时按 FX_CONFIG -> ./config.yaml 顺序查找。"""
cfg_path = path or os.environ.get("FX_CONFIG") or "config.yaml"
data = dict(DEFAULTS)
p = Path(cfg_path)
if p.exists():
with open(p, "r", encoding="utf-8") as f:
loaded = yaml.safe_load(f) or {}
if not isinstance(loaded, dict):
raise ValueError(f"配置文件格式错误(应为 YAML 映射): {p}")
data = _deep_merge(data, loaded)
data = _apply_env(data)
notify = data["notify"]
feishu_on = bool(notify["feishu"].get("enabled")) and bool(notify["feishu"]["webhook"])
channels = []
for name in notify.get("channels") or []:
if name == "feishu" and not feishu_on:
continue
if name == "wecom" and not notify["wecom"]["webhook"]:
continue
channels.append(name)
polling = data["polling"]
cfg = Config(
shop_id=str(data["shop_id"]),
timezone=str(data.get("timezone") or "Asia/Shanghai"),
api=ApiCfg(
base_url=data["api"]["base_url"],
order_path=data["api"]["order_path"],
# YAML 多行折叠可能往 query 里折出空格,登录链接会失效,这里兜底清掉
login_url="".join(str(data["api"]["login_url"]).split()),
timeout=int(data["api"]["timeout"]),
max_retries=int(data["api"]["max_retries"]),
),
notify=NotifyCfg(
channels=channels,
alert_cooldown_sec=int(notify["alert_cooldown_sec"]),
wecom_webhook=notify["wecom"]["webhook"],
feishu_webhook=notify["feishu"]["webhook"],
feishu_enabled=feishu_on,
),
polling=PollingCfg(
peak_hours=[tuple(h) for h in polling["peak_hours"]],
interval_min=int(polling["interval_min"]),
interval_max=int(polling["interval_max"]),
peak_page_size=int(polling["peak_page_size"]),
idle_page_size=int(polling["idle_page_size"]),
night_start_min=parse_hhmm(polling["night_start"]),
night_end_min=parse_hhmm(polling["night_end"]),
night_check_sec=int(polling["night_check_sec"]),
keepalive_sec=int(polling["keepalive_sec"]),
bulk_summary_threshold=int(polling["bulk_summary_threshold"]),
),
paths=PathsCfg(
cookies=Path(data["paths"]["cookies"]),
state=Path(data["paths"]["state"]),
logs=Path(data["paths"]["logs"]),
),
admin=AdminCfg(
enabled=_as_bool(data["admin"]["enabled"]),
host=data["admin"]["host"],
port=int(data["admin"]["port"]),
token=data["admin"]["token"],
),
log=LogCfg(
level=str(data["log"]["level"]).upper(),
max_bytes=int(data["log"]["max_bytes"]),
backup_count=int(data["log"]["backup_count"]),
),
tts=TtsCfg(
enabled=_as_bool(data["tts"]["enabled"]),
voice_prompt=data["tts"].get("voice_prompt") or "",
),
raw=data,
)
cfg.ensure_dirs()
return cfg