# -*- coding: utf-8 -*- """Load Douyin cookie from sh2 config.ini (same source as DouyinLiveRecorder).""" from __future__ import annotations import configparser from pathlib import Path from typing import Optional # Known sh2 cookie locations — first hit wins DEFAULT_COOKIE_PATHS = [ Path(r"C:\project\sh2\d2ypp2\config\config.ini"), Path(__file__).resolve().parents[2] / "config" / "douyin_cookie.ini", ] def read_ini_cookie(path: Path, section: str = "Cookie", key: str = "抖音cookie") -> str: if not path.is_file(): return "" # RawConfigParser: cookie values contain many '%' encodings parser = configparser.RawConfigParser() try: parser.read(path, encoding="utf-8") except Exception: try: parser.read(path, encoding="utf-8-sig") except Exception: return "" if not parser.has_section(section): return "" try: return (parser.get(section, key) or "").strip() except Exception: # try ascii key aliases for alt in ("douyin_cookie", "dy_cookie", "抖音cookie"): try: return (parser.get(section, alt) or "").strip() except Exception: continue return "" def find_sh2_cookie(extra_paths: Optional[list[Path]] = None) -> tuple[str, str]: """Return (cookie, source_path). Empty cookie if not found.""" paths = list(extra_paths or []) + list(DEFAULT_COOKIE_PATHS) seen: set[str] = set() for p in paths: key = str(p.resolve()) if p.exists() else str(p) if key in seen: continue seen.add(key) cookie = read_ini_cookie(p) if cookie: return cookie, str(p) return "", "" def bootstrap_cookie_into_db() -> dict: """If dy_cookie empty, import from sh2 config.ini.""" from . import db db.init_db() cfg = db.get_settings_map() current = str(cfg.get("dy_cookie") or "").strip() if current: return {"ok": True, "action": "keep", "length": len(current), "source": "db"} cookie, source = find_sh2_cookie() if not cookie: return {"ok": False, "action": "missing", "length": 0, "source": ""} db.update_settings_map({"dy_cookie": cookie}) return {"ok": True, "action": "imported", "length": len(cookie), "source": source} def force_sync_cookie_from_sh2() -> dict: """Always overwrite dy_cookie from sh2 if present.""" from . import db db.init_db() cookie, source = find_sh2_cookie() if not cookie: return {"ok": False, "action": "missing", "length": 0, "source": ""} db.update_settings_map({"dy_cookie": cookie}) return {"ok": True, "action": "synced", "length": len(cookie), "source": source}