Add ops Neko tab with hub/edge pairing; keep native assign Neko.
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>
This commit is contained in:
parent
e82407fceb
commit
d3f17f7477
@ -343,11 +343,13 @@ def init_db() -> None:
|
|||||||
from . import x_clips_db as _x_clips_db
|
from . import x_clips_db as _x_clips_db
|
||||||
from . import yt_long_db as _yt_long_db
|
from . import yt_long_db as _yt_long_db
|
||||||
from . import yt_assign_db as _yt_assign_db
|
from . import yt_assign_db as _yt_assign_db
|
||||||
|
from . import ops_neko_db as _ops_neko_db
|
||||||
|
|
||||||
_x2_db.ensure_x2_tables(conn)
|
_x2_db.ensure_x2_tables(conn)
|
||||||
_x_clips_db.ensure_x_clips_tables(conn)
|
_x_clips_db.ensure_x_clips_tables(conn)
|
||||||
_yt_long_db.ensure_yt_long_tables(conn)
|
_yt_long_db.ensure_yt_long_tables(conn)
|
||||||
_yt_assign_db.ensure_yt_assign_tables(conn)
|
_yt_assign_db.ensure_yt_assign_tables(conn)
|
||||||
|
_ops_neko_db.ensure_ops_neko_tables(conn)
|
||||||
_caption_pool.ensure_caption_pool_table(conn)
|
_caption_pool.ensure_caption_pool_table(conn)
|
||||||
_caption_pool.seed_caption_pool(conn)
|
_caption_pool.seed_caption_pool(conn)
|
||||||
sc_cols = {r[1] for r in conn.execute("PRAGMA table_info(shorts_channels)").fetchall()}
|
sc_cols = {r[1] for r in conn.execute("PRAGMA table_info(shorts_channels)").fetchall()}
|
||||||
@ -504,6 +506,11 @@ def _seed_defaults(conn: sqlite3.Connection) -> None:
|
|||||||
"egress_cover_uploads": True,
|
"egress_cover_uploads": True,
|
||||||
# Host shape: vps (lean) | physical (ShellCrash + multi-Neko). Empty = infer.
|
# Host shape: vps (lean) | physical (ShellCrash + multi-Neko). Empty = infer.
|
||||||
"host_profile": "",
|
"host_profile": "",
|
||||||
|
# Ops Neko peer (independent of YouTube 分配 Neko)
|
||||||
|
"ops_neko_peer_role": "off",
|
||||||
|
"ops_neko_peer_token": "",
|
||||||
|
"ops_neko_peer_base_url": "",
|
||||||
|
"ops_neko_public_base": "",
|
||||||
# TikTok pipeline (fully isolated from Shorts)
|
# TikTok pipeline (fully isolated from Shorts)
|
||||||
"tiktok_enabled": False,
|
"tiktok_enabled": False,
|
||||||
"tiktok_clip_sec": 75,
|
"tiktok_clip_sec": 75,
|
||||||
|
|||||||
@ -3212,6 +3212,22 @@ async def youtube_assign_group_neko(group_id: str, body: dict[str, Any] | None =
|
|||||||
return {"ok": True, "group": g, "neko": neko_result or inst}
|
return {"ok": True, "group": g, "neko": neko_result or inst}
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/api/youtube/assign/groups/{group_id}/neko-open-prefer")
|
||||||
|
async def youtube_assign_neko_open_prefer(group_id: str, body: dict[str, Any] = Body(default={})) -> dict[str, Any]:
|
||||||
|
"""Switch default「打开工作室」target: local native Neko vs paired physical ops-neko.
|
||||||
|
|
||||||
|
Native douyinweb-neko-* is always retained (default stopped). This only changes which URL is preferred.
|
||||||
|
"""
|
||||||
|
prefer = str((body or {}).get("prefer") or "").strip().lower()
|
||||||
|
try:
|
||||||
|
g = await asyncio.to_thread(yt_assign_db.set_neko_open_prefer, group_id, prefer)
|
||||||
|
except ValueError as exc:
|
||||||
|
raise HTTPException(400, str(exc)) from exc
|
||||||
|
if not g:
|
||||||
|
raise HTTPException(404, "分组不存在")
|
||||||
|
return {"ok": True, "group": g}
|
||||||
|
|
||||||
|
|
||||||
@app.delete("/api/youtube/assign/groups/{group_id}")
|
@app.delete("/api/youtube/assign/groups/{group_id}")
|
||||||
async def yt_assign_delete_group(group_id: str) -> dict[str, Any]:
|
async def yt_assign_delete_group(group_id: str) -> dict[str, Any]:
|
||||||
return yt_assign_db.delete_group(group_id)
|
return yt_assign_db.delete_group(group_id)
|
||||||
@ -3646,6 +3662,177 @@ async def ops_host_profile_set(body: dict[str, Any]) -> dict[str, Any]:
|
|||||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||||
|
|
||||||
|
|
||||||
|
# ----- Ops Neko fleet (independent of YouTube 分配 Neko) -----
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/ops/neko")
|
||||||
|
async def ops_neko_overview() -> dict[str, Any]:
|
||||||
|
from . import host_profile
|
||||||
|
from . import ops_neko
|
||||||
|
from . import ops_neko_db
|
||||||
|
|
||||||
|
return {
|
||||||
|
"ok": True,
|
||||||
|
"peer": await asyncio.to_thread(ops_neko_db.peer_status),
|
||||||
|
"host_profile": await asyncio.to_thread(host_profile.status),
|
||||||
|
"instances": await asyncio.to_thread(ops_neko.list_enriched),
|
||||||
|
"isolation": {
|
||||||
|
"assign_prefix": "douyinweb-neko-",
|
||||||
|
"ops_prefix": "douyinweb-ops-neko-",
|
||||||
|
"ops_http_base": ops_neko.HTTP_BASE,
|
||||||
|
"ops_mux_base": ops_neko.MUX_BASE,
|
||||||
|
"path": "/ops-neko/{slot}/",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/api/ops/neko/instances")
|
||||||
|
async def ops_neko_create(body: dict[str, Any] = Body(default={})) -> dict[str, Any]:
|
||||||
|
"""Create ops-neko slot; Docker provisioned stopped (default)."""
|
||||||
|
from . import ops_neko
|
||||||
|
|
||||||
|
name = str((body or {}).get("name") or "")
|
||||||
|
note = str((body or {}).get("note") or "")
|
||||||
|
try:
|
||||||
|
return await asyncio.to_thread(ops_neko.create_and_provision, name=name, note=note)
|
||||||
|
except Exception as exc:
|
||||||
|
raise HTTPException(status_code=500, detail=str(exc)[:400]) from exc
|
||||||
|
|
||||||
|
|
||||||
|
@app.patch("/api/ops/neko/instances/{instance_id}")
|
||||||
|
async def ops_neko_patch(instance_id: str, body: dict[str, Any] = Body(default={})) -> dict[str, Any]:
|
||||||
|
from . import ops_neko
|
||||||
|
from . import ops_neko_db
|
||||||
|
|
||||||
|
row = await asyncio.to_thread(
|
||||||
|
ops_neko_db.update_instance,
|
||||||
|
instance_id,
|
||||||
|
name=body.get("name"),
|
||||||
|
note=body.get("note"),
|
||||||
|
bind_remote_group_id=body.get("bind_remote_group_id"),
|
||||||
|
bind_remote_name=body.get("bind_remote_name"),
|
||||||
|
)
|
||||||
|
if not row:
|
||||||
|
raise HTTPException(status_code=404, detail="not found")
|
||||||
|
return {"ok": True, "instance": await asyncio.to_thread(ops_neko.enrich, row)}
|
||||||
|
|
||||||
|
|
||||||
|
@app.delete("/api/ops/neko/instances/{instance_id}")
|
||||||
|
async def ops_neko_delete(instance_id: str) -> dict[str, Any]:
|
||||||
|
from . import ops_neko
|
||||||
|
|
||||||
|
return await asyncio.to_thread(ops_neko.remove_instance, instance_id)
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/api/ops/neko/instances/{instance_id}/start")
|
||||||
|
async def ops_neko_start(instance_id: str) -> dict[str, Any]:
|
||||||
|
from . import ops_neko
|
||||||
|
from . import ops_neko_db
|
||||||
|
|
||||||
|
inst = await asyncio.to_thread(ops_neko_db.get_instance, instance_id)
|
||||||
|
if not inst:
|
||||||
|
raise HTTPException(status_code=404, detail="not found")
|
||||||
|
return await asyncio.to_thread(ops_neko.start_slot, int(inst.get("slot") or 0))
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/api/ops/neko/instances/{instance_id}/stop")
|
||||||
|
async def ops_neko_stop(instance_id: str) -> dict[str, Any]:
|
||||||
|
from . import ops_neko
|
||||||
|
from . import ops_neko_db
|
||||||
|
|
||||||
|
inst = await asyncio.to_thread(ops_neko_db.get_instance, instance_id)
|
||||||
|
if not inst:
|
||||||
|
raise HTTPException(status_code=404, detail="not found")
|
||||||
|
return await asyncio.to_thread(ops_neko.stop_slot, int(inst.get("slot") or 0))
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/ops/neko/peer")
|
||||||
|
async def ops_neko_peer_get() -> dict[str, Any]:
|
||||||
|
from . import ops_neko_db
|
||||||
|
|
||||||
|
return await asyncio.to_thread(ops_neko_db.peer_status)
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/api/ops/neko/peer")
|
||||||
|
async def ops_neko_peer_set(body: dict[str, Any] = Body(default={})) -> dict[str, Any]:
|
||||||
|
from . import ops_neko_db
|
||||||
|
|
||||||
|
try:
|
||||||
|
return await asyncio.to_thread(
|
||||||
|
ops_neko_db.save_peer,
|
||||||
|
role=body.get("role"),
|
||||||
|
peer_base_url=body.get("peer_base_url"),
|
||||||
|
public_base=body.get("public_base"),
|
||||||
|
token=body.get("token"),
|
||||||
|
rotate_token=bool(body.get("rotate_token")),
|
||||||
|
)
|
||||||
|
except ValueError as exc:
|
||||||
|
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/ops/neko/hub/assign-cards")
|
||||||
|
async def ops_neko_hub_assign_cards(request: Request) -> dict[str, Any]:
|
||||||
|
"""Token-auth export of YouTube 分配 cards for physical edge binding."""
|
||||||
|
from . import ops_neko
|
||||||
|
from . import ops_neko_db
|
||||||
|
|
||||||
|
token = (
|
||||||
|
request.headers.get("X-Ops-Neko-Token")
|
||||||
|
or request.headers.get("x-ops-neko-token")
|
||||||
|
or ""
|
||||||
|
).strip()
|
||||||
|
if not await asyncio.to_thread(ops_neko_db.verify_peer_token, token):
|
||||||
|
raise HTTPException(status_code=401, detail="invalid ops neko peer token")
|
||||||
|
st = await asyncio.to_thread(ops_neko_db.peer_status)
|
||||||
|
cards = await asyncio.to_thread(ops_neko.hub_assign_cards)
|
||||||
|
return {"ok": True, "time": time.time(), "cards": cards, "role": st.get("role")}
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/api/ops/neko/hub/bind")
|
||||||
|
async def ops_neko_hub_bind(request: Request, body: dict[str, Any] = Body(default={})) -> dict[str, Any]:
|
||||||
|
"""Physical edge registers: VPS assign group → ops-neko open URL."""
|
||||||
|
from . import ops_neko_db
|
||||||
|
from . import yt_assign_db
|
||||||
|
|
||||||
|
token = (
|
||||||
|
request.headers.get("X-Ops-Neko-Token")
|
||||||
|
or request.headers.get("x-ops-neko-token")
|
||||||
|
or ""
|
||||||
|
).strip()
|
||||||
|
if not await asyncio.to_thread(ops_neko_db.verify_peer_token, token):
|
||||||
|
raise HTTPException(status_code=401, detail="invalid ops neko peer token")
|
||||||
|
gid = str((body or {}).get("group_id") or "").strip()
|
||||||
|
open_url = str((body or {}).get("open_url") or "").strip()
|
||||||
|
if not gid or not open_url:
|
||||||
|
raise HTTPException(status_code=400, detail="group_id and open_url required")
|
||||||
|
row = await asyncio.to_thread(
|
||||||
|
yt_assign_db.set_ops_neko_bind,
|
||||||
|
gid,
|
||||||
|
open_url=open_url,
|
||||||
|
slot=int((body or {}).get("slot") or 0),
|
||||||
|
edge_label=str((body or {}).get("edge_label") or ""),
|
||||||
|
)
|
||||||
|
if not row:
|
||||||
|
raise HTTPException(status_code=404, detail="assign group not found")
|
||||||
|
return {"ok": True, "group": row}
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/api/ops/neko/remote-cards")
|
||||||
|
async def ops_neko_remote_cards() -> dict[str, Any]:
|
||||||
|
"""Edge pulls assign cards from configured hub."""
|
||||||
|
from . import ops_neko
|
||||||
|
|
||||||
|
return await asyncio.to_thread(ops_neko.pull_remote_cards)
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/api/ops/neko/instances/{instance_id}/push-bind")
|
||||||
|
async def ops_neko_push_bind(instance_id: str) -> dict[str, Any]:
|
||||||
|
"""Edge: push current bind to VPS hub so assign「打开工作室」hits this ops-neko."""
|
||||||
|
from . import ops_neko
|
||||||
|
|
||||||
|
return await asyncio.to_thread(ops_neko.push_bind_to_hub, instance_id)
|
||||||
|
|
||||||
|
|
||||||
@app.get("/api/ops")
|
@app.get("/api/ops")
|
||||||
async def ops_snapshot() -> dict[str, Any]:
|
async def ops_snapshot() -> dict[str, Any]:
|
||||||
"""Umami / ntfy / DNS / systemd health snapshot for the ops control page."""
|
"""Umami / ntfy / DNS / systemd health snapshot for the ops control page."""
|
||||||
|
|||||||
383
backend/app/ops_neko.py
Normal file
383
backend/app/ops_neko.py
Normal file
@ -0,0 +1,383 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""Ops-tab Neko Docker fleet — isolated from youtube_neko (assign).
|
||||||
|
|
||||||
|
Containers: douyinweb-ops-neko-{slot}
|
||||||
|
HTTP ports: 18200+(slot-1) (assign uses 9200+)
|
||||||
|
WebRTC mux: 62300+(slot-1) (assign uses 52300+)
|
||||||
|
Path for Caddy: /ops-neko/{slot}/ → host:1820x
|
||||||
|
|
||||||
|
Create always leaves containers stopped unless start() is called.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import shutil
|
||||||
|
import subprocess
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from . import ops_neko_db
|
||||||
|
from .config import settings
|
||||||
|
|
||||||
|
|
||||||
|
HTTP_BASE = 18200
|
||||||
|
MUX_BASE = 62300
|
||||||
|
UDP_BASE = 62500
|
||||||
|
UDP_SPAN = 10
|
||||||
|
|
||||||
|
|
||||||
|
def _run(cmd: list[str], timeout: int = 60) -> tuple[int, str]:
|
||||||
|
try:
|
||||||
|
p = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout, check=False)
|
||||||
|
return int(p.returncode), ((p.stdout or "") + (p.stderr or "")).strip()
|
||||||
|
except Exception as exc:
|
||||||
|
return 1, str(exc)
|
||||||
|
|
||||||
|
|
||||||
|
def _root() -> Path:
|
||||||
|
p = settings.data_dir / "ops_neko"
|
||||||
|
p.mkdir(parents=True, exist_ok=True)
|
||||||
|
(p / "profiles").mkdir(parents=True, exist_ok=True)
|
||||||
|
return p
|
||||||
|
|
||||||
|
|
||||||
|
def _compose_path() -> Path:
|
||||||
|
return _root() / "docker-compose.yml"
|
||||||
|
|
||||||
|
|
||||||
|
def _container_name(slot: int) -> str:
|
||||||
|
return f"douyinweb-ops-neko-{int(slot)}"
|
||||||
|
|
||||||
|
|
||||||
|
def _http_port(slot: int) -> int:
|
||||||
|
return HTTP_BASE + int(slot) - 1
|
||||||
|
|
||||||
|
|
||||||
|
def _mux(slot: int) -> int:
|
||||||
|
return MUX_BASE + int(slot) - 1
|
||||||
|
|
||||||
|
|
||||||
|
def _udp_range(slot: int) -> str:
|
||||||
|
lo = UDP_BASE + (int(slot) - 1) * UDP_SPAN
|
||||||
|
hi = lo + UDP_SPAN - 1
|
||||||
|
return f"{lo}-{hi}"
|
||||||
|
|
||||||
|
|
||||||
|
def _q(value: str) -> str:
|
||||||
|
return json.dumps(str(value), ensure_ascii=False)
|
||||||
|
|
||||||
|
|
||||||
|
def _http_bind() -> str:
|
||||||
|
return str(getattr(settings, "neko_http_bind", "") or "127.0.0.1").strip() or "127.0.0.1"
|
||||||
|
|
||||||
|
|
||||||
|
def _profile(slot: int) -> Path:
|
||||||
|
p = _root() / "profiles" / str(int(slot))
|
||||||
|
p.mkdir(parents=True, exist_ok=True)
|
||||||
|
return p
|
||||||
|
|
||||||
|
|
||||||
|
def _instance_id_file(slot: int) -> Path:
|
||||||
|
p = _root() / "instance_ids"
|
||||||
|
p.mkdir(parents=True, exist_ok=True)
|
||||||
|
f = p / f"{int(slot)}.txt"
|
||||||
|
f.write_text(f"ops-{int(slot)}\n", encoding="utf-8")
|
||||||
|
return f
|
||||||
|
|
||||||
|
|
||||||
|
def _compose_cmd(*args: str) -> list[str]:
|
||||||
|
path = str(_compose_path())
|
||||||
|
if shutil.which("docker-compose"):
|
||||||
|
return ["docker-compose", "-f", path, *args]
|
||||||
|
code, _ = _run(["docker", "compose", "version"], timeout=15)
|
||||||
|
if code == 0:
|
||||||
|
return ["docker", "compose", "-f", path, *args]
|
||||||
|
raise RuntimeError("未找到 docker compose")
|
||||||
|
|
||||||
|
|
||||||
|
def _render_compose(max_slot: int) -> str:
|
||||||
|
from . import youtube_neko as yn
|
||||||
|
|
||||||
|
image = str(getattr(settings, "neko_image", "") or "ghcr.io/m1k1o/neko/google-chrome:3.0.0")
|
||||||
|
user_pass = str(getattr(settings, "neko_user_pass", "") or "douyinweb")
|
||||||
|
admin_pass = str(getattr(settings, "neko_admin_pass", "") or "neko")
|
||||||
|
nat1to1 = yn._detect_public_ip() # noqa: SLF001
|
||||||
|
shm = str(getattr(settings, "neko_shm_size", "") or "512mb")
|
||||||
|
screen = str(getattr(settings, "neko_desktop_screen", "") or "1280x720@15")
|
||||||
|
max_fps = str(getattr(settings, "neko_max_fps", "") or "15")
|
||||||
|
bitrate = str(getattr(settings, "neko_video_bitrate", "") or "1200")
|
||||||
|
icelite = str(getattr(settings, "neko_webrtc_icelite", "") or "0")
|
||||||
|
start_url = str(
|
||||||
|
getattr(settings, "neko_start_url", "")
|
||||||
|
or "https://accounts.google.com/ServiceLogin?continue=https://studio.youtube.com/"
|
||||||
|
)
|
||||||
|
assets = yn._asset_root() # noqa: SLF001
|
||||||
|
managed = yn._managed_policies_enabled() # noqa: SLF001
|
||||||
|
policy_dir = assets / ("policies" if managed else "no-managed-policies")
|
||||||
|
seed_dir = assets / "tampermonkey-seed"
|
||||||
|
live_ops_dir = assets / "live-ops-extension"
|
||||||
|
provisioning_dir = assets / "provisioning"
|
||||||
|
browser_launch = assets / "browser-launch.sh"
|
||||||
|
supervisor = assets / yn._supervisor_conf_name() # noqa: SLF001
|
||||||
|
for required in (seed_dir, live_ops_dir, provisioning_dir, browser_launch, supervisor, policy_dir):
|
||||||
|
if not required.exists():
|
||||||
|
raise RuntimeError(f"Neko asset missing: {required}")
|
||||||
|
yn._ensure_browser_launch_exec() # noqa: SLF001
|
||||||
|
proxy = yn._neko_browser_proxy_value() # noqa: SLF001
|
||||||
|
|
||||||
|
lines = ["# Generated by douyinWEB ops_neko — independent of assign fleet", "services:"]
|
||||||
|
n = max(1, int(max_slot))
|
||||||
|
for idx in range(1, n + 1):
|
||||||
|
http_port = _http_port(idx)
|
||||||
|
mux = _mux(idx)
|
||||||
|
udp = _udp_range(idx)
|
||||||
|
profile = _profile(idx)
|
||||||
|
id_file = _instance_id_file(idx)
|
||||||
|
lines.extend(
|
||||||
|
[
|
||||||
|
f" opsneko{idx}:",
|
||||||
|
f" image: {_q(image)}",
|
||||||
|
' restart: "no"',
|
||||||
|
f" shm_size: {_q(shm)}",
|
||||||
|
" cap_add:",
|
||||||
|
" - SYS_ADMIN",
|
||||||
|
" security_opt:",
|
||||||
|
" - apparmor:unconfined",
|
||||||
|
" extra_hosts:",
|
||||||
|
' - "host.docker.internal:host-gateway"',
|
||||||
|
f" container_name: {_container_name(idx)}",
|
||||||
|
" environment:",
|
||||||
|
' TZ: "America/Chicago"',
|
||||||
|
' DISPLAY: ":99.0"',
|
||||||
|
' NEKO_SERVER_BIND: ":8080"',
|
||||||
|
' NEKO_SERVER_PROXY: "true"',
|
||||||
|
' NEKO_MEMBER_PROVIDER: "multiuser"',
|
||||||
|
f" NEKO_MEMBER_MULTIUSER_USER_PASSWORD: {_q(user_pass)}",
|
||||||
|
f" NEKO_MEMBER_MULTIUSER_ADMIN_PASSWORD: {_q(admin_pass)}",
|
||||||
|
f" NEKO_DESKTOP_SCREEN: {_q(screen)}",
|
||||||
|
f" NEKO_MAX_FPS: {_q(max_fps)}",
|
||||||
|
f" NEKO_VIDEO_BITRATE: {_q(bitrate)}",
|
||||||
|
f" NEKO_WEBRTC_ICELITE: {_q(icelite)}",
|
||||||
|
f" NEKO_WEBRTC_NAT1TO1: {_q(nat1to1)}",
|
||||||
|
f" NEKO_WEBRTC_TCPMUX: {_q(str(mux))}",
|
||||||
|
f" NEKO_WEBRTC_UDPMUX: {_q(str(mux))}",
|
||||||
|
f" NEKO_WEBRTC_EPR: {_q(udp)}",
|
||||||
|
f" NEKO_START_URL: {_q(start_url)}",
|
||||||
|
f" NEKO_BROWSER_PROXY: {_q(proxy)}",
|
||||||
|
f" NEKO_INSTANCE_ID: {_q(f'ops-{idx}')}",
|
||||||
|
" ports:",
|
||||||
|
f' - "{_http_bind()}:{http_port}:8080"',
|
||||||
|
f' - "{mux}:{mux}/tcp"',
|
||||||
|
f' - "{mux}:{mux}/udp"',
|
||||||
|
f' - "{udp}:{udp}/udp"',
|
||||||
|
" volumes:",
|
||||||
|
f" - {_q(f'{profile}:/home/neko/.config/chromium')}",
|
||||||
|
f" - {_q(f'{profile}:/home/neko/.config/google-chrome')}",
|
||||||
|
f" - {_q(f'{policy_dir}:/etc/chromium/policies/managed:ro')}",
|
||||||
|
f" - {_q(f'{seed_dir}:/etc/neko/tampermonkey-seed:ro')}",
|
||||||
|
f" - {_q(f'{live_ops_dir}:/etc/neko/live-ops-extension:ro')}",
|
||||||
|
f" - {_q(f'{id_file}:/etc/neko/live-ops-extension/instance_id.txt:ro')}",
|
||||||
|
f" - {_q(f'{provisioning_dir}:/var/www/provisioning:ro')}",
|
||||||
|
f" - {_q(f'{browser_launch}:/etc/neko/browser-launch.sh:ro')}",
|
||||||
|
f" - {_q(f'{supervisor}:/etc/neko/supervisord/{yn._supervisor_conf_name()}:ro')}", # noqa: SLF001
|
||||||
|
]
|
||||||
|
)
|
||||||
|
return "\n".join(lines) + "\n"
|
||||||
|
|
||||||
|
|
||||||
|
def _container_running(slot: int) -> bool:
|
||||||
|
code, out = _run(
|
||||||
|
["docker", "inspect", "-f", "{{.State.Running}}", _container_name(slot)],
|
||||||
|
timeout=8,
|
||||||
|
)
|
||||||
|
return code == 0 and "true" in (out or "").lower()
|
||||||
|
|
||||||
|
|
||||||
|
def _public_neko_url(slot: int) -> str:
|
||||||
|
from . import db
|
||||||
|
|
||||||
|
cfg = db.get_settings_map()
|
||||||
|
base = str(cfg.get("ops_neko_public_base") or "").strip().rstrip("/")
|
||||||
|
if not base:
|
||||||
|
base = str(getattr(settings, "public_base_url", "") or "").strip().rstrip("/")
|
||||||
|
if not base:
|
||||||
|
return f"/ops-neko/{int(slot)}/"
|
||||||
|
return f"{base}/ops-neko/{int(slot)}/"
|
||||||
|
|
||||||
|
|
||||||
|
def sync_compose(*, start_slots: set[int] | None = None) -> dict[str, Any]:
|
||||||
|
"""Rewrite compose for current max slot; create containers; start only requested."""
|
||||||
|
max_slot = max(ops_neko_db.max_slot(), 1) if ops_neko_db.list_instances() else 0
|
||||||
|
if max_slot < 1:
|
||||||
|
return {"ok": True, "skipped": "no_instances"}
|
||||||
|
text = _render_compose(max_slot)
|
||||||
|
_compose_path().write_text(text, encoding="utf-8")
|
||||||
|
start_slots = start_slots or set()
|
||||||
|
code, out = _run(_compose_cmd("up", "-d", "--no-start"), timeout=600)
|
||||||
|
if code != 0 and "--no-start" in (out or "").lower():
|
||||||
|
code, out = _run(_compose_cmd("up", "-d"), timeout=600)
|
||||||
|
if code == 0:
|
||||||
|
for idx in range(1, max_slot + 1):
|
||||||
|
if idx not in start_slots:
|
||||||
|
_run(["docker", "stop", "-t", "5", _container_name(idx)], timeout=30)
|
||||||
|
if code != 0:
|
||||||
|
return {"ok": False, "error": (out or "compose up failed")[:500]}
|
||||||
|
started: list[int] = []
|
||||||
|
for idx in sorted(start_slots):
|
||||||
|
if 1 <= idx <= max_slot:
|
||||||
|
c2, o2 = _run(["docker", "start", _container_name(idx)], timeout=90)
|
||||||
|
if c2 == 0:
|
||||||
|
started.append(idx)
|
||||||
|
else:
|
||||||
|
return {"ok": False, "error": (o2 or "start failed")[:300], "started": started}
|
||||||
|
return {"ok": True, "max_slot": max_slot, "started": started}
|
||||||
|
|
||||||
|
|
||||||
|
def create_and_provision(*, name: str = "", note: str = "") -> dict[str, Any]:
|
||||||
|
row = ops_neko_db.create_instance(name=name, note=note)
|
||||||
|
sync = sync_compose(start_slots=set()) # always stopped after create
|
||||||
|
return {"ok": True, "instance": enrich(row), "docker": sync}
|
||||||
|
|
||||||
|
|
||||||
|
def start_slot(slot: int) -> dict[str, Any]:
|
||||||
|
inst = next((r for r in ops_neko_db.list_instances() if int(r.get("slot") or 0) == int(slot)), None)
|
||||||
|
if not inst:
|
||||||
|
return {"ok": False, "error": "instance not found"}
|
||||||
|
sync = sync_compose(start_slots={int(slot)})
|
||||||
|
if not sync.get("ok"):
|
||||||
|
return sync
|
||||||
|
ops_neko_db.update_instance(str(inst["id"]), want_running=True)
|
||||||
|
return {"ok": True, "instance": enrich(ops_neko_db.get_instance(str(inst["id"])) or inst), "docker": sync}
|
||||||
|
|
||||||
|
|
||||||
|
def stop_slot(slot: int) -> dict[str, Any]:
|
||||||
|
inst = next((r for r in ops_neko_db.list_instances() if int(r.get("slot") or 0) == int(slot)), None)
|
||||||
|
if not inst:
|
||||||
|
return {"ok": False, "error": "instance not found"}
|
||||||
|
code, out = _run(["docker", "stop", "-t", "8", _container_name(int(slot))], timeout=45)
|
||||||
|
ops_neko_db.update_instance(str(inst["id"]), want_running=False)
|
||||||
|
return {
|
||||||
|
"ok": code == 0 or "no such container" in (out or "").lower(),
|
||||||
|
"detail": out[:200],
|
||||||
|
"instance": enrich(ops_neko_db.get_instance(str(inst["id"])) or inst),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def remove_instance(instance_id: str) -> dict[str, Any]:
|
||||||
|
inst = ops_neko_db.get_instance(instance_id)
|
||||||
|
if not inst:
|
||||||
|
return {"ok": False, "error": "not found"}
|
||||||
|
slot = int(inst.get("slot") or 0)
|
||||||
|
_run(["docker", "rm", "-f", _container_name(slot)], timeout=45)
|
||||||
|
ops_neko_db.delete_instance(instance_id)
|
||||||
|
# refresh compose without deleted slot
|
||||||
|
if ops_neko_db.list_instances():
|
||||||
|
sync_compose(start_slots=set())
|
||||||
|
return {"ok": True, "deleted": instance_id, "slot": slot}
|
||||||
|
|
||||||
|
|
||||||
|
def enrich(row: dict[str, Any] | None) -> dict[str, Any]:
|
||||||
|
if not row:
|
||||||
|
return {}
|
||||||
|
out = dict(row)
|
||||||
|
slot = int(out.get("slot") or 0)
|
||||||
|
out["running"] = _container_running(slot) if slot else False
|
||||||
|
out["container"] = _container_name(slot) if slot else ""
|
||||||
|
out["http_port"] = _http_port(slot) if slot else 0
|
||||||
|
out["open_url"] = _public_neko_url(slot) if slot else ""
|
||||||
|
out["want_running"] = bool(out.get("want_running"))
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def list_enriched() -> list[dict[str, Any]]:
|
||||||
|
return [enrich(r) for r in ops_neko_db.list_instances()]
|
||||||
|
|
||||||
|
|
||||||
|
def hub_assign_cards() -> list[dict[str, Any]]:
|
||||||
|
"""Cards published by hub for edge manual binding (YouTube 分配 groups)."""
|
||||||
|
from . import yt_assign_db
|
||||||
|
|
||||||
|
cards = []
|
||||||
|
for g in yt_assign_db.list_groups(include_urls=False):
|
||||||
|
cards.append(
|
||||||
|
{
|
||||||
|
"id": str(g.get("id") or ""),
|
||||||
|
"name": str(g.get("name") or ""),
|
||||||
|
"youtube_channel_id": str(g.get("youtube_channel_id") or ""),
|
||||||
|
"enabled": bool(g.get("enabled")),
|
||||||
|
"neko_instance_id": int(g.get("neko_instance_id") or 0),
|
||||||
|
"assign_neko_enabled": bool(g.get("neko_enabled")),
|
||||||
|
"has_stream_key": bool(str(g.get("stream_key") or "").strip()),
|
||||||
|
# Native always exists on hub; remote bind is additive.
|
||||||
|
"neko_local_studio_url": str(g.get("neko_local_studio_url") or g.get("neko_studio_url") or ""),
|
||||||
|
"ops_neko_open_url": str(g.get("ops_neko_open_url") or ""),
|
||||||
|
"ops_neko_bound": bool(g.get("ops_neko_bound")),
|
||||||
|
"neko_open_prefer": str(g.get("neko_open_prefer") or "local"),
|
||||||
|
}
|
||||||
|
)
|
||||||
|
return cards
|
||||||
|
|
||||||
|
|
||||||
|
def pull_remote_cards() -> dict[str, Any]:
|
||||||
|
"""Edge: HTTP pull hub assign cards using peer URL + token."""
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
from . import db
|
||||||
|
|
||||||
|
st = ops_neko_db.peer_status()
|
||||||
|
if st.get("role") != "edge":
|
||||||
|
return {"ok": False, "error": "peer role is not edge"}
|
||||||
|
base = str(st.get("peer_base_url") or "").strip().rstrip("/")
|
||||||
|
cfg = db.get_settings_map()
|
||||||
|
token = str(cfg.get("ops_neko_peer_token") or "").strip()
|
||||||
|
if not base or not token:
|
||||||
|
return {"ok": False, "error": "请填写 hub 域名与 token"}
|
||||||
|
url = f"{base}/api/ops/neko/hub/assign-cards"
|
||||||
|
try:
|
||||||
|
with httpx.Client(timeout=25.0, trust_env=False, follow_redirects=True) as client:
|
||||||
|
r = client.get(url, headers={"X-Ops-Neko-Token": token})
|
||||||
|
if r.status_code != 200:
|
||||||
|
return {"ok": False, "error": f"hub HTTP {r.status_code}: {r.text[:200]}"}
|
||||||
|
data = r.json()
|
||||||
|
return {"ok": True, "cards": data.get("cards") or [], "hub": base, "fetched_at": data.get("time")}
|
||||||
|
except Exception as exc:
|
||||||
|
return {"ok": False, "error": str(exc)[:300]}
|
||||||
|
|
||||||
|
|
||||||
|
def push_bind_to_hub(instance_id: str) -> dict[str, Any]:
|
||||||
|
"""Edge → hub: register this ops-neko open URL onto the VPS assign group."""
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
from . import db
|
||||||
|
|
||||||
|
st = ops_neko_db.peer_status()
|
||||||
|
if st.get("role") != "edge":
|
||||||
|
return {"ok": False, "error": "仅 edge(物理机)向 hub 登记绑定"}
|
||||||
|
base = str(st.get("peer_base_url") or "").strip().rstrip("/")
|
||||||
|
cfg = db.get_settings_map()
|
||||||
|
token = str(cfg.get("ops_neko_peer_token") or "").strip()
|
||||||
|
if not base or not token:
|
||||||
|
return {"ok": False, "error": "请填写 hub 域名与 token"}
|
||||||
|
inst = ops_neko_db.get_instance(instance_id)
|
||||||
|
if not inst:
|
||||||
|
return {"ok": False, "error": "instance not found"}
|
||||||
|
gid = str(inst.get("bind_remote_group_id") or "").strip()
|
||||||
|
if not gid:
|
||||||
|
return {"ok": False, "error": "尚未选择要绑定的 VPS 分配频道"}
|
||||||
|
open_url = _public_neko_url(int(inst.get("slot") or 0))
|
||||||
|
payload = {
|
||||||
|
"group_id": gid,
|
||||||
|
"open_url": open_url,
|
||||||
|
"slot": int(inst.get("slot") or 0),
|
||||||
|
"edge_label": str(inst.get("name") or f"ops-{inst.get('slot')}"),
|
||||||
|
"running": _container_running(int(inst.get("slot") or 0)),
|
||||||
|
}
|
||||||
|
url = f"{base}/api/ops/neko/hub/bind"
|
||||||
|
try:
|
||||||
|
with httpx.Client(timeout=25.0, trust_env=False, follow_redirects=True) as client:
|
||||||
|
r = client.post(url, headers={"X-Ops-Neko-Token": token}, json=payload)
|
||||||
|
if r.status_code != 200:
|
||||||
|
return {"ok": False, "error": f"hub HTTP {r.status_code}: {r.text[:200]}", "payload": payload}
|
||||||
|
return {"ok": True, "hub": base, "payload": payload, "response": r.json()}
|
||||||
|
except Exception as exc:
|
||||||
|
return {"ok": False, "error": str(exc)[:300], "payload": payload}
|
||||||
261
backend/app/ops_neko_db.py
Normal file
261
backend/app/ops_neko_db.py
Normal file
@ -0,0 +1,261 @@
|
|||||||
|
# -*- 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)
|
||||||
@ -36,6 +36,8 @@ _PUBLIC_API_EXACT = {
|
|||||||
"/api/x2/extension/ws",
|
"/api/x2/extension/ws",
|
||||||
"/api/youtube/studio/ingest",
|
"/api/youtube/studio/ingest",
|
||||||
"/hub/youtube/live/ingest",
|
"/hub/youtube/live/ingest",
|
||||||
|
"/api/ops/neko/hub/assign-cards",
|
||||||
|
"/api/ops/neko/hub/bind",
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@ -98,6 +98,13 @@ def ensure_yt_assign_tables(conn: sqlite3.Connection) -> None:
|
|||||||
for col, ddl in [
|
for col, ddl in [
|
||||||
("neko_instance_id", "INTEGER NOT NULL DEFAULT 0"),
|
("neko_instance_id", "INTEGER NOT NULL DEFAULT 0"),
|
||||||
("neko_enabled", "INTEGER NOT NULL DEFAULT 0"),
|
("neko_enabled", "INTEGER NOT NULL DEFAULT 0"),
|
||||||
|
# Remote ops-neko (physical tab) — additive; never replaces native douyinweb-neko-*
|
||||||
|
("ops_neko_open_url", "TEXT NOT NULL DEFAULT ''"),
|
||||||
|
("ops_neko_slot", "INTEGER NOT NULL DEFAULT 0"),
|
||||||
|
("ops_neko_edge_label", "TEXT NOT NULL DEFAULT ''"),
|
||||||
|
("ops_neko_bound_at", "REAL NOT NULL DEFAULT 0"),
|
||||||
|
# Which desktop the assign「打开」button prefers: local (native) | remote (ops-neko tab)
|
||||||
|
("neko_open_prefer", "TEXT NOT NULL DEFAULT 'local'"),
|
||||||
]:
|
]:
|
||||||
if col not in gcols:
|
if col not in gcols:
|
||||||
conn.execute(f"ALTER TABLE yt_assign_groups ADD COLUMN {col} {ddl}")
|
conn.execute(f"ALTER TABLE yt_assign_groups ADD COLUMN {col} {ddl}")
|
||||||
@ -324,16 +331,107 @@ def _public_group(
|
|||||||
out["featured"] = featured
|
out["featured"] = featured
|
||||||
if slots is not None:
|
if slots is not None:
|
||||||
out["slots"] = slots
|
out["slots"] = slots
|
||||||
|
local_studio = ""
|
||||||
if neko_id > 0:
|
if neko_id > 0:
|
||||||
try:
|
try:
|
||||||
from . import youtube_neko
|
from . import youtube_neko
|
||||||
|
|
||||||
out["neko_studio_url"] = youtube_neko.public_studio_url(neko_id)
|
local_studio = youtube_neko.public_studio_url(neko_id)
|
||||||
except Exception:
|
except Exception:
|
||||||
out["neko_studio_url"] = ""
|
local_studio = ""
|
||||||
|
# Native assign Neko URL is always kept (VPS/physical local docker — default stopped).
|
||||||
|
out["neko_studio_url"] = local_studio
|
||||||
|
out["neko_local_studio_url"] = local_studio
|
||||||
|
|
||||||
|
remote = str(out.get("ops_neko_open_url") or "").strip()
|
||||||
|
if remote and not remote.endswith("/"):
|
||||||
|
remote = f"{remote}/"
|
||||||
|
out["ops_neko_open_url"] = remote
|
||||||
|
out["ops_neko_bound"] = bool(remote)
|
||||||
|
out["ops_neko_slot"] = int(out.get("ops_neko_slot") or 0)
|
||||||
|
prefer = str(out.get("neko_open_prefer") or "local").strip().lower()
|
||||||
|
if prefer not in {"local", "remote"}:
|
||||||
|
prefer = "local"
|
||||||
|
# Cannot prefer remote if unbound — fall back to local.
|
||||||
|
if prefer == "remote" and not remote:
|
||||||
|
prefer = "local"
|
||||||
|
out["neko_open_prefer"] = prefer
|
||||||
|
# Default click target for「打开工作室」— switchable; never deletes native URL.
|
||||||
|
if prefer == "remote" and remote:
|
||||||
|
out["neko_open_url"] = remote
|
||||||
|
out["neko_open_source"] = "remote"
|
||||||
|
else:
|
||||||
|
out["neko_open_url"] = local_studio
|
||||||
|
out["neko_open_source"] = "local"
|
||||||
return out
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def set_ops_neko_bind(
|
||||||
|
group_id: str,
|
||||||
|
*,
|
||||||
|
open_url: str,
|
||||||
|
slot: int = 0,
|
||||||
|
edge_label: str = "",
|
||||||
|
) -> dict[str, Any] | None:
|
||||||
|
"""Hub-side: attach physical ops-neko URL. Does NOT touch native neko_instance_id / neko_enabled."""
|
||||||
|
gid = str(group_id or "").strip()
|
||||||
|
if not gid:
|
||||||
|
return None
|
||||||
|
url = str(open_url or "").strip()
|
||||||
|
if url and not url.endswith("/"):
|
||||||
|
url = f"{url}/"
|
||||||
|
now = time.time()
|
||||||
|
with _lock:
|
||||||
|
conn = _connect()
|
||||||
|
try:
|
||||||
|
ensure_yt_assign_tables(conn)
|
||||||
|
conn.execute(
|
||||||
|
"""
|
||||||
|
UPDATE yt_assign_groups SET
|
||||||
|
ops_neko_open_url = ?,
|
||||||
|
ops_neko_slot = ?,
|
||||||
|
ops_neko_edge_label = ?,
|
||||||
|
ops_neko_bound_at = ?,
|
||||||
|
updated_at = ?
|
||||||
|
WHERE id = ?
|
||||||
|
""",
|
||||||
|
(
|
||||||
|
url,
|
||||||
|
int(slot or 0),
|
||||||
|
str(edge_label or "")[:120],
|
||||||
|
now if url else 0,
|
||||||
|
now,
|
||||||
|
gid,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
return get_group(gid)
|
||||||
|
|
||||||
|
|
||||||
|
def set_neko_open_prefer(group_id: str, prefer: str) -> dict[str, Any] | None:
|
||||||
|
"""local = native /neko/N/; remote = paired ops-neko tab URL. Native instance always retained."""
|
||||||
|
p = str(prefer or "local").strip().lower()
|
||||||
|
if p not in {"local", "remote"}:
|
||||||
|
raise ValueError("prefer must be local|remote")
|
||||||
|
gid = str(group_id or "").strip()
|
||||||
|
if not gid:
|
||||||
|
return None
|
||||||
|
with _lock:
|
||||||
|
conn = _connect()
|
||||||
|
try:
|
||||||
|
ensure_yt_assign_tables(conn)
|
||||||
|
conn.execute(
|
||||||
|
"UPDATE yt_assign_groups SET neko_open_prefer = ?, updated_at = ? WHERE id = ?",
|
||||||
|
(p, time.time(), gid),
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
return get_group(gid)
|
||||||
|
|
||||||
|
|
||||||
def _slot_select_sql() -> str:
|
def _slot_select_sql() -> str:
|
||||||
return """
|
return """
|
||||||
SELECT s.*, p.url AS url, p.note AS pool_note, p.title AS title,
|
SELECT s.*, p.url AS url, p.note AS pool_note, p.title AS title,
|
||||||
|
|||||||
430
frontend/src/app/ops/neko/page.tsx
Normal file
430
frontend/src/app/ops/neko/page.tsx
Normal file
@ -0,0 +1,430 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useCallback, useEffect, useState } from "react";
|
||||||
|
import {
|
||||||
|
ExternalLink,
|
||||||
|
Loader2,
|
||||||
|
Monitor,
|
||||||
|
Plus,
|
||||||
|
RefreshCw,
|
||||||
|
Server,
|
||||||
|
Link2,
|
||||||
|
} from "lucide-react";
|
||||||
|
|
||||||
|
import { Shell } from "@/components/Shell";
|
||||||
|
import { useToast } from "@/components/Toast";
|
||||||
|
import { useConfirm } from "@/components/ConfirmDialog";
|
||||||
|
import { fetchJson } from "@/lib/api";
|
||||||
|
|
||||||
|
type Peer = {
|
||||||
|
role?: string;
|
||||||
|
peer_base_url?: string;
|
||||||
|
public_base?: string;
|
||||||
|
has_token?: boolean;
|
||||||
|
token_suffix?: string;
|
||||||
|
token?: string;
|
||||||
|
hint?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
type Instance = {
|
||||||
|
id: string;
|
||||||
|
slot?: number;
|
||||||
|
name?: string;
|
||||||
|
note?: string;
|
||||||
|
running?: boolean;
|
||||||
|
want_running?: boolean;
|
||||||
|
open_url?: string;
|
||||||
|
http_port?: number;
|
||||||
|
bind_remote_group_id?: string;
|
||||||
|
bind_remote_name?: string;
|
||||||
|
container?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
type RemoteCard = {
|
||||||
|
id: string;
|
||||||
|
name?: string;
|
||||||
|
neko_instance_id?: number;
|
||||||
|
ops_neko_bound?: boolean;
|
||||||
|
neko_open_prefer?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export default function OpsNekoPage() {
|
||||||
|
const toast = useToast();
|
||||||
|
const confirm = useConfirm();
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
const [busy, setBusy] = useState("");
|
||||||
|
const [peer, setPeer] = useState<Peer>({});
|
||||||
|
const [instances, setInstances] = useState<Instance[]>([]);
|
||||||
|
const [hostProfile, setHostProfile] = useState("");
|
||||||
|
const [role, setRole] = useState("off");
|
||||||
|
const [peerBase, setPeerBase] = useState("");
|
||||||
|
const [publicBase, setPublicBase] = useState("");
|
||||||
|
const [tokenInput, setTokenInput] = useState("");
|
||||||
|
const [remoteCards, setRemoteCards] = useState<RemoteCard[]>([]);
|
||||||
|
const [newName, setNewName] = useState("");
|
||||||
|
|
||||||
|
const load = useCallback(async () => {
|
||||||
|
try {
|
||||||
|
const d = (await fetchJson("/api/ops/neko")) as {
|
||||||
|
peer?: Peer;
|
||||||
|
instances?: Instance[];
|
||||||
|
host_profile?: { profile?: string };
|
||||||
|
};
|
||||||
|
setPeer(d.peer || {});
|
||||||
|
setInstances(d.instances || []);
|
||||||
|
setHostProfile(String(d.host_profile?.profile || ""));
|
||||||
|
setRole(String(d.peer?.role || "off"));
|
||||||
|
setPeerBase(String(d.peer?.peer_base_url || ""));
|
||||||
|
setPublicBase(String(d.peer?.public_base || ""));
|
||||||
|
} catch (e) {
|
||||||
|
toast.push((e as Error).message, "err");
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
}, [toast]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
void load();
|
||||||
|
}, [load]);
|
||||||
|
|
||||||
|
async function savePeer(extra: Record<string, unknown> = {}) {
|
||||||
|
setBusy("peer");
|
||||||
|
try {
|
||||||
|
const d = (await fetchJson("/api/ops/neko/peer", {
|
||||||
|
method: "POST",
|
||||||
|
body: JSON.stringify({
|
||||||
|
role,
|
||||||
|
peer_base_url: peerBase,
|
||||||
|
public_base: publicBase,
|
||||||
|
token: tokenInput || undefined,
|
||||||
|
...extra,
|
||||||
|
}),
|
||||||
|
})) as Peer & { token?: string };
|
||||||
|
setPeer(d);
|
||||||
|
if (d.token) {
|
||||||
|
setTokenInput(d.token);
|
||||||
|
toast.push("已生成 token(请复制到对端)", "ok");
|
||||||
|
} else {
|
||||||
|
toast.push("配对配置已保存", "ok");
|
||||||
|
}
|
||||||
|
await load();
|
||||||
|
} catch (e) {
|
||||||
|
toast.push((e as Error).message, "err");
|
||||||
|
} finally {
|
||||||
|
setBusy("");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function createInstance() {
|
||||||
|
setBusy("create");
|
||||||
|
try {
|
||||||
|
await fetchJson("/api/ops/neko/instances", {
|
||||||
|
method: "POST",
|
||||||
|
body: JSON.stringify({ name: newName }),
|
||||||
|
});
|
||||||
|
setNewName("");
|
||||||
|
toast.push("已创建 Ops Neko(默认停止,与分配原生 Neko 隔离)", "ok");
|
||||||
|
await load();
|
||||||
|
} catch (e) {
|
||||||
|
toast.push((e as Error).message, "err");
|
||||||
|
} finally {
|
||||||
|
setBusy("");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function act(id: string, action: "start" | "stop" | "delete") {
|
||||||
|
if (action === "delete") {
|
||||||
|
const ok = await confirm({
|
||||||
|
title: "删除此 Ops Neko?",
|
||||||
|
message: "只删运维 Tab 实例,不影响 YouTube 分配页的原生 Neko。",
|
||||||
|
confirmLabel: "删除",
|
||||||
|
destructive: true,
|
||||||
|
});
|
||||||
|
if (!ok) return;
|
||||||
|
}
|
||||||
|
setBusy(id + action);
|
||||||
|
try {
|
||||||
|
if (action === "delete") {
|
||||||
|
await fetchJson(`/api/ops/neko/instances/${encodeURIComponent(id)}`, { method: "DELETE" });
|
||||||
|
} else {
|
||||||
|
await fetchJson(`/api/ops/neko/instances/${encodeURIComponent(id)}/${action}`, {
|
||||||
|
method: "POST",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
await load();
|
||||||
|
} catch (e) {
|
||||||
|
toast.push((e as Error).message, "err");
|
||||||
|
} finally {
|
||||||
|
setBusy("");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function pullCards() {
|
||||||
|
setBusy("pull");
|
||||||
|
try {
|
||||||
|
const d = (await fetchJson("/api/ops/neko/remote-cards", { method: "POST" })) as {
|
||||||
|
ok?: boolean;
|
||||||
|
cards?: RemoteCard[];
|
||||||
|
error?: string;
|
||||||
|
};
|
||||||
|
if (!d.ok) throw new Error(d.error || "拉取失败");
|
||||||
|
setRemoteCards(d.cards || []);
|
||||||
|
toast.push(`已拉取 ${(d.cards || []).length} 张 VPS 分配卡片`, "ok");
|
||||||
|
} catch (e) {
|
||||||
|
toast.push((e as Error).message, "err");
|
||||||
|
} finally {
|
||||||
|
setBusy("");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function bindAndPush(inst: Instance, card: RemoteCard) {
|
||||||
|
setBusy("bind");
|
||||||
|
try {
|
||||||
|
await fetchJson(`/api/ops/neko/instances/${encodeURIComponent(inst.id)}`, {
|
||||||
|
method: "PATCH",
|
||||||
|
body: JSON.stringify({
|
||||||
|
bind_remote_group_id: card.id,
|
||||||
|
bind_remote_name: card.name || "",
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
const push = (await fetchJson(
|
||||||
|
`/api/ops/neko/instances/${encodeURIComponent(inst.id)}/push-bind`,
|
||||||
|
{ method: "POST" },
|
||||||
|
)) as { ok?: boolean; error?: string };
|
||||||
|
if (!push.ok) throw new Error(push.error || "登记到 VPS 失败");
|
||||||
|
toast.push(`已绑定并登记到 VPS:${card.name || card.id}(VPS 原生 Neko 仍保留)`, "ok");
|
||||||
|
await load();
|
||||||
|
} catch (e) {
|
||||||
|
toast.push((e as Error).message, "err");
|
||||||
|
} finally {
|
||||||
|
setBusy("");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Shell>
|
||||||
|
<div className="animate-fade-up space-y-5">
|
||||||
|
<header className="flex flex-wrap items-start justify-between gap-3">
|
||||||
|
<div>
|
||||||
|
<h1 className="font-display text-2xl font-semibold text-white">运维 · Neko</h1>
|
||||||
|
<p className="mt-1 max-w-2xl text-sm text-slate-400">
|
||||||
|
独立实例池(<span className="font-mono text-slate-300">douyinweb-ops-neko-*</span>
|
||||||
|
),与分配页原生 Neko(<span className="font-mono text-slate-300">douyinweb-neko-*</span>
|
||||||
|
)互不影响。VPS 频道原生 Neko 永远保留、默认停止;物理机在此创建实例后配对到 VPS
|
||||||
|
分配卡,分配页用开关选择「打开本机 / 打开物理机」。
|
||||||
|
</p>
|
||||||
|
{hostProfile ? (
|
||||||
|
<p className="mt-1 text-[11px] text-slate-500">当前主机形态:{hostProfile}</p>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => void load()}
|
||||||
|
className="inline-flex items-center gap-1.5 rounded-xl border border-white/10 bg-white/5 px-3 py-2 text-xs text-slate-300"
|
||||||
|
>
|
||||||
|
<RefreshCw className="h-3.5 w-3.5" />
|
||||||
|
刷新
|
||||||
|
</button>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<section className="rounded-2xl border border-white/10 bg-white/[0.03] p-4">
|
||||||
|
<h2 className="flex items-center gap-2 text-sm font-medium text-white">
|
||||||
|
<Server className="h-4 w-4 text-teal-300" />
|
||||||
|
跨机配对(域名 + Token)
|
||||||
|
</h2>
|
||||||
|
<p className="mt-1 text-[11px] text-slate-500">{peer.hint || "选择 hub / edge"}</p>
|
||||||
|
<div className="mt-3 grid gap-3 sm:grid-cols-2">
|
||||||
|
<label className="block text-[11px] text-slate-400">
|
||||||
|
角色
|
||||||
|
<select
|
||||||
|
value={role}
|
||||||
|
onChange={(e) => setRole(e.target.value)}
|
||||||
|
className="mt-1 w-full rounded-xl border border-white/10 bg-black/40 px-3 py-2 text-sm text-white"
|
||||||
|
>
|
||||||
|
<option value="off">off(本机独立)</option>
|
||||||
|
<option value="hub">hub(通常 VPS:发布分配卡)</option>
|
||||||
|
<option value="edge">edge(通常物理机:建 Neko 并登记)</option>
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
<label className="block text-[11px] text-slate-400">
|
||||||
|
Hub 域名(edge 填 VPS,如 https://dylive.nomadro.com)
|
||||||
|
<input
|
||||||
|
value={peerBase}
|
||||||
|
onChange={(e) => setPeerBase(e.target.value)}
|
||||||
|
className="mt-1 w-full rounded-xl border border-white/10 bg-black/40 px-3 py-2 text-sm text-white"
|
||||||
|
placeholder="https://dylive.nomadro.com"
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<label className="block text-[11px] text-slate-400">
|
||||||
|
本机 Neko 公网根(edge 建议 .cn,如 https://dy.nomadro.cn)
|
||||||
|
<input
|
||||||
|
value={publicBase}
|
||||||
|
onChange={(e) => setPublicBase(e.target.value)}
|
||||||
|
className="mt-1 w-full rounded-xl border border-white/10 bg-black/40 px-3 py-2 text-sm text-white"
|
||||||
|
placeholder="https://dy.nomadro.cn"
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<label className="block text-[11px] text-slate-400">
|
||||||
|
Token{peer.has_token ? `(已有 …${peer.token_suffix})` : ""}
|
||||||
|
<input
|
||||||
|
value={tokenInput}
|
||||||
|
onChange={(e) => setTokenInput(e.target.value)}
|
||||||
|
className="mt-1 w-full rounded-xl border border-white/10 bg-black/40 px-3 py-2 font-mono text-sm text-white"
|
||||||
|
placeholder="hub 生成后粘贴到 edge"
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
<div className="mt-3 flex flex-wrap gap-2">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
disabled={Boolean(busy)}
|
||||||
|
onClick={() => void savePeer()}
|
||||||
|
className="rounded-xl bg-teal-500/20 px-3 py-2 text-xs text-teal-100 ring-1 ring-teal-400/30"
|
||||||
|
>
|
||||||
|
保存配对
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
disabled={Boolean(busy)}
|
||||||
|
onClick={() => void savePeer({ rotate_token: true })}
|
||||||
|
className="rounded-xl border border-white/10 bg-white/5 px-3 py-2 text-xs text-slate-300"
|
||||||
|
>
|
||||||
|
生成新 Token(hub)
|
||||||
|
</button>
|
||||||
|
{role === "edge" ? (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
disabled={Boolean(busy)}
|
||||||
|
onClick={() => void pullCards()}
|
||||||
|
className="inline-flex items-center gap-1 rounded-xl border border-violet-500/30 bg-violet-500/10 px-3 py-2 text-xs text-violet-100"
|
||||||
|
>
|
||||||
|
<Link2 className="h-3.5 w-3.5" />
|
||||||
|
拉取 VPS 分配卡片
|
||||||
|
</button>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section className="rounded-2xl border border-white/10 bg-white/[0.03] p-4">
|
||||||
|
<div className="flex flex-wrap items-end justify-between gap-3">
|
||||||
|
<h2 className="flex items-center gap-2 text-sm font-medium text-white">
|
||||||
|
<Monitor className="h-4 w-4 text-violet-300" />
|
||||||
|
Ops Neko 实例
|
||||||
|
</h2>
|
||||||
|
<div className="flex flex-wrap gap-2">
|
||||||
|
<input
|
||||||
|
value={newName}
|
||||||
|
onChange={(e) => setNewName(e.target.value)}
|
||||||
|
placeholder="名称(可选)"
|
||||||
|
className="rounded-xl border border-white/10 bg-black/40 px-3 py-2 text-sm text-white"
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
disabled={busy === "create"}
|
||||||
|
onClick={() => void createInstance()}
|
||||||
|
className="inline-flex items-center gap-1 rounded-xl bg-violet-500/20 px-3 py-2 text-xs text-violet-100 ring-1 ring-violet-400/30"
|
||||||
|
>
|
||||||
|
{busy === "create" ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <Plus className="h-3.5 w-3.5" />}
|
||||||
|
新建(默认停止)
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{loading ? (
|
||||||
|
<p className="mt-4 text-sm text-slate-500">加载中…</p>
|
||||||
|
) : instances.length === 0 ? (
|
||||||
|
<p className="mt-4 text-sm text-slate-500">暂无实例。物理机建议在此创建;VPS 也可建但默认停着省内存。</p>
|
||||||
|
) : (
|
||||||
|
<ul className="mt-4 space-y-3">
|
||||||
|
{instances.map((inst) => (
|
||||||
|
<li
|
||||||
|
key={inst.id}
|
||||||
|
className="rounded-xl border border-white/10 bg-black/25 p-3"
|
||||||
|
>
|
||||||
|
<div className="flex flex-wrap items-center justify-between gap-2">
|
||||||
|
<div>
|
||||||
|
<p className="text-sm text-white">
|
||||||
|
#{inst.slot} {inst.name || "Ops Neko"}
|
||||||
|
<span
|
||||||
|
className={`ml-2 rounded-md px-1.5 py-0.5 text-[10px] ${
|
||||||
|
inst.running
|
||||||
|
? "bg-emerald-500/20 text-emerald-200"
|
||||||
|
: "bg-white/5 text-slate-400"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{inst.running ? "运行中" : "已停止"}
|
||||||
|
</span>
|
||||||
|
</p>
|
||||||
|
<p className="mt-0.5 font-mono text-[10px] text-slate-500">
|
||||||
|
{inst.container} · :{inst.http_port}
|
||||||
|
{inst.bind_remote_name
|
||||||
|
? ` · 绑定 ${inst.bind_remote_name}`
|
||||||
|
: inst.bind_remote_group_id
|
||||||
|
? ` · 绑定 ${inst.bind_remote_group_id.slice(0, 8)}…`
|
||||||
|
: ""}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div className="flex flex-wrap gap-1.5">
|
||||||
|
{inst.open_url ? (
|
||||||
|
<a
|
||||||
|
href={inst.open_url}
|
||||||
|
target="_blank"
|
||||||
|
rel="noreferrer"
|
||||||
|
className="inline-flex items-center gap-1 rounded-lg border border-white/10 px-2.5 py-1.5 text-[11px] text-slate-200"
|
||||||
|
>
|
||||||
|
<ExternalLink className="h-3 w-3" />
|
||||||
|
打开
|
||||||
|
</a>
|
||||||
|
) : null}
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
disabled={Boolean(busy)}
|
||||||
|
onClick={() => void act(inst.id, "start")}
|
||||||
|
className="rounded-lg bg-emerald-500/15 px-2.5 py-1.5 text-[11px] text-emerald-100"
|
||||||
|
>
|
||||||
|
启动
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
disabled={Boolean(busy)}
|
||||||
|
onClick={() => void act(inst.id, "stop")}
|
||||||
|
className="rounded-lg bg-rose-500/15 px-2.5 py-1.5 text-[11px] text-rose-100"
|
||||||
|
>
|
||||||
|
停止
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
disabled={Boolean(busy)}
|
||||||
|
onClick={() => void act(inst.id, "delete")}
|
||||||
|
className="rounded-lg bg-white/5 px-2.5 py-1.5 text-[11px] text-slate-400"
|
||||||
|
>
|
||||||
|
删除
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{role === "edge" && remoteCards.length > 0 ? (
|
||||||
|
<div className="mt-2 flex flex-wrap gap-1.5">
|
||||||
|
<span className="w-full text-[10px] text-slate-500">配对到 VPS 分配频道并登记:</span>
|
||||||
|
{remoteCards.map((c) => (
|
||||||
|
<button
|
||||||
|
key={c.id}
|
||||||
|
type="button"
|
||||||
|
disabled={Boolean(busy)}
|
||||||
|
onClick={() => void bindAndPush(inst, c)}
|
||||||
|
className="rounded-lg border border-teal-500/25 bg-teal-500/10 px-2 py-1 text-[10px] text-teal-100"
|
||||||
|
>
|
||||||
|
{c.name || c.id.slice(0, 8)}
|
||||||
|
{c.ops_neko_bound ? " ·已绑" : ""}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
</Shell>
|
||||||
|
);
|
||||||
|
}
|
||||||
@ -32,7 +32,16 @@ type GroupLike = {
|
|||||||
featured?: Array<{ url?: string }>;
|
featured?: Array<{ url?: string }>;
|
||||||
neko_instance_id?: number;
|
neko_instance_id?: number;
|
||||||
neko_enabled?: boolean;
|
neko_enabled?: boolean;
|
||||||
|
/** Always native local /neko/N/ — never removed when remote is paired. */
|
||||||
neko_studio_url?: string;
|
neko_studio_url?: string;
|
||||||
|
neko_local_studio_url?: string;
|
||||||
|
ops_neko_open_url?: string;
|
||||||
|
ops_neko_bound?: boolean;
|
||||||
|
ops_neko_slot?: number;
|
||||||
|
ops_neko_edge_label?: string;
|
||||||
|
neko_open_prefer?: "local" | "remote";
|
||||||
|
neko_open_url?: string;
|
||||||
|
neko_open_source?: "local" | "remote";
|
||||||
};
|
};
|
||||||
|
|
||||||
type NekoState = {
|
type NekoState = {
|
||||||
@ -119,12 +128,27 @@ export function YtRelayProStatusPanel({
|
|||||||
const [nekoBusy, setNekoBusy] = useState(false);
|
const [nekoBusy, setNekoBusy] = useState(false);
|
||||||
const [nekoState, setNekoState] = useState<NekoState | null>((row?.neko as NekoState) || null);
|
const [nekoState, setNekoState] = useState<NekoState | null>((row?.neko as NekoState) || null);
|
||||||
const [nekoPollErr, setNekoPollErr] = useState("");
|
const [nekoPollErr, setNekoPollErr] = useState("");
|
||||||
const studioUrl = String(nekoState?.studio_url || group.neko_studio_url || "").trim();
|
const [openPrefer, setOpenPrefer] = useState<"local" | "remote">(
|
||||||
|
group.neko_open_prefer === "remote" ? "remote" : "local",
|
||||||
|
);
|
||||||
|
const localStudioUrl = String(
|
||||||
|
group.neko_local_studio_url || group.neko_studio_url || nekoState?.studio_url || "",
|
||||||
|
).trim();
|
||||||
|
const remoteStudioUrl = String(group.ops_neko_open_url || "").trim();
|
||||||
|
const remoteBound = Boolean(group.ops_neko_bound || remoteStudioUrl);
|
||||||
|
const preferredUrl =
|
||||||
|
openPrefer === "remote" && remoteStudioUrl
|
||||||
|
? remoteStudioUrl
|
||||||
|
: localStudioUrl || String(nekoState?.studio_url || "").trim();
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
setNekoEnabled(Boolean(group.neko_enabled ?? row?.neko_enabled));
|
setNekoEnabled(Boolean(group.neko_enabled ?? row?.neko_enabled));
|
||||||
}, [group.id, group.neko_enabled, row?.neko_enabled]);
|
}, [group.id, group.neko_enabled, row?.neko_enabled]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setOpenPrefer(group.neko_open_prefer === "remote" ? "remote" : "local");
|
||||||
|
}, [group.id, group.neko_open_prefer]);
|
||||||
|
|
||||||
// Prefer Neko snapshot from relay/status (3.5s) — avoids a second docker poll loop.
|
// Prefer Neko snapshot from relay/status (3.5s) — avoids a second docker poll loop.
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (row?.neko) {
|
if (row?.neko) {
|
||||||
@ -174,6 +198,34 @@ export function YtRelayProStatusPanel({
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function setPrefer(prefer: "local" | "remote") {
|
||||||
|
if (prefer === "remote" && !remoteBound) {
|
||||||
|
toast.push("尚未配对物理机 Neko(运维 → Neko)", "err");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setNekoBusy(true);
|
||||||
|
try {
|
||||||
|
const r = (await fetchJson(
|
||||||
|
`/api/youtube/assign/groups/${encodeURIComponent(group.id)}/neko-open-prefer`,
|
||||||
|
{ method: "POST", body: JSON.stringify({ prefer }) },
|
||||||
|
)) as { group?: GroupLike };
|
||||||
|
if (r.group?.neko_open_prefer === "remote" || r.group?.neko_open_prefer === "local") {
|
||||||
|
setOpenPrefer(r.group.neko_open_prefer);
|
||||||
|
} else {
|
||||||
|
setOpenPrefer(prefer);
|
||||||
|
}
|
||||||
|
toast.push(
|
||||||
|
prefer === "remote" ? "默认打开:物理机 Neko(原生实例仍保留)" : "默认打开:本机原生 Neko",
|
||||||
|
"ok",
|
||||||
|
);
|
||||||
|
onNekoChange?.();
|
||||||
|
} catch (e) {
|
||||||
|
toast.push((e as Error).message, "err");
|
||||||
|
} finally {
|
||||||
|
setNekoBusy(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="overflow-hidden rounded-2xl border border-cyan-500/20 bg-gradient-to-br from-cyan-500/[0.09] via-[#0a121c]/80 to-violet-500/[0.05] p-4 shadow-[inset_0_1px_0_rgba(255,255,255,0.04)] ring-1 ring-white/[0.03] transition duration-300 hover:border-cyan-400/30">
|
<div className="overflow-hidden rounded-2xl border border-cyan-500/20 bg-gradient-to-br from-cyan-500/[0.09] via-[#0a121c]/80 to-violet-500/[0.05] p-4 shadow-[inset_0_1px_0_rgba(255,255,255,0.04)] ring-1 ring-white/[0.03] transition duration-300 hover:border-cyan-400/30">
|
||||||
<div className="flex flex-wrap items-center justify-between gap-2">
|
<div className="flex flex-wrap items-center justify-between gap-2">
|
||||||
@ -328,21 +380,73 @@ export function YtRelayProStatusPanel({
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<p className="mt-2 text-[10px] leading-relaxed text-slate-500">
|
<p className="mt-2 text-[10px] leading-relaxed text-slate-500">
|
||||||
物理机经 ShellClash 出海;勿同时开太多实例以免内存打满。密码{" "}
|
本机原生 Neko #{instanceId} 始终保留(默认停止)。可另配对物理机「运维 → Neko」实例;用下方开关选择默认打开目标。密码{" "}
|
||||||
<span className="font-mono text-slate-400">douyinweb</span>
|
<span className="font-mono text-slate-400">douyinweb</span>
|
||||||
。打开工作室请用带尾斜杠地址。
|
。地址须带尾斜杠。
|
||||||
{nekoPollErr ? <span className="ml-2 text-rose-300">({nekoPollErr})</span> : null}
|
{nekoPollErr ? <span className="ml-2 text-rose-300">({nekoPollErr})</span> : null}
|
||||||
</p>
|
</p>
|
||||||
|
{remoteBound ? (
|
||||||
|
<div className="mt-2 flex flex-wrap items-center gap-2 rounded-lg border border-teal-500/20 bg-teal-500/[0.06] px-2.5 py-2">
|
||||||
|
<span className="text-[10px] text-teal-100/90">默认打开</span>
|
||||||
|
<div className="inline-flex rounded-full border border-white/10 bg-black/30 p-0.5">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
disabled={nekoBusy}
|
||||||
|
onClick={() => void setPrefer("local")}
|
||||||
|
className={`rounded-full px-2.5 py-1 text-[10px] ${
|
||||||
|
openPrefer === "local" ? "bg-violet-400/90 text-slate-900" : "text-slate-400"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
本机原生
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
disabled={nekoBusy}
|
||||||
|
onClick={() => void setPrefer("remote")}
|
||||||
|
className={`rounded-full px-2.5 py-1 text-[10px] ${
|
||||||
|
openPrefer === "remote" ? "bg-teal-400/90 text-slate-900" : "text-slate-400"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
物理机 Tab
|
||||||
|
{group.ops_neko_slot ? ` #${group.ops_neko_slot}` : ""}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
{group.ops_neko_edge_label ? (
|
||||||
|
<span className="font-mono text-[10px] text-slate-500">{group.ops_neko_edge_label}</span>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
<div className="mt-2 flex flex-wrap gap-1.5">
|
<div className="mt-2 flex flex-wrap gap-1.5">
|
||||||
{studioUrl ? (
|
{preferredUrl ? (
|
||||||
<a
|
<a
|
||||||
href={studioUrl}
|
href={preferredUrl}
|
||||||
target="_blank"
|
target="_blank"
|
||||||
rel="noreferrer"
|
rel="noreferrer"
|
||||||
className="inline-flex items-center gap-1 rounded-lg border border-violet-500/30 bg-violet-500/10 px-2.5 py-1.5 text-[11px] text-violet-100 hover:bg-violet-500/20"
|
className="inline-flex items-center gap-1 rounded-lg border border-violet-500/30 bg-violet-500/10 px-2.5 py-1.5 text-[11px] text-violet-100 hover:bg-violet-500/20"
|
||||||
>
|
>
|
||||||
<ExternalLink className="h-3 w-3" />
|
<ExternalLink className="h-3 w-3" />
|
||||||
打开工作室
|
打开工作室
|
||||||
|
{openPrefer === "remote" && remoteBound ? "(物理机)" : "(本机)"}
|
||||||
|
</a>
|
||||||
|
) : null}
|
||||||
|
{localStudioUrl && remoteBound ? (
|
||||||
|
<a
|
||||||
|
href={localStudioUrl}
|
||||||
|
target="_blank"
|
||||||
|
rel="noreferrer"
|
||||||
|
className="inline-flex items-center gap-1 rounded-lg border border-white/10 bg-white/5 px-2.5 py-1.5 text-[11px] text-slate-300 hover:bg-white/10"
|
||||||
|
>
|
||||||
|
本机原生
|
||||||
|
</a>
|
||||||
|
) : null}
|
||||||
|
{remoteStudioUrl ? (
|
||||||
|
<a
|
||||||
|
href={remoteStudioUrl}
|
||||||
|
target="_blank"
|
||||||
|
rel="noreferrer"
|
||||||
|
className="inline-flex items-center gap-1 rounded-lg border border-teal-500/30 bg-teal-500/10 px-2.5 py-1.5 text-[11px] text-teal-100 hover:bg-teal-500/20"
|
||||||
|
>
|
||||||
|
物理机 Neko
|
||||||
</a>
|
</a>
|
||||||
) : null}
|
) : null}
|
||||||
<button
|
<button
|
||||||
@ -350,8 +454,9 @@ export function YtRelayProStatusPanel({
|
|||||||
disabled={nekoBusy || !nekoEnabled}
|
disabled={nekoBusy || !nekoEnabled}
|
||||||
onClick={() => void postNeko({ action: "start" })}
|
onClick={() => void postNeko({ action: "start" })}
|
||||||
className="rounded-lg bg-emerald-500/15 px-2.5 py-1.5 text-[11px] text-emerald-100 disabled:opacity-40"
|
className="rounded-lg bg-emerald-500/15 px-2.5 py-1.5 text-[11px] text-emerald-100 disabled:opacity-40"
|
||||||
|
title="仅启停本机原生 Docker Neko,不影响物理机 Tab 实例"
|
||||||
>
|
>
|
||||||
启动 Neko
|
启动本机 Neko
|
||||||
</button>
|
</button>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
@ -359,7 +464,7 @@ export function YtRelayProStatusPanel({
|
|||||||
onClick={() => void postNeko({ enabled: false, action: "stop" })}
|
onClick={() => void postNeko({ enabled: false, action: "stop" })}
|
||||||
className="rounded-lg bg-rose-500/15 px-2.5 py-1.5 text-[11px] text-rose-100 disabled:opacity-40"
|
className="rounded-lg bg-rose-500/15 px-2.5 py-1.5 text-[11px] text-rose-100 disabled:opacity-40"
|
||||||
>
|
>
|
||||||
停止 Neko
|
停止本机 Neko
|
||||||
</button>
|
</button>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
@ -368,7 +473,7 @@ export function YtRelayProStatusPanel({
|
|||||||
className="inline-flex items-center gap-1 rounded-lg bg-white/5 px-2.5 py-1.5 text-[11px] text-slate-300 disabled:opacity-40"
|
className="inline-flex items-center gap-1 rounded-lg bg-white/5 px-2.5 py-1.5 text-[11px] text-slate-300 disabled:opacity-40"
|
||||||
>
|
>
|
||||||
<RotateCw className="h-3 w-3" />
|
<RotateCw className="h-3 w-3" />
|
||||||
重启
|
重启本机
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
{(() => {
|
{(() => {
|
||||||
|
|||||||
@ -34,6 +34,7 @@ export const LIVE_TABS: NavItem[] = [
|
|||||||
/** Sub-tabs under 运维 */
|
/** Sub-tabs under 运维 */
|
||||||
export const OPS_TABS: NavItem[] = [
|
export const OPS_TABS: NavItem[] = [
|
||||||
{ href: "/ops", label: "运维", emoji: "🛰️" },
|
{ href: "/ops", label: "运维", emoji: "🛰️" },
|
||||||
|
{ href: "/ops/neko", label: "Neko", emoji: "🖥️" },
|
||||||
{ href: "/clash", label: "Clash", emoji: "🧿" },
|
{ href: "/clash", label: "Clash", emoji: "🧿" },
|
||||||
{ href: "/downloads", label: "下载", emoji: "⬇️" },
|
{ href: "/downloads", label: "下载", emoji: "⬇️" },
|
||||||
];
|
];
|
||||||
@ -46,6 +47,8 @@ export type NavSection = "overview" | "live" | "ops";
|
|||||||
|
|
||||||
export function navPathActive(pathname: string, href: string): boolean {
|
export function navPathActive(pathname: string, href: string): boolean {
|
||||||
if (href === "/") return pathname === "/";
|
if (href === "/") return pathname === "/";
|
||||||
|
// /ops must not steal /ops/neko (and other ops children)
|
||||||
|
if (href === "/ops") return pathname === "/ops" || pathname.startsWith("/ops/mobile");
|
||||||
return pathname === href || pathname.startsWith(`${href}/`);
|
return pathname === href || pathname.startsWith(`${href}/`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user