from __future__ import annotations import json import os import sqlite3 import threading from datetime import datetime, timezone from pathlib import Path from typing import Any, Optional from maintain.paths_config import CPA_AUTHS_DIR ROOT = Path(__file__).resolve().parent.parent DB_PATH = ROOT / "maintain" / "data" / "maintain.db" ACCOUNTS_OAUTH = ROOT / "accounts" / "oauth" _lock = threading.Lock() def resolve_oauth_stats_dir() -> Path: """ 统计 / 巡检用的 codex JSON 目录。 配置留空时使用 maintain/paths_config.CPA_AUTHS_DIR(部署时写死挂载点)。 若需退回项目内目录,在「配置编辑」显式填项目 accounts/oauth 绝对路径。 """ raw = get_setting("codex_stats_oauth_dir", "").strip() if not raw: return Path(CPA_AUTHS_DIR).expanduser().resolve() return Path(raw).expanduser().resolve() def safe_unlink_oauth_json(path_str: str) -> bool: """仅允许删除「统计目录」下的 .json 文件,防路径穿越。""" try: p = Path(path_str).resolve() root = resolve_oauth_stats_dir() p.relative_to(root) except (ValueError, OSError): return False if p.suffix.lower() != ".json": return False if not p.is_file(): return False try: p.unlink() return True except OSError: return False def _conn() -> sqlite3.Connection: DB_PATH.parent.mkdir(parents=True, exist_ok=True) c = sqlite3.connect(str(DB_PATH), check_same_thread=False) c.row_factory = sqlite3.Row return c def init_db() -> None: with _lock: c = _conn() try: c.executescript( """ CREATE TABLE IF NOT EXISTS cpa ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, code TEXT NOT NULL UNIQUE, target_count INTEGER NOT NULL DEFAULT 0, api_base_url TEXT DEFAULT '' ); CREATE TABLE IF NOT EXISTS settings ( key TEXT PRIMARY KEY, value TEXT NOT NULL ); CREATE TABLE IF NOT EXISTS proxies ( id INTEGER PRIMARY KEY AUTOINCREMENT, url TEXT NOT NULL, label TEXT DEFAULT '', enabled INTEGER NOT NULL DEFAULT 1 ); CREATE TABLE IF NOT EXISTS tasks ( id INTEGER PRIMARY KEY AUTOINCREMENT, task_type TEXT NOT NULL, status TEXT NOT NULL, message TEXT DEFAULT '', cpa_id INTEGER, total INTEGER DEFAULT 0, done INTEGER DEFAULT 0, created_at TEXT NOT NULL, updated_at TEXT NOT NULL ); """ ) cur = c.execute("SELECT COUNT(*) FROM cpa") if cur.fetchone()[0] == 0: c.execute( "INSERT INTO cpa (name, code, target_count, api_base_url) VALUES (?,?,?,?)", ("账号池", "default", 500, ""), ) defaults = { "auto_inspect_enabled": "0", "inspect_interval_min": "60", "use_proxy_pool_auto": "1", "max_auto_register_per_tick": "30", "default_threads": "1", "skip_oauth": "0", "manual_default_proxy": "", # 子进程流水线(run.py → 迁出 JSON),与维护台共用 pipeline_state.json "pipeline_auto_enabled": "0", "pipeline_interval_min": "10", "pipeline_run_script": str(ROOT / "run.py"), "pipeline_oauth_dir": str(ROOT / "accounts" / "oauth"), "cpa_target_dir": CPA_AUTHS_DIR, "pipeline_python_bin": "python3", "run_subprocess_timeout_sec": "480", "cpa_exit_on_empty": "0", "dingtalk_webhook": "", "dingtalk_secret": "", # Cliproxy 管理端巡检(与 Web 管理台「探测模型」同源) "cliproxy_management_base": "", "cliproxy_management_key": "", "cliproxy_probe_timeout_sec": "30", "cliproxy_sweeper_threshold": "3", "cliproxy_sweeper_run_mode": "delete", "cliproxy_sweeper_allow_name_fallback": "1", # 与 paths_config.CPA_AUTHS_DIR 一致;可在 Web 里改 "codex_stats_oauth_dir": CPA_AUTHS_DIR, "inspect_probe_valid_json": "", "pipeline_state_file": str(ROOT / "maintain" / "data" / "pipeline_state.json"), "pipeline_log_file": str(ROOT / "maintain" / "data" / "pipeline.log"), "pipeline_lock_file": str(ROOT / "maintain" / "data" / "cpa_runner.lock"), } for k, v in defaults.items(): c.execute( "INSERT OR IGNORE INTO settings (key, value) VALUES (?, ?)", (k, v) ) c.commit() finally: c.close() def get_setting(key: str, default: str = "") -> str: with _lock: c = _conn() try: row = c.execute("SELECT value FROM settings WHERE key=?", (key,)).fetchone() return row["value"] if row else default finally: c.close() def set_setting(key: str, value: str) -> None: with _lock: c = _conn() try: c.execute( "INSERT INTO settings (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value=excluded.value", (key, value), ) c.commit() finally: c.close() def all_settings() -> dict[str, str]: with _lock: c = _conn() try: rows = c.execute("SELECT key, value FROM settings").fetchall() return {r["key"]: r["value"] for r in rows} finally: c.close() def list_cpas() -> list[dict[str, Any]]: with _lock: c = _conn() try: rows = c.execute( "SELECT id, name, code, target_count, api_base_url FROM cpa ORDER BY id" ).fetchall() return [dict(r) for r in rows] finally: c.close() def update_cpa( cpa_id: int, *, name: Optional[str] = None, target_count: Optional[int] = None, api_base_url: Optional[str] = None, ) -> None: with _lock: c = _conn() try: if name is not None: c.execute("UPDATE cpa SET name=? WHERE id=?", (name, cpa_id)) if target_count is not None: c.execute("UPDATE cpa SET target_count=? WHERE id=?", (target_count, cpa_id)) if api_base_url is not None: c.execute("UPDATE cpa SET api_base_url=? WHERE id=?", (api_base_url, cpa_id)) c.commit() finally: c.close() def list_proxies() -> list[dict[str, Any]]: with _lock: c = _conn() try: rows = c.execute( "SELECT id, url, label, enabled FROM proxies ORDER BY id" ).fetchall() return [dict(r) for r in rows] finally: c.close() def add_proxy(url: str, label: str = "") -> int: with _lock: c = _conn() try: cur = c.execute( "INSERT INTO proxies (url, label, enabled) VALUES (?,?,1)", (url.strip(), label.strip()), ) c.commit() return int(cur.lastrowid) finally: c.close() def delete_proxy(proxy_id: int) -> None: with _lock: c = _conn() try: c.execute("DELETE FROM proxies WHERE id=?", (proxy_id,)) c.commit() finally: c.close() def pick_random_proxy_url() -> Optional[str]: rows = [p for p in list_proxies() if p.get("enabled")] if not rows: return None import random return random.choice(rows)["url"] def cliproxy_inspect_configured() -> bool: return bool(get_setting("cliproxy_management_base", "").strip()) and bool( get_setting("cliproxy_management_key", "").strip() ) def _oauth_json_is_codex_candidate(data: dict[str, Any], *, strict_codex_type: bool) -> bool: if data.get("disabled"): return False if strict_codex_type: return data.get("type") == "codex" t = data.get("type") if t == "codex": return True if t in (None, ""): return True return False def _oauth_cpa_id_from_json(data: dict[str, Any]) -> int: cid = data.get("cpa_id") if cid is None: return 1 try: return int(cid) except (TypeError, ValueError): return 1 def parse_inspect_probe_cache() -> Optional[dict[str, Any]]: raw = get_setting("inspect_probe_valid_json", "").strip() if not raw: return None try: o = json.loads(raw) except (json.JSONDecodeError, TypeError): return None if not isinstance(o, dict) or "by_cpa" not in o: return None return o def list_oauth_codex_entries() -> list[dict[str, Any]]: """每个统计目录下 *.json 一条;stem 与 Cliproxy auth 文件名对应。""" root = resolve_oauth_stats_dir() strict = root.resolve() == ACCOUNTS_OAUTH.resolve() out: list[dict[str, Any]] = [] if not root.is_dir(): return out for path in sorted(root.glob("*.json")): try: with open(path, encoding="utf-8") as f: data = json.load(f) except Exception: continue if not isinstance(data, dict): continue if not _oauth_json_is_codex_candidate(data, strict_codex_type=strict): continue cid = _oauth_cpa_id_from_json(data) out.append({"cpa_id": cid, "stem": path.stem, "path": str(path)}) return out def count_oauth_accounts_by_cpa() -> dict[int, int]: """按统计目录统计;无 cpa_id 归入 id=1。""" root = resolve_oauth_stats_dir() strict = root.resolve() == ACCOUNTS_OAUTH.resolve() counts: dict[int, int] = {} if not root.is_dir(): return counts for path in root.glob("*.json"): try: with open(path, encoding="utf-8") as f: data = json.load(f) except Exception: continue if not isinstance(data, dict): continue if not _oauth_json_is_codex_candidate(data, strict_codex_type=strict): continue cid = _oauth_cpa_id_from_json(data) counts[cid] = counts.get(cid, 0) + 1 return counts def overview_stats() -> dict[str, Any]: cpas = list_cpas() by_file = count_oauth_accounts_by_cpa() probe = parse_inspect_probe_cache() use_probe = cliproxy_inspect_configured() and probe is not None by_valid: dict[int, int] = {} if use_probe and isinstance(probe.get("by_cpa"), dict): raw_bc = probe["by_cpa"] for c in cpas: cid = c["id"] v = raw_bc.get(str(cid), raw_bc.get(cid)) if v is None: v = 0 try: by_valid[cid] = int(v) except (TypeError, ValueError): by_valid[cid] = 0 rows = [] total = 0 total_raw = 0 total_target = 0 for c in cpas: cid = c["id"] n_raw = by_file.get(cid, 0) total_raw += n_raw n = by_valid.get(cid, n_raw) if use_probe else n_raw total += n tgt = int(c["target_count"] or 0) total_target += tgt health = (n / tgt * 100.0) if tgt > 0 else 100.0 gap = max(0, tgt - n) status = "健康" if health >= 95 else ("偏低" if health >= 70 else "告警") row: dict[str, Any] = { **c, "candidates": n, "health_pct": round(health, 2), "gap": gap, "status": status, } if use_probe and n_raw != n: row["raw_candidates"] = n_raw rows.append(row) global_health = (total / total_target * 100.0) if total_target > 0 else 100.0 out: dict[str, Any] = { "cpas": rows, "total_accounts": total, "total_candidates": total, "total_target": total_target, "global_health_pct": round(global_health, 2), "global_status": "健康" if global_health >= 95 else ("偏低" if global_health >= 70 else "告警"), "inspect_probe_mode": use_probe, "inspect_last_at": (probe or {}).get("probed_at") if use_probe else None, "total_accounts_raw": total_raw, } if cliproxy_inspect_configured() and not use_probe: out["inspect_probe_pending"] = True stats_root = resolve_oauth_stats_dir() out["oauth_stats_dir"] = str(stats_root) out["oauth_stats_dir_is_default"] = stats_root.resolve() == ACCOUNTS_OAUTH.resolve() return out def create_task( task_type: str, status: str, message: str = "", cpa_id: Optional[int] = None, total: int = 0, ) -> int: now = datetime.now(timezone.utc).isoformat() with _lock: c = _conn() try: cur = c.execute( """INSERT INTO tasks (task_type, status, message, cpa_id, total, done, created_at, updated_at) VALUES (?,?,?,?,?,?,?,?)""", (task_type, status, message, cpa_id, total, 0, now, now), ) c.commit() return int(cur.lastrowid) finally: c.close() def update_task( task_id: int, *, status: Optional[str] = None, message: Optional[str] = None, done: Optional[int] = None, ) -> None: now = datetime.now(timezone.utc).isoformat() parts = ["updated_at=?"] vals: list[Any] = [now] if status is not None: parts.append("status=?") vals.append(status) if message is not None: parts.append("message=?") vals.append(message) if done is not None: parts.append("done=?") vals.append(done) vals.append(task_id) with _lock: c = _conn() try: c.execute(f"UPDATE tasks SET {','.join(parts)} WHERE id=?", vals) c.commit() finally: c.close() def get_active_task() -> Optional[dict[str, Any]]: with _lock: c = _conn() try: row = c.execute( """SELECT * FROM tasks WHERE status IN ('running','queued') ORDER BY id DESC LIMIT 1""" ).fetchone() return dict(row) if row else None finally: c.close() def get_task(task_id: int) -> Optional[dict[str, Any]]: with _lock: c = _conn() try: row = c.execute("SELECT * FROM tasks WHERE id=?", (task_id,)).fetchone() return dict(row) if row else None finally: c.close() def list_recent_tasks(limit: int = 20) -> list[dict[str, Any]]: lim = max(1, min(int(limit), 100)) with _lock: c = _conn() try: rows = c.execute( "SELECT * FROM tasks ORDER BY id DESC LIMIT ?", (lim,), ).fetchall() return [dict(r) for r in rows] finally: c.close()