# -*- coding: utf-8 -*- """Ops-tab Neko fleet — independent from yt_assign / youtube_neko. Manual peer pairing (best practice): Hub (usually VPS): generates token, publishes YouTube 分配 cards. Edge (usually physical): pastes hub URL + token, pulls cards, manually binds each ops-neko slot to a remote card. No auto-start of assign Nekos. """ from __future__ import annotations import secrets import sqlite3 import time import uuid from typing import Any, Optional from .db import _connect, _lock, _row_to_dict def ensure_ops_neko_tables(conn: sqlite3.Connection) -> None: conn.execute( """ CREATE TABLE IF NOT EXISTS ops_neko_instances ( id TEXT PRIMARY KEY, slot INTEGER NOT NULL UNIQUE, name TEXT NOT NULL DEFAULT '', note TEXT NOT NULL DEFAULT '', want_running INTEGER NOT NULL DEFAULT 0, bind_remote_group_id TEXT NOT NULL DEFAULT '', bind_remote_name TEXT NOT NULL DEFAULT '', created_at REAL NOT NULL, updated_at REAL NOT NULL ) """ ) conn.execute( "CREATE INDEX IF NOT EXISTS idx_ops_neko_slot ON ops_neko_instances(slot)" ) # Hub-side catalog of physical edge ops-neko instances (pushed by edge). conn.execute( """ CREATE TABLE IF NOT EXISTS ops_neko_edge_catalog ( id TEXT PRIMARY KEY, edge_id TEXT NOT NULL DEFAULT '', edge_label TEXT NOT NULL DEFAULT '', slot INTEGER NOT NULL DEFAULT 0, name TEXT NOT NULL DEFAULT '', open_url TEXT NOT NULL DEFAULT '', running INTEGER NOT NULL DEFAULT 0, last_seen REAL NOT NULL DEFAULT 0, UNIQUE(edge_id, slot) ) """ ) conn.execute( "CREATE INDEX IF NOT EXISTS idx_ops_neko_catalog_seen ON ops_neko_edge_catalog(last_seen DESC)" ) def _ensure() -> None: with _lock: conn = _connect() try: ensure_ops_neko_tables(conn) conn.commit() finally: conn.close() def list_instances() -> list[dict[str, Any]]: _ensure() with _lock: conn = _connect() try: ensure_ops_neko_tables(conn) rows = conn.execute( "SELECT * FROM ops_neko_instances ORDER BY slot ASC" ).fetchall() return [_row_to_dict(r) for r in rows] finally: conn.close() def get_instance(instance_id: str) -> dict[str, Any] | None: _ensure() with _lock: conn = _connect() try: ensure_ops_neko_tables(conn) row = conn.execute( "SELECT * FROM ops_neko_instances WHERE id = ?", (str(instance_id),), ).fetchone() return _row_to_dict(row) if row else None finally: conn.close() def next_slot() -> int: rows = list_instances() used = {int(r.get("slot") or 0) for r in rows} slot = 1 while slot in used: slot += 1 return slot def create_instance(*, name: str = "", note: str = "") -> dict[str, Any]: """Create a stopped ops-neko slot (want_running=0). Docker create is separate.""" _ensure() now = time.time() slot = next_slot() cid = str(uuid.uuid4()) label = (name or f"Ops Neko {slot}").strip()[:120] with _lock: conn = _connect() try: ensure_ops_neko_tables(conn) conn.execute( """ INSERT INTO ops_neko_instances( id, slot, name, note, want_running, bind_remote_group_id, bind_remote_name, created_at, updated_at ) VALUES (?, ?, ?, ?, 0, '', '', ?, ?) """, (cid, slot, label, str(note or "")[:500], now, now), ) conn.commit() row = conn.execute( "SELECT * FROM ops_neko_instances WHERE id = ?", (cid,) ).fetchone() return _row_to_dict(row) if row else {"id": cid, "slot": slot} finally: conn.close() def update_instance(instance_id: str, **fields: Any) -> dict[str, Any] | None: allowed = { "name", "note", "want_running", "bind_remote_group_id", "bind_remote_name", } patch: dict[str, Any] = {} for k, v in fields.items(): if k not in allowed or v is None: continue if k == "want_running": patch[k] = 1 if v else 0 elif k in {"name", "note", "bind_remote_group_id", "bind_remote_name"}: patch[k] = str(v).strip() if k == "name": patch[k] = patch[k][:120] if k == "note": patch[k] = patch[k][:500] if k == "bind_remote_group_id": patch[k] = patch[k][:64] if k == "bind_remote_name": patch[k] = patch[k][:120] if not patch: return get_instance(instance_id) patch["updated_at"] = time.time() with _lock: conn = _connect() try: ensure_ops_neko_tables(conn) sets = ", ".join(f"{k} = ?" for k in patch) params = list(patch.values()) + [str(instance_id)] conn.execute( f"UPDATE ops_neko_instances SET {sets} WHERE id = ?", params, ) conn.commit() row = conn.execute( "SELECT * FROM ops_neko_instances WHERE id = ?", (str(instance_id),), ).fetchone() return _row_to_dict(row) if row else None finally: conn.close() def delete_instance(instance_id: str) -> bool: with _lock: conn = _connect() try: ensure_ops_neko_tables(conn) cur = conn.execute( "DELETE FROM ops_neko_instances WHERE id = ?", (str(instance_id),), ) conn.commit() return int(cur.rowcount or 0) > 0 finally: conn.close() def max_slot() -> int: rows = list_instances() if not rows: return 0 return max(int(r.get("slot") or 0) for r in rows) # --- peer settings (kv) --- PEER_KEYS = ( "ops_neko_peer_role", # off | hub | edge "ops_neko_peer_token", "ops_neko_peer_base_url", "ops_neko_public_base", # where browser opens /ops-neko/N/ (may be .cn) ) def peer_status() -> dict[str, Any]: from . import db from . import youtube_neko cfg = db.get_settings_map() role = str(cfg.get("ops_neko_peer_role") or "off").strip().lower() if role not in {"off", "hub", "edge"}: role = "off" token = str(cfg.get("ops_neko_peer_token") or "").strip() base = str(cfg.get("ops_neko_peer_base_url") or "").strip().rstrip("/") public = str(cfg.get("ops_neko_public_base") or "").strip().rstrip("/") effective = youtube_neko.preferred_neko_public_base(override=public) return { "ok": True, "role": role, "peer_base_url": base, "public_base": public, "effective_public_base": effective, "cn_edge_usable": youtube_neko.cn_edge_usable() if youtube_neko._physical_dual_edge() else False, # noqa: SLF001 "has_token": bool(token), "token_suffix": token[-4:] if len(token) >= 4 else "", "hint": { "off": "本机独立运维 Neko(与分配页同一套 Studio/TM/代理配置)", "hub": "本机对外发布「YouTube 分配」卡片(通常 VPS);把 token 填到物理机", "edge": "物理机:Neko 优先腾讯云 wg-dy-cn(.cn);不通才回退 VPS(.com)。实例配置与分配页一致。", }.get(role, ""), } def save_peer( *, role: Optional[str] = None, peer_base_url: Optional[str] = None, public_base: Optional[str] = None, token: Optional[str] = None, rotate_token: bool = False, ) -> dict[str, Any]: from . import db patch: dict[str, Any] = {} if role is not None: r = str(role).strip().lower() if r not in {"off", "hub", "edge"}: raise ValueError("role must be off|hub|edge") patch["ops_neko_peer_role"] = r if peer_base_url is not None: patch["ops_neko_peer_base_url"] = str(peer_base_url).strip().rstrip("/") if public_base is not None: patch["ops_neko_public_base"] = str(public_base).strip().rstrip("/") if rotate_token: patch["ops_neko_peer_token"] = secrets.token_urlsafe(24) elif token is not None: patch["ops_neko_peer_token"] = str(token).strip() if patch: db.update_settings_map(patch) out = peer_status() if rotate_token or (token is not None and str(token).strip()): cfg = db.get_settings_map() out["token"] = str(cfg.get("ops_neko_peer_token") or "") return out def verify_peer_token(provided: str) -> bool: from . import db cfg = db.get_settings_map() want = str(cfg.get("ops_neko_peer_token") or "").strip() got = str(provided or "").strip() return bool(want) and bool(got) and secrets.compare_digest(want, got) def ensure_hub_credentials(*, rotate: bool = False) -> dict[str, Any]: """VPS hub pairing card: public domain + token (create if missing).""" from . import db from . import host_profile from .config import settings profile = host_profile.infer_profile() cfg = db.get_settings_map() role = str(cfg.get("ops_neko_peer_role") or "off").strip().lower() token = str(cfg.get("ops_neko_peer_token") or "").strip() patch: dict[str, Any] = {} if profile == "vps" and role != "hub": patch["ops_neko_peer_role"] = "hub" role = "hub" if rotate or (role == "hub" and not token): patch["ops_neko_peer_token"] = secrets.token_urlsafe(24) if patch: db.update_settings_map(patch) cfg = db.get_settings_map() role = str(cfg.get("ops_neko_peer_role") or role).strip().lower() token = str(cfg.get("ops_neko_peer_token") or "").strip() domain = str(getattr(settings, "public_base_url", "") or "").strip().rstrip("/") if not domain: domain = str(cfg.get("public_base_url") or "").strip().rstrip("/") st = peer_status() st["profile"] = profile st["domain"] = domain st["token"] = token if role == "hub" else "" st["ready"] = bool(role == "hub" and domain and token) return st def upsert_edge_catalog( items: list[dict[str, Any]], *, edge_id: str = "", edge_label: str = "", ) -> list[dict[str, Any]]: """Replace/merge catalog rows pushed by a physical edge.""" _ensure() now = time.time() eid = str(edge_id or edge_label or "edge").strip()[:80] or "edge" elabel = str(edge_label or eid).strip()[:120] rows_out: list[dict[str, Any]] = [] with _lock: conn = _connect() try: ensure_ops_neko_tables(conn) for it in items or []: slot = int(it.get("slot") or 0) if slot < 1: continue open_url = str(it.get("open_url") or "").strip() if open_url and not open_url.endswith("/"): open_url = f"{open_url}/" name = str(it.get("name") or f"Ops Neko {slot}").strip()[:120] running = 1 if it.get("running") else 0 rid = str(it.get("id") or f"{eid}:{slot}")[:80] conn.execute( """ INSERT INTO ops_neko_edge_catalog( id, edge_id, edge_label, slot, name, open_url, running, last_seen ) VALUES (?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(edge_id, slot) DO UPDATE SET id=excluded.id, edge_label=excluded.edge_label, name=excluded.name, open_url=excluded.open_url, running=excluded.running, last_seen=excluded.last_seen """, (rid, eid, elabel, slot, name, open_url, running, now), ) # Drop stale rows for this edge not in the push (optional cleanup) keep_slots = {int(it.get("slot") or 0) for it in (items or []) if int(it.get("slot") or 0) > 0} if keep_slots: placeholders = ",".join("?" * len(keep_slots)) conn.execute( f"DELETE FROM ops_neko_edge_catalog WHERE edge_id = ? AND slot NOT IN ({placeholders})", (eid, *sorted(keep_slots)), ) conn.commit() rows = conn.execute( "SELECT * FROM ops_neko_edge_catalog ORDER BY edge_label ASC, slot ASC" ).fetchall() rows_out = [_row_to_dict(r) for r in rows] finally: conn.close() return rows_out def list_edge_catalog(*, max_age_sec: float = 86400.0) -> list[dict[str, Any]]: """Hub UI dropdown: recent physical ops-neko instances.""" _ensure() cutoff = time.time() - float(max_age_sec) with _lock: conn = _connect() try: ensure_ops_neko_tables(conn) rows = conn.execute( """ SELECT * FROM ops_neko_edge_catalog WHERE last_seen >= ? AND open_url != '' ORDER BY edge_label ASC, slot ASC """, (cutoff,), ).fetchall() return [_row_to_dict(r) for r in rows] finally: conn.close()