import json import threading from pathlib import Path ROOT = Path(__file__).resolve().parents[3] PATH = ROOT / "cache" / "huangdou" / "accounts.json" _lock = threading.Lock() def load() -> list[dict]: with _lock: return _parse() def replace(rows: list) -> list[dict]: cleaned = [] seen: set[str] = set() if isinstance(rows, list): for item in rows: if not isinstance(item, dict): continue username = str(item.get("username") or "").strip() password = str(item.get("password") or "") if not username or not password or username in seen: continue seen.add(username) cleaned.append( { "username": username, "password": password, "nickname": str(item.get("nickname") or "").strip(), } ) if len(cleaned) >= 30: break with _lock: PATH.parent.mkdir(parents=True, exist_ok=True) temporary = PATH.with_suffix(".json.tmp") temporary.write_text(json.dumps({"accounts": cleaned}, ensure_ascii=False), encoding="utf-8") temporary.replace(PATH) return cleaned def _parse() -> list[dict]: if not PATH.is_file(): return [] try: data = json.loads(PATH.read_text(encoding="utf-8")) except (OSError, json.JSONDecodeError): return [] rows = data.get("accounts") if isinstance(data, dict) else None if not isinstance(rows, list): return [] cleaned = [] seen: set[str] = set() for item in rows: if not isinstance(item, dict): continue username = str(item.get("username") or "").strip() password = str(item.get("password") or "") if not username or not password or username in seen: continue seen.add(username) cleaned.append( { "username": username, "password": password, "nickname": str(item.get("nickname") or "").strip(), } ) return cleaned