Physical ops-neko binds to VPS assign cards; assign UI switches local vs remote open without removing douyinweb-neko-*. Co-authored-by: Cursor <cursoragent@cursor.com>
262 lines
8.0 KiB
Python
262 lines
8.0 KiB
Python
# -*- 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)"
|
||
)
|
||
|
||
|
||
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
|
||
|
||
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("/")
|
||
return {
|
||
"ok": True,
|
||
"role": role,
|
||
"peer_base_url": base,
|
||
"public_base": public,
|
||
"has_token": bool(token),
|
||
"token_suffix": token[-4:] if len(token) >= 4 else "",
|
||
"hint": {
|
||
"off": "本机独立运维 Neko,不跨机同步分配卡片",
|
||
"hub": "本机对外发布「YouTube 分配」卡片(通常 VPS);把 token 填到物理机",
|
||
"edge": "本机拉取 hub 的分配卡片并手动绑定(通常物理机 + ShellCrash Neko)",
|
||
}.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)
|