feat: per-channel Neko studio in YouTube assign Pro panel
This commit is contained in:
parent
d60d3e5ac0
commit
e3d7d7a813
@ -63,6 +63,15 @@ class Settings(BaseSettings):
|
|||||||
admin_password: str = "Xiao4669805@"
|
admin_password: str = "Xiao4669805@"
|
||||||
session_secret: str = "douyinweb-session-2026"
|
session_secret: str = "douyinweb-session-2026"
|
||||||
|
|
||||||
|
# Neko browser (per YouTube assign group) — US VPS direct, no ShellClash
|
||||||
|
neko_enabled: bool = True
|
||||||
|
neko_http_port_base: int = 9200
|
||||||
|
neko_webrtc_mux_base: int = 52300
|
||||||
|
neko_user_pass: str = "douyinweb"
|
||||||
|
neko_admin_pass: str = "Xiao4669805@"
|
||||||
|
neko_image: str = "ghcr.io/m1k1o/neko/chromium:3.0.0"
|
||||||
|
neko_nat1to1: str = ""
|
||||||
|
|
||||||
class Config:
|
class Config:
|
||||||
env_prefix = "DY_"
|
env_prefix = "DY_"
|
||||||
env_file = ".env"
|
env_file = ".env"
|
||||||
|
|||||||
@ -417,6 +417,11 @@ def _seed_defaults(conn: sqlite3.Connection) -> None:
|
|||||||
"yt_live_interval_sec": 90.0,
|
"yt_live_interval_sec": 90.0,
|
||||||
"yt_batch_size": 8,
|
"yt_batch_size": 8,
|
||||||
"yt_request_gap_sec": 2.0,
|
"yt_request_gap_sec": 2.0,
|
||||||
|
# YouTube Douyin→YT live relay (FFmpeg RTMPS)
|
||||||
|
"youtube_relay_enabled": False,
|
||||||
|
"youtube_relay_bitrate": 2500,
|
||||||
|
"youtube_relay_use_rtmps": True,
|
||||||
|
"youtube_relay_respect_schedule": True,
|
||||||
# Shorts pipeline
|
# Shorts pipeline
|
||||||
"shorts_enabled": False,
|
"shorts_enabled": False,
|
||||||
"shorts_clip_sec": 15,
|
"shorts_clip_sec": 15,
|
||||||
@ -442,7 +447,7 @@ def _seed_defaults(conn: sqlite3.Connection) -> None:
|
|||||||
"shorts_oauth_redirect_uri": (
|
"shorts_oauth_redirect_uri": (
|
||||||
f"{str(settings.public_base_url or '').strip().rstrip('/')}/api/shorts/oauth/callback"
|
f"{str(settings.public_base_url or '').strip().rstrip('/')}/api/shorts/oauth/callback"
|
||||||
if str(settings.public_base_url or "").strip()
|
if str(settings.public_base_url or "").strip()
|
||||||
else "https://dylive.nomadro.com/api/shorts/oauth/callback"
|
else ""
|
||||||
),
|
),
|
||||||
# Named OAuth apps A/B/C/D — configure once in settings; channels pick a profile
|
# Named OAuth apps A/B/C/D — configure once in settings; channels pick a profile
|
||||||
"shorts_oauth_profiles": [
|
"shorts_oauth_profiles": [
|
||||||
@ -543,7 +548,11 @@ def _seed_defaults(conn: sqlite3.Connection) -> None:
|
|||||||
"tiktok_oauth_check_interval_sec": 3600,
|
"tiktok_oauth_check_interval_sec": 3600,
|
||||||
"tiktok_oauth_client_key": "",
|
"tiktok_oauth_client_key": "",
|
||||||
"tiktok_oauth_client_secret": "",
|
"tiktok_oauth_client_secret": "",
|
||||||
"tiktok_oauth_redirect_uri": "https://dylive.nomadro.com/api/tiktok/oauth/callback/",
|
"tiktok_oauth_redirect_uri": (
|
||||||
|
f"{str(settings.public_base_url or '').strip().rstrip('/')}/api/tiktok/oauth/callback/"
|
||||||
|
if str(settings.public_base_url or "").strip()
|
||||||
|
else ""
|
||||||
|
),
|
||||||
# Ops / audit / archive (all off by default — no behavior change on existing installs)
|
# Ops / audit / archive (all off by default — no behavior change on existing installs)
|
||||||
"settings_audit_enabled": True,
|
"settings_audit_enabled": True,
|
||||||
"db_backup_enabled": False,
|
"db_backup_enabled": False,
|
||||||
|
|||||||
@ -84,6 +84,9 @@ from .shorts_pipeline import shorts_pipeline
|
|||||||
from .tiktok_pipeline import tiktok_pipeline
|
from .tiktok_pipeline import tiktok_pipeline
|
||||||
from .x_clips_pipeline import x_clips_pipeline
|
from .x_clips_pipeline import x_clips_pipeline
|
||||||
from .yt_long_pipeline import yt_long_pipeline
|
from .yt_long_pipeline import yt_long_pipeline
|
||||||
|
from .youtube_relay_pipeline import youtube_relay_pipeline
|
||||||
|
from . import youtube_relay_sessions as relay_sessions
|
||||||
|
from . import youtube_neko
|
||||||
from . import tiktok_session
|
from . import tiktok_session
|
||||||
from .timeutil import stamp_beijing
|
from .timeutil import stamp_beijing
|
||||||
|
|
||||||
@ -175,9 +178,14 @@ async def lifespan(_: FastAPI):
|
|||||||
await _boot("tiktok", tiktok_pipeline.start)
|
await _boot("tiktok", tiktok_pipeline.start)
|
||||||
await _boot("x_clips", x_clips_pipeline.start)
|
await _boot("x_clips", x_clips_pipeline.start)
|
||||||
await _boot("yt_long", yt_long_pipeline.start)
|
await _boot("yt_long", yt_long_pipeline.start)
|
||||||
|
await _boot("youtube_relay", youtube_relay_pipeline.start)
|
||||||
|
|
||||||
asyncio.create_task(_start_workers())
|
asyncio.create_task(_start_workers())
|
||||||
yield
|
yield
|
||||||
|
try:
|
||||||
|
await youtube_relay_pipeline.stop()
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
try:
|
try:
|
||||||
await yt_long_pipeline.stop()
|
await yt_long_pipeline.stop()
|
||||||
except Exception:
|
except Exception:
|
||||||
@ -267,6 +275,7 @@ async def health() -> dict[str, Any]:
|
|||||||
out["shorts"] = await asyncio.to_thread(shorts_pipeline.status)
|
out["shorts"] = await asyncio.to_thread(shorts_pipeline.status)
|
||||||
out["yt_long"] = await asyncio.to_thread(yt_long_pipeline.status)
|
out["yt_long"] = await asyncio.to_thread(yt_long_pipeline.status)
|
||||||
out["youtube_monitor"] = await asyncio.to_thread(yt_monitor.status)
|
out["youtube_monitor"] = await asyncio.to_thread(yt_monitor.status)
|
||||||
|
out["youtube_relay"] = await asyncio.to_thread(youtube_relay_pipeline.status)
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
out["status_error"] = str(exc)[:120]
|
out["status_error"] = str(exc)[:120]
|
||||||
|
|
||||||
@ -581,10 +590,10 @@ def _retry_shorts_job_record(job_id: str) -> dict[str, Any]:
|
|||||||
|
|
||||||
|
|
||||||
@app.get("/api/shorts/status")
|
@app.get("/api/shorts/status")
|
||||||
async def shorts_status() -> dict[str, Any]:
|
async def shorts_status(request: Request) -> dict[str, Any]:
|
||||||
st = await asyncio.to_thread(shorts_pipeline.status)
|
st = await asyncio.to_thread(shorts_pipeline.status)
|
||||||
st["oauth_configured"] = shorts_oauth.oauth_client_configured()
|
st["oauth_configured"] = shorts_oauth.oauth_client_configured()
|
||||||
st["oauth_redirect_uri"] = shorts_oauth.resolve_redirect_uri("https://dylive.nomadro.com")
|
st["oauth_redirect_uri"] = shorts_oauth.resolve_redirect_uri(_request_public_base(request))
|
||||||
st["oauth_scopes"] = shorts_oauth.requested_scopes()
|
st["oauth_scopes"] = shorts_oauth.requested_scopes()
|
||||||
cfg = await _db(db.get_settings_map)
|
cfg = await _db(db.get_settings_map)
|
||||||
st["gcp_project_id"] = str(cfg.get("shorts_gcp_project_id") or "live-473104")
|
st["gcp_project_id"] = str(cfg.get("shorts_gcp_project_id") or "live-473104")
|
||||||
@ -2803,15 +2812,170 @@ async def yt_assign_get_group(group_id: str) -> dict[str, Any]:
|
|||||||
@app.patch("/api/youtube/assign/groups/{group_id}")
|
@app.patch("/api/youtube/assign/groups/{group_id}")
|
||||||
async def yt_assign_update_group(group_id: str, body: YtAssignGroupUpdate) -> dict[str, Any]:
|
async def yt_assign_update_group(group_id: str, body: YtAssignGroupUpdate) -> dict[str, Any]:
|
||||||
try:
|
try:
|
||||||
|
prev = yt_assign_db.get_group(group_id)
|
||||||
g = yt_assign_db.update_group(
|
g = yt_assign_db.update_group(
|
||||||
group_id,
|
group_id,
|
||||||
**body.model_dump(exclude_unset=True),
|
**body.model_dump(exclude_unset=True),
|
||||||
)
|
)
|
||||||
|
if prev and prev.get("enabled") and not g.get("enabled"):
|
||||||
|
await youtube_relay_pipeline.stop_group(group_id)
|
||||||
return {"ok": True, "group": g}
|
return {"ok": True, "group": g}
|
||||||
except ValueError as exc:
|
except ValueError as exc:
|
||||||
raise HTTPException(400, str(exc)) from exc
|
raise HTTPException(400, str(exc)) from exc
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/youtube/relay/status")
|
||||||
|
async def youtube_relay_status() -> dict[str, Any]:
|
||||||
|
return await asyncio.to_thread(youtube_relay_pipeline.status)
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/api/youtube/relay/start")
|
||||||
|
async def youtube_relay_start() -> dict[str, Any]:
|
||||||
|
db.update_settings_map({"youtube_relay_enabled": True})
|
||||||
|
await youtube_relay_pipeline.start()
|
||||||
|
return await asyncio.to_thread(youtube_relay_pipeline.status)
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/api/youtube/relay/stop")
|
||||||
|
async def youtube_relay_stop() -> dict[str, Any]:
|
||||||
|
db.update_settings_map({"youtube_relay_enabled": False})
|
||||||
|
await youtube_relay_pipeline.stop()
|
||||||
|
return await asyncio.to_thread(youtube_relay_pipeline.status)
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/api/youtube/relay/groups/{group_id}/start")
|
||||||
|
async def youtube_relay_group_start(group_id: str) -> dict[str, Any]:
|
||||||
|
try:
|
||||||
|
return await youtube_relay_pipeline.start_group(group_id)
|
||||||
|
except ValueError as exc:
|
||||||
|
raise HTTPException(400, str(exc)) from exc
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/api/youtube/relay/groups/{group_id}/stop")
|
||||||
|
async def youtube_relay_group_stop(group_id: str) -> dict[str, Any]:
|
||||||
|
return await youtube_relay_pipeline.stop_group(group_id)
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/api/youtube/relay/groups/{group_id}/restart")
|
||||||
|
async def youtube_relay_group_restart(group_id: str) -> dict[str, Any]:
|
||||||
|
try:
|
||||||
|
return await youtube_relay_pipeline.restart_group(group_id)
|
||||||
|
except ValueError as exc:
|
||||||
|
raise HTTPException(400, str(exc)) from exc
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/youtube/relay/process_monitor")
|
||||||
|
async def youtube_relay_process_monitor() -> dict[str, Any]:
|
||||||
|
"""PM2-compatible process monitor snapshot (cloud pipeline)."""
|
||||||
|
return await asyncio.to_thread(youtube_relay_pipeline.status)
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/youtube/relay/sessions")
|
||||||
|
async def youtube_relay_sessions_list(
|
||||||
|
group_id: str = "",
|
||||||
|
process: str = "",
|
||||||
|
q: str = "",
|
||||||
|
date_from: str = "",
|
||||||
|
date_to: str = "",
|
||||||
|
status: str = "",
|
||||||
|
limit: int = 50,
|
||||||
|
offset: int = 0,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
gid = (group_id or process or "").strip()
|
||||||
|
return await asyncio.to_thread(
|
||||||
|
relay_sessions.list_sessions,
|
||||||
|
group_id=gid,
|
||||||
|
q=q,
|
||||||
|
date_from=date_from,
|
||||||
|
date_to=date_to,
|
||||||
|
status=status,
|
||||||
|
limit=limit,
|
||||||
|
offset=offset,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/youtube/relay/sessions/stats")
|
||||||
|
async def youtube_relay_sessions_stats(
|
||||||
|
group_id: str = "",
|
||||||
|
process: str = "",
|
||||||
|
q: str = "",
|
||||||
|
date_from: str = "",
|
||||||
|
date_to: str = "",
|
||||||
|
status: str = "",
|
||||||
|
top_anchors: int = 20,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
gid = (group_id or process or "").strip()
|
||||||
|
return await asyncio.to_thread(
|
||||||
|
relay_sessions.summarize_sessions,
|
||||||
|
group_id=gid,
|
||||||
|
q=q,
|
||||||
|
date_from=date_from,
|
||||||
|
date_to=date_to,
|
||||||
|
status=status,
|
||||||
|
top_anchors=top_anchors,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/youtube/relay/sessions/{session_id}")
|
||||||
|
async def youtube_relay_session_detail(session_id: int) -> dict[str, Any]:
|
||||||
|
row = await asyncio.to_thread(relay_sessions.get_session, session_id)
|
||||||
|
if not row:
|
||||||
|
raise HTTPException(404, "会话不存在")
|
||||||
|
return row
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/youtube/neko/status")
|
||||||
|
async def youtube_neko_status() -> dict[str, Any]:
|
||||||
|
groups = await asyncio.to_thread(yt_assign_db.list_groups, False)
|
||||||
|
ids = [int(g.get("neko_instance_id") or 0) for g in groups]
|
||||||
|
desired = max(ids) if ids else 0
|
||||||
|
return await asyncio.to_thread(youtube_neko.status_summary, desired=desired)
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/api/youtube/neko/instances/{instance_id}/{action}")
|
||||||
|
async def youtube_neko_instance_action(instance_id: int, action: str) -> dict[str, Any]:
|
||||||
|
try:
|
||||||
|
result = await asyncio.to_thread(youtube_neko.instance_action, instance_id, action)
|
||||||
|
return {"ok": True, **result}
|
||||||
|
except ValueError as exc:
|
||||||
|
raise HTTPException(400, str(exc)) from exc
|
||||||
|
except RuntimeError as exc:
|
||||||
|
raise HTTPException(500, str(exc)) from exc
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/api/youtube/assign/groups/{group_id}/neko")
|
||||||
|
async def youtube_assign_group_neko(group_id: str, body: dict[str, Any] | None = None) -> dict[str, Any]:
|
||||||
|
"""Toggle Neko for one assign group; optional action start|stop|restart."""
|
||||||
|
body = body or {}
|
||||||
|
g = yt_assign_db.get_group(group_id)
|
||||||
|
if not g:
|
||||||
|
raise HTTPException(404, "分组不存在")
|
||||||
|
instance_id = int(g.get("neko_instance_id") or 0)
|
||||||
|
if instance_id < 1:
|
||||||
|
raise HTTPException(400, "该分组未分配 Neko 实例")
|
||||||
|
|
||||||
|
if "enabled" in body:
|
||||||
|
g = yt_assign_db.update_group(group_id, neko_enabled=bool(body.get("enabled")))
|
||||||
|
|
||||||
|
action = str(body.get("action") or "").strip().lower()
|
||||||
|
neko_result: dict[str, Any] | None = None
|
||||||
|
if action in {"start", "stop", "restart"}:
|
||||||
|
if action == "start" and not g.get("neko_enabled"):
|
||||||
|
g = yt_assign_db.update_group(group_id, neko_enabled=True)
|
||||||
|
try:
|
||||||
|
neko_result = await asyncio.to_thread(youtube_neko.instance_action, instance_id, action)
|
||||||
|
except (ValueError, RuntimeError) as exc:
|
||||||
|
raise HTTPException(400, str(exc)) from exc
|
||||||
|
elif g.get("neko_enabled"):
|
||||||
|
try:
|
||||||
|
neko_result = await asyncio.to_thread(youtube_neko.instance_action, instance_id, "start")
|
||||||
|
except RuntimeError:
|
||||||
|
neko_result = None
|
||||||
|
|
||||||
|
inst = await asyncio.to_thread(youtube_neko._container_state, instance_id)
|
||||||
|
return {"ok": True, "group": g, "neko": neko_result or inst}
|
||||||
|
|
||||||
|
|
||||||
@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)
|
||||||
|
|||||||
@ -369,6 +369,7 @@ class YtAssignGroupUpdate(BaseModel):
|
|||||||
note: Optional[str] = None
|
note: Optional[str] = None
|
||||||
enabled: Optional[bool] = None
|
enabled: Optional[bool] = None
|
||||||
sort_order: Optional[int] = None
|
sort_order: Optional[int] = None
|
||||||
|
neko_enabled: Optional[bool] = None
|
||||||
|
|
||||||
|
|
||||||
class YtAssignPoolAdd(BaseModel):
|
class YtAssignPoolAdd(BaseModel):
|
||||||
|
|||||||
@ -165,17 +165,23 @@ def oauth_client_configured() -> bool:
|
|||||||
|
|
||||||
def resolve_redirect_uri(request_base: str = "") -> str:
|
def resolve_redirect_uri(request_base: str = "") -> str:
|
||||||
cfg = _cfg()
|
cfg = _cfg()
|
||||||
custom = str(cfg.get("shorts_oauth_redirect_uri") or "").strip()
|
from urllib.parse import urlparse
|
||||||
if custom:
|
|
||||||
return custom.rstrip("/")
|
|
||||||
base = (request_base or "").rstrip("/")
|
|
||||||
if base:
|
|
||||||
return f"{base}/api/shorts/oauth/callback"
|
|
||||||
from .config import settings as app_settings
|
from .config import settings as app_settings
|
||||||
|
|
||||||
pub = str(getattr(app_settings, "public_base_url", "") or "").strip().rstrip("/")
|
pub = str(getattr(app_settings, "public_base_url", "") or "").strip().rstrip("/")
|
||||||
if pub:
|
base = pub or (request_base or "").rstrip("/")
|
||||||
return f"{pub}/api/shorts/oauth/callback"
|
derived = f"{base}/api/shorts/oauth/callback" if base else ""
|
||||||
|
|
||||||
|
custom = str(cfg.get("shorts_oauth_redirect_uri") or "").strip().rstrip("/")
|
||||||
|
if custom and pub:
|
||||||
|
if urlparse(custom).netloc == urlparse(pub).netloc:
|
||||||
|
return custom
|
||||||
|
return derived or custom
|
||||||
|
if custom:
|
||||||
|
return custom
|
||||||
|
if derived:
|
||||||
|
return derived
|
||||||
return "https://dylive.nomadro.com/api/shorts/oauth/callback"
|
return "https://dylive.nomadro.com/api/shorts/oauth/callback"
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@ -35,13 +35,22 @@ def oauth_configured(cfg: dict[str, Any] | None = None) -> bool:
|
|||||||
|
|
||||||
def resolve_redirect_uri(request_base: str = "") -> str:
|
def resolve_redirect_uri(request_base: str = "") -> str:
|
||||||
cfg = _cfg()
|
cfg = _cfg()
|
||||||
custom = str(cfg.get("tiktok_oauth_redirect_uri") or "").strip()
|
from urllib.parse import urlparse
|
||||||
|
|
||||||
|
from .config import settings as app_settings
|
||||||
|
|
||||||
|
pub = str(getattr(app_settings, "public_base_url", "") or "").strip().rstrip("/")
|
||||||
|
base = pub or (request_base or "").rstrip("/")
|
||||||
|
derived = f"{base}/api/tiktok/oauth/callback/" if base else ""
|
||||||
|
|
||||||
|
custom = str(cfg.get("tiktok_oauth_redirect_uri") or "").strip().rstrip("/")
|
||||||
if custom:
|
if custom:
|
||||||
uri = custom.rstrip("/") + "/"
|
custom_uri = custom.rstrip("/") + "/"
|
||||||
return uri
|
if pub and urlparse(custom_uri).netloc != urlparse(pub).netloc:
|
||||||
base = (request_base or "").rstrip("/")
|
return derived or custom_uri
|
||||||
if base:
|
return custom_uri
|
||||||
return f"{base}/api/tiktok/oauth/callback/"
|
if derived:
|
||||||
|
return derived
|
||||||
return "https://dylive.nomadro.com/api/tiktok/oauth/callback/"
|
return "https://dylive.nomadro.com/api/tiktok/oauth/callback/"
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
367
backend/app/youtube_neko.py
Normal file
367
backend/app/youtube_neko.py
Normal file
@ -0,0 +1,367 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""Per-channel Neko browser (Docker) for YouTube Studio — no ShellClash/WireGuard."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import shutil
|
||||||
|
import subprocess
|
||||||
|
import threading
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any
|
||||||
|
from urllib.parse import urlparse
|
||||||
|
|
||||||
|
from .config import settings
|
||||||
|
|
||||||
|
_lock = threading.RLock()
|
||||||
|
MAX_INSTANCES = 32
|
||||||
|
MIN_UDP_PORT = 52000
|
||||||
|
|
||||||
|
|
||||||
|
def _neko_root() -> Path:
|
||||||
|
p = settings.data_dir / "neko"
|
||||||
|
p.mkdir(parents=True, exist_ok=True)
|
||||||
|
(p / "profiles").mkdir(parents=True, exist_ok=True)
|
||||||
|
return p
|
||||||
|
|
||||||
|
|
||||||
|
def _compose_path() -> Path:
|
||||||
|
return _neko_root() / "docker-compose.yml"
|
||||||
|
|
||||||
|
|
||||||
|
def _http_port(instance_id: int) -> int:
|
||||||
|
return int(getattr(settings, "neko_http_port_base", 9200) or 9200) + instance_id - 1
|
||||||
|
|
||||||
|
|
||||||
|
def _webrtc_mux(instance_id: int) -> int:
|
||||||
|
return int(getattr(settings, "neko_webrtc_mux_base", 52300) or 52300) + instance_id - 1
|
||||||
|
|
||||||
|
|
||||||
|
def _udp_range(instance_id: int) -> str:
|
||||||
|
base = MIN_UDP_PORT + (instance_id - 1) * 100
|
||||||
|
return f"{base}-{base + 98}"
|
||||||
|
|
||||||
|
|
||||||
|
def _container_name(instance_id: int) -> str:
|
||||||
|
return f"douyinweb-neko-{instance_id}"
|
||||||
|
|
||||||
|
|
||||||
|
def _docker_available() -> bool:
|
||||||
|
return bool(shutil.which("docker"))
|
||||||
|
|
||||||
|
|
||||||
|
def _run(cmd: list[str], *, timeout: float = 120.0) -> tuple[int, str]:
|
||||||
|
try:
|
||||||
|
proc = subprocess.run(
|
||||||
|
cmd,
|
||||||
|
capture_output=True,
|
||||||
|
text=True,
|
||||||
|
timeout=timeout,
|
||||||
|
check=False,
|
||||||
|
)
|
||||||
|
out = (proc.stdout or "") + (proc.stderr or "")
|
||||||
|
return proc.returncode, out.strip()
|
||||||
|
except subprocess.TimeoutExpired:
|
||||||
|
return 124, "timeout"
|
||||||
|
except OSError as exc:
|
||||||
|
return 1, str(exc)
|
||||||
|
|
||||||
|
|
||||||
|
def _public_base() -> str:
|
||||||
|
return str(settings.public_base_url or "").strip().rstrip("/")
|
||||||
|
|
||||||
|
|
||||||
|
def public_studio_url(instance_id: int) -> str:
|
||||||
|
base = _public_base()
|
||||||
|
if base:
|
||||||
|
return f"{base}/neko/{instance_id}/"
|
||||||
|
return f"http://127.0.0.1:{_http_port(instance_id)}/"
|
||||||
|
|
||||||
|
|
||||||
|
def _render_compose(count: int) -> str:
|
||||||
|
image = str(getattr(settings, "neko_image", "") or "ghcr.io/m1k1o/neko/chromium:3.0.0")
|
||||||
|
user_pass = str(getattr(settings, "neko_user_pass", "") or "douyinweb")
|
||||||
|
admin_pass = str(getattr(settings, "neko_admin_pass", "") or "douyinweb")
|
||||||
|
nat1to1 = str(getattr(settings, "neko_nat1to1", "") or "").strip()
|
||||||
|
start_url = "https://studio.youtube.com/"
|
||||||
|
root = _neko_root()
|
||||||
|
lines = ["# Generated by douyinWEB — do not edit", "services:"]
|
||||||
|
for idx in range(1, count + 1):
|
||||||
|
http_port = _http_port(idx)
|
||||||
|
mux = _webrtc_mux(idx)
|
||||||
|
udp = _udp_range(idx)
|
||||||
|
profile = root / "profiles" / str(idx)
|
||||||
|
profile.mkdir(parents=True, exist_ok=True)
|
||||||
|
lines.extend(
|
||||||
|
[
|
||||||
|
f" neko{idx}:",
|
||||||
|
f" image: {image}",
|
||||||
|
" restart: unless-stopped",
|
||||||
|
" shm_size: 512mb",
|
||||||
|
" cap_add:",
|
||||||
|
" - SYS_ADMIN",
|
||||||
|
" security_opt:",
|
||||||
|
" - apparmor:unconfined",
|
||||||
|
f" container_name: {_container_name(idx)}",
|
||||||
|
" environment:",
|
||||||
|
" TZ: America/Chicago",
|
||||||
|
' NEKO_SERVER_BIND: ":8080"',
|
||||||
|
' NEKO_MEMBER_PROVIDER: "multiuser"',
|
||||||
|
f" NEKO_MEMBER_MULTIUSER_USER_PASSWORD: {user_pass}",
|
||||||
|
f" NEKO_MEMBER_MULTIUSER_ADMIN_PASSWORD: {admin_pass}",
|
||||||
|
" NEKO_DESKTOP_SCREEN: 1280x720@15",
|
||||||
|
" NEKO_MAX_FPS: 15",
|
||||||
|
" NEKO_VIDEO_BITRATE: 1200",
|
||||||
|
" NEKO_WEBRTC_ICELITE: 1",
|
||||||
|
f" NEKO_WEBRTC_NAT1TO1: {nat1to1}",
|
||||||
|
f" NEKO_WEBRTC_TCPMUX: {mux}",
|
||||||
|
f" NEKO_WEBRTC_UDPMUX: {mux}",
|
||||||
|
f" NEKO_WEBRTC_EPR: {udp}",
|
||||||
|
f" NEKO_START_URL: {start_url}",
|
||||||
|
" NEKO_BROWSER_PROXY: ''",
|
||||||
|
" ports:",
|
||||||
|
f' - "127.0.0.1:{http_port}:8080"',
|
||||||
|
f' - "127.0.0.1:{mux}:{mux}/tcp"',
|
||||||
|
f' - "127.0.0.1:{mux}:{mux}/udp"',
|
||||||
|
f' - "127.0.0.1:{udp}:{udp}/udp"',
|
||||||
|
" volumes:",
|
||||||
|
f' - "{profile}:/home/neko/.config/chromium"',
|
||||||
|
f' - "{profile}:/home/neko/.config/google-chrome"',
|
||||||
|
]
|
||||||
|
)
|
||||||
|
return "\n".join(lines) + "\n"
|
||||||
|
|
||||||
|
|
||||||
|
def _compose_cmd(*args: str) -> list[str]:
|
||||||
|
return ["docker", "compose", "-f", str(_compose_path()), *args]
|
||||||
|
|
||||||
|
|
||||||
|
def _container_state(instance_id: int) -> dict[str, Any]:
|
||||||
|
name = _container_name(instance_id)
|
||||||
|
port = _http_port(instance_id)
|
||||||
|
out: dict[str, Any] = {
|
||||||
|
"id": instance_id,
|
||||||
|
"container": name,
|
||||||
|
"http_port": port,
|
||||||
|
"studio_url": public_studio_url(instance_id),
|
||||||
|
"exists": False,
|
||||||
|
"running": False,
|
||||||
|
"ready": False,
|
||||||
|
"status": "missing",
|
||||||
|
"detail": "",
|
||||||
|
}
|
||||||
|
if not _docker_available():
|
||||||
|
out["detail"] = "docker_unavailable"
|
||||||
|
return out
|
||||||
|
code, text = _run(
|
||||||
|
["docker", "inspect", name, "--format", "{{json .State}}"],
|
||||||
|
timeout=15,
|
||||||
|
)
|
||||||
|
if code != 0:
|
||||||
|
out["detail"] = text[:200]
|
||||||
|
return out
|
||||||
|
out["exists"] = True
|
||||||
|
try:
|
||||||
|
state = json.loads(text or "{}")
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
out["detail"] = text[:200]
|
||||||
|
return out
|
||||||
|
running = bool(state.get("Running"))
|
||||||
|
health = str((state.get("Health") or {}).get("Status") or "")
|
||||||
|
out["running"] = running
|
||||||
|
out["status"] = health if health else ("running" if running else str(state.get("Status") or "stopped"))
|
||||||
|
if running:
|
||||||
|
hc, _ = _run(["curl", "-sS", "-o", "/dev/null", "-w", "%{http_code}", f"http://127.0.0.1:{port}/"], timeout=8)
|
||||||
|
out["ready"] = hc == 200
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def ensure_capacity(desired: int, *, start_instances: set[int] | None = None) -> dict[str, Any]:
|
||||||
|
"""Render compose for `desired` instances; create containers (optionally start subset)."""
|
||||||
|
desired = max(0, min(MAX_INSTANCES, int(desired or 0)))
|
||||||
|
if desired == 0:
|
||||||
|
return {"ok": True, "desired": 0, "changed": False, "message": "no_instances"}
|
||||||
|
if not _docker_available():
|
||||||
|
return {"ok": False, "desired": desired, "error": "Docker 不可用,请先在服务器安装 Docker"}
|
||||||
|
|
||||||
|
with _lock:
|
||||||
|
compose = _compose_path()
|
||||||
|
text = _render_compose(desired)
|
||||||
|
changed = not compose.is_file() or compose.read_text(encoding="utf-8") != text
|
||||||
|
if changed:
|
||||||
|
compose.write_text(text, encoding="utf-8")
|
||||||
|
|
||||||
|
code, out = _run(_compose_cmd("up", "-d", "--remove-orphans"), timeout=300)
|
||||||
|
if code != 0:
|
||||||
|
return {"ok": False, "desired": desired, "error": out[:500] or "compose up failed"}
|
||||||
|
|
||||||
|
started: list[int] = []
|
||||||
|
stopped: list[int] = []
|
||||||
|
for idx in range(1, desired + 1):
|
||||||
|
should_run = start_instances is None or idx in start_instances
|
||||||
|
if should_run:
|
||||||
|
c, _ = _run(["docker", "start", _container_name(idx)], timeout=45)
|
||||||
|
if c == 0:
|
||||||
|
started.append(idx)
|
||||||
|
else:
|
||||||
|
c, _ = _run(["docker", "stop", "-t", "8", _container_name(idx)], timeout=30)
|
||||||
|
if c == 0:
|
||||||
|
stopped.append(idx)
|
||||||
|
|
||||||
|
sync_nginx_proxy(desired)
|
||||||
|
return {
|
||||||
|
"ok": True,
|
||||||
|
"desired": desired,
|
||||||
|
"changed": changed,
|
||||||
|
"started": started,
|
||||||
|
"stopped": stopped,
|
||||||
|
"detail": out[:300],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def sync_nginx_proxy(count: int) -> dict[str, Any]:
|
||||||
|
"""Write nginx reverse-proxy snippets for /neko/{id}/ → local ports."""
|
||||||
|
base = _public_base()
|
||||||
|
if not base:
|
||||||
|
return {"ok": False, "skipped": "no_public_base"}
|
||||||
|
host = urlparse(base).hostname or ""
|
||||||
|
if not host:
|
||||||
|
return {"ok": False, "skipped": "no_host"}
|
||||||
|
conf_path = Path("/etc/nginx/conf.d/douyinweb-neko.conf")
|
||||||
|
if not conf_path.parent.is_dir():
|
||||||
|
return {"ok": False, "skipped": "no_nginx"}
|
||||||
|
|
||||||
|
blocks: list[str] = []
|
||||||
|
for idx in range(1, max(0, int(count)) + 1):
|
||||||
|
port = _http_port(idx)
|
||||||
|
mux = _webrtc_mux(idx)
|
||||||
|
blocks.append(
|
||||||
|
f"""
|
||||||
|
location ^~ /neko/{idx}/ {{
|
||||||
|
proxy_pass http://127.0.0.1:{port}/;
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
proxy_set_header Upgrade $http_upgrade;
|
||||||
|
proxy_set_header Connection "upgrade";
|
||||||
|
proxy_read_timeout 3600s;
|
||||||
|
}}
|
||||||
|
location ^~ /neko/{idx}/ws {{
|
||||||
|
proxy_pass http://127.0.0.1:{port}/ws;
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
proxy_set_header Upgrade $http_upgrade;
|
||||||
|
proxy_set_header Connection "upgrade";
|
||||||
|
proxy_read_timeout 3600s;
|
||||||
|
}}
|
||||||
|
location ^~ /neko/{idx}/mux/ {{
|
||||||
|
proxy_pass http://127.0.0.1:{mux}/;
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
proxy_set_header Upgrade $http_upgrade;
|
||||||
|
proxy_set_header Connection "upgrade";
|
||||||
|
}}"""
|
||||||
|
)
|
||||||
|
body = f"""# douyinWEB Neko reverse proxy — auto-generated
|
||||||
|
server {{
|
||||||
|
listen 80;
|
||||||
|
server_name {host};
|
||||||
|
{''.join(blocks)}
|
||||||
|
}}
|
||||||
|
"""
|
||||||
|
# Merge into existing ssl server via include pattern
|
||||||
|
include_path = Path("/etc/nginx/conf.d/douyinweb-neko-locations.conf")
|
||||||
|
loc_body = "\n".join(blocks)
|
||||||
|
try:
|
||||||
|
include_path.write_text(loc_body + "\n", encoding="utf-8")
|
||||||
|
# Patch main vhost if snippet marker missing
|
||||||
|
vhost = Path(f"/etc/nginx/conf.d/dy-nomadro-live.conf")
|
||||||
|
if not vhost.is_file():
|
||||||
|
for p in Path("/etc/nginx/conf.d").glob("*.conf"):
|
||||||
|
if "nomadro" in p.name or "douyin" in p.name:
|
||||||
|
vhost = p
|
||||||
|
break
|
||||||
|
if vhost.is_file():
|
||||||
|
raw = vhost.read_text(encoding="utf-8")
|
||||||
|
marker = "include /etc/nginx/conf.d/douyinweb-neko-locations.conf;"
|
||||||
|
if marker not in raw and "douyinweb-neko-locations" not in raw:
|
||||||
|
raw = raw.replace(
|
||||||
|
"location / {",
|
||||||
|
f" {marker}\n\n location / {{",
|
||||||
|
1,
|
||||||
|
)
|
||||||
|
vhost.write_text(raw, encoding="utf-8")
|
||||||
|
_run(["nginx", "-t"], timeout=15)
|
||||||
|
_run(["systemctl", "reload", "nginx"], timeout=15)
|
||||||
|
return {"ok": True, "instances": count}
|
||||||
|
except OSError as exc:
|
||||||
|
return {"ok": False, "error": str(exc)}
|
||||||
|
|
||||||
|
|
||||||
|
def instance_action(instance_id: int, action: str) -> dict[str, Any]:
|
||||||
|
action = str(action or "").strip().lower()
|
||||||
|
if action not in {"status", "start", "stop", "restart"}:
|
||||||
|
raise ValueError(f"不支持的操作: {action}")
|
||||||
|
if instance_id < 1 or instance_id > MAX_INSTANCES:
|
||||||
|
raise ValueError(f"实例编号须在 1–{MAX_INSTANCES}")
|
||||||
|
|
||||||
|
before = _container_state(instance_id)
|
||||||
|
message = f"Neko {instance_id}: {before.get('status')}"
|
||||||
|
|
||||||
|
if action == "start":
|
||||||
|
ensure_capacity(instance_id, start_instances={instance_id})
|
||||||
|
code, out = _run(["docker", "start", _container_name(instance_id)], timeout=60)
|
||||||
|
if code != 0 and not before.get("exists"):
|
||||||
|
ensure_capacity(instance_id, start_instances={instance_id})
|
||||||
|
code, out = _run(["docker", "start", _container_name(instance_id)], timeout=60)
|
||||||
|
if code != 0:
|
||||||
|
raise RuntimeError(out or "启动失败")
|
||||||
|
message = f"Neko {instance_id} 已启动"
|
||||||
|
elif action == "stop":
|
||||||
|
if before.get("exists"):
|
||||||
|
code, out = _run(["docker", "stop", "-t", "10", _container_name(instance_id)], timeout=45)
|
||||||
|
if code != 0:
|
||||||
|
raise RuntimeError(out or "停止失败")
|
||||||
|
message = f"Neko {instance_id} 已停止"
|
||||||
|
elif action == "restart":
|
||||||
|
ensure_capacity(instance_id, start_instances={instance_id})
|
||||||
|
code, out = _run(["docker", "restart", "-t", "8", _container_name(instance_id)], timeout=90)
|
||||||
|
if code != 0:
|
||||||
|
raise RuntimeError(out or "重启失败")
|
||||||
|
message = f"Neko {instance_id} 已重启"
|
||||||
|
|
||||||
|
after = _container_state(instance_id)
|
||||||
|
after["action"] = action
|
||||||
|
after["message"] = message
|
||||||
|
after["available"] = _docker_available()
|
||||||
|
return after
|
||||||
|
|
||||||
|
|
||||||
|
def list_instances(count: int) -> list[dict[str, Any]]:
|
||||||
|
return [_container_state(i) for i in range(1, max(0, int(count)) + 1)]
|
||||||
|
|
||||||
|
|
||||||
|
def status_summary(*, desired: int) -> dict[str, Any]:
|
||||||
|
desired = max(0, min(MAX_INSTANCES, int(desired or 0)))
|
||||||
|
instances = list_instances(desired)
|
||||||
|
running = sum(1 for x in instances if x.get("running"))
|
||||||
|
return {
|
||||||
|
"available": _docker_available(),
|
||||||
|
"desired": desired,
|
||||||
|
"running": running,
|
||||||
|
"instances": instances,
|
||||||
|
"enabled": bool(getattr(settings, "neko_enabled", True)),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def sync_for_groups(groups: list[dict[str, Any]]) -> dict[str, Any]:
|
||||||
|
"""Ensure docker capacity matches assign groups; start only neko_enabled groups."""
|
||||||
|
ids = [int(g.get("neko_instance_id") or 0) for g in groups if int(g.get("neko_instance_id") or 0) > 0]
|
||||||
|
desired = max(ids) if ids else 0
|
||||||
|
if desired == 0:
|
||||||
|
return {"ok": True, "desired": 0}
|
||||||
|
start_set = {
|
||||||
|
int(g.get("neko_instance_id") or 0)
|
||||||
|
for g in groups
|
||||||
|
if g.get("neko_enabled") and int(g.get("neko_instance_id") or 0) > 0
|
||||||
|
}
|
||||||
|
return ensure_capacity(desired, start_instances=start_set)
|
||||||
337
backend/app/youtube_relay.py
Normal file
337
backend/app/youtube_relay.py
Normal file
@ -0,0 +1,337 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""FFmpeg Douyin live → YouTube RTMPS relay (cloud server, no ShellCrash/Neko)."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import re
|
||||||
|
import subprocess
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
from typing import Any, Callable
|
||||||
|
|
||||||
|
from .config import settings
|
||||||
|
|
||||||
|
|
||||||
|
class RelayStreamEnded(Exception):
|
||||||
|
"""Source ended (anchor offline)."""
|
||||||
|
|
||||||
|
|
||||||
|
class RelaySourceStalled(Exception):
|
||||||
|
"""No progress from FFmpeg — try another source URL."""
|
||||||
|
|
||||||
|
|
||||||
|
MAX_RELAY_LOG_LINES = 200
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class RelayStats:
|
||||||
|
speed: float = 0.0
|
||||||
|
frame: int = 0
|
||||||
|
pid: int = 0
|
||||||
|
running: bool = False
|
||||||
|
last_line: str = ""
|
||||||
|
recent_log: list[str] = field(default_factory=list)
|
||||||
|
|
||||||
|
|
||||||
|
def _headers_arg() -> str:
|
||||||
|
return (
|
||||||
|
"User-Agent: Mozilla/5.0 (iPhone; CPU iPhone OS 18_1 like Mac OS X) "
|
||||||
|
"AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.1 Mobile/15E148 Safari/604.1\r\n"
|
||||||
|
"Referer: https://live.douyin.com/\r\n"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _bitrate_triplet(kbps: int) -> tuple[str, str, str]:
|
||||||
|
n = max(1500, min(int(kbps), 9000))
|
||||||
|
s = f"{n}k"
|
||||||
|
return s, s, f"{n * 2}k"
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_ffmpeg_line(line: str) -> tuple[float | None, int | None]:
|
||||||
|
speed = None
|
||||||
|
frame = None
|
||||||
|
m = re.search(r"speed=\s*([\d.]+)x", line)
|
||||||
|
if m:
|
||||||
|
try:
|
||||||
|
speed = float(m.group(1))
|
||||||
|
except ValueError:
|
||||||
|
pass
|
||||||
|
m2 = re.search(r"frame=\s*(\d+)", line)
|
||||||
|
if m2:
|
||||||
|
try:
|
||||||
|
frame = int(m2.group(1))
|
||||||
|
except ValueError:
|
||||||
|
pass
|
||||||
|
return speed, frame
|
||||||
|
|
||||||
|
|
||||||
|
def build_youtube_rtmp_url(stream_key: str, *, use_rtmps: bool = True) -> str:
|
||||||
|
key = str(stream_key or "").strip()
|
||||||
|
if not key:
|
||||||
|
raise ValueError("缺少 YouTube 直播 KEY")
|
||||||
|
if key.startswith("rtmp"):
|
||||||
|
return key
|
||||||
|
base = "rtmps://a.rtmps.youtube.com/live2/" if use_rtmps else "rtmp://a.rtmp.youtube.com/live2/"
|
||||||
|
return f"{base}{key}"
|
||||||
|
|
||||||
|
|
||||||
|
def build_ffmpeg_relay_cmd(
|
||||||
|
input_url: str,
|
||||||
|
youtube_rtmp: str,
|
||||||
|
*,
|
||||||
|
bitrate_kbps: int = 4000,
|
||||||
|
ffmpeg_bin: str | None = None,
|
||||||
|
) -> list[str]:
|
||||||
|
b_v, maxrate, bufsize = _bitrate_triplet(bitrate_kbps)
|
||||||
|
ff = str(ffmpeg_bin or settings.ffmpeg_bin or "ffmpeg")
|
||||||
|
vf = (
|
||||||
|
"fps=30,scale=720:1280:force_original_aspect_ratio=decrease:flags=bilinear,"
|
||||||
|
"pad=720:1280:(ow-iw)/2:(oh-ih)/2:black"
|
||||||
|
)
|
||||||
|
is_flv = ".flv" in input_url.lower() or "pull-" in input_url.lower()
|
||||||
|
input_args: list[str] = []
|
||||||
|
if is_flv:
|
||||||
|
input_args = ["-reconnect", "1", "-reconnect_at_eof", "1", "-reconnect_streamed", "1", "-reconnect_delay_max", "30"]
|
||||||
|
return [
|
||||||
|
ff,
|
||||||
|
"-y",
|
||||||
|
"-loglevel",
|
||||||
|
"info",
|
||||||
|
"-nostdin",
|
||||||
|
"-stats",
|
||||||
|
"-rw_timeout",
|
||||||
|
"50000000",
|
||||||
|
*input_args,
|
||||||
|
"-fflags",
|
||||||
|
"+genpts+discardcorrupt",
|
||||||
|
"-thread_queue_size",
|
||||||
|
"2048",
|
||||||
|
"-headers",
|
||||||
|
_headers_arg(),
|
||||||
|
"-re",
|
||||||
|
"-i",
|
||||||
|
input_url,
|
||||||
|
"-vf",
|
||||||
|
vf,
|
||||||
|
"-c:v",
|
||||||
|
"libx264",
|
||||||
|
"-preset",
|
||||||
|
"veryfast",
|
||||||
|
"-tune",
|
||||||
|
"zerolatency",
|
||||||
|
"-profile:v",
|
||||||
|
"high",
|
||||||
|
"-level",
|
||||||
|
"4.0",
|
||||||
|
"-b:v",
|
||||||
|
b_v,
|
||||||
|
"-minrate",
|
||||||
|
b_v,
|
||||||
|
"-maxrate",
|
||||||
|
maxrate,
|
||||||
|
"-bufsize",
|
||||||
|
bufsize,
|
||||||
|
"-g",
|
||||||
|
"60",
|
||||||
|
"-keyint_min",
|
||||||
|
"60",
|
||||||
|
"-r",
|
||||||
|
"30",
|
||||||
|
"-pix_fmt",
|
||||||
|
"yuv420p",
|
||||||
|
"-c:a",
|
||||||
|
"aac",
|
||||||
|
"-b:a",
|
||||||
|
"128k",
|
||||||
|
"-ar",
|
||||||
|
"48000",
|
||||||
|
"-ac",
|
||||||
|
"2",
|
||||||
|
"-af",
|
||||||
|
"aresample=async=1:first_pts=0",
|
||||||
|
"-flags",
|
||||||
|
"+global_header",
|
||||||
|
"-flvflags",
|
||||||
|
"no_duration_filesize",
|
||||||
|
"-f",
|
||||||
|
"flv",
|
||||||
|
youtube_rtmp,
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def _terminate_proc(proc: subprocess.Popen | None) -> None:
|
||||||
|
if not proc:
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
if proc.poll() is None:
|
||||||
|
proc.terminate()
|
||||||
|
try:
|
||||||
|
proc.wait(timeout=5)
|
||||||
|
except subprocess.TimeoutExpired:
|
||||||
|
proc.kill()
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class RelayPushSession:
|
||||||
|
"""One FFmpeg push subprocess with stderr monitoring."""
|
||||||
|
|
||||||
|
STALE_SEC = 90.0
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
*,
|
||||||
|
group_id: str,
|
||||||
|
input_url: str,
|
||||||
|
youtube_rtmp: str,
|
||||||
|
anchor_name: str = "",
|
||||||
|
source_url: str = "",
|
||||||
|
room_id: str = "",
|
||||||
|
bitrate_kbps: int = 4000,
|
||||||
|
on_stats: Callable[[RelayStats], None] | None = None,
|
||||||
|
) -> None:
|
||||||
|
self.group_id = group_id
|
||||||
|
self.input_url = input_url
|
||||||
|
self.youtube_rtmp = youtube_rtmp
|
||||||
|
self.anchor_name = anchor_name
|
||||||
|
self.source_url = source_url
|
||||||
|
self.room_id = room_id
|
||||||
|
self.bitrate_kbps = bitrate_kbps
|
||||||
|
self.on_stats = on_stats
|
||||||
|
self._proc: subprocess.Popen | None = None
|
||||||
|
self._stop = threading.Event()
|
||||||
|
self._thread: threading.Thread | None = None
|
||||||
|
self.stats = RelayStats()
|
||||||
|
|
||||||
|
def start(self) -> None:
|
||||||
|
if self._thread and self._thread.is_alive():
|
||||||
|
return
|
||||||
|
self._stop.clear()
|
||||||
|
self._thread = threading.Thread(target=self._run, name=f"yt-relay-{self.group_id}", daemon=True)
|
||||||
|
self._thread.start()
|
||||||
|
|
||||||
|
def stop(self) -> None:
|
||||||
|
self._stop.set()
|
||||||
|
_terminate_proc(self._proc)
|
||||||
|
if self._thread:
|
||||||
|
self._thread.join(timeout=8)
|
||||||
|
self.stats.running = False
|
||||||
|
|
||||||
|
def _run(self) -> None:
|
||||||
|
cmd = build_ffmpeg_relay_cmd(
|
||||||
|
self.input_url,
|
||||||
|
self.youtube_rtmp,
|
||||||
|
bitrate_kbps=self.bitrate_kbps,
|
||||||
|
)
|
||||||
|
import queue as _queue
|
||||||
|
|
||||||
|
q: _queue.Queue[str | None] = _queue.Queue()
|
||||||
|
self.stats.recent_log.append(f"[ffmpeg] cmd={cmd[0]} bitrate={self.bitrate_kbps}k")
|
||||||
|
self.stats.recent_log.append(f"[ffmpeg] -i {self.input_url[:180]}")
|
||||||
|
|
||||||
|
def _reader() -> None:
|
||||||
|
proc = self._proc
|
||||||
|
if not proc or not proc.stderr:
|
||||||
|
q.put(None)
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
for line in proc.stderr:
|
||||||
|
if self._stop.is_set():
|
||||||
|
break
|
||||||
|
q.put(line.rstrip("\n"))
|
||||||
|
except Exception as exc:
|
||||||
|
q.put(f"[ffmpeg] reader error: {exc}")
|
||||||
|
finally:
|
||||||
|
q.put(None)
|
||||||
|
|
||||||
|
while not self._stop.is_set():
|
||||||
|
try:
|
||||||
|
self._proc = subprocess.Popen(
|
||||||
|
cmd,
|
||||||
|
stdin=subprocess.DEVNULL,
|
||||||
|
stdout=subprocess.DEVNULL,
|
||||||
|
stderr=subprocess.PIPE,
|
||||||
|
text=True,
|
||||||
|
bufsize=1,
|
||||||
|
)
|
||||||
|
except FileNotFoundError:
|
||||||
|
self.stats.recent_log.append("[ffmpeg] ERROR: ffmpeg binary not found")
|
||||||
|
self.stats.running = False
|
||||||
|
if self.on_stats:
|
||||||
|
try:
|
||||||
|
self.on_stats(self.stats)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
return
|
||||||
|
except Exception as exc:
|
||||||
|
self.stats.recent_log.append(f"[ffmpeg] ERROR spawn failed: {exc}")
|
||||||
|
self.stats.running = False
|
||||||
|
if self.on_stats:
|
||||||
|
try:
|
||||||
|
self.on_stats(self.stats)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
return
|
||||||
|
|
||||||
|
self.stats.pid = int(self._proc.pid or 0)
|
||||||
|
self.stats.running = True
|
||||||
|
self.stats.recent_log.append(f"[ffmpeg] pid={self.stats.pid} started")
|
||||||
|
if self.on_stats:
|
||||||
|
try:
|
||||||
|
self.on_stats(self.stats)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
last_out = time.time()
|
||||||
|
reader = threading.Thread(target=_reader, daemon=True)
|
||||||
|
reader.start()
|
||||||
|
|
||||||
|
while not self._stop.is_set():
|
||||||
|
try:
|
||||||
|
line = q.get(timeout=2.0)
|
||||||
|
except _queue.Empty:
|
||||||
|
if time.time() - last_out > self.STALE_SEC:
|
||||||
|
self.stats.recent_log.append("[ffmpeg] stale: no stderr for 90s, restarting")
|
||||||
|
_terminate_proc(self._proc)
|
||||||
|
break
|
||||||
|
continue
|
||||||
|
if line is None:
|
||||||
|
break
|
||||||
|
last_out = time.time()
|
||||||
|
self.stats.last_line = line[:240]
|
||||||
|
self.stats.recent_log.append(line[:500])
|
||||||
|
if len(self.stats.recent_log) > MAX_RELAY_LOG_LINES:
|
||||||
|
self.stats.recent_log = self.stats.recent_log[-MAX_RELAY_LOG_LINES:]
|
||||||
|
sp, fr = _parse_ffmpeg_line(line)
|
||||||
|
if sp is not None:
|
||||||
|
self.stats.speed = sp
|
||||||
|
if fr is not None:
|
||||||
|
self.stats.frame = fr
|
||||||
|
if self.on_stats:
|
||||||
|
try:
|
||||||
|
self.on_stats(self.stats)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
low = line.lower()
|
||||||
|
if "end of file" in low or "stream ended" in low:
|
||||||
|
_terminate_proc(self._proc)
|
||||||
|
break
|
||||||
|
if "404 not found" in low or "403 forbidden" in low:
|
||||||
|
_terminate_proc(self._proc)
|
||||||
|
break
|
||||||
|
|
||||||
|
code = self._proc.poll() if self._proc else None
|
||||||
|
self.stats.recent_log.append(f"[ffmpeg] exited code={code}")
|
||||||
|
if self.on_stats:
|
||||||
|
try:
|
||||||
|
self.on_stats(self.stats)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
_terminate_proc(self._proc)
|
||||||
|
self.stats.running = False
|
||||||
|
if self._stop.is_set():
|
||||||
|
return
|
||||||
|
time.sleep(3)
|
||||||
|
if self._stop.is_set():
|
||||||
|
return
|
||||||
|
|
||||||
|
self.stats.running = False
|
||||||
157
backend/app/youtube_relay_db.py
Normal file
157
backend/app/youtube_relay_db.py
Normal file
@ -0,0 +1,157 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""YouTube live relay state — Douyin FLV/HLS → RTMPS ingest."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import sqlite3
|
||||||
|
import time
|
||||||
|
from typing import Any, Optional
|
||||||
|
|
||||||
|
from .db import _connect, _lock, _row_to_dict
|
||||||
|
|
||||||
|
|
||||||
|
def ensure_yt_relay_tables(conn: sqlite3.Connection) -> None:
|
||||||
|
conn.execute(
|
||||||
|
"""
|
||||||
|
CREATE TABLE IF NOT EXISTS yt_relay_states (
|
||||||
|
group_id TEXT PRIMARY KEY,
|
||||||
|
status TEXT NOT NULL DEFAULT 'idle',
|
||||||
|
source_url TEXT NOT NULL DEFAULT '',
|
||||||
|
source_room_id TEXT NOT NULL DEFAULT '',
|
||||||
|
anchor_name TEXT NOT NULL DEFAULT '',
|
||||||
|
stream_input TEXT NOT NULL DEFAULT '',
|
||||||
|
ffmpeg_pid INTEGER NOT NULL DEFAULT 0,
|
||||||
|
speed REAL NOT NULL DEFAULT 0,
|
||||||
|
frame INTEGER NOT NULL DEFAULT 0,
|
||||||
|
error TEXT NOT NULL DEFAULT '',
|
||||||
|
started_at REAL NOT NULL DEFAULT 0,
|
||||||
|
updated_at REAL NOT NULL DEFAULT 0,
|
||||||
|
push_seconds REAL NOT NULL DEFAULT 0,
|
||||||
|
recent_log TEXT NOT NULL DEFAULT '[]'
|
||||||
|
)
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
conn.execute("ALTER TABLE yt_relay_states ADD COLUMN recent_log TEXT NOT NULL DEFAULT '[]'")
|
||||||
|
except sqlite3.OperationalError:
|
||||||
|
pass
|
||||||
|
conn.execute(
|
||||||
|
"CREATE INDEX IF NOT EXISTS idx_yt_relay_status ON yt_relay_states(status, updated_at)"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_recent_log(raw: Any) -> list[str]:
|
||||||
|
if isinstance(raw, list):
|
||||||
|
return [str(x)[:500] for x in raw][-200:]
|
||||||
|
text = str(raw or "").strip()
|
||||||
|
if not text:
|
||||||
|
return []
|
||||||
|
try:
|
||||||
|
data = json.loads(text)
|
||||||
|
if isinstance(data, list):
|
||||||
|
return [str(x)[:500] for x in data][-200:]
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
return [text[:500]]
|
||||||
|
|
||||||
|
|
||||||
|
def _serialize_recent_log(lines: list[str] | None) -> str:
|
||||||
|
if not lines:
|
||||||
|
return "[]"
|
||||||
|
return json.dumps([str(x)[:500] for x in lines][-200:], ensure_ascii=False)
|
||||||
|
|
||||||
|
|
||||||
|
def get_relay_state(group_id: str) -> dict[str, Any] | None:
|
||||||
|
gid = str(group_id or "").strip()
|
||||||
|
if not gid:
|
||||||
|
return None
|
||||||
|
with _lock:
|
||||||
|
conn = _connect()
|
||||||
|
try:
|
||||||
|
ensure_yt_relay_tables(conn)
|
||||||
|
row = conn.execute("SELECT * FROM yt_relay_states WHERE group_id = ?", (gid,)).fetchone()
|
||||||
|
out = _row_to_dict(row) if row else None
|
||||||
|
if out and "recent_log" in out:
|
||||||
|
out["recent_log"] = _parse_recent_log(out.get("recent_log"))
|
||||||
|
return out
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def list_relay_states() -> list[dict[str, Any]]:
|
||||||
|
with _lock:
|
||||||
|
conn = _connect()
|
||||||
|
try:
|
||||||
|
ensure_yt_relay_tables(conn)
|
||||||
|
rows = conn.execute(
|
||||||
|
"SELECT * FROM yt_relay_states ORDER BY updated_at DESC"
|
||||||
|
).fetchall()
|
||||||
|
return [_row_to_dict(r) for r in rows] # type: ignore
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def upsert_relay_state(group_id: str, **fields: Any) -> dict[str, Any]:
|
||||||
|
gid = str(group_id or "").strip()
|
||||||
|
now = time.time()
|
||||||
|
with _lock:
|
||||||
|
conn = _connect()
|
||||||
|
try:
|
||||||
|
ensure_yt_relay_tables(conn)
|
||||||
|
existing = conn.execute(
|
||||||
|
"SELECT group_id FROM yt_relay_states WHERE group_id = ?", (gid,)
|
||||||
|
).fetchone()
|
||||||
|
data = dict(fields)
|
||||||
|
if "recent_log" in data:
|
||||||
|
data["recent_log"] = _serialize_recent_log(_parse_recent_log(data.get("recent_log")))
|
||||||
|
data["updated_at"] = now
|
||||||
|
if existing:
|
||||||
|
sets = ", ".join(f"{k} = ?" for k in data)
|
||||||
|
conn.execute(
|
||||||
|
f"UPDATE yt_relay_states SET {sets} WHERE group_id = ?",
|
||||||
|
(*data.values(), gid),
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
cols = ["group_id", *data.keys()]
|
||||||
|
placeholders = ", ".join("?" for _ in cols)
|
||||||
|
conn.execute(
|
||||||
|
f"INSERT INTO yt_relay_states ({', '.join(cols)}) VALUES ({placeholders})",
|
||||||
|
(gid, *data.values()),
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
row = conn.execute("SELECT * FROM yt_relay_states WHERE group_id = ?", (gid,)).fetchone()
|
||||||
|
return _row_to_dict(row) or {"group_id": gid}
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def clear_relay_state(group_id: str, *, status: str = "idle", error: str = "") -> None:
|
||||||
|
upsert_relay_state(
|
||||||
|
group_id,
|
||||||
|
status=status,
|
||||||
|
source_url="",
|
||||||
|
source_room_id="",
|
||||||
|
anchor_name="",
|
||||||
|
stream_input="",
|
||||||
|
ffmpeg_pid=0,
|
||||||
|
speed=0,
|
||||||
|
frame=0,
|
||||||
|
error=str(error or "")[:500],
|
||||||
|
started_at=0,
|
||||||
|
push_seconds=0,
|
||||||
|
recent_log="[]",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def delete_relay_state(group_id: str) -> None:
|
||||||
|
gid = str(group_id or "").strip()
|
||||||
|
if not gid:
|
||||||
|
return
|
||||||
|
with _lock:
|
||||||
|
conn = _connect()
|
||||||
|
try:
|
||||||
|
ensure_yt_relay_tables(conn)
|
||||||
|
conn.execute("DELETE FROM yt_relay_states WHERE group_id = ?", (gid,))
|
||||||
|
conn.commit()
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
446
backend/app/youtube_relay_pipeline.py
Normal file
446
backend/app/youtube_relay_pipeline.py
Normal file
@ -0,0 +1,446 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""Background worker: Douyin live → YouTube RTMPS relay per assign group."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import time
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from . import db
|
||||||
|
from . import yt_assign_db
|
||||||
|
from . import youtube_relay_db
|
||||||
|
from .shorts_clip import resolve_stream_candidates
|
||||||
|
from . import youtube_relay_sessions as relay_sessions
|
||||||
|
from .youtube_relay import RelayPushSession, RelayStats, build_youtube_rtmp_url
|
||||||
|
from .youtube_relay_status import log_age_seconds, summarize_relay_group, _key_suffix
|
||||||
|
|
||||||
|
|
||||||
|
def _live_room_ids() -> set[str]:
|
||||||
|
rows = db.list_live_douyin_rooms_for_shorts(limit=500)
|
||||||
|
return {str(r.get("room_id") or "").strip() for r in rows if r.get("room_id")}
|
||||||
|
|
||||||
|
|
||||||
|
def pick_source_for_group(group: dict[str, Any], *, respect_schedule: bool = True) -> dict[str, str] | None:
|
||||||
|
"""Choose Douyin source from 精选列表 only; prefer live rooms, then list order."""
|
||||||
|
gid = str(group.get("id") or "")
|
||||||
|
if not gid or not group.get("enabled"):
|
||||||
|
return None
|
||||||
|
if respect_schedule:
|
||||||
|
sched = yt_assign_db.build_rotation_schedule(include_urls=False)
|
||||||
|
active_map = {
|
||||||
|
str(c.get("group_id") or ""): bool(c.get("active"))
|
||||||
|
for c in (sched.get("channels") or [])
|
||||||
|
}
|
||||||
|
if active_map and gid in active_map and not active_map[gid]:
|
||||||
|
return None
|
||||||
|
|
||||||
|
live_ids = _live_room_ids()
|
||||||
|
candidates: list[dict[str, Any]] = []
|
||||||
|
for idx, item in enumerate(group.get("featured") or []):
|
||||||
|
if item.get("blacklisted"):
|
||||||
|
continue
|
||||||
|
url = str(item.get("url") or "").strip()
|
||||||
|
if not url:
|
||||||
|
continue
|
||||||
|
rid = str(item.get("room_id") or "").strip()
|
||||||
|
live = rid in live_ids if rid else False
|
||||||
|
candidates.append(
|
||||||
|
{
|
||||||
|
"url": url,
|
||||||
|
"room_id": rid,
|
||||||
|
"title": str(item.get("title") or item.get("pool_note") or "").strip(),
|
||||||
|
"live": live,
|
||||||
|
"idx": idx,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
candidates.sort(key=lambda x: (0 if x["live"] else 1, x["idx"]))
|
||||||
|
for c in candidates:
|
||||||
|
return {
|
||||||
|
"source_url": c["url"],
|
||||||
|
"room_id": c["room_id"],
|
||||||
|
"anchor_name": c["title"],
|
||||||
|
}
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
class YoutubeRelayPipeline:
|
||||||
|
def __init__(self) -> None:
|
||||||
|
self._task: asyncio.Task | None = None
|
||||||
|
self._stop = asyncio.Event()
|
||||||
|
self._sessions: dict[str, RelayPushSession] = {}
|
||||||
|
# Manual Start holds the lane even outside schedule until Stop / auto window reclaim.
|
||||||
|
self._manual_hold: set[str] = set()
|
||||||
|
self.last_error = ""
|
||||||
|
self.processed = 0
|
||||||
|
|
||||||
|
def status(self) -> dict[str, Any]:
|
||||||
|
cfg = db.get_settings_map()
|
||||||
|
groups = yt_assign_db.list_groups(include_urls=False)
|
||||||
|
groups_full = {str(g.get("id") or ""): g for g in yt_assign_db.list_groups(include_urls=True)}
|
||||||
|
states = {str(s.get("group_id") or ""): s for s in youtube_relay_db.list_relay_states()}
|
||||||
|
relay_groups: list[dict[str, Any]] = []
|
||||||
|
entries: list[dict[str, Any]] = []
|
||||||
|
pushing = 0
|
||||||
|
pipeline_enabled = bool(cfg.get("youtube_relay_enabled"))
|
||||||
|
now = time.time()
|
||||||
|
for g in groups:
|
||||||
|
gid = str(g.get("id") or "")
|
||||||
|
gf = groups_full.get(gid) or g
|
||||||
|
st = dict(states.get(gid) or {})
|
||||||
|
sess = self._sessions.get(gid)
|
||||||
|
running = bool(sess and sess.stats.running)
|
||||||
|
recent_log = list(
|
||||||
|
sess.stats.recent_log if sess else youtube_relay_db._parse_recent_log(st.get("recent_log"))
|
||||||
|
)
|
||||||
|
st["recent_log"] = recent_log
|
||||||
|
monitor = summarize_relay_group(
|
||||||
|
group=gf,
|
||||||
|
st=st,
|
||||||
|
session_running=running,
|
||||||
|
pipeline_enabled=pipeline_enabled,
|
||||||
|
log_age_seconds=log_age_seconds(st, now),
|
||||||
|
)
|
||||||
|
if monitor.get("is_pushing"):
|
||||||
|
pushing += 1
|
||||||
|
row = {
|
||||||
|
"group_id": gid,
|
||||||
|
"name": g.get("name"),
|
||||||
|
"channel_pk": g.get("channel_pk"),
|
||||||
|
"enabled": bool(g.get("enabled")),
|
||||||
|
"status": "pushing" if running else str(st.get("status") or "idle"),
|
||||||
|
"error": st.get("error") or "",
|
||||||
|
"manual_hold": gid in self._manual_hold,
|
||||||
|
**monitor,
|
||||||
|
}
|
||||||
|
relay_groups.append(row)
|
||||||
|
entries.append({**monitor, "channel_pk": g.get("channel_pk"), "manual_hold": gid in self._manual_hold})
|
||||||
|
schedule = yt_assign_db.build_rotation_schedule(include_urls=True)
|
||||||
|
return {
|
||||||
|
"running": bool(self._task and not self._task.done()),
|
||||||
|
"enabled": pipeline_enabled,
|
||||||
|
"pushing_count": pushing,
|
||||||
|
"group_count": len(groups),
|
||||||
|
"enabled_groups": sum(1 for g in groups if g.get("enabled")),
|
||||||
|
"last_error": self.last_error,
|
||||||
|
"douyin_live_count": len(_live_room_ids()),
|
||||||
|
"process_backend": "cloud_pipeline",
|
||||||
|
"family": "youtube",
|
||||||
|
"light": True,
|
||||||
|
"entries": entries,
|
||||||
|
"settings": {
|
||||||
|
"youtube_relay_enabled": pipeline_enabled,
|
||||||
|
"youtube_relay_bitrate": int(cfg.get("youtube_relay_bitrate") or 2500),
|
||||||
|
"youtube_relay_use_rtmps": bool(cfg.get("youtube_relay_use_rtmps", True)),
|
||||||
|
"youtube_relay_respect_schedule": bool(cfg.get("youtube_relay_respect_schedule", True)),
|
||||||
|
},
|
||||||
|
"groups": relay_groups,
|
||||||
|
"schedule": schedule,
|
||||||
|
}
|
||||||
|
|
||||||
|
async def start(self) -> None:
|
||||||
|
if self._task and not self._task.done():
|
||||||
|
return
|
||||||
|
self._stop.clear()
|
||||||
|
self._task = asyncio.create_task(self._loop(), name="youtube-relay-pipeline")
|
||||||
|
|
||||||
|
async def stop(self) -> None:
|
||||||
|
self._stop.set()
|
||||||
|
for sess in list(self._sessions.values()):
|
||||||
|
await asyncio.to_thread(sess.stop)
|
||||||
|
self._sessions.clear()
|
||||||
|
self._manual_hold.clear()
|
||||||
|
if self._task:
|
||||||
|
try:
|
||||||
|
await asyncio.wait_for(self._task, timeout=8)
|
||||||
|
except Exception:
|
||||||
|
self._task.cancel()
|
||||||
|
self._task = None
|
||||||
|
|
||||||
|
async def start_group(self, group_id: str) -> dict[str, Any]:
|
||||||
|
"""Manual Start — always ignores schedule (like sh2 Pro Start)."""
|
||||||
|
gid = str(group_id or "").strip()
|
||||||
|
g = yt_assign_db.get_group(gid)
|
||||||
|
if not g:
|
||||||
|
raise ValueError("分配组不存在")
|
||||||
|
if not g.get("enabled"):
|
||||||
|
raise ValueError("该组已停用")
|
||||||
|
if not str(g.get("stream_key") or "").strip() and not g.get("has_stream_key"):
|
||||||
|
raise ValueError("请先配置 YouTube 直播 KEY")
|
||||||
|
featured = [x for x in (g.get("featured") or []) if str(x.get("url") or "").strip() and not x.get("blacklisted")]
|
||||||
|
if not featured:
|
||||||
|
raise ValueError("直播地址列表(精选)为空,请先加入抖音房间")
|
||||||
|
|
||||||
|
self._manual_hold.add(gid)
|
||||||
|
result = await self._ensure_group_relay(g, force=True, respect_schedule=False)
|
||||||
|
if not result.get("ok"):
|
||||||
|
self._manual_hold.discard(gid)
|
||||||
|
raise ValueError(str(result.get("error") or "启动推流失败"))
|
||||||
|
return {"ok": True, "group_id": gid, **result}
|
||||||
|
|
||||||
|
async def _halt_session(self, group_id: str, *, reason: str = "stopped") -> None:
|
||||||
|
"""Stop FFmpeg for a group without clearing manual_hold."""
|
||||||
|
gid = str(group_id or "").strip()
|
||||||
|
sess = self._sessions.pop(gid, None)
|
||||||
|
if sess:
|
||||||
|
await asyncio.to_thread(sess.stop)
|
||||||
|
youtube_relay_db.clear_relay_state(gid, status="stopped")
|
||||||
|
await asyncio.to_thread(relay_sessions.end_session, gid, reason=reason)
|
||||||
|
|
||||||
|
async def stop_group(self, group_id: str) -> dict[str, Any]:
|
||||||
|
gid = str(group_id or "").strip()
|
||||||
|
self._manual_hold.discard(gid)
|
||||||
|
await self._halt_session(gid, reason="stopped")
|
||||||
|
return {"ok": True, "group_id": gid}
|
||||||
|
|
||||||
|
async def restart_group(self, group_id: str) -> dict[str, Any]:
|
||||||
|
gid = str(group_id or "").strip()
|
||||||
|
await self.stop_group(gid)
|
||||||
|
return await self.start_group(gid)
|
||||||
|
|
||||||
|
async def _loop(self) -> None:
|
||||||
|
while not self._stop.is_set():
|
||||||
|
try:
|
||||||
|
cfg = db.get_settings_map()
|
||||||
|
if not cfg.get("youtube_relay_enabled"):
|
||||||
|
# Auto off: leave manual-hold sessions alone; stop orphan auto sessions.
|
||||||
|
for gid in list(self._sessions.keys()):
|
||||||
|
if gid not in self._manual_hold:
|
||||||
|
await self.stop_group(gid)
|
||||||
|
await asyncio.sleep(2.0)
|
||||||
|
continue
|
||||||
|
respect = bool(cfg.get("youtube_relay_respect_schedule", True))
|
||||||
|
groups = yt_assign_db.list_groups(include_urls=True)
|
||||||
|
active_ids: set[str] = set()
|
||||||
|
for g in groups:
|
||||||
|
gid = str(g.get("id") or "")
|
||||||
|
if not gid or not g.get("enabled"):
|
||||||
|
if gid:
|
||||||
|
await self.stop_group(gid)
|
||||||
|
continue
|
||||||
|
if not str(g.get("stream_key") or "").strip() and not g.get("has_stream_key"):
|
||||||
|
await self.stop_group(gid)
|
||||||
|
continue
|
||||||
|
manual = gid in self._manual_hold
|
||||||
|
src = pick_source_for_group(g, respect_schedule=False if manual else respect)
|
||||||
|
if not src:
|
||||||
|
if manual and gid in self._sessions:
|
||||||
|
# Keep manual push; still tick stats.
|
||||||
|
active_ids.add(gid)
|
||||||
|
continue
|
||||||
|
await self.stop_group(gid)
|
||||||
|
continue
|
||||||
|
active_ids.add(gid)
|
||||||
|
await self._ensure_group_relay(
|
||||||
|
g,
|
||||||
|
source=src,
|
||||||
|
cfg=cfg,
|
||||||
|
respect_schedule=False if manual else respect,
|
||||||
|
)
|
||||||
|
for gid in list(self._sessions.keys()):
|
||||||
|
if gid not in active_ids and gid not in self._manual_hold:
|
||||||
|
await self.stop_group(gid)
|
||||||
|
await self._tick_stats()
|
||||||
|
except Exception as exc:
|
||||||
|
self.last_error = str(exc)[:240]
|
||||||
|
await asyncio.sleep(4.0)
|
||||||
|
|
||||||
|
async def _stop_all_sessions(self) -> None:
|
||||||
|
for gid in list(self._sessions.keys()):
|
||||||
|
await self.stop_group(gid)
|
||||||
|
|
||||||
|
async def _ensure_group_relay(
|
||||||
|
self,
|
||||||
|
group: dict[str, Any],
|
||||||
|
*,
|
||||||
|
source: dict[str, str] | None = None,
|
||||||
|
cfg: dict[str, Any] | None = None,
|
||||||
|
force: bool = False,
|
||||||
|
respect_schedule: bool | None = None,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
cfg = cfg or db.get_settings_map()
|
||||||
|
gid = str(group.get("id") or "")
|
||||||
|
if respect_schedule is None:
|
||||||
|
respect_schedule = bool(cfg.get("youtube_relay_respect_schedule", True))
|
||||||
|
if force:
|
||||||
|
respect_schedule = False
|
||||||
|
|
||||||
|
src = source or pick_source_for_group(group, respect_schedule=respect_schedule)
|
||||||
|
if not src:
|
||||||
|
# Distinguish schedule block vs empty featured for diagnostics.
|
||||||
|
any_src = pick_source_for_group(group, respect_schedule=False)
|
||||||
|
if any_src and respect_schedule:
|
||||||
|
err = "当前不在分配时段,自动推流已跳过(手动「开始」可强制推流)"
|
||||||
|
else:
|
||||||
|
err = "直播地址列表为空或没有可用抖音源"
|
||||||
|
youtube_relay_db.upsert_relay_state(
|
||||||
|
gid,
|
||||||
|
status="idle",
|
||||||
|
error=err,
|
||||||
|
recent_log=[f"[relay] skip: {err}"],
|
||||||
|
)
|
||||||
|
if force:
|
||||||
|
return {"ok": False, "error": err}
|
||||||
|
# Auto path: stop if running.
|
||||||
|
if gid in self._sessions and gid not in self._manual_hold:
|
||||||
|
await self.stop_group(gid)
|
||||||
|
return {"ok": False, "error": err}
|
||||||
|
|
||||||
|
existing = self._sessions.get(gid)
|
||||||
|
if existing and existing.stats.running and not force:
|
||||||
|
if existing.source_url == src.get("source_url"):
|
||||||
|
return {"ok": True, "group_id": gid, "reused": True}
|
||||||
|
await self._halt_session(gid, reason="source_switch")
|
||||||
|
elif existing and force:
|
||||||
|
await self._halt_session(gid, reason="restart")
|
||||||
|
|
||||||
|
if force:
|
||||||
|
self._manual_hold.add(gid)
|
||||||
|
|
||||||
|
stream_key = str(group.get("stream_key") or "").strip()
|
||||||
|
if not stream_key:
|
||||||
|
raw = yt_assign_db.get_group(gid)
|
||||||
|
stream_key = str((raw or {}).get("stream_key") or "").strip()
|
||||||
|
if not stream_key:
|
||||||
|
err = "缺少 stream key"
|
||||||
|
youtube_relay_db.upsert_relay_state(gid, status="error", error=err, recent_log=[f"[relay] {err}"])
|
||||||
|
return {"ok": False, "error": err}
|
||||||
|
|
||||||
|
boot_log = [
|
||||||
|
f"[relay] resolve {src.get('source_url') or ''}",
|
||||||
|
f"[relay] room={src.get('room_id') or '-'} anchor={src.get('anchor_name') or '-'}",
|
||||||
|
]
|
||||||
|
youtube_relay_db.upsert_relay_state(
|
||||||
|
gid,
|
||||||
|
status="starting",
|
||||||
|
source_url=src.get("source_url") or "",
|
||||||
|
source_room_id=src.get("room_id") or "",
|
||||||
|
anchor_name=src.get("anchor_name") or "",
|
||||||
|
error="",
|
||||||
|
recent_log=boot_log,
|
||||||
|
)
|
||||||
|
|
||||||
|
cookie = str(cfg.get("douyin_cookie") or "")
|
||||||
|
cands = await resolve_stream_candidates(
|
||||||
|
source_url=src["source_url"],
|
||||||
|
cookie=cookie,
|
||||||
|
prefer_fresh=True,
|
||||||
|
)
|
||||||
|
if not cands:
|
||||||
|
err = "无法解析抖音直播流(房间未开播或 Cookie 失效)"
|
||||||
|
boot_log.append(f"[relay] ERROR {err}")
|
||||||
|
youtube_relay_db.upsert_relay_state(
|
||||||
|
gid,
|
||||||
|
status="error",
|
||||||
|
error=err,
|
||||||
|
source_url=src.get("source_url") or "",
|
||||||
|
source_room_id=src.get("room_id") or "",
|
||||||
|
anchor_name=src.get("anchor_name") or "",
|
||||||
|
recent_log=boot_log,
|
||||||
|
)
|
||||||
|
return {"ok": False, "error": err}
|
||||||
|
|
||||||
|
try:
|
||||||
|
rtmp = build_youtube_rtmp_url(
|
||||||
|
stream_key,
|
||||||
|
use_rtmps=bool(cfg.get("youtube_relay_use_rtmps", True)),
|
||||||
|
)
|
||||||
|
except ValueError as exc:
|
||||||
|
err = str(exc)
|
||||||
|
boot_log.append(f"[relay] ERROR {err}")
|
||||||
|
youtube_relay_db.upsert_relay_state(gid, status="error", error=err, recent_log=boot_log)
|
||||||
|
return {"ok": False, "error": err}
|
||||||
|
|
||||||
|
now = time.time()
|
||||||
|
boot_log.append(f"[relay] input {cands[0][:160]}")
|
||||||
|
boot_log.append(f"[relay] output {rtmp.split('/')[-1][:8]}… via {'rtmps' if 'rtmps' in rtmp else 'rtmp'}")
|
||||||
|
boot_log.append("[relay] starting ffmpeg…")
|
||||||
|
|
||||||
|
def _on_stats(st: RelayStats) -> None:
|
||||||
|
youtube_relay_db.upsert_relay_state(
|
||||||
|
gid,
|
||||||
|
status="pushing",
|
||||||
|
speed=float(st.speed),
|
||||||
|
frame=int(st.frame),
|
||||||
|
ffmpeg_pid=int(st.pid),
|
||||||
|
recent_log=st.recent_log,
|
||||||
|
)
|
||||||
|
|
||||||
|
old = self._sessions.pop(gid, None)
|
||||||
|
if old:
|
||||||
|
await asyncio.to_thread(old.stop)
|
||||||
|
await asyncio.to_thread(relay_sessions.end_session, gid, reason="restart")
|
||||||
|
|
||||||
|
sess = RelayPushSession(
|
||||||
|
group_id=gid,
|
||||||
|
input_url=cands[0],
|
||||||
|
youtube_rtmp=rtmp,
|
||||||
|
anchor_name=src.get("anchor_name") or "",
|
||||||
|
source_url=src.get("source_url") or "",
|
||||||
|
room_id=src.get("room_id") or "",
|
||||||
|
bitrate_kbps=int(cfg.get("youtube_relay_bitrate") or 4000),
|
||||||
|
on_stats=_on_stats,
|
||||||
|
)
|
||||||
|
# Seed in-memory log so UI sees lines before first ffmpeg frame
|
||||||
|
sess.stats.recent_log = list(boot_log)
|
||||||
|
self._sessions[gid] = sess
|
||||||
|
youtube_relay_db.upsert_relay_state(
|
||||||
|
gid,
|
||||||
|
status="starting",
|
||||||
|
source_url=src.get("source_url") or "",
|
||||||
|
source_room_id=src.get("room_id") or "",
|
||||||
|
anchor_name=src.get("anchor_name") or "",
|
||||||
|
stream_input=cands[0][:500],
|
||||||
|
started_at=now,
|
||||||
|
error="",
|
||||||
|
recent_log=boot_log,
|
||||||
|
)
|
||||||
|
await asyncio.to_thread(sess.start)
|
||||||
|
# Give reader a brief moment to attach
|
||||||
|
await asyncio.sleep(0.4)
|
||||||
|
sk = _key_suffix(ginfo if (ginfo := yt_assign_db.get_group(gid)) else group)
|
||||||
|
await asyncio.to_thread(
|
||||||
|
relay_sessions.start_session,
|
||||||
|
gid,
|
||||||
|
channel_name=str((ginfo or group).get("name") or ""),
|
||||||
|
anchor_name=src.get("anchor_name") or "",
|
||||||
|
source_url=src.get("source_url") or "",
|
||||||
|
source_room_id=src.get("room_id") or "",
|
||||||
|
youtube_key_suffix=sk,
|
||||||
|
metadata={"stream_input": cands[0][:240]},
|
||||||
|
)
|
||||||
|
self.processed += 1
|
||||||
|
return {
|
||||||
|
"ok": True,
|
||||||
|
"group_id": gid,
|
||||||
|
"source_url": src.get("source_url") or "",
|
||||||
|
"ffmpeg_pid": int(sess.stats.pid or 0),
|
||||||
|
"manual_hold": gid in self._manual_hold,
|
||||||
|
}
|
||||||
|
|
||||||
|
async def _tick_stats(self) -> None:
|
||||||
|
now = time.time()
|
||||||
|
for gid, sess in list(self._sessions.items()):
|
||||||
|
if sess.stats.running:
|
||||||
|
st = youtube_relay_db.get_relay_state(gid) or {}
|
||||||
|
started = float(st.get("started_at") or now)
|
||||||
|
youtube_relay_db.upsert_relay_state(
|
||||||
|
gid,
|
||||||
|
status="pushing",
|
||||||
|
speed=float(sess.stats.speed),
|
||||||
|
frame=int(sess.stats.frame),
|
||||||
|
ffmpeg_pid=int(sess.stats.pid),
|
||||||
|
push_seconds=max(0.0, now - started),
|
||||||
|
recent_log=sess.stats.recent_log,
|
||||||
|
)
|
||||||
|
elif gid in self._sessions:
|
||||||
|
st = youtube_relay_db.get_relay_state(gid) or {}
|
||||||
|
if str(st.get("status") or "") == "pushing":
|
||||||
|
youtube_relay_db.upsert_relay_state(
|
||||||
|
gid,
|
||||||
|
status="reconnecting",
|
||||||
|
error=(sess.stats.last_line or "推流中断")[:500],
|
||||||
|
recent_log=sess.stats.recent_log,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
youtube_relay_pipeline = YoutubeRelayPipeline()
|
||||||
330
backend/app/youtube_relay_sessions.py
Normal file
330
backend/app/youtube_relay_sessions.py
Normal file
@ -0,0 +1,330 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""YouTube relay session history — cloud pipeline (group_id as process key)."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import sqlite3
|
||||||
|
import time
|
||||||
|
import uuid
|
||||||
|
from datetime import datetime
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from .db import _connect, _lock, _row_to_dict
|
||||||
|
|
||||||
|
_ACTIVE: dict[str, int] = {}
|
||||||
|
|
||||||
|
|
||||||
|
def ensure_yt_relay_sessions(conn: sqlite3.Connection) -> None:
|
||||||
|
conn.execute(
|
||||||
|
"""
|
||||||
|
CREATE TABLE IF NOT EXISTS yt_relay_sessions (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
session_uuid TEXT NOT NULL UNIQUE,
|
||||||
|
group_id TEXT NOT NULL DEFAULT '',
|
||||||
|
channel_name TEXT NOT NULL DEFAULT '',
|
||||||
|
anchor_name TEXT NOT NULL DEFAULT '',
|
||||||
|
source_url TEXT NOT NULL DEFAULT '',
|
||||||
|
source_room_id TEXT NOT NULL DEFAULT '',
|
||||||
|
stream_title TEXT NOT NULL DEFAULT '',
|
||||||
|
youtube_key_suffix TEXT NOT NULL DEFAULT '',
|
||||||
|
started_at REAL NOT NULL,
|
||||||
|
ended_at REAL,
|
||||||
|
duration_seconds REAL NOT NULL DEFAULT 0,
|
||||||
|
push_date TEXT NOT NULL DEFAULT '',
|
||||||
|
status TEXT NOT NULL DEFAULT 'active',
|
||||||
|
end_reason TEXT NOT NULL DEFAULT '',
|
||||||
|
metadata_json TEXT NOT NULL DEFAULT '{}',
|
||||||
|
created_at REAL NOT NULL,
|
||||||
|
updated_at REAL NOT NULL
|
||||||
|
)
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
conn.execute(
|
||||||
|
"CREATE INDEX IF NOT EXISTS idx_yt_relay_sess_group ON yt_relay_sessions(group_id, started_at DESC)"
|
||||||
|
)
|
||||||
|
conn.execute(
|
||||||
|
"CREATE INDEX IF NOT EXISTS idx_yt_relay_sess_date ON yt_relay_sessions(push_date DESC, started_at DESC)"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _push_date(ts: float) -> str:
|
||||||
|
try:
|
||||||
|
return datetime.fromtimestamp(ts).strftime("%Y-%m-%d")
|
||||||
|
except (OSError, ValueError, OverflowError):
|
||||||
|
return ""
|
||||||
|
|
||||||
|
|
||||||
|
def _row_session(row: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
out = dict(row)
|
||||||
|
meta = out.pop("metadata_json", "{}")
|
||||||
|
try:
|
||||||
|
out["metadata"] = json.loads(meta) if meta else {}
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
out["metadata"] = {}
|
||||||
|
started = float(out.get("started_at") or 0)
|
||||||
|
ended = out.get("ended_at")
|
||||||
|
stored = float(out.get("duration_seconds") or 0)
|
||||||
|
if ended:
|
||||||
|
out["duration_seconds"] = int(max(0, float(ended) - started)) if started else int(stored)
|
||||||
|
elif stored > 0:
|
||||||
|
out["duration_seconds"] = int(stored)
|
||||||
|
elif started > 0:
|
||||||
|
out["duration_seconds"] = int(max(0, time.time() - started))
|
||||||
|
else:
|
||||||
|
out["duration_seconds"] = 0
|
||||||
|
out["process"] = out.get("group_id") or ""
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def start_session(
|
||||||
|
group_id: str,
|
||||||
|
*,
|
||||||
|
channel_name: str = "",
|
||||||
|
anchor_name: str = "",
|
||||||
|
source_url: str = "",
|
||||||
|
source_room_id: str = "",
|
||||||
|
youtube_key_suffix: str = "",
|
||||||
|
metadata: dict[str, Any] | None = None,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
gid = str(group_id or "").strip()
|
||||||
|
now = time.time()
|
||||||
|
with _lock:
|
||||||
|
conn = _connect()
|
||||||
|
try:
|
||||||
|
ensure_yt_relay_sessions(conn)
|
||||||
|
open_row = conn.execute(
|
||||||
|
"SELECT id FROM yt_relay_sessions WHERE group_id = ? AND ended_at IS NULL ORDER BY started_at DESC LIMIT 1",
|
||||||
|
(gid,),
|
||||||
|
).fetchone()
|
||||||
|
if open_row:
|
||||||
|
sid = int(open_row[0])
|
||||||
|
_ACTIVE[gid] = sid
|
||||||
|
row = conn.execute("SELECT * FROM yt_relay_sessions WHERE id = ?", (sid,)).fetchone()
|
||||||
|
return _row_session(_row_to_dict(row) or {"id": sid, "group_id": gid})
|
||||||
|
for other_gid, sid in list(_ACTIVE.items()):
|
||||||
|
if other_gid == gid:
|
||||||
|
continue
|
||||||
|
open_others = conn.execute(
|
||||||
|
"SELECT id, group_id FROM yt_relay_sessions WHERE group_id = ? AND ended_at IS NULL",
|
||||||
|
(gid,),
|
||||||
|
).fetchall()
|
||||||
|
for r in open_others:
|
||||||
|
_close(conn, int(r[0]), ended_at=now, reason="source_switch")
|
||||||
|
session_uuid = str(uuid.uuid4())
|
||||||
|
conn.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO yt_relay_sessions(
|
||||||
|
session_uuid, group_id, channel_name, anchor_name, source_url, source_room_id,
|
||||||
|
stream_title, youtube_key_suffix, started_at, duration_seconds, push_date,
|
||||||
|
status, end_reason, metadata_json, created_at, updated_at
|
||||||
|
) VALUES (?, ?, ?, ?, ?, ?, '', ?, ?, 0, ?, 'active', '', ?, ?, ?)
|
||||||
|
""",
|
||||||
|
(
|
||||||
|
session_uuid,
|
||||||
|
gid,
|
||||||
|
channel_name[:200],
|
||||||
|
anchor_name[:200],
|
||||||
|
source_url[:500],
|
||||||
|
source_room_id[:64],
|
||||||
|
youtube_key_suffix[:32],
|
||||||
|
now,
|
||||||
|
_push_date(now),
|
||||||
|
json.dumps(metadata or {}, ensure_ascii=False),
|
||||||
|
now,
|
||||||
|
now,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
sid = int(conn.execute("SELECT last_insert_rowid()").fetchone()[0])
|
||||||
|
conn.commit()
|
||||||
|
_ACTIVE[gid] = sid
|
||||||
|
row = conn.execute("SELECT * FROM yt_relay_sessions WHERE id = ?", (sid,)).fetchone()
|
||||||
|
return _row_session(_row_to_dict(row) or {"id": sid, "group_id": gid})
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def end_session(group_id: str, *, reason: str = "stopped", ended_at: float | None = None) -> dict[str, Any] | None:
|
||||||
|
gid = str(group_id or "").strip()
|
||||||
|
with _lock:
|
||||||
|
conn = _connect()
|
||||||
|
try:
|
||||||
|
ensure_yt_relay_sessions(conn)
|
||||||
|
row = conn.execute(
|
||||||
|
"SELECT id FROM yt_relay_sessions WHERE group_id = ? AND ended_at IS NULL ORDER BY started_at DESC LIMIT 1",
|
||||||
|
(gid,),
|
||||||
|
).fetchone()
|
||||||
|
if not row:
|
||||||
|
_ACTIVE.pop(gid, None)
|
||||||
|
return None
|
||||||
|
sid = int(row[0])
|
||||||
|
session = _close(conn, sid, ended_at=ended_at, reason=reason)
|
||||||
|
conn.commit()
|
||||||
|
_ACTIVE.pop(gid, None)
|
||||||
|
return session
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def _close(
|
||||||
|
conn: sqlite3.Connection,
|
||||||
|
session_id: int,
|
||||||
|
*,
|
||||||
|
ended_at: float | None = None,
|
||||||
|
reason: str = "",
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
now = float(ended_at or time.time())
|
||||||
|
row = conn.execute("SELECT * FROM yt_relay_sessions WHERE id = ?", (session_id,)).fetchone()
|
||||||
|
if not row:
|
||||||
|
return {"id": session_id}
|
||||||
|
data = _row_to_dict(row) or {}
|
||||||
|
started = float(data.get("started_at") or now)
|
||||||
|
duration = max(0.0, now - started)
|
||||||
|
conn.execute(
|
||||||
|
"""
|
||||||
|
UPDATE yt_relay_sessions SET
|
||||||
|
ended_at = ?, duration_seconds = ?, status = 'ended', end_reason = ?, updated_at = ?
|
||||||
|
WHERE id = ?
|
||||||
|
""",
|
||||||
|
(now, duration, str(reason or "")[:200], now, session_id),
|
||||||
|
)
|
||||||
|
updated = conn.execute("SELECT * FROM yt_relay_sessions WHERE id = ?", (session_id,)).fetchone()
|
||||||
|
return _row_session(_row_to_dict(updated) or data)
|
||||||
|
|
||||||
|
|
||||||
|
def list_sessions(
|
||||||
|
*,
|
||||||
|
group_id: str = "",
|
||||||
|
q: str = "",
|
||||||
|
date_from: str = "",
|
||||||
|
date_to: str = "",
|
||||||
|
status: str = "",
|
||||||
|
limit: int = 50,
|
||||||
|
offset: int = 0,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
clauses: list[str] = []
|
||||||
|
params: list[Any] = []
|
||||||
|
if group_id.strip():
|
||||||
|
clauses.append("group_id = ?")
|
||||||
|
params.append(group_id.strip())
|
||||||
|
if status == "active":
|
||||||
|
clauses.append("ended_at IS NULL")
|
||||||
|
elif status == "ended":
|
||||||
|
clauses.append("ended_at IS NOT NULL")
|
||||||
|
if date_from.strip():
|
||||||
|
clauses.append("push_date >= ?")
|
||||||
|
params.append(date_from.strip())
|
||||||
|
if date_to.strip():
|
||||||
|
clauses.append("push_date <= ?")
|
||||||
|
params.append(date_to.strip())
|
||||||
|
if q.strip():
|
||||||
|
like = f"%{q.strip()}%"
|
||||||
|
clauses.append(
|
||||||
|
"(anchor_name LIKE ? OR source_url LIKE ? OR source_room_id LIKE ? OR channel_name LIKE ?)"
|
||||||
|
)
|
||||||
|
params.extend([like, like, like, like])
|
||||||
|
where = ("WHERE " + " AND ".join(clauses)) if clauses else ""
|
||||||
|
lim = max(1, min(int(limit), 200))
|
||||||
|
off = max(0, int(offset))
|
||||||
|
with _lock:
|
||||||
|
conn = _connect()
|
||||||
|
try:
|
||||||
|
ensure_yt_relay_sessions(conn)
|
||||||
|
rows = conn.execute(
|
||||||
|
f"SELECT * FROM yt_relay_sessions {where} ORDER BY started_at DESC LIMIT ? OFFSET ?",
|
||||||
|
(*params, lim, off),
|
||||||
|
).fetchall()
|
||||||
|
total = conn.execute(f"SELECT COUNT(*) FROM yt_relay_sessions {where}", params).fetchone()[0]
|
||||||
|
return {
|
||||||
|
"sessions": [_row_session(_row_to_dict(r) or {}) for r in rows],
|
||||||
|
"total": int(total or 0),
|
||||||
|
"limit": lim,
|
||||||
|
"offset": off,
|
||||||
|
}
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def summarize_sessions(
|
||||||
|
*,
|
||||||
|
group_id: str = "",
|
||||||
|
q: str = "",
|
||||||
|
date_from: str = "",
|
||||||
|
date_to: str = "",
|
||||||
|
status: str = "",
|
||||||
|
top_anchors: int = 20,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
data = list_sessions(group_id=group_id, q=q, date_from=date_from, date_to=date_to, status=status, limit=5000, offset=0)
|
||||||
|
sessions = data.get("sessions") or []
|
||||||
|
now = time.time()
|
||||||
|
by_anchor: dict[str, dict[str, Any]] = {}
|
||||||
|
by_date: dict[str, dict[str, Any]] = {}
|
||||||
|
by_hour = [0] * 24
|
||||||
|
total_duration = 0.0
|
||||||
|
active_count = 0
|
||||||
|
duration_values: list[float] = []
|
||||||
|
|
||||||
|
for s in sessions:
|
||||||
|
dur = float(s.get("duration_seconds") or 0)
|
||||||
|
if not s.get("ended_at") and s.get("started_at"):
|
||||||
|
dur = max(dur, now - float(s["started_at"]))
|
||||||
|
active_count += 1
|
||||||
|
total_duration += dur
|
||||||
|
duration_values.append(dur)
|
||||||
|
anchor = str(s.get("anchor_name") or "未知").strip() or "未知"
|
||||||
|
ac = by_anchor.setdefault(anchor, {"anchor_name": anchor, "sessions": 0, "duration_seconds": 0.0})
|
||||||
|
ac["sessions"] += 1
|
||||||
|
ac["duration_seconds"] += dur
|
||||||
|
pd = str(s.get("push_date") or "")
|
||||||
|
if pd:
|
||||||
|
d = by_date.setdefault(pd, {"date": pd, "sessions": 0, "duration_seconds": 0.0, "anchors": set()})
|
||||||
|
d["sessions"] += 1
|
||||||
|
d["duration_seconds"] += dur
|
||||||
|
d["anchors"].add(anchor)
|
||||||
|
started = float(s.get("started_at") or 0)
|
||||||
|
if started > 0:
|
||||||
|
try:
|
||||||
|
by_hour[datetime.fromtimestamp(started).hour] += 1
|
||||||
|
except (OSError, ValueError, OverflowError):
|
||||||
|
pass
|
||||||
|
|
||||||
|
top = sorted(by_anchor.values(), key=lambda x: (-x["sessions"], -x["duration_seconds"]))[: max(1, top_anchors)]
|
||||||
|
for t in top:
|
||||||
|
t["hours_total"] = round(t["duration_seconds"] / 3600, 2)
|
||||||
|
|
||||||
|
dates_sorted = sorted(by_date.values(), key=lambda x: x["date"])
|
||||||
|
by_date_out = [
|
||||||
|
{
|
||||||
|
"date": d["date"],
|
||||||
|
"sessions": d["sessions"],
|
||||||
|
"hours": round(d["duration_seconds"] / 3600, 2),
|
||||||
|
"unique_anchors": len(d["anchors"]),
|
||||||
|
}
|
||||||
|
for d in dates_sorted[-60:]
|
||||||
|
]
|
||||||
|
|
||||||
|
avg_d = total_duration / len(sessions) if sessions else 0
|
||||||
|
return {
|
||||||
|
"overview": {
|
||||||
|
"sessions": len(sessions),
|
||||||
|
"unique_anchors": len(by_anchor),
|
||||||
|
"active_sessions": active_count,
|
||||||
|
"total_hours": round(total_duration / 3600, 2),
|
||||||
|
"avg_duration_seconds": int(avg_d),
|
||||||
|
"date_from": dates_sorted[0]["date"] if dates_sorted else "",
|
||||||
|
"date_to": dates_sorted[-1]["date"] if dates_sorted else "",
|
||||||
|
},
|
||||||
|
"top_anchors": top,
|
||||||
|
"by_hour": {"starts": by_hour, "labels": [f"{h:02d}:00" for h in range(24)]},
|
||||||
|
"by_date": by_date_out,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def get_session(session_id: int) -> dict[str, Any] | None:
|
||||||
|
with _lock:
|
||||||
|
conn = _connect()
|
||||||
|
try:
|
||||||
|
ensure_yt_relay_sessions(conn)
|
||||||
|
row = conn.execute("SELECT * FROM yt_relay_sessions WHERE id = ?", (int(session_id),)).fetchone()
|
||||||
|
return _row_session(_row_to_dict(row) or {}) if row else None
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
267
backend/app/youtube_relay_status.py
Normal file
267
backend/app/youtube_relay_status.py
Normal file
@ -0,0 +1,267 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""Relay business/process status — adapted from sh2 process_runtime_status (cloud, no PM2)."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import re
|
||||||
|
import time
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
_FFMPEG_PROGRESS_RE = re.compile(
|
||||||
|
r"frame=\s*(?P<frame>\d+).*?"
|
||||||
|
r"(?:fps=\s*(?P<fps>[\d.]+)\s*)?"
|
||||||
|
r"(?:time=(?P<h>\d+):(?P<m>\d+):(?P<s>\d+(?:\.\d+)?).*?)?"
|
||||||
|
r"bitrate=\s*(?P<bitrate>[\d.]+\s*kbits/s)?.*?"
|
||||||
|
r"speed=\s*(?P<speed>\d+(?:\.\d+)?)x",
|
||||||
|
re.IGNORECASE,
|
||||||
|
)
|
||||||
|
|
||||||
|
_ERROR_HINTS = (
|
||||||
|
"error",
|
||||||
|
"failed",
|
||||||
|
"403 forbidden",
|
||||||
|
"404 not found",
|
||||||
|
"unauthorized",
|
||||||
|
"forbidden",
|
||||||
|
"io error",
|
||||||
|
"error opening output",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _norm_log(text: str) -> str:
|
||||||
|
return (text or "").replace("\r\n", "\n").replace("\r", "\n")
|
||||||
|
|
||||||
|
|
||||||
|
def _has_any(text: str, patterns: tuple[str, ...]) -> bool:
|
||||||
|
low = text.lower()
|
||||||
|
return any(p in low for p in patterns)
|
||||||
|
|
||||||
|
|
||||||
|
def _looks_like_youtube_key_rejected(tail: str) -> bool:
|
||||||
|
if not _has_any(tail, ("rtmps://a.rtmps.youtube.com/live2/", "rtmp://a.rtmp.youtube.com/live2/")):
|
||||||
|
return False
|
||||||
|
if not _has_any(tail, ("error opening output", "error opening output file")):
|
||||||
|
return False
|
||||||
|
return _has_any(tail, ("io error", "401", "403", "unauthorized", "forbidden", "input/output error"))
|
||||||
|
|
||||||
|
|
||||||
|
def _ffmpeg_progress_samples(tail: str) -> list[dict[str, float | int]]:
|
||||||
|
samples: list[dict[str, float | int]] = []
|
||||||
|
for match in _FFMPEG_PROGRESS_RE.finditer(tail or ""):
|
||||||
|
try:
|
||||||
|
frame = int(match.group("frame"))
|
||||||
|
speed = float(match.group("speed"))
|
||||||
|
media_time = 0.0
|
||||||
|
if match.group("h") is not None:
|
||||||
|
media_time = (
|
||||||
|
int(match.group("h")) * 3600
|
||||||
|
+ int(match.group("m")) * 60
|
||||||
|
+ float(match.group("s") or 0)
|
||||||
|
)
|
||||||
|
row: dict[str, float | int] = {"frame": frame, "time": media_time, "speed": speed}
|
||||||
|
if match.group("fps"):
|
||||||
|
row["fps"] = float(match.group("fps"))
|
||||||
|
br = match.group("bitrate") or ""
|
||||||
|
m = re.search(r"([\d.]+)", br)
|
||||||
|
if m:
|
||||||
|
row["bitrate"] = float(m.group(1))
|
||||||
|
samples.append(row)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
continue
|
||||||
|
return samples[-8:]
|
||||||
|
|
||||||
|
|
||||||
|
def _progress_stalled(samples: list[dict[str, float | int]]) -> bool:
|
||||||
|
if len(samples) < 3:
|
||||||
|
return False
|
||||||
|
tail = samples[-3:]
|
||||||
|
frames = {int(r["frame"]) for r in tail}
|
||||||
|
times = {round(float(r["time"]), 2) for r in tail}
|
||||||
|
return len(frames) == 1 and len(times) == 1
|
||||||
|
|
||||||
|
|
||||||
|
def _speed_low(samples: list[dict[str, float | int]], threshold: float = 0.98) -> bool:
|
||||||
|
if len(samples) < 4:
|
||||||
|
return False
|
||||||
|
tail = samples[-4:]
|
||||||
|
if not all(float(r["speed"]) < threshold for r in tail):
|
||||||
|
return False
|
||||||
|
return int(tail[-1]["frame"]) > int(tail[0]["frame"]) or float(tail[-1]["time"]) > float(tail[0]["time"])
|
||||||
|
|
||||||
|
|
||||||
|
def split_relay_logs(lines: list[str] | None) -> tuple[str, str]:
|
||||||
|
out: list[str] = []
|
||||||
|
err: list[str] = []
|
||||||
|
for line in lines or []:
|
||||||
|
low = line.lower()
|
||||||
|
if any(h in low for h in _ERROR_HINTS):
|
||||||
|
err.append(line)
|
||||||
|
else:
|
||||||
|
out.append(line)
|
||||||
|
return "\n".join(out), "\n".join(err)
|
||||||
|
|
||||||
|
|
||||||
|
def summarize_relay_group(
|
||||||
|
*,
|
||||||
|
group: dict[str, Any],
|
||||||
|
st: dict[str, Any],
|
||||||
|
session_running: bool,
|
||||||
|
pipeline_enabled: bool,
|
||||||
|
log_age_seconds: float | None = None,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
"""Build process_monitor-style row for one assign group."""
|
||||||
|
gid = str(group.get("id") or st.get("group_id") or "")
|
||||||
|
has_key = bool(group.get("has_stream_key") or str(group.get("stream_key") or "").strip())
|
||||||
|
enabled = bool(group.get("enabled", True))
|
||||||
|
featured = group.get("featured") or []
|
||||||
|
featured_urls = [str(x.get("url") or "").strip() for x in featured if str(x.get("url") or "").strip()]
|
||||||
|
douyin_count = sum(1 for u in featured_urls if "douyin" in u.lower())
|
||||||
|
|
||||||
|
recent_log_lines = st.get("recent_log") if isinstance(st.get("recent_log"), list) else []
|
||||||
|
if not recent_log_lines and isinstance(st.get("recent_log"), str):
|
||||||
|
recent_log_lines = [st["recent_log"]]
|
||||||
|
recent_log, recent_error = split_relay_logs(recent_log_lines)
|
||||||
|
tail = _norm_log(f"{recent_log}\n{recent_error}")[-8000:].lower()
|
||||||
|
|
||||||
|
raw_status = str(st.get("status") or "idle").lower()
|
||||||
|
if session_running:
|
||||||
|
process_status = "online"
|
||||||
|
elif not enabled:
|
||||||
|
process_status = "stopped"
|
||||||
|
elif has_key and pipeline_enabled:
|
||||||
|
process_status = "configured" if raw_status in {"idle", "stopped"} else raw_status
|
||||||
|
elif has_key:
|
||||||
|
process_status = "configured"
|
||||||
|
else:
|
||||||
|
process_status = "stopped"
|
||||||
|
|
||||||
|
pids: list[int] = []
|
||||||
|
pid = int(st.get("ffmpeg_pid") or 0)
|
||||||
|
if pid > 0:
|
||||||
|
pids = [pid]
|
||||||
|
|
||||||
|
progress_samples = _ffmpeg_progress_samples(tail)
|
||||||
|
latest = progress_samples[-1] if progress_samples else {}
|
||||||
|
progress_stalled = _progress_stalled(progress_samples)
|
||||||
|
speed_low = _speed_low(progress_samples)
|
||||||
|
has_progress = "frame=" in tail and "speed=" in tail
|
||||||
|
log_recent = log_age_seconds is None or log_age_seconds <= 20
|
||||||
|
has_worker = bool(pids) or session_running
|
||||||
|
|
||||||
|
business_status = "inactive"
|
||||||
|
business_note = "未运行"
|
||||||
|
if not has_key:
|
||||||
|
business_status = "misconfigured"
|
||||||
|
business_note = "缺少 YouTube 直播 KEY"
|
||||||
|
elif not enabled:
|
||||||
|
business_status = "inactive"
|
||||||
|
business_note = "频道已停用"
|
||||||
|
elif not featured_urls:
|
||||||
|
business_status = "misconfigured"
|
||||||
|
business_note = "直播地址列表(精选)为空"
|
||||||
|
elif _looks_like_youtube_key_rejected(tail):
|
||||||
|
business_status = "youtube_key_rejected"
|
||||||
|
business_note = "YouTube 拒绝了 RTMPS 推流,请检查直播 KEY 或网络"
|
||||||
|
elif raw_status == "error" and st.get("error"):
|
||||||
|
business_status = "error"
|
||||||
|
business_note = str(st.get("error") or "")[:240]
|
||||||
|
elif session_running and has_progress and log_recent and progress_stalled:
|
||||||
|
business_status = "source_stalled"
|
||||||
|
business_note = "FFmpeg 在运行但帧/时间进度停滞"
|
||||||
|
elif session_running and has_progress and log_recent and speed_low:
|
||||||
|
business_status = "relay_slow"
|
||||||
|
business_note = "推流速度低于实时"
|
||||||
|
elif session_running and has_progress and log_recent:
|
||||||
|
business_status = "streaming"
|
||||||
|
business_note = "正在推流到 YouTube"
|
||||||
|
elif session_running and has_worker and log_recent and _has_any(tail, ("opening input", "opening output", "rtmps://")):
|
||||||
|
business_status = "relay_starting"
|
||||||
|
business_note = "FFmpeg 已启动,等待进度上报"
|
||||||
|
elif pipeline_enabled and enabled and has_key and not session_running:
|
||||||
|
if raw_status == "reconnecting":
|
||||||
|
business_status = "relay_starting"
|
||||||
|
business_note = "推流中断,正在重连"
|
||||||
|
elif log_age_seconds is not None and log_age_seconds > 180 and has_worker:
|
||||||
|
business_status = "stale"
|
||||||
|
business_note = "进程在线但日志心跳过期"
|
||||||
|
else:
|
||||||
|
live_ids_hint = bool(st.get("source_room_id"))
|
||||||
|
if live_ids_hint and not session_running:
|
||||||
|
business_status = "waiting_source"
|
||||||
|
business_note = "等待可用抖音源或 Worker 调度"
|
||||||
|
else:
|
||||||
|
business_status = "monitoring"
|
||||||
|
business_note = "Worker 运行中,等待推流"
|
||||||
|
elif has_key and featured_urls and pipeline_enabled:
|
||||||
|
business_status = "ready"
|
||||||
|
business_note = "已配置,等待自动推流"
|
||||||
|
elif process_status == "configured":
|
||||||
|
business_status = "ready"
|
||||||
|
business_note = "已配置(未推流)"
|
||||||
|
|
||||||
|
is_pushing = business_status in {"streaming", "relay_slow"} or (
|
||||||
|
business_status == "source_stalled" and has_progress and has_worker
|
||||||
|
)
|
||||||
|
|
||||||
|
speed = latest.get("speed")
|
||||||
|
if speed is None and st.get("speed"):
|
||||||
|
try:
|
||||||
|
speed = float(st.get("speed"))
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
speed = None
|
||||||
|
|
||||||
|
frame = latest.get("frame")
|
||||||
|
if frame is None and st.get("frame"):
|
||||||
|
try:
|
||||||
|
frame = int(st.get("frame"))
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
frame = None
|
||||||
|
|
||||||
|
return {
|
||||||
|
"group_id": gid,
|
||||||
|
"label": group.get("name") or gid,
|
||||||
|
"process_status": process_status,
|
||||||
|
"business_status": business_status,
|
||||||
|
"business_note": business_note,
|
||||||
|
"is_pushing": is_pushing,
|
||||||
|
"ffmpeg_active": has_worker,
|
||||||
|
"ffmpeg_pids": pids,
|
||||||
|
"ffmpeg_pid": pids[0] if pids else 0,
|
||||||
|
"ffmpeg_speed": speed,
|
||||||
|
"ffmpeg_frame": frame,
|
||||||
|
"ffmpeg_fps": latest.get("fps"),
|
||||||
|
"ffmpeg_bitrate_kbps": latest.get("bitrate"),
|
||||||
|
"ffmpeg_time_seconds": latest.get("time"),
|
||||||
|
"ffmpeg_progress_stalled": progress_stalled,
|
||||||
|
"ffmpeg_speed_low": speed_low,
|
||||||
|
"log_age_seconds": log_age_seconds,
|
||||||
|
"recent_log": recent_log,
|
||||||
|
"recent_error": recent_error,
|
||||||
|
"source_title": st.get("anchor_name") or "",
|
||||||
|
"source_room_id": st.get("source_room_id") or st.get("room_id") or "",
|
||||||
|
"source_url": st.get("source_url") or "",
|
||||||
|
"source_display": st.get("anchor_name") or "",
|
||||||
|
"url_count": len(featured_urls),
|
||||||
|
"douyin_count": douyin_count,
|
||||||
|
"has_stream_key": has_key,
|
||||||
|
"stream_key_suffix": _key_suffix(group),
|
||||||
|
"push_seconds": float(st.get("push_seconds") or 0),
|
||||||
|
"started_at": float(st.get("started_at") or 0),
|
||||||
|
"updated_at": float(st.get("updated_at") or 0),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _key_suffix(group: dict[str, Any]) -> str:
|
||||||
|
sk = str(group.get("stream_key") or "").strip()
|
||||||
|
if len(sk) >= 4:
|
||||||
|
return sk[-4:]
|
||||||
|
masked = str(group.get("stream_key_masked") or "")
|
||||||
|
if masked.startswith("***") and len(masked) > 3:
|
||||||
|
return masked[3:]
|
||||||
|
return ""
|
||||||
|
|
||||||
|
|
||||||
|
def log_age_seconds(st: dict[str, Any], now: float | None = None) -> float | None:
|
||||||
|
updated = float(st.get("updated_at") or 0)
|
||||||
|
if updated <= 0:
|
||||||
|
return None
|
||||||
|
return max(0.0, (now or time.time()) - updated)
|
||||||
@ -93,6 +93,25 @@ def ensure_yt_assign_tables(conn: sqlite3.Connection) -> None:
|
|||||||
conn.execute(
|
conn.execute(
|
||||||
"CREATE INDEX IF NOT EXISTS idx_yt_assign_slot_group ON yt_assign_slot_urls(group_id, sort_order)"
|
"CREATE INDEX IF NOT EXISTS idx_yt_assign_slot_group ON yt_assign_slot_urls(group_id, sort_order)"
|
||||||
)
|
)
|
||||||
|
gcols = {str(r[1]) for r in conn.execute("PRAGMA table_info(yt_assign_groups)").fetchall()}
|
||||||
|
for col, ddl in [
|
||||||
|
("neko_instance_id", "INTEGER NOT NULL DEFAULT 0"),
|
||||||
|
("neko_enabled", "INTEGER NOT NULL DEFAULT 0"),
|
||||||
|
]:
|
||||||
|
if col not in gcols:
|
||||||
|
conn.execute(f"ALTER TABLE yt_assign_groups ADD COLUMN {col} {ddl}")
|
||||||
|
orphans = conn.execute(
|
||||||
|
"SELECT id FROM yt_assign_groups WHERE COALESCE(neko_instance_id, 0) = 0 ORDER BY sort_order ASC, created_at ASC"
|
||||||
|
).fetchall()
|
||||||
|
if orphans:
|
||||||
|
max_row = conn.execute("SELECT COALESCE(MAX(neko_instance_id), 0) AS m FROM yt_assign_groups").fetchone()
|
||||||
|
next_id = int(max_row["m"] if max_row else 0)
|
||||||
|
for row in orphans:
|
||||||
|
next_id += 1
|
||||||
|
conn.execute(
|
||||||
|
"UPDATE yt_assign_groups SET neko_instance_id = ? WHERE id = ?",
|
||||||
|
(next_id, str(row["id"])),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def parse_pool_line(raw: str) -> dict[str, str]:
|
def parse_pool_line(raw: str) -> dict[str, str]:
|
||||||
@ -227,6 +246,9 @@ def _beijing_hour_fraction(ts: float | None = None) -> float:
|
|||||||
def _public_group(row: dict[str, Any], *, pool: list | None = None, featured: list | None = None, slots: list | None = None) -> dict[str, Any]:
|
def _public_group(row: dict[str, Any], *, pool: list | None = None, featured: list | None = None, slots: list | None = None) -> dict[str, Any]:
|
||||||
out = dict(row)
|
out = dict(row)
|
||||||
out["enabled"] = bool(out.get("enabled"))
|
out["enabled"] = bool(out.get("enabled"))
|
||||||
|
out["neko_enabled"] = bool(out.get("neko_enabled"))
|
||||||
|
neko_id = int(out.get("neko_instance_id") or 0)
|
||||||
|
out["neko_instance_id"] = neko_id
|
||||||
sk = str(out.get("stream_key") or "")
|
sk = str(out.get("stream_key") or "")
|
||||||
out["has_stream_key"] = bool(sk.strip())
|
out["has_stream_key"] = bool(sk.strip())
|
||||||
out["stream_key_masked"] = ("***" + sk[-4:]) if len(sk) > 6 else ("***" if sk else "")
|
out["stream_key_masked"] = ("***" + sk[-4:]) if len(sk) > 6 else ("***" if sk else "")
|
||||||
@ -236,6 +258,13 @@ def _public_group(row: dict[str, Any], *, pool: list | None = None, featured: li
|
|||||||
out["featured"] = featured
|
out["featured"] = featured
|
||||||
if slots is not None:
|
if slots is not None:
|
||||||
out["slots"] = slots
|
out["slots"] = slots
|
||||||
|
if neko_id > 0:
|
||||||
|
try:
|
||||||
|
from . import youtube_neko
|
||||||
|
|
||||||
|
out["neko_studio_url"] = youtube_neko.public_studio_url(neko_id)
|
||||||
|
except Exception:
|
||||||
|
out["neko_studio_url"] = ""
|
||||||
return out
|
return out
|
||||||
|
|
||||||
|
|
||||||
@ -352,12 +381,17 @@ def create_group(
|
|||||||
ensure_yt_assign_tables(conn)
|
ensure_yt_assign_tables(conn)
|
||||||
max_ord = conn.execute("SELECT COALESCE(MAX(sort_order), 0) AS m FROM yt_assign_groups").fetchone()
|
max_ord = conn.execute("SELECT COALESCE(MAX(sort_order), 0) AS m FROM yt_assign_groups").fetchone()
|
||||||
sort_order = int(max_ord["m"] if max_ord else 0) + 1
|
sort_order = int(max_ord["m"] if max_ord else 0) + 1
|
||||||
|
max_neko = conn.execute(
|
||||||
|
"SELECT COALESCE(MAX(neko_instance_id), 0) AS m FROM yt_assign_groups"
|
||||||
|
).fetchone()
|
||||||
|
neko_instance_id = int(max_neko["m"] if max_neko else 0) + 1
|
||||||
conn.execute(
|
conn.execute(
|
||||||
"""
|
"""
|
||||||
INSERT INTO yt_assign_groups(
|
INSERT INTO yt_assign_groups(
|
||||||
id, name, channel_pk, youtube_channel_id, stream_key, note,
|
id, name, channel_pk, youtube_channel_id, stream_key, note,
|
||||||
enabled, sort_order, created_at, updated_at
|
enabled, sort_order, neko_instance_id, neko_enabled,
|
||||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
created_at, updated_at
|
||||||
|
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||||
""",
|
""",
|
||||||
(
|
(
|
||||||
gid,
|
gid,
|
||||||
@ -368,6 +402,8 @@ def create_group(
|
|||||||
str(note or "").strip()[:500],
|
str(note or "").strip()[:500],
|
||||||
1 if enabled else 0,
|
1 if enabled else 0,
|
||||||
sort_order,
|
sort_order,
|
||||||
|
neko_instance_id,
|
||||||
|
0,
|
||||||
now,
|
now,
|
||||||
now,
|
now,
|
||||||
),
|
),
|
||||||
@ -375,7 +411,14 @@ def create_group(
|
|||||||
conn.commit()
|
conn.commit()
|
||||||
finally:
|
finally:
|
||||||
conn.close()
|
conn.close()
|
||||||
return get_group(gid) or {"id": gid}
|
group = get_group(gid) or {"id": gid}
|
||||||
|
try:
|
||||||
|
from . import youtube_neko
|
||||||
|
|
||||||
|
youtube_neko.sync_for_groups(list_groups(include_urls=False))
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
return group
|
||||||
|
|
||||||
|
|
||||||
def update_group(group_id: str, **fields: Any) -> dict[str, Any]:
|
def update_group(group_id: str, **fields: Any) -> dict[str, Any]:
|
||||||
@ -389,6 +432,7 @@ def update_group(group_id: str, **fields: Any) -> dict[str, Any]:
|
|||||||
"note",
|
"note",
|
||||||
"enabled",
|
"enabled",
|
||||||
"sort_order",
|
"sort_order",
|
||||||
|
"neko_enabled",
|
||||||
}
|
}
|
||||||
patch: dict[str, Any] = {}
|
patch: dict[str, Any] = {}
|
||||||
for k, v in fields.items():
|
for k, v in fields.items():
|
||||||
@ -396,6 +440,8 @@ def update_group(group_id: str, **fields: Any) -> dict[str, Any]:
|
|||||||
continue
|
continue
|
||||||
if k == "enabled":
|
if k == "enabled":
|
||||||
patch[k] = 1 if v else 0
|
patch[k] = 1 if v else 0
|
||||||
|
elif k == "neko_enabled":
|
||||||
|
patch[k] = 1 if v else 0
|
||||||
elif k == "sort_order":
|
elif k == "sort_order":
|
||||||
try:
|
try:
|
||||||
patch[k] = int(v)
|
patch[k] = int(v)
|
||||||
@ -445,7 +491,15 @@ def update_group(group_id: str, **fields: Any) -> dict[str, Any]:
|
|||||||
conn.commit()
|
conn.commit()
|
||||||
finally:
|
finally:
|
||||||
conn.close()
|
conn.close()
|
||||||
return get_group(group_id) or {}
|
group = get_group(group_id) or {}
|
||||||
|
if "neko_enabled" in patch:
|
||||||
|
try:
|
||||||
|
from . import youtube_neko
|
||||||
|
|
||||||
|
youtube_neko.sync_for_groups(list_groups(include_urls=False))
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
return group
|
||||||
|
|
||||||
|
|
||||||
def delete_group(group_id: str) -> dict[str, Any]:
|
def delete_group(group_id: str) -> dict[str, Any]:
|
||||||
@ -458,9 +512,16 @@ def delete_group(group_id: str) -> dict[str, Any]:
|
|||||||
n_pool = conn.execute("DELETE FROM yt_assign_pool_urls WHERE group_id = ?", (group_id,)).rowcount
|
n_pool = conn.execute("DELETE FROM yt_assign_pool_urls WHERE group_id = ?", (group_id,)).rowcount
|
||||||
n = conn.execute("DELETE FROM yt_assign_groups WHERE id = ?", (group_id,)).rowcount
|
n = conn.execute("DELETE FROM yt_assign_groups WHERE id = ?", (group_id,)).rowcount
|
||||||
conn.commit()
|
conn.commit()
|
||||||
return {"ok": True, "deleted": int(n), "pool_deleted": int(n_pool)}
|
result = {"ok": True, "deleted": int(n), "pool_deleted": int(n_pool)}
|
||||||
finally:
|
finally:
|
||||||
conn.close()
|
conn.close()
|
||||||
|
try:
|
||||||
|
from . import youtube_neko
|
||||||
|
|
||||||
|
youtube_neko.sync_for_groups(list_groups(include_urls=False))
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
def add_pool_urls(
|
def add_pool_urls(
|
||||||
|
|||||||
@ -21,7 +21,7 @@ import { EnableSwitch } from "@/components/EnableSwitch";
|
|||||||
import { Shell } from "@/components/Shell";
|
import { Shell } from "@/components/Shell";
|
||||||
import { useConfirm } from "@/components/ConfirmDialog";
|
import { useConfirm } from "@/components/ConfirmDialog";
|
||||||
import { useToast } from "@/components/Toast";
|
import { useToast } from "@/components/Toast";
|
||||||
import { GoogleOauthSetupWizard } from "@/components/GoogleOauthSetupWizard";
|
import { GoogleOauthSetupWizard, defaultShortsRedirectUri } from "@/components/GoogleOauthSetupWizard";
|
||||||
import { OauthClientBadge, normalizeOauthProfileId } from "@/components/OauthClientBadge";
|
import { OauthClientBadge, normalizeOauthProfileId } from "@/components/OauthClientBadge";
|
||||||
import { ShortsJobDetailModal } from "@/components/ShortsJobDetailModal";
|
import { ShortsJobDetailModal } from "@/components/ShortsJobDetailModal";
|
||||||
import {
|
import {
|
||||||
@ -736,7 +736,7 @@ export default function ShortsPage() {
|
|||||||
{showWizard || !status?.oauth_configured ? (
|
{showWizard || !status?.oauth_configured ? (
|
||||||
<GoogleOauthSetupWizard
|
<GoogleOauthSetupWizard
|
||||||
initialProjectId={String(status?.gcp_project_id || "live-473104")}
|
initialProjectId={String(status?.gcp_project_id || "live-473104")}
|
||||||
redirectUri={String(status?.oauth_redirect_uri || "https://dylive.nomadro.com/api/shorts/oauth/callback")}
|
redirectUri={String(status?.oauth_redirect_uri || defaultShortsRedirectUri())}
|
||||||
configured={Boolean(status?.oauth_configured)}
|
configured={Boolean(status?.oauth_configured)}
|
||||||
onSaved={() => void load()}
|
onSaved={() => void load()}
|
||||||
/>
|
/>
|
||||||
|
|||||||
436
frontend/src/app/youtube-relay-log/page.tsx
Normal file
436
frontend/src/app/youtube-relay-log/page.tsx
Normal file
@ -0,0 +1,436 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import Link from "next/link";
|
||||||
|
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||||
|
import { ExternalLink, Loader2, RefreshCw, Search } from "lucide-react";
|
||||||
|
|
||||||
|
import { Shell } from "@/components/Shell";
|
||||||
|
import { SessionCharts, type RelayStats } from "@/components/SessionCharts";
|
||||||
|
import { fetchJson, fmtDuration, fmtTs } from "@/lib/api";
|
||||||
|
import { useAutoRefresh } from "@/lib/realtime";
|
||||||
|
|
||||||
|
type RelaySession = {
|
||||||
|
id: number;
|
||||||
|
session_uuid?: string;
|
||||||
|
group_id?: string;
|
||||||
|
process?: string;
|
||||||
|
channel_name?: string;
|
||||||
|
anchor_name?: string;
|
||||||
|
source_url?: string;
|
||||||
|
source_room_id?: string;
|
||||||
|
stream_title?: string;
|
||||||
|
youtube_key_suffix?: string;
|
||||||
|
started_at?: number;
|
||||||
|
ended_at?: number | null;
|
||||||
|
duration_seconds?: number;
|
||||||
|
push_date?: string;
|
||||||
|
status?: string;
|
||||||
|
end_reason?: string;
|
||||||
|
metadata?: Record<string, unknown>;
|
||||||
|
};
|
||||||
|
|
||||||
|
type AssignGroup = { id: string; name?: string };
|
||||||
|
|
||||||
|
function douyinUrl(session: RelaySession): string {
|
||||||
|
if (session.source_url?.includes("live.douyin.com")) return session.source_url;
|
||||||
|
if (session.source_room_id) return `https://live.douyin.com/${session.source_room_id}`;
|
||||||
|
return session.source_url || "";
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function YoutubeRelayLogPage() {
|
||||||
|
const [groupId, setGroupId] = useState("");
|
||||||
|
const [q, setQ] = useState("");
|
||||||
|
const [dateFrom, setDateFrom] = useState("");
|
||||||
|
const [dateTo, setDateTo] = useState("");
|
||||||
|
const [status, setStatus] = useState("");
|
||||||
|
const [sessions, setSessions] = useState<RelaySession[]>([]);
|
||||||
|
const [stats, setStats] = useState<RelayStats | null>(null);
|
||||||
|
const [total, setTotal] = useState(0);
|
||||||
|
const [offset, setOffset] = useState(0);
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
const [error, setError] = useState("");
|
||||||
|
const [selected, setSelected] = useState<RelaySession | null>(null);
|
||||||
|
const [tab, setTab] = useState<"charts" | "list">("charts");
|
||||||
|
const [groups, setGroups] = useState<AssignGroup[]>([]);
|
||||||
|
const limit = 50;
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (typeof window === "undefined") return;
|
||||||
|
const p = new URLSearchParams(window.location.search);
|
||||||
|
const gid = p.get("group_id") || p.get("process") || "";
|
||||||
|
if (gid) setGroupId(gid);
|
||||||
|
const sq = p.get("q");
|
||||||
|
if (sq) setQ(sq);
|
||||||
|
const sf = p.get("date_from");
|
||||||
|
if (sf) setDateFrom(sf);
|
||||||
|
const st = p.get("date_to");
|
||||||
|
if (st) setDateTo(st);
|
||||||
|
const ss = p.get("status");
|
||||||
|
if (ss) setStatus(ss);
|
||||||
|
const sid = p.get("session");
|
||||||
|
if (sid) {
|
||||||
|
void fetchJson(`/api/youtube/relay/sessions/${sid}`)
|
||||||
|
.then((d) => setSelected(d as RelaySession))
|
||||||
|
.catch(() => undefined);
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
void fetchJson("/api/youtube/assign/groups")
|
||||||
|
.then((d) => setGroups((d.groups || d) as AssignGroup[]))
|
||||||
|
.catch(() => undefined);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const filterParams = useMemo(() => {
|
||||||
|
const params = new URLSearchParams();
|
||||||
|
if (groupId.trim()) params.set("group_id", groupId.trim());
|
||||||
|
if (q.trim()) params.set("q", q.trim());
|
||||||
|
if (dateFrom) params.set("date_from", dateFrom);
|
||||||
|
if (dateTo) params.set("date_to", dateTo);
|
||||||
|
if (status) params.set("status", status);
|
||||||
|
return params;
|
||||||
|
}, [groupId, q, dateFrom, dateTo, status]);
|
||||||
|
|
||||||
|
const queryString = useMemo(() => {
|
||||||
|
const params = new URLSearchParams(filterParams);
|
||||||
|
params.set("limit", String(limit));
|
||||||
|
params.set("offset", String(offset));
|
||||||
|
return params.toString();
|
||||||
|
}, [filterParams, offset]);
|
||||||
|
|
||||||
|
const statsQuery = useMemo(() => {
|
||||||
|
const params = new URLSearchParams(filterParams);
|
||||||
|
params.set("top_anchors", "25");
|
||||||
|
return params.toString();
|
||||||
|
}, [filterParams]);
|
||||||
|
|
||||||
|
const load = useCallback(async () => {
|
||||||
|
setLoading(true);
|
||||||
|
setError("");
|
||||||
|
try {
|
||||||
|
const [listData, statsData] = await Promise.all([
|
||||||
|
fetchJson(`/api/youtube/relay/sessions?${queryString}`),
|
||||||
|
fetchJson(`/api/youtube/relay/sessions/stats?${statsQuery}`),
|
||||||
|
]);
|
||||||
|
setSessions(listData.sessions || []);
|
||||||
|
setTotal(Number(listData.total) || 0);
|
||||||
|
setStats(statsData);
|
||||||
|
} catch (e) {
|
||||||
|
setError((e as Error).message);
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
}, [queryString, statsQuery]);
|
||||||
|
|
||||||
|
useAutoRefresh(load, { intervalMs: 20000 });
|
||||||
|
|
||||||
|
const pageCount = Math.max(1, Math.ceil(total / limit));
|
||||||
|
const pageIndex = Math.floor(offset / limit) + 1;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Shell>
|
||||||
|
<div className="mb-4 flex flex-wrap items-start justify-between gap-3">
|
||||||
|
<div>
|
||||||
|
<h2 className="font-display text-2xl font-semibold">📋 YouTube 推流日志</h2>
|
||||||
|
<p className="mt-1 max-w-3xl text-sm text-slate-400">
|
||||||
|
云管道 FFmpeg 推流历史:每位主播的开播频率、时段规律与累计时长;列表保留逐场明细,便于追溯。
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div className="flex flex-wrap gap-2">
|
||||||
|
<Link
|
||||||
|
href="/youtube"
|
||||||
|
className="rounded-lg border border-white/10 bg-white/5 px-3 py-2 text-sm text-slate-300 hover:bg-white/10"
|
||||||
|
>
|
||||||
|
← 分配 / 转播
|
||||||
|
</Link>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => void load()}
|
||||||
|
disabled={loading}
|
||||||
|
className="inline-flex items-center gap-2 rounded-lg border border-white/10 bg-white/5 px-3 py-2 text-sm hover:bg-white/10 disabled:opacity-50"
|
||||||
|
>
|
||||||
|
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <RefreshCw className="h-4 w-4" />}
|
||||||
|
刷新
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mb-4 grid gap-3 rounded-xl border border-white/10 bg-black/30 p-4 md:grid-cols-2 xl:grid-cols-6">
|
||||||
|
<label className="block text-xs text-slate-400 xl:col-span-1">
|
||||||
|
频道 / 进程
|
||||||
|
<select
|
||||||
|
value={groupId}
|
||||||
|
onChange={(e) => {
|
||||||
|
setOffset(0);
|
||||||
|
setGroupId(e.target.value);
|
||||||
|
}}
|
||||||
|
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm"
|
||||||
|
>
|
||||||
|
<option value="">全部频道</option>
|
||||||
|
{groups.map((g) => (
|
||||||
|
<option key={g.id} value={g.id}>
|
||||||
|
{g.name || g.id}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
<label className="block text-xs text-slate-400 xl:col-span-2">
|
||||||
|
检索(昵称 / URL / 房间号)
|
||||||
|
<div className="relative mt-1">
|
||||||
|
<Search className="pointer-events-none absolute left-3 top-2.5 h-4 w-4 text-slate-500" />
|
||||||
|
<input
|
||||||
|
value={q}
|
||||||
|
onChange={(e) => {
|
||||||
|
setOffset(0);
|
||||||
|
setQ(e.target.value);
|
||||||
|
}}
|
||||||
|
className="w-full rounded-lg border border-white/10 bg-slate-900 py-2 pl-9 pr-3 text-sm"
|
||||||
|
placeholder="例如:柠檬茶、745277409780"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</label>
|
||||||
|
<label className="block text-xs text-slate-400">
|
||||||
|
开始日期
|
||||||
|
<input
|
||||||
|
type="date"
|
||||||
|
value={dateFrom}
|
||||||
|
onChange={(e) => {
|
||||||
|
setOffset(0);
|
||||||
|
setDateFrom(e.target.value);
|
||||||
|
}}
|
||||||
|
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm"
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<label className="block text-xs text-slate-400">
|
||||||
|
结束日期
|
||||||
|
<input
|
||||||
|
type="date"
|
||||||
|
value={dateTo}
|
||||||
|
onChange={(e) => {
|
||||||
|
setOffset(0);
|
||||||
|
setDateTo(e.target.value);
|
||||||
|
}}
|
||||||
|
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm"
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<label className="block text-xs text-slate-400">
|
||||||
|
状态
|
||||||
|
<select
|
||||||
|
value={status}
|
||||||
|
onChange={(e) => {
|
||||||
|
setOffset(0);
|
||||||
|
setStatus(e.target.value);
|
||||||
|
}}
|
||||||
|
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm"
|
||||||
|
>
|
||||||
|
<option value="">全部</option>
|
||||||
|
<option value="active">进行中</option>
|
||||||
|
<option value="ended">已结束</option>
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{error ? (
|
||||||
|
<div className="mb-4 rounded-lg border border-rose-500/30 bg-rose-500/10 px-4 py-3 text-sm text-rose-100">
|
||||||
|
{error}
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
<div className="mb-4 flex gap-2">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setTab("charts")}
|
||||||
|
className={`rounded-lg px-3 py-1.5 text-sm ${
|
||||||
|
tab === "charts" ? "bg-white/15 text-white" : "bg-white/5 text-zinc-400 hover:bg-white/10"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
可视化分析
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setTab("list")}
|
||||||
|
className={`rounded-lg px-3 py-1.5 text-sm ${
|
||||||
|
tab === "list" ? "bg-white/15 text-white" : "bg-white/5 text-zinc-400 hover:bg-white/10"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
场次列表 ({total})
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{tab === "charts" ? <SessionCharts stats={stats} /> : null}
|
||||||
|
|
||||||
|
{tab === "list" ? (
|
||||||
|
<>
|
||||||
|
<div className="overflow-hidden rounded-xl border border-white/10 bg-black/20">
|
||||||
|
<div className="overflow-x-auto">
|
||||||
|
<table className="min-w-full text-left text-sm">
|
||||||
|
<thead className="bg-white/5 text-xs uppercase tracking-wide text-zinc-400">
|
||||||
|
<tr>
|
||||||
|
<th className="px-3 py-3">主播昵称</th>
|
||||||
|
<th className="px-3 py-3">直播间 URL</th>
|
||||||
|
<th className="px-3 py-3">推流开始</th>
|
||||||
|
<th className="px-3 py-3">推流结束</th>
|
||||||
|
<th className="px-3 py-3">总时长</th>
|
||||||
|
<th className="px-3 py-3">推流日期</th>
|
||||||
|
<th className="px-3 py-3">YT 密钥</th>
|
||||||
|
<th className="px-3 py-3">频道</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{sessions.map((session) => {
|
||||||
|
const url = douyinUrl(session);
|
||||||
|
return (
|
||||||
|
<tr
|
||||||
|
key={session.id}
|
||||||
|
className="cursor-pointer border-t border-white/5 hover:bg-white/[0.03]"
|
||||||
|
onClick={() => setSelected(session)}
|
||||||
|
>
|
||||||
|
<td className="px-3 py-3 font-medium text-zinc-100">{session.anchor_name || "—"}</td>
|
||||||
|
<td className="max-w-[14rem] truncate px-3 py-3 font-mono text-xs text-cyan-300/90">
|
||||||
|
{url ? (
|
||||||
|
<a
|
||||||
|
href={url}
|
||||||
|
target="_blank"
|
||||||
|
rel="noreferrer"
|
||||||
|
className="hover:underline"
|
||||||
|
onClick={(e) => e.stopPropagation()}
|
||||||
|
>
|
||||||
|
{url.replace(/^https?:\/\//, "")}
|
||||||
|
</a>
|
||||||
|
) : (
|
||||||
|
"—"
|
||||||
|
)}
|
||||||
|
</td>
|
||||||
|
<td className="whitespace-nowrap px-3 py-3 text-zinc-300">{fmtTs(session.started_at)}</td>
|
||||||
|
<td className="whitespace-nowrap px-3 py-3 text-zinc-300">
|
||||||
|
{session.ended_at ? fmtTs(session.ended_at) : "进行中"}
|
||||||
|
</td>
|
||||||
|
<td className="whitespace-nowrap px-3 py-3 font-mono text-zinc-200">
|
||||||
|
{fmtDuration(session.duration_seconds)}
|
||||||
|
</td>
|
||||||
|
<td className="whitespace-nowrap px-3 py-3">{session.push_date || "—"}</td>
|
||||||
|
<td className="whitespace-nowrap px-3 py-3 font-mono text-xs text-amber-200/90">
|
||||||
|
{session.youtube_key_suffix ? `…${session.youtube_key_suffix}` : "—"}
|
||||||
|
</td>
|
||||||
|
<td className="px-3 py-3 text-xs text-zinc-400">
|
||||||
|
{session.channel_name || session.process || "—"}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
{!loading && sessions.length === 0 ? (
|
||||||
|
<tr>
|
||||||
|
<td colSpan={8} className="px-3 py-10 text-center text-zinc-500">
|
||||||
|
暂无推流记录。在分配页开启自动推流并开始转播后,会话将自动写入此处。
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
) : null}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mt-4 flex items-center justify-between text-sm text-zinc-400">
|
||||||
|
<span>
|
||||||
|
共 {total} 条 · 第 {pageIndex}/{pageCount}
|
||||||
|
</span>
|
||||||
|
<div className="flex gap-2">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
disabled={offset <= 0 || loading}
|
||||||
|
onClick={() => setOffset(Math.max(0, offset - limit))}
|
||||||
|
className="rounded-lg border border-white/10 px-3 py-1.5 disabled:opacity-40"
|
||||||
|
>
|
||||||
|
上一页
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
disabled={offset + limit >= total || loading}
|
||||||
|
onClick={() => setOffset(offset + limit)}
|
||||||
|
className="rounded-lg border border-white/10 px-3 py-1.5 disabled:opacity-40"
|
||||||
|
>
|
||||||
|
下一页
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
{selected ? (
|
||||||
|
<div
|
||||||
|
className="fixed inset-0 z-50 flex items-center justify-center bg-black/70 p-4"
|
||||||
|
onClick={() => setSelected(null)}
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
className="max-h-[90vh] w-full max-w-2xl overflow-y-auto rounded-2xl border border-white/10 bg-zinc-950 p-5 shadow-2xl"
|
||||||
|
onClick={(e) => e.stopPropagation()}
|
||||||
|
>
|
||||||
|
<div className="flex items-start justify-between gap-3">
|
||||||
|
<div>
|
||||||
|
<h2 className="text-lg font-semibold">{selected.anchor_name || "推流详情"}</h2>
|
||||||
|
<p className="mt-1 text-sm text-zinc-400">{selected.stream_title || selected.channel_name || "—"}</p>
|
||||||
|
</div>
|
||||||
|
<button type="button" className="text-zinc-400 hover:text-zinc-200" onClick={() => setSelected(null)}>
|
||||||
|
✕
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<dl className="mt-4 grid gap-2 text-sm">
|
||||||
|
<div>
|
||||||
|
<dt className="text-zinc-500">直播间 URL</dt>
|
||||||
|
<dd className="break-all font-mono text-cyan-300">
|
||||||
|
{douyinUrl(selected) ? (
|
||||||
|
<a
|
||||||
|
href={douyinUrl(selected)}
|
||||||
|
target="_blank"
|
||||||
|
rel="noreferrer"
|
||||||
|
className="inline-flex items-center gap-1 hover:underline"
|
||||||
|
>
|
||||||
|
{douyinUrl(selected)} <ExternalLink className="h-3.5 w-3.5" />
|
||||||
|
</a>
|
||||||
|
) : (
|
||||||
|
"—"
|
||||||
|
)}
|
||||||
|
</dd>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<dt className="text-zinc-500">房间号</dt>
|
||||||
|
<dd>{selected.source_room_id || "—"}</dd>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<dt className="text-zinc-500">推流开始</dt>
|
||||||
|
<dd>{fmtTs(selected.started_at)}</dd>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<dt className="text-zinc-500">推流结束</dt>
|
||||||
|
<dd>{selected.ended_at ? fmtTs(selected.ended_at) : "进行中"}</dd>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<dt className="text-zinc-500">总时长</dt>
|
||||||
|
<dd>{fmtDuration(selected.duration_seconds)}</dd>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<dt className="text-zinc-500">推流日期</dt>
|
||||||
|
<dd>{selected.push_date || "—"}</dd>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<dt className="text-zinc-500">频道 / 进程</dt>
|
||||||
|
<dd>
|
||||||
|
{selected.channel_name ? `${selected.channel_name} · ` : ""}
|
||||||
|
{selected.group_id || selected.process || "—"}
|
||||||
|
</dd>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<dt className="text-zinc-500">结束原因</dt>
|
||||||
|
<dd>{selected.end_reason || "—"}</dd>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<dt className="text-zinc-500">YouTube 推流密钥(后几位)</dt>
|
||||||
|
<dd className="font-mono">{selected.youtube_key_suffix ? `…${selected.youtube_key_suffix}` : "—"}</dd>
|
||||||
|
</div>
|
||||||
|
</dl>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
</Shell>
|
||||||
|
);
|
||||||
|
}
|
||||||
@ -6,7 +6,15 @@ import { Check, Copy, ExternalLink } from "lucide-react";
|
|||||||
import { fetchJson } from "@/lib/api";
|
import { fetchJson } from "@/lib/api";
|
||||||
|
|
||||||
const DEFAULT_PROJECT = "live-473104";
|
const DEFAULT_PROJECT = "live-473104";
|
||||||
const DEFAULT_REDIRECT = "https://dylive.nomadro.com/api/shorts/oauth/callback";
|
|
||||||
|
function defaultShortsRedirectUri(): string {
|
||||||
|
if (typeof window !== "undefined" && window.location?.origin) {
|
||||||
|
return `${window.location.origin}/api/shorts/oauth/callback`;
|
||||||
|
}
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
|
||||||
|
export { defaultShortsRedirectUri };
|
||||||
|
|
||||||
function gcpLinks(projectId: string) {
|
function gcpLinks(projectId: string) {
|
||||||
const p = encodeURIComponent(projectId || DEFAULT_PROJECT);
|
const p = encodeURIComponent(projectId || DEFAULT_PROJECT);
|
||||||
@ -31,7 +39,7 @@ export function GoogleOauthSetupWizard({
|
|||||||
initialProjectId = DEFAULT_PROJECT,
|
initialProjectId = DEFAULT_PROJECT,
|
||||||
initialClientId = "",
|
initialClientId = "",
|
||||||
initialClientSecret = "",
|
initialClientSecret = "",
|
||||||
redirectUri = DEFAULT_REDIRECT,
|
redirectUri = defaultShortsRedirectUri(),
|
||||||
configured = false,
|
configured = false,
|
||||||
onSaved,
|
onSaved,
|
||||||
}: Props) {
|
}: Props) {
|
||||||
|
|||||||
@ -17,6 +17,10 @@ import {
|
|||||||
} from "lucide-react";
|
} from "lucide-react";
|
||||||
|
|
||||||
import { DouyinLiveBadge } from "@/components/DouyinLiveBadge";
|
import { DouyinLiveBadge } from "@/components/DouyinLiveBadge";
|
||||||
|
import { YtRelayLiveLogCard } from "@/components/YtRelayLiveLogCard";
|
||||||
|
import { YtRelayProStatusPanel } from "@/components/YtRelayProStatusPanel";
|
||||||
|
import { businessStatusLabel, isLivePushingRow, type RelayMonitorRow } from "@/lib/ytRelayStatus";
|
||||||
|
import { EnableSwitch } from "@/components/EnableSwitch";
|
||||||
import { useConfirm } from "@/components/ConfirmDialog";
|
import { useConfirm } from "@/components/ConfirmDialog";
|
||||||
import { ImageLightbox } from "@/components/ImageLightbox";
|
import { ImageLightbox } from "@/components/ImageLightbox";
|
||||||
import { useToast } from "@/components/Toast";
|
import { useToast } from "@/components/Toast";
|
||||||
@ -81,6 +85,9 @@ type AssignGroup = {
|
|||||||
has_stream_key?: boolean;
|
has_stream_key?: boolean;
|
||||||
note?: string;
|
note?: string;
|
||||||
enabled?: boolean;
|
enabled?: boolean;
|
||||||
|
neko_instance_id?: number;
|
||||||
|
neko_enabled?: boolean;
|
||||||
|
neko_studio_url?: string;
|
||||||
pool?: PoolUrl[];
|
pool?: PoolUrl[];
|
||||||
featured?: FeaturedUrl[];
|
featured?: FeaturedUrl[];
|
||||||
slots?: SlotUrl[];
|
slots?: SlotUrl[];
|
||||||
@ -104,6 +111,33 @@ type RotationSchedule = {
|
|||||||
channels?: ScheduleChannel[];
|
channels?: ScheduleChannel[];
|
||||||
};
|
};
|
||||||
|
|
||||||
|
type RelayGroup = {
|
||||||
|
group_id: string;
|
||||||
|
status?: string;
|
||||||
|
anchor_name?: string;
|
||||||
|
source_url?: string;
|
||||||
|
room_id?: string;
|
||||||
|
speed?: number;
|
||||||
|
frame?: number;
|
||||||
|
ffmpeg_pid?: number;
|
||||||
|
error?: string;
|
||||||
|
started_at?: number;
|
||||||
|
push_seconds?: number;
|
||||||
|
recent_log?: string[];
|
||||||
|
has_stream_key?: boolean;
|
||||||
|
enabled?: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
type RelayStatus = {
|
||||||
|
running?: boolean;
|
||||||
|
enabled?: boolean;
|
||||||
|
pushing_count?: number;
|
||||||
|
douyin_live_count?: number;
|
||||||
|
last_error?: string;
|
||||||
|
groups?: RelayGroup[];
|
||||||
|
entries?: RelayMonitorRow[];
|
||||||
|
};
|
||||||
|
|
||||||
function formatExportLine(url: string, title?: string): string {
|
function formatExportLine(url: string, title?: string): string {
|
||||||
const u = String(url || "").trim();
|
const u = String(url || "").trim();
|
||||||
const t = String(title || "").trim();
|
const t = String(title || "").trim();
|
||||||
@ -240,6 +274,9 @@ export function YtAssignPanel({ channels }: { channels: ManagedChannel[] }) {
|
|||||||
const [lightbox, setLightbox] = useState<{ src: string; title?: string; subtitle?: string } | null>(
|
const [lightbox, setLightbox] = useState<{ src: string; title?: string; subtitle?: string } | null>(
|
||||||
null
|
null
|
||||||
);
|
);
|
||||||
|
const [relayStatus, setRelayStatus] = useState<RelayStatus | null>(null);
|
||||||
|
const [relayBusy, setRelayBusy] = useState(false);
|
||||||
|
const [relayKickId, setRelayKickId] = useState("");
|
||||||
|
|
||||||
const selected = useMemo(() => groups.find((g) => g.id === groupId) || null, [groups, groupId]);
|
const selected = useMemo(() => groups.find((g) => g.id === groupId) || null, [groups, groupId]);
|
||||||
const featuredIds = useMemo(
|
const featuredIds = useMemo(
|
||||||
@ -276,6 +313,24 @@ export function YtAssignPanel({ channels }: { channels: ManagedChannel[] }) {
|
|||||||
return m;
|
return m;
|
||||||
}, [channels]);
|
}, [channels]);
|
||||||
|
|
||||||
|
const relayByGroupId = useMemo(() => {
|
||||||
|
const m: Record<string, RelayGroup> = {};
|
||||||
|
for (const g of relayStatus?.groups || []) {
|
||||||
|
if (g.group_id) m[g.group_id] = g;
|
||||||
|
}
|
||||||
|
return m;
|
||||||
|
}, [relayStatus?.groups]);
|
||||||
|
|
||||||
|
const relayEntries = useMemo(
|
||||||
|
() => (relayStatus?.entries || relayStatus?.groups || []) as RelayMonitorRow[],
|
||||||
|
[relayStatus?.entries, relayStatus?.groups]
|
||||||
|
);
|
||||||
|
|
||||||
|
const selectedMonitor = useMemo(
|
||||||
|
() => relayEntries.find((e) => e.group_id === groupId),
|
||||||
|
[relayEntries, groupId]
|
||||||
|
);
|
||||||
|
|
||||||
function profileFor(pk: string): YtProfileSnippet | undefined {
|
function profileFor(pk: string): YtProfileSnippet | undefined {
|
||||||
if (profiles[pk]) return profiles[pk];
|
if (profiles[pk]) return profiles[pk];
|
||||||
const ch = channelById[pk];
|
const ch = channelById[pk];
|
||||||
@ -300,6 +355,15 @@ export function YtAssignPanel({ channels }: { channels: ManagedChannel[] }) {
|
|||||||
}
|
}
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
|
const loadRelay = useCallback(async () => {
|
||||||
|
try {
|
||||||
|
const st = await fetchJson("/api/youtube/relay/status");
|
||||||
|
setRelayStatus(st as RelayStatus);
|
||||||
|
} catch {
|
||||||
|
// relay API may fail when logged out; keep last state
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
const loadGroups = useCallback(async () => {
|
const loadGroups = useCallback(async () => {
|
||||||
setBusy(true);
|
setBusy(true);
|
||||||
try {
|
try {
|
||||||
@ -359,7 +423,49 @@ export function YtAssignPanel({ channels }: { channels: ManagedChannel[] }) {
|
|||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
void loadGroups();
|
void loadGroups();
|
||||||
void loadAllProfiles();
|
void loadAllProfiles();
|
||||||
}, [loadGroups, loadAllProfiles]);
|
void loadRelay();
|
||||||
|
const t = setInterval(() => void loadRelay(), 3500);
|
||||||
|
return () => clearInterval(t);
|
||||||
|
}, [loadGroups, loadAllProfiles, loadRelay]);
|
||||||
|
|
||||||
|
async function toggleRelayPipeline(on: boolean) {
|
||||||
|
if (!on) {
|
||||||
|
const ok = await confirm({
|
||||||
|
title: "关闭自动推流?",
|
||||||
|
message: "关闭后将停止所有 FFmpeg 推流,不再向 YouTube Live 转播。",
|
||||||
|
confirmLabel: "关闭",
|
||||||
|
destructive: true,
|
||||||
|
});
|
||||||
|
if (!ok) return;
|
||||||
|
}
|
||||||
|
setRelayBusy(true);
|
||||||
|
try {
|
||||||
|
await fetchJson(on ? "/api/youtube/relay/start" : "/api/youtube/relay/stop", { method: "POST" });
|
||||||
|
toast.push(on ? "自动推流已开启" : "自动推流已关闭", "ok");
|
||||||
|
await loadRelay();
|
||||||
|
} catch (e) {
|
||||||
|
toast.push((e as Error).message, "err");
|
||||||
|
} finally {
|
||||||
|
setRelayBusy(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function kickRelayGroup(gid: string, action: "start" | "stop" | "restart") {
|
||||||
|
setRelayKickId(gid);
|
||||||
|
try {
|
||||||
|
const path =
|
||||||
|
action === "restart"
|
||||||
|
? `/api/youtube/relay/groups/${gid}/restart`
|
||||||
|
: `/api/youtube/relay/groups/${gid}/${action}`;
|
||||||
|
await fetchJson(path, { method: "POST" });
|
||||||
|
toast.push(action === "start" ? "已触发推流" : action === "stop" ? "已停止推流" : "已重新开始", "ok");
|
||||||
|
await loadRelay();
|
||||||
|
} catch (e) {
|
||||||
|
toast.push((e as Error).message, "err");
|
||||||
|
} finally {
|
||||||
|
setRelayKickId("");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!selected) {
|
if (!selected) {
|
||||||
@ -693,10 +799,18 @@ export function YtAssignPanel({ channels }: { channels: ManagedChannel[] }) {
|
|||||||
<div>
|
<div>
|
||||||
<h3 className="text-sm font-medium text-slate-100">转播分配</h3>
|
<h3 className="text-sm font-medium text-slate-100">转播分配</h3>
|
||||||
<p className="mt-0.5 text-xs text-slate-500">
|
<p className="mt-0.5 text-xs text-slate-500">
|
||||||
频道 + 直播 KEY → 抖音 URL 普通池 → 精选(实时转播)。支持粘贴「URL,主播: 名称,」。
|
频道 + 直播 KEY → 抖音 URL 池 → 直播地址列表(精选)。开启自动推流后 FFmpeg 仅转播精选列表到 YouTube Live。
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex flex-wrap gap-2">
|
<div className="flex flex-wrap items-center gap-2">
|
||||||
|
<EnableSwitch
|
||||||
|
checked={Boolean(relayStatus?.enabled)}
|
||||||
|
busy={relayBusy}
|
||||||
|
accent="pink"
|
||||||
|
size="md"
|
||||||
|
label={relayStatus?.enabled ? "自动推流 开" : "自动推流 关"}
|
||||||
|
onChange={(v) => void toggleRelayPipeline(v)}
|
||||||
|
/>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
disabled={busy}
|
disabled={busy}
|
||||||
@ -709,7 +823,10 @@ export function YtAssignPanel({ channels }: { channels: ManagedChannel[] }) {
|
|||||||
</button>
|
</button>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={() => void loadGroups()}
|
onClick={() => {
|
||||||
|
void loadGroups();
|
||||||
|
void loadRelay();
|
||||||
|
}}
|
||||||
className="inline-flex items-center gap-1 rounded-xl border border-white/10 bg-white/5 px-3 py-2 text-sm"
|
className="inline-flex items-center gap-1 rounded-xl border border-white/10 bg-white/5 px-3 py-2 text-sm"
|
||||||
>
|
>
|
||||||
{busy ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <RefreshCw className="h-3.5 w-3.5" />}
|
{busy ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <RefreshCw className="h-3.5 w-3.5" />}
|
||||||
@ -718,6 +835,23 @@ export function YtAssignPanel({ channels }: { channels: ManagedChannel[] }) {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div className="mb-3 grid gap-2 sm:grid-cols-2 lg:grid-cols-4">
|
||||||
|
{[
|
||||||
|
{ label: "抖音在播", value: relayStatus?.douyin_live_count ?? "—" },
|
||||||
|
{ label: "推流中", value: relayStatus?.pushing_count ?? 0 },
|
||||||
|
{ label: "Worker", value: relayStatus?.running ? "运行" : "停" },
|
||||||
|
{ label: "时段", value: schedule?.now_label || "—" },
|
||||||
|
].map((item) => (
|
||||||
|
<div key={item.label} className="rounded-xl border border-white/10 bg-black/30 px-3 py-2">
|
||||||
|
<div className="text-[10px] uppercase tracking-wider text-slate-500">{item.label}</div>
|
||||||
|
<div className="mt-0.5 text-sm font-semibold tabular-nums text-slate-100">{item.value}</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
{relayStatus?.last_error ? (
|
||||||
|
<div className="mb-3 rounded-lg bg-rose-500/10 px-3 py-2 text-[11px] text-rose-200">{relayStatus.last_error}</div>
|
||||||
|
) : null}
|
||||||
|
|
||||||
<div className="grid gap-2 sm:grid-cols-[1.2fr_1fr_auto]">
|
<div className="grid gap-2 sm:grid-cols-[1.2fr_1fr_auto]">
|
||||||
<select
|
<select
|
||||||
value={newChannelPk}
|
value={newChannelPk}
|
||||||
@ -834,6 +968,9 @@ export function YtAssignPanel({ channels }: { channels: ManagedChannel[] }) {
|
|||||||
const ch = channelById[pk];
|
const ch = channelById[pk];
|
||||||
const active = g.id === groupId;
|
const active = g.id === groupId;
|
||||||
const sch = (schedule?.channels || []).find((c) => c.group_id === g.id);
|
const sch = (schedule?.channels || []).find((c) => c.group_id === g.id);
|
||||||
|
const relay = relayByGroupId[g.id];
|
||||||
|
const monitor = relayEntries.find((e) => e.group_id === g.id);
|
||||||
|
const pushing = isLivePushingRow(monitor) || relay?.status === "pushing";
|
||||||
return (
|
return (
|
||||||
<button
|
<button
|
||||||
key={g.id}
|
key={g.id}
|
||||||
@ -841,8 +978,12 @@ export function YtAssignPanel({ channels }: { channels: ManagedChannel[] }) {
|
|||||||
onClick={() => setGroupId(g.id)}
|
onClick={() => setGroupId(g.id)}
|
||||||
className={`w-full min-w-0 overflow-hidden rounded-xl border p-2.5 text-left transition ${
|
className={`w-full min-w-0 overflow-hidden rounded-xl border p-2.5 text-left transition ${
|
||||||
active
|
active
|
||||||
? "border-rose-400/40 bg-rose-500/10"
|
? pushing
|
||||||
: "border-white/10 bg-black/30 hover:bg-white/5"
|
? "border-rose-400/50 bg-rose-500/10"
|
||||||
|
: "border-rose-400/40 bg-rose-500/10"
|
||||||
|
: pushing
|
||||||
|
? "border-rose-500/30 bg-rose-500/5 hover:bg-rose-500/10"
|
||||||
|
: "border-white/10 bg-black/30 hover:bg-white/5"
|
||||||
}`}
|
}`}
|
||||||
>
|
>
|
||||||
<YtChannelProfileSnippet
|
<YtChannelProfileSnippet
|
||||||
@ -863,6 +1004,13 @@ export function YtAssignPanel({ channels }: { channels: ManagedChannel[] }) {
|
|||||||
</span>
|
</span>
|
||||||
) : null}
|
) : null}
|
||||||
<span>{g.has_stream_key ? "KEY✓" : "无 KEY"}</span>
|
<span>{g.has_stream_key ? "KEY✓" : "无 KEY"}</span>
|
||||||
|
{pushing ? (
|
||||||
|
<span className="inline-flex items-center gap-0.5 text-rose-300">
|
||||||
|
{businessStatusLabel(monitor)}
|
||||||
|
</span>
|
||||||
|
) : monitor?.business_status === "error" || monitor?.business_status === "youtube_key_rejected" ? (
|
||||||
|
<span className="text-amber-300">推流错误</span>
|
||||||
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
</button>
|
</button>
|
||||||
);
|
);
|
||||||
@ -888,10 +1036,24 @@ export function YtAssignPanel({ channels }: { channels: ManagedChannel[] }) {
|
|||||||
(约 {selectedSchedule.slot_hours} 小时)
|
(约 {selectedSchedule.slot_hours} 小时)
|
||||||
{selectedSchedule.active ? (
|
{selectedSchedule.active ? (
|
||||||
<span className="ml-2 text-teal-300">● 当前正在轮播</span>
|
<span className="ml-2 text-teal-300">● 当前正在轮播</span>
|
||||||
) : null}
|
) : (
|
||||||
|
<span className="ml-2 text-slate-400">非当前时段</span>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
|
<YtRelayProStatusPanel
|
||||||
|
group={selected}
|
||||||
|
row={selectedMonitor}
|
||||||
|
relayKickId={relayKickId}
|
||||||
|
onStart={(id) => void kickRelayGroup(id, "start")}
|
||||||
|
onStop={(id) => void kickRelayGroup(id, "stop")}
|
||||||
|
onRestart={(id) => void kickRelayGroup(id, "restart")}
|
||||||
|
onNekoChange={() => void loadGroups()}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<YtRelayLiveLogCard row={selectedMonitor} onRefresh={() => void loadRelay()} />
|
||||||
|
|
||||||
<section className="rounded-2xl border border-white/10 bg-black/25 p-4">
|
<section className="rounded-2xl border border-white/10 bg-black/25 p-4">
|
||||||
<div className="mb-3 flex flex-wrap items-center justify-between gap-2">
|
<div className="mb-3 flex flex-wrap items-center justify-between gap-2">
|
||||||
<h4 className="text-sm font-medium text-slate-100">直播 KEY / 备注</h4>
|
<h4 className="text-sm font-medium text-slate-100">直播 KEY / 备注</h4>
|
||||||
@ -962,7 +1124,7 @@ export function YtAssignPanel({ channels }: { channels: ManagedChannel[] }) {
|
|||||||
</section>
|
</section>
|
||||||
|
|
||||||
<div className="grid gap-4 lg:grid-cols-2 xl:grid-cols-3">
|
<div className="grid gap-4 lg:grid-cols-2 xl:grid-cols-3">
|
||||||
<section className="rounded-2xl border border-white/10 bg-black/25 p-4">
|
<section className="order-2 rounded-2xl border border-white/10 bg-black/25 p-4 lg:order-2 xl:order-2">
|
||||||
<div className="mb-1 flex flex-wrap items-center justify-between gap-2">
|
<div className="mb-1 flex flex-wrap items-center justify-between gap-2">
|
||||||
<h4 className="text-sm font-medium text-slate-100">
|
<h4 className="text-sm font-medium text-slate-100">
|
||||||
普通列表(URL 池)· {(selected.pool || []).length}
|
普通列表(URL 池)· {(selected.pool || []).length}
|
||||||
@ -1106,7 +1268,7 @@ export function YtAssignPanel({ channels }: { channels: ManagedChannel[] }) {
|
|||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<section className="rounded-2xl border border-violet-500/25 bg-violet-500/5 p-4 xl:col-span-1">
|
<section className="order-3 rounded-2xl border border-violet-500/25 bg-violet-500/5 p-4 xl:order-3 xl:col-span-1">
|
||||||
<div className="mb-1 flex flex-wrap items-center justify-between gap-2">
|
<div className="mb-1 flex flex-wrap items-center justify-between gap-2">
|
||||||
<h4 className="text-sm font-medium text-violet-50">
|
<h4 className="text-sm font-medium text-violet-50">
|
||||||
时间段列表(轮播)· {(selected.slots || []).length}
|
时间段列表(轮播)· {(selected.slots || []).length}
|
||||||
@ -1245,10 +1407,10 @@ export function YtAssignPanel({ channels }: { channels: ManagedChannel[] }) {
|
|||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<section className="rounded-2xl border border-amber-500/20 bg-amber-500/5 p-4">
|
<section className="order-1 rounded-2xl border border-amber-500/20 bg-amber-500/5 p-4 lg:col-span-2 xl:order-1 xl:col-span-1">
|
||||||
<div className="mb-1 flex flex-wrap items-center justify-between gap-2">
|
<div className="mb-1 flex flex-wrap items-center justify-between gap-2">
|
||||||
<h4 className="text-sm font-medium text-amber-50">
|
<h4 className="text-sm font-medium text-amber-50">
|
||||||
精选列表(实时转播)· {(selected.featured || []).length}
|
直播地址列表 · {(selected.featured || []).length}
|
||||||
</h4>
|
</h4>
|
||||||
<div className="flex flex-wrap gap-1.5">
|
<div className="flex flex-wrap gap-1.5">
|
||||||
<button
|
<button
|
||||||
@ -1269,7 +1431,9 @@ export function YtAssignPanel({ channels }: { channels: ManagedChannel[] }) {
|
|||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<p className="mb-3 text-[11px] text-amber-100/70">只能从普通池选出;真正用于实时转播的子集。</p>
|
<p className="mb-3 text-[11px] text-amber-100/70">
|
||||||
|
即分配页的精选列表;FFmpeg 推流只从此列表选源(优先在播)。从普通池点 ★ 加入。
|
||||||
|
</p>
|
||||||
<div className="max-h-[28rem] space-y-2 overflow-y-auto">
|
<div className="max-h-[28rem] space-y-2 overflow-y-auto">
|
||||||
{(selected.featured || []).length === 0 ? (
|
{(selected.featured || []).length === 0 ? (
|
||||||
<div className="py-10 text-center text-xs text-amber-100/50">
|
<div className="py-10 text-center text-xs text-amber-100/50">
|
||||||
|
|||||||
106
frontend/src/components/YtRelayLiveLogCard.tsx
Normal file
106
frontend/src/components/YtRelayLiveLogCard.tsx
Normal file
@ -0,0 +1,106 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { AlertTriangle, Pause, Play, RefreshCw } from "lucide-react";
|
||||||
|
import { useEffect, useRef, useState } from "react";
|
||||||
|
|
||||||
|
import { isLivePushingRow, type RelayMonitorRow } from "@/lib/ytRelayStatus";
|
||||||
|
|
||||||
|
type Props = {
|
||||||
|
row?: RelayMonitorRow;
|
||||||
|
pollMs?: number;
|
||||||
|
onRefresh?: () => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function YtRelayLiveLogCard({ row, pollMs = 3500, onRefresh }: Props) {
|
||||||
|
const [paused, setPaused] = useState(false);
|
||||||
|
const outRef = useRef<HTMLPreElement>(null);
|
||||||
|
const errRef = useRef<HTMLPreElement>(null);
|
||||||
|
|
||||||
|
const recentLog = row?.recent_log || "";
|
||||||
|
const recentError = row?.recent_error || "";
|
||||||
|
const pushingNow = isLivePushingRow(row);
|
||||||
|
const youtubeKeyRejected = row?.business_status === "youtube_key_rejected";
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (paused) return;
|
||||||
|
for (const el of [outRef.current, errRef.current]) {
|
||||||
|
if (el) el.scrollTop = el.scrollHeight;
|
||||||
|
}
|
||||||
|
}, [recentLog, recentError, paused]);
|
||||||
|
|
||||||
|
const refreshBadge =
|
||||||
|
pollMs >= 8000 ? "慢速刷新" : pollMs >= 4000 ? "常速刷新" : "快速刷新";
|
||||||
|
|
||||||
|
return (
|
||||||
|
<section className="rounded-2xl border border-emerald-500/20 bg-gradient-to-b from-emerald-500/[0.07] to-black/40 p-4 ring-1 ring-white/[0.04]">
|
||||||
|
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||||
|
<div className="flex flex-wrap items-center gap-2">
|
||||||
|
<h3 className="text-sm font-semibold text-white">当前直播日志</h3>
|
||||||
|
{pushingNow ? (
|
||||||
|
<span className="inline-flex items-center gap-1.5 rounded-full bg-emerald-500/15 px-2.5 py-0.5 text-[10px] font-medium text-emerald-100 ring-1 ring-emerald-500/25">
|
||||||
|
<span className="live-dot" />
|
||||||
|
推流中
|
||||||
|
</span>
|
||||||
|
) : null}
|
||||||
|
<span className="rounded-full bg-zinc-500/15 px-2 py-0.5 text-[10px] font-medium text-zinc-200 ring-1 ring-zinc-500/25">
|
||||||
|
{refreshBadge}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div className="flex flex-wrap gap-2">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => onRefresh?.()}
|
||||||
|
className="inline-flex items-center gap-1 rounded-lg border border-white/10 bg-white/[0.05] px-3 py-1.5 text-xs text-zinc-300 hover:bg-white/[0.08]"
|
||||||
|
>
|
||||||
|
<RefreshCw className="h-3.5 w-3.5" />
|
||||||
|
立即拉取
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setPaused((p) => !p)}
|
||||||
|
className={`inline-flex items-center gap-1 rounded-lg px-3 py-1.5 text-xs ring-1 ${
|
||||||
|
paused
|
||||||
|
? "bg-amber-500/20 text-amber-100 ring-amber-500/35"
|
||||||
|
: "border border-white/10 bg-black/30 text-zinc-300"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{paused ? <Play className="h-3.5 w-3.5" /> : <Pause className="h-3.5 w-3.5" />}
|
||||||
|
{paused ? "继续滚动" : "暂停滚动"}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{youtubeKeyRejected ? (
|
||||||
|
<div className="mt-4 rounded-lg border border-rose-500/30 bg-rose-500/[0.10] px-3 py-2.5 text-xs text-rose-100 ring-1 ring-rose-500/15">
|
||||||
|
<div className="flex gap-2">
|
||||||
|
<AlertTriangle className="mt-0.5 h-4 w-4 shrink-0 text-rose-300" />
|
||||||
|
<p>
|
||||||
|
YouTube 已拒绝 RTMPS 推流。请从 YouTube Studio 复制当前直播间的完整串流密钥,保存后重新开始。
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
<div className="mt-4 grid gap-4 lg:grid-cols-2">
|
||||||
|
<div>
|
||||||
|
<div className="text-[11px] font-semibold uppercase tracking-wider text-emerald-400/90">进程输出</div>
|
||||||
|
<pre
|
||||||
|
ref={outRef}
|
||||||
|
className="mt-2 max-h-[min(22rem,42vh)] min-h-[12rem] overflow-auto whitespace-pre-wrap rounded-xl border border-emerald-500/20 bg-black/55 p-3 font-mono text-[10px] leading-relaxed text-emerald-100/95"
|
||||||
|
>
|
||||||
|
{recentLog.trim() || "(暂无)"}
|
||||||
|
</pre>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<div className="text-[11px] font-semibold uppercase tracking-wider text-rose-400/90">异常信息</div>
|
||||||
|
<pre
|
||||||
|
ref={errRef}
|
||||||
|
className="mt-2 max-h-[min(22rem,42vh)] min-h-[12rem] overflow-auto whitespace-pre-wrap rounded-xl border border-rose-500/20 bg-black/55 p-3 font-mono text-[10px] leading-relaxed text-rose-100/95"
|
||||||
|
>
|
||||||
|
{recentError.trim() || row?.error || "(暂无)"}
|
||||||
|
</pre>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
297
frontend/src/components/YtRelayProStatusPanel.tsx
Normal file
297
frontend/src/components/YtRelayProStatusPanel.tsx
Normal file
@ -0,0 +1,297 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import Link from "next/link";
|
||||||
|
import { useCallback, useEffect, useState } from "react";
|
||||||
|
import { ExternalLink, Loader2, Monitor, RotateCw } from "lucide-react";
|
||||||
|
|
||||||
|
import { DouyinLiveBadge } from "@/components/DouyinLiveBadge";
|
||||||
|
import { EnableSwitch } from "@/components/EnableSwitch";
|
||||||
|
import { useToast } from "@/components/Toast";
|
||||||
|
import {
|
||||||
|
formatFfmpegStatsBrief,
|
||||||
|
mergeFfmpegMetrics,
|
||||||
|
speedToneClass,
|
||||||
|
} from "@/lib/ffmpegMetrics";
|
||||||
|
import { fetchJson } from "@/lib/api";
|
||||||
|
import {
|
||||||
|
businessStatusBadgeClass,
|
||||||
|
businessStatusLabel,
|
||||||
|
isLivePushingRow,
|
||||||
|
laneStatusEmoji,
|
||||||
|
procStartBlocked,
|
||||||
|
type RelayMonitorRow,
|
||||||
|
} from "@/lib/ytRelayStatus";
|
||||||
|
|
||||||
|
type GroupLike = {
|
||||||
|
id: string;
|
||||||
|
name?: string;
|
||||||
|
enabled?: boolean;
|
||||||
|
has_stream_key?: boolean;
|
||||||
|
featured?: Array<{ url?: string }>;
|
||||||
|
neko_instance_id?: number;
|
||||||
|
neko_enabled?: boolean;
|
||||||
|
neko_studio_url?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
type NekoState = {
|
||||||
|
running?: boolean;
|
||||||
|
ready?: boolean;
|
||||||
|
status?: string;
|
||||||
|
studio_url?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
type Props = {
|
||||||
|
group: GroupLike;
|
||||||
|
row?: RelayMonitorRow;
|
||||||
|
relayKickId: string;
|
||||||
|
onStart: (id: string) => void;
|
||||||
|
onStop: (id: string) => void;
|
||||||
|
onRestart: (id: string) => void;
|
||||||
|
onNekoChange?: () => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
function nekoStatusLabel(st?: NekoState | null): string {
|
||||||
|
if (!st) return "未配置";
|
||||||
|
if (st.ready) return "运行中";
|
||||||
|
if (st.running) return "启动中";
|
||||||
|
return st.status === "missing" ? "未创建" : "已停止";
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Single-channel Pro relay status + per-channel Neko studio — embedded in 分配. */
|
||||||
|
export function YtRelayProStatusPanel({
|
||||||
|
group,
|
||||||
|
row,
|
||||||
|
relayKickId,
|
||||||
|
onStart,
|
||||||
|
onStop,
|
||||||
|
onRestart,
|
||||||
|
onNekoChange,
|
||||||
|
}: Props) {
|
||||||
|
const toast = useToast();
|
||||||
|
const laneName = group.name || "未命名频道";
|
||||||
|
const douyinSubtitle = row?.source_display || row?.source_title || "";
|
||||||
|
const dUrl = row?.source_url || "";
|
||||||
|
const suf = row?.stream_key_suffix || "—";
|
||||||
|
const urlCount = row?.url_count ?? (group.featured || []).length;
|
||||||
|
const dyCount = row?.douyin_count ?? urlCount;
|
||||||
|
const blocked = procStartBlocked(row);
|
||||||
|
const metrics = mergeFfmpegMetrics(row, row?.recent_log || "");
|
||||||
|
const statsText = formatFfmpegStatsBrief(metrics, { live: metrics.live || isLivePushingRow(row) });
|
||||||
|
const busy = relayKickId === group.id;
|
||||||
|
|
||||||
|
const instanceId = Number(group.neko_instance_id || 0);
|
||||||
|
const [nekoEnabled, setNekoEnabled] = useState(Boolean(group.neko_enabled));
|
||||||
|
const [nekoBusy, setNekoBusy] = useState(false);
|
||||||
|
const [nekoState, setNekoState] = useState<NekoState | null>(null);
|
||||||
|
const studioUrl = String(nekoState?.studio_url || group.neko_studio_url || "").trim();
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setNekoEnabled(Boolean(group.neko_enabled));
|
||||||
|
}, [group.id, group.neko_enabled]);
|
||||||
|
|
||||||
|
const refreshNeko = useCallback(async () => {
|
||||||
|
if (instanceId < 1) return;
|
||||||
|
try {
|
||||||
|
const st = (await fetchJson("/api/youtube/neko/status")) as { instances?: NekoState[] };
|
||||||
|
const inst = (st.instances || []).find((x) => Number((x as { id?: number }).id) === instanceId);
|
||||||
|
if (inst) setNekoState(inst);
|
||||||
|
} catch {
|
||||||
|
/* ignore poll errors */
|
||||||
|
}
|
||||||
|
}, [instanceId]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
void refreshNeko();
|
||||||
|
if (instanceId < 1) return;
|
||||||
|
const t = window.setInterval(() => void refreshNeko(), 12000);
|
||||||
|
return () => window.clearInterval(t);
|
||||||
|
}, [instanceId, refreshNeko]);
|
||||||
|
|
||||||
|
async function postNeko(body: Record<string, unknown>) {
|
||||||
|
setNekoBusy(true);
|
||||||
|
try {
|
||||||
|
const r = (await fetchJson(`/api/youtube/assign/groups/${encodeURIComponent(group.id)}/neko`, {
|
||||||
|
method: "POST",
|
||||||
|
body: JSON.stringify(body),
|
||||||
|
})) as { group?: GroupLike; neko?: NekoState };
|
||||||
|
if (r.group) setNekoEnabled(Boolean(r.group.neko_enabled));
|
||||||
|
if (r.neko) setNekoState(r.neko);
|
||||||
|
onNekoChange?.();
|
||||||
|
await refreshNeko();
|
||||||
|
} catch (e) {
|
||||||
|
toast.push((e as Error).message, "err");
|
||||||
|
} finally {
|
||||||
|
setNekoBusy(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="rounded-xl border border-cyan-500/25 bg-gradient-to-br from-cyan-500/[0.1] via-black/30 to-violet-500/[0.06] p-4 ring-1 ring-white/[0.04]">
|
||||||
|
<h4 className="text-xs font-semibold uppercase tracking-wider text-cyan-200/90">Pro 转播实况</h4>
|
||||||
|
<p className="mt-1 text-[11px] text-slate-500">
|
||||||
|
本频道 FFmpeg 推流进程。直播地址列表 = 下方精选;开启顶部「自动推流」后 Worker 持续调度。
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<div className="mt-3 flex flex-wrap items-center gap-2 rounded-lg border border-white/10 bg-black/30 px-3 py-2.5 text-xs sm:flex-nowrap">
|
||||||
|
<div className="min-w-0 flex-1">
|
||||||
|
<div className="flex flex-wrap items-center gap-2">
|
||||||
|
<span className="font-medium text-zinc-100">
|
||||||
|
<span className="mr-1.5" aria-hidden>
|
||||||
|
{laneStatusEmoji(row)}
|
||||||
|
</span>
|
||||||
|
{laneName}
|
||||||
|
</span>
|
||||||
|
<span
|
||||||
|
className={`shrink-0 rounded-md px-2 py-0.5 text-[10px] font-medium ring-1 ${businessStatusBadgeClass(row)}`}
|
||||||
|
>
|
||||||
|
{businessStatusLabel(row)}
|
||||||
|
</span>
|
||||||
|
{row?.source_room_id ? <DouyinLiveBadge roomId={row.source_room_id} compact showOffline /> : null}
|
||||||
|
</div>
|
||||||
|
<div className="mt-0.5 flex flex-wrap items-center gap-x-2 gap-y-0.5 font-mono text-[10px] text-slate-500">
|
||||||
|
{douyinSubtitle && douyinSubtitle !== laneName ? (
|
||||||
|
<>
|
||||||
|
<span className="truncate text-slate-400" title={douyinSubtitle}>
|
||||||
|
抖音源 {douyinSubtitle}
|
||||||
|
</span>
|
||||||
|
<span className="text-slate-600">·</span>
|
||||||
|
</>
|
||||||
|
) : null}
|
||||||
|
<span>key …{suf}</span>
|
||||||
|
<span className="text-slate-600">·</span>
|
||||||
|
<span>URL {urlCount}</span>
|
||||||
|
<span className="text-slate-600">·</span>
|
||||||
|
<span>DY {dyCount}</span>
|
||||||
|
{statsText ? (
|
||||||
|
<>
|
||||||
|
<span className="text-slate-600">·</span>
|
||||||
|
<span className={speedToneClass(metrics.speed, metrics.speedLow, metrics.progressStalled)}>
|
||||||
|
{statsText}
|
||||||
|
</span>
|
||||||
|
</>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
{dUrl ? (
|
||||||
|
<a
|
||||||
|
href={dUrl}
|
||||||
|
target="_blank"
|
||||||
|
rel="noreferrer"
|
||||||
|
className="mt-1 block max-w-full truncate text-cyan-300/90 underline-offset-2 hover:underline"
|
||||||
|
title={dUrl}
|
||||||
|
>
|
||||||
|
打开源站 · {dUrl.replace(/^https?:\/\//, "")}
|
||||||
|
</a>
|
||||||
|
) : (
|
||||||
|
<span className="mt-1 block text-slate-600">—</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex w-full shrink-0 flex-wrap items-center justify-end gap-1.5 sm:w-auto">
|
||||||
|
<Link
|
||||||
|
href={`/youtube-relay-log?group_id=${encodeURIComponent(group.id)}`}
|
||||||
|
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"
|
||||||
|
>
|
||||||
|
历史
|
||||||
|
</Link>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
disabled={!group.enabled || !group.has_stream_key || blocked || busy}
|
||||||
|
onClick={() => onStart(group.id)}
|
||||||
|
className="rounded-lg bg-emerald-500/20 px-2.5 py-1.5 text-[11px] text-emerald-100 ring-1 ring-emerald-500/30 disabled:opacity-40"
|
||||||
|
>
|
||||||
|
{busy ? <Loader2 className="h-3 w-3 animate-spin" /> : "开始"}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
disabled={busy}
|
||||||
|
onClick={() => onStop(group.id)}
|
||||||
|
className="rounded-lg bg-rose-500/15 px-2.5 py-1.5 text-[11px] text-rose-100 ring-1 ring-rose-500/25 disabled:opacity-40"
|
||||||
|
>
|
||||||
|
停止
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
disabled={!group.enabled || !group.has_stream_key || busy}
|
||||||
|
onClick={() => onRestart(group.id)}
|
||||||
|
className="inline-flex items-center gap-1 rounded-lg bg-amber-500/15 px-2.5 py-1.5 text-[11px] text-amber-100 ring-1 ring-amber-500/25 disabled:opacity-40"
|
||||||
|
>
|
||||||
|
<RotateCw className="h-3 w-3" />
|
||||||
|
重新开始
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{instanceId > 0 ? (
|
||||||
|
<div className="mt-3 rounded-lg border border-violet-500/20 bg-violet-500/[0.06] px-3 py-2.5">
|
||||||
|
<div className="flex flex-wrap items-center justify-between gap-2">
|
||||||
|
<div className="flex items-center gap-2 text-xs">
|
||||||
|
<Monitor className="h-3.5 w-3.5 text-violet-300" />
|
||||||
|
<span className="font-medium text-violet-100">
|
||||||
|
Neko 工作室
|
||||||
|
<span className="ml-1.5 font-mono text-[10px] text-slate-500">#{instanceId}</span>
|
||||||
|
</span>
|
||||||
|
<span
|
||||||
|
className={`rounded px-1.5 py-0.5 text-[10px] ${
|
||||||
|
nekoState?.ready
|
||||||
|
? "bg-emerald-500/20 text-emerald-200"
|
||||||
|
: nekoState?.running
|
||||||
|
? "bg-amber-500/20 text-amber-100"
|
||||||
|
: "bg-white/5 text-slate-400"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{nekoStatusLabel(nekoState)}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<EnableSwitch
|
||||||
|
checked={nekoEnabled}
|
||||||
|
disabled={nekoBusy}
|
||||||
|
label="启用"
|
||||||
|
onChange={(v) => void postNeko({ enabled: v, action: v ? "start" : "stop" })}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<p className="mt-1 text-[10px] text-slate-500">
|
||||||
|
新建分组时自动分配 Neko 实例(默认关闭)。用于 YouTube Studio 操作,不阻塞 FFmpeg 推流。美国 VPS 直连,不走 ShellClash。
|
||||||
|
</p>
|
||||||
|
<div className="mt-2 flex flex-wrap gap-1.5">
|
||||||
|
{studioUrl ? (
|
||||||
|
<a
|
||||||
|
href={studioUrl}
|
||||||
|
target="_blank"
|
||||||
|
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"
|
||||||
|
>
|
||||||
|
<ExternalLink className="h-3 w-3" />
|
||||||
|
打开工作室
|
||||||
|
</a>
|
||||||
|
) : null}
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
disabled={nekoBusy || !nekoEnabled}
|
||||||
|
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"
|
||||||
|
>
|
||||||
|
启动 Neko
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
disabled={nekoBusy}
|
||||||
|
onClick={() => void postNeko({ action: "stop" })}
|
||||||
|
className="rounded-lg bg-rose-500/15 px-2.5 py-1.5 text-[11px] text-rose-100 disabled:opacity-40"
|
||||||
|
>
|
||||||
|
停止 Neko
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
disabled={nekoBusy || !nekoEnabled}
|
||||||
|
onClick={() => void postNeko({ action: "restart" })}
|
||||||
|
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" />
|
||||||
|
重启
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
120
frontend/src/lib/ffmpegMetrics.ts
Normal file
120
frontend/src/lib/ffmpegMetrics.ts
Normal file
@ -0,0 +1,120 @@
|
|||||||
|
export type FfmpegMetrics = {
|
||||||
|
frame?: number;
|
||||||
|
fps?: number;
|
||||||
|
speed?: number;
|
||||||
|
bitrate?: number;
|
||||||
|
drop?: number;
|
||||||
|
dup?: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
type ProcessRowHint = {
|
||||||
|
ffmpeg_speed?: number | null;
|
||||||
|
ffmpeg_frame?: number | null;
|
||||||
|
ffmpeg_fps?: number | null;
|
||||||
|
ffmpeg_bitrate_kbps?: number | null;
|
||||||
|
ffmpeg_active?: boolean;
|
||||||
|
is_pushing?: boolean;
|
||||||
|
ffmpeg_speed_low?: boolean;
|
||||||
|
ffmpeg_progress_stalled?: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
const KV_RE = /\b(frame|fps|bitrate|speed|drop|dup)\s*=\s*([^\s]+)/gi;
|
||||||
|
|
||||||
|
function parseMetricNumber(value: string, asInt = false): number | undefined {
|
||||||
|
const cleaned = value.replace(/kbits\/s/gi, "").replace(/x$/i, "").trim();
|
||||||
|
const match = cleaned.match(/-?\d+(?:\.\d+)?/);
|
||||||
|
if (!match) return undefined;
|
||||||
|
const parsed = asInt ? parseInt(match[0], 10) : Number(match[0]);
|
||||||
|
return Number.isFinite(parsed) ? parsed : undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function latestFfmpegStatsLine(logText: string, lookback = 12): string {
|
||||||
|
const lines = logText
|
||||||
|
.split(/\r?\n/)
|
||||||
|
.map((line) => line.trim())
|
||||||
|
.filter(Boolean);
|
||||||
|
const tail = lines.slice(-lookback);
|
||||||
|
for (let idx = tail.length - 1; idx >= 0; idx -= 1) {
|
||||||
|
const lower = tail[idx].toLowerCase();
|
||||||
|
if (lower.includes("frame=") && lower.includes("speed=")) return tail[idx];
|
||||||
|
}
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
|
||||||
|
export function parseFfmpegMetricsFromLog(...texts: string[]): FfmpegMetrics {
|
||||||
|
const raw = texts.filter(Boolean).join("\n");
|
||||||
|
const statsLine = latestFfmpegStatsLine(raw.slice(-16000));
|
||||||
|
const metrics: FfmpegMetrics = {};
|
||||||
|
if (!statsLine) return metrics;
|
||||||
|
KV_RE.lastIndex = 0;
|
||||||
|
let match: RegExpExecArray | null;
|
||||||
|
while ((match = KV_RE.exec(statsLine)) !== null) {
|
||||||
|
const key = match[1].toLowerCase() as keyof FfmpegMetrics;
|
||||||
|
const value = match[2];
|
||||||
|
if (key === "frame" || key === "drop" || key === "dup") {
|
||||||
|
const parsed = parseMetricNumber(value, true);
|
||||||
|
if (parsed != null) metrics[key] = parsed;
|
||||||
|
} else if (key === "fps" || key === "speed" || key === "bitrate") {
|
||||||
|
const parsed = parseMetricNumber(value);
|
||||||
|
if (parsed != null) metrics[key] = parsed;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return metrics;
|
||||||
|
}
|
||||||
|
|
||||||
|
function pickNumber(...values: Array<number | null | undefined>): number | undefined {
|
||||||
|
for (const value of values) {
|
||||||
|
if (typeof value === "number" && Number.isFinite(value)) return value;
|
||||||
|
}
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function mergeFfmpegMetrics(
|
||||||
|
row?: ProcessRowHint,
|
||||||
|
logText = "",
|
||||||
|
): FfmpegMetrics & { speedLow?: boolean; progressStalled?: boolean; live: boolean } {
|
||||||
|
const fromLog = parseFfmpegMetricsFromLog(logText);
|
||||||
|
const live = !!row?.is_pushing;
|
||||||
|
return {
|
||||||
|
frame: pickNumber(row?.ffmpeg_frame, fromLog.frame),
|
||||||
|
fps: pickNumber(row?.ffmpeg_fps, fromLog.fps),
|
||||||
|
speed: pickNumber(row?.ffmpeg_speed, fromLog.speed),
|
||||||
|
bitrate: pickNumber(row?.ffmpeg_bitrate_kbps, fromLog.bitrate),
|
||||||
|
drop: fromLog.drop,
|
||||||
|
dup: fromLog.dup,
|
||||||
|
speedLow: row?.ffmpeg_speed_low,
|
||||||
|
progressStalled: row?.ffmpeg_progress_stalled,
|
||||||
|
live,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function formatBitrateLabel(kbps: number | undefined | null): string | null {
|
||||||
|
if (typeof kbps !== "number" || !Number.isFinite(kbps) || kbps <= 0) return null;
|
||||||
|
if (kbps >= 1000) return `${(kbps / 1000).toFixed(1)} Mbps`;
|
||||||
|
return `${Math.round(kbps)} kbps`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function formatFfmpegMetricValue(value: number | undefined, suffix = "", digits = 2): string {
|
||||||
|
if (typeof value !== "number" || !Number.isFinite(value)) return "—";
|
||||||
|
const text = value >= 100 ? String(Math.round(value)) : value.toFixed(digits).replace(/\.00$/, "");
|
||||||
|
return `${text}${suffix}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function formatFfmpegStatsBrief(metrics: FfmpegMetrics, opts?: { live?: boolean }): string {
|
||||||
|
const parts = [
|
||||||
|
`fps ${formatFfmpegMetricValue(metrics.fps)}`,
|
||||||
|
`speed ${formatFfmpegMetricValue(metrics.speed, "x")}`,
|
||||||
|
`frame ${formatFfmpegMetricValue(metrics.frame, "", 0)}`,
|
||||||
|
];
|
||||||
|
const bitrate = formatBitrateLabel(metrics.bitrate);
|
||||||
|
if (bitrate) parts.push(bitrate);
|
||||||
|
if (!opts?.live && parts.every((part) => part.endsWith("—"))) return "";
|
||||||
|
return parts.join(" · ");
|
||||||
|
}
|
||||||
|
|
||||||
|
export function speedToneClass(speed?: number, speedLow?: boolean, progressStalled?: boolean): string {
|
||||||
|
if (progressStalled) return "text-rose-300";
|
||||||
|
if (speedLow || (typeof speed === "number" && speed > 0 && speed < 0.95)) return "text-amber-200";
|
||||||
|
if (typeof speed === "number" && speed >= 0.95) return "text-emerald-200";
|
||||||
|
return "text-cyan-100";
|
||||||
|
}
|
||||||
86
frontend/src/lib/ytRelayStatus.ts
Normal file
86
frontend/src/lib/ytRelayStatus.ts
Normal file
@ -0,0 +1,86 @@
|
|||||||
|
export type RelayMonitorRow = {
|
||||||
|
group_id?: string;
|
||||||
|
label?: string;
|
||||||
|
process_status?: string;
|
||||||
|
business_status?: string;
|
||||||
|
business_note?: string;
|
||||||
|
is_pushing?: boolean;
|
||||||
|
ffmpeg_active?: boolean;
|
||||||
|
ffmpeg_pid?: number;
|
||||||
|
ffmpeg_speed?: number | null;
|
||||||
|
ffmpeg_frame?: number | null;
|
||||||
|
ffmpeg_fps?: number | null;
|
||||||
|
ffmpeg_bitrate_kbps?: number | null;
|
||||||
|
ffmpeg_time_seconds?: number | null;
|
||||||
|
ffmpeg_speed_low?: boolean;
|
||||||
|
ffmpeg_progress_stalled?: boolean;
|
||||||
|
log_age_seconds?: number | null;
|
||||||
|
recent_log?: string;
|
||||||
|
recent_error?: string;
|
||||||
|
error?: string;
|
||||||
|
push_seconds?: number;
|
||||||
|
source_url?: string;
|
||||||
|
source_title?: string;
|
||||||
|
source_display?: string;
|
||||||
|
source_room_id?: string;
|
||||||
|
url_count?: number;
|
||||||
|
douyin_count?: number;
|
||||||
|
has_stream_key?: boolean;
|
||||||
|
stream_key_suffix?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function businessStatusLabel(row?: RelayMonitorRow): string {
|
||||||
|
const business = (row?.business_status || "").trim().toLowerCase();
|
||||||
|
if (business === "ready") return "已配置";
|
||||||
|
if (business === "streaming") return "推流中";
|
||||||
|
if (business === "source_stalled") return "源卡住";
|
||||||
|
if (business === "relay_slow") return "低速推流";
|
||||||
|
if (business === "relay_starting") return "转推启动中";
|
||||||
|
if (business === "waiting_source") return "等待上游";
|
||||||
|
if (business === "source_live") return "源已开播";
|
||||||
|
if (business === "monitoring") return "监控中";
|
||||||
|
if (business === "misconfigured") return "密钥异常";
|
||||||
|
if (business === "youtube_key_rejected") return "密钥被拒";
|
||||||
|
if (business === "stale") return "心跳过期";
|
||||||
|
if (business === "error") return "异常";
|
||||||
|
if (business === "inactive") return "未运行";
|
||||||
|
const ps = (row?.process_status || "").trim().toLowerCase();
|
||||||
|
if (ps === "online" || ps === "running") return "运行中";
|
||||||
|
return "空闲";
|
||||||
|
}
|
||||||
|
|
||||||
|
export function businessStatusBadgeClass(row?: RelayMonitorRow): string {
|
||||||
|
const business = (row?.business_status || "").trim().toLowerCase();
|
||||||
|
if (business === "ready") return "bg-sky-500/15 text-sky-100 ring-sky-500/25";
|
||||||
|
if (business === "streaming") return "bg-emerald-500/15 text-emerald-200 ring-emerald-500/30";
|
||||||
|
if (business === "relay_slow") return "bg-amber-500/15 text-amber-100 ring-amber-500/25";
|
||||||
|
if (business === "source_stalled") return "bg-rose-500/15 text-rose-100 ring-rose-500/25";
|
||||||
|
if (business === "waiting_source" || business === "monitoring" || business === "relay_starting") {
|
||||||
|
return "bg-amber-500/15 text-amber-100 ring-amber-500/25";
|
||||||
|
}
|
||||||
|
if (business === "source_live") return "bg-sky-500/15 text-sky-100 ring-sky-500/25";
|
||||||
|
if (business === "misconfigured" || business === "youtube_key_rejected" || business === "error" || business === "stale") {
|
||||||
|
return "bg-rose-500/15 text-rose-100 ring-rose-500/25";
|
||||||
|
}
|
||||||
|
return "bg-zinc-600/20 text-zinc-400 ring-zinc-500/25";
|
||||||
|
}
|
||||||
|
|
||||||
|
export function laneStatusEmoji(row?: RelayMonitorRow): string {
|
||||||
|
const business = (row?.business_status || "").trim().toLowerCase();
|
||||||
|
if (business === "streaming") return "🟢";
|
||||||
|
if (business === "relay_slow") return "🟡";
|
||||||
|
if (business === "source_stalled") return "🟠";
|
||||||
|
if (business === "relay_starting") return "🔵";
|
||||||
|
if (business === "youtube_key_rejected" || business === "error") return "🔴";
|
||||||
|
if (business === "source_live") return "🔵";
|
||||||
|
if (business === "waiting_source") return "⚪";
|
||||||
|
return "⚫";
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isLivePushingRow(row?: RelayMonitorRow): boolean {
|
||||||
|
return !!row?.is_pushing || row?.business_status === "streaming" || row?.business_status === "relay_slow";
|
||||||
|
}
|
||||||
|
|
||||||
|
export function procStartBlocked(row?: RelayMonitorRow): boolean {
|
||||||
|
return isLivePushingRow(row) || row?.process_status === "online";
|
||||||
|
}
|
||||||
9
frontend/src/lib/ytRelayUi.ts
Normal file
9
frontend/src/lib/ytRelayUi.ts
Normal file
@ -0,0 +1,9 @@
|
|||||||
|
export function fmtRelayUptime(sec?: number) {
|
||||||
|
const s = Math.max(0, Math.floor(Number(sec || 0)));
|
||||||
|
const h = Math.floor(s / 3600);
|
||||||
|
const m = Math.floor((s % 3600) / 60);
|
||||||
|
const r = s % 60;
|
||||||
|
if (h > 0) return `${h}h ${m}m`;
|
||||||
|
if (m > 0) return `${m}m ${r}s`;
|
||||||
|
return `${r}s`;
|
||||||
|
}
|
||||||
487
scripts/_deploy_dy_nomadro.py
Normal file
487
scripts/_deploy_dy_nomadro.py
Normal file
@ -0,0 +1,487 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""Full deploy douyinWEB to dy.nomadro.live (108.174.50.68)."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import tarfile
|
||||||
|
import tempfile
|
||||||
|
import time
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import paramiko
|
||||||
|
|
||||||
|
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||||
|
|
||||||
|
HOST = "108.174.50.68"
|
||||||
|
USER = "root"
|
||||||
|
PASSWORD = "Xiao4669805"
|
||||||
|
DOMAIN = "dy.nomadro.live"
|
||||||
|
ADMIN_USER = "hackrobot"
|
||||||
|
ADMIN_PASS = "Xiao4669805@"
|
||||||
|
APP_DIR = "/opt/douyinWEB"
|
||||||
|
LOCAL_ROOT = Path(__file__).resolve().parents[1]
|
||||||
|
|
||||||
|
WEB_PORT = 4015
|
||||||
|
API_PORT = 8014
|
||||||
|
PB_PORT = 8092
|
||||||
|
YT_PORT = 8020
|
||||||
|
S3_PORT = 8333
|
||||||
|
PUBLIC_BASE = f"https://{DOMAIN}"
|
||||||
|
|
||||||
|
SKIP_DIRS = {
|
||||||
|
".git",
|
||||||
|
"node_modules",
|
||||||
|
".next",
|
||||||
|
"__pycache__",
|
||||||
|
".venv",
|
||||||
|
"venv",
|
||||||
|
"backend/data/covers",
|
||||||
|
"backend/data/clips",
|
||||||
|
"backend/data/monitor.db",
|
||||||
|
"backend/data/monitor.db-shm",
|
||||||
|
"backend/data/monitor.db-wal",
|
||||||
|
"pb/pb_data",
|
||||||
|
"scripts/_audit",
|
||||||
|
}
|
||||||
|
SKIP_EXTS = {".pyc", ".pyo"}
|
||||||
|
|
||||||
|
|
||||||
|
def should_skip(rel: str) -> bool:
|
||||||
|
parts = Path(rel).parts
|
||||||
|
for i in range(len(parts)):
|
||||||
|
sub = "/".join(parts[: i + 1])
|
||||||
|
if sub in SKIP_DIRS or parts[i] in SKIP_DIRS:
|
||||||
|
return True
|
||||||
|
if rel.endswith(tuple(SKIP_EXTS)):
|
||||||
|
return True
|
||||||
|
if "scripts/_audit" in rel.replace("\\", "/"):
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def make_tarball() -> Path:
|
||||||
|
tmp = tempfile.NamedTemporaryFile(suffix=".tar.gz", delete=False)
|
||||||
|
tmp.close()
|
||||||
|
tar_path = Path(tmp.name)
|
||||||
|
print(f"[pack] {LOCAL_ROOT} -> {tar_path}", flush=True)
|
||||||
|
with tarfile.open(tar_path, "w:gz") as tar:
|
||||||
|
for root, dirs, files in os.walk(LOCAL_ROOT):
|
||||||
|
dirs[:] = [d for d in dirs if d not in SKIP_DIRS and not d.startswith(".git")]
|
||||||
|
for name in files:
|
||||||
|
full = Path(root) / name
|
||||||
|
rel = full.relative_to(LOCAL_ROOT).as_posix()
|
||||||
|
if should_skip(rel):
|
||||||
|
continue
|
||||||
|
if rel.startswith("scripts/_") and rel.endswith(".txt"):
|
||||||
|
continue
|
||||||
|
tar.add(full, arcname=rel)
|
||||||
|
print(f"[pack] size {tar_path.stat().st_size / 1024 / 1024:.1f} MB", flush=True)
|
||||||
|
return tar_path
|
||||||
|
|
||||||
|
|
||||||
|
BOOTSTRAP_SH = r"""#!/usr/bin/env bash
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
DOMAIN="__DOMAIN__"
|
||||||
|
ADMIN_USER="__ADMIN_USER__"
|
||||||
|
ADMIN_PASS="__ADMIN_PASS__"
|
||||||
|
APP_DIR="__APP_DIR__"
|
||||||
|
PUBLIC_BASE="__PUBLIC_BASE__"
|
||||||
|
WEB_PORT="__WEB_PORT__"
|
||||||
|
API_PORT="__API_PORT__"
|
||||||
|
PB_PORT="__PB_PORT__"
|
||||||
|
YT_PORT="__YT_PORT__"
|
||||||
|
S3_PORT="__S3_PORT__"
|
||||||
|
SW_MASTER_PORT=19333
|
||||||
|
SW_VOLUME_PORT=18080
|
||||||
|
SW_FILER_PORT=18888
|
||||||
|
PB_VER=0.25.8
|
||||||
|
WEED_VER=3.80
|
||||||
|
S3_ACCESS=douyin
|
||||||
|
S3_BUCKET=douyin-covers
|
||||||
|
PB_ADMIN_EMAIL="${ADMIN_USER}@${DOMAIN}"
|
||||||
|
ENV_FILE=/etc/douyinweb.env
|
||||||
|
|
||||||
|
log() { printf '\n[%s] %s\n' "$(date '+%F %T')" "$*"; }
|
||||||
|
|
||||||
|
export DEBIAN_FRONTEND=noninteractive
|
||||||
|
log "install packages"
|
||||||
|
apt-get update -y
|
||||||
|
apt-get install -y --no-install-recommends \
|
||||||
|
git curl unzip ca-certificates ffmpeg \
|
||||||
|
python3 python3-venv python3-pip \
|
||||||
|
nginx certbot python3-certbot-nginx
|
||||||
|
|
||||||
|
if ! command -v node >/dev/null 2>&1 || [ "$(node -v | tr -d v | cut -d. -f1)" -lt 18 ]; then
|
||||||
|
curl -fsSL https://deb.nodesource.com/setup_20.x | bash -
|
||||||
|
apt-get install -y nodejs
|
||||||
|
fi
|
||||||
|
node -v
|
||||||
|
python3 --version
|
||||||
|
ffmpeg -version | head -1
|
||||||
|
|
||||||
|
if [ ! -f "$ENV_FILE" ]; then
|
||||||
|
SESSION_SECRET=$(openssl rand -hex 24)
|
||||||
|
S3_SECRET=$(openssl rand -hex 18)
|
||||||
|
cat >"$ENV_FILE" <<EOF
|
||||||
|
DOMAIN=${DOMAIN}
|
||||||
|
PUBLIC_BASE=${PUBLIC_BASE}
|
||||||
|
ADMIN_USER=${ADMIN_USER}
|
||||||
|
SESSION_SECRET=${SESSION_SECRET}
|
||||||
|
S3_SECRET=${S3_SECRET}
|
||||||
|
S3_ACCESS=${S3_ACCESS}
|
||||||
|
S3_BUCKET=${S3_BUCKET}
|
||||||
|
WEB_PORT=${WEB_PORT}
|
||||||
|
API_PORT=${API_PORT}
|
||||||
|
PB_PORT=${PB_PORT}
|
||||||
|
YT_PORT=${YT_PORT}
|
||||||
|
S3_PORT=${S3_PORT}
|
||||||
|
EOF
|
||||||
|
chmod 600 "$ENV_FILE"
|
||||||
|
fi
|
||||||
|
# shellcheck disable=SC1090
|
||||||
|
source "$ENV_FILE"
|
||||||
|
|
||||||
|
log "extract app to $APP_DIR"
|
||||||
|
mkdir -p "$APP_DIR"
|
||||||
|
rm -rf "$APP_DIR"/*
|
||||||
|
tar -xzf /tmp/douyinweb_deploy.tar.gz -C "$APP_DIR"
|
||||||
|
# Never import another environment's runtime DB (no default Douyin room URLs on fresh install)
|
||||||
|
rm -f "$APP_DIR/backend/data/monitor.db" \
|
||||||
|
"$APP_DIR/backend/data/monitor.db-shm" \
|
||||||
|
"$APP_DIR/backend/data/monitor.db-wal"
|
||||||
|
mkdir -p "$APP_DIR/backend/data/covers" "$APP_DIR/backend/data/clips" "$APP_DIR/pb/pb_data"
|
||||||
|
|
||||||
|
log "pocketbase"
|
||||||
|
mkdir -p "$APP_DIR/pb"
|
||||||
|
if [ ! -x "$APP_DIR/pb/pocketbase" ]; then
|
||||||
|
curl -fsSL -o /tmp/pb.zip \
|
||||||
|
"https://github.com/pocketbase/pocketbase/releases/download/v${PB_VER}/pocketbase_${PB_VER}_linux_amd64.zip"
|
||||||
|
unzip -o /tmp/pb.zip pocketbase -d "$APP_DIR/pb"
|
||||||
|
chmod +x "$APP_DIR/pb/pocketbase"
|
||||||
|
rm -f /tmp/pb.zip
|
||||||
|
fi
|
||||||
|
|
||||||
|
log "seaweedfs"
|
||||||
|
mkdir -p /opt/seaweedfs /data/douyinweb-seaweed/{master,volume,filer} /etc/seaweedfs
|
||||||
|
if [ ! -x /opt/seaweedfs/weed ]; then
|
||||||
|
curl -fsSL -o /tmp/weed.tgz \
|
||||||
|
"https://github.com/seaweedfs/seaweedfs/releases/download/${WEED_VER}/linux_amd64.tar.gz"
|
||||||
|
tar -xzf /tmp/weed.tgz -C /opt/seaweedfs weed
|
||||||
|
chmod +x /opt/seaweedfs/weed
|
||||||
|
rm -f /tmp/weed.tgz
|
||||||
|
fi
|
||||||
|
cat >/etc/seaweedfs/douyinweb-s3.json <<EOF
|
||||||
|
{
|
||||||
|
"identities": [{
|
||||||
|
"name": "douyinweb",
|
||||||
|
"credentials": [{"accessKey": "${S3_ACCESS}", "secretKey": "${S3_SECRET}"}],
|
||||||
|
"actions": ["Admin", "Read", "Write", "List", "Tagging"]
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
EOF
|
||||||
|
|
||||||
|
NODE_BIN=$(command -v node)
|
||||||
|
NPM_BIN=$(command -v npm)
|
||||||
|
|
||||||
|
log "systemd units"
|
||||||
|
cat >/etc/systemd/system/douyinweb-pb.service <<EOF
|
||||||
|
[Unit]
|
||||||
|
Description=DouyinWEB PocketBase
|
||||||
|
After=network.target
|
||||||
|
[Service]
|
||||||
|
Type=simple
|
||||||
|
WorkingDirectory=${APP_DIR}/pb
|
||||||
|
ExecStart=${APP_DIR}/pb/pocketbase serve --http=127.0.0.1:${PB_PORT}
|
||||||
|
Restart=always
|
||||||
|
RestartSec=3
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
||||||
|
EOF
|
||||||
|
|
||||||
|
cat >/etc/systemd/system/douyinweb-yt.service <<EOF
|
||||||
|
[Unit]
|
||||||
|
Description=DouyinWEB YouTube.js sidecar
|
||||||
|
After=network.target
|
||||||
|
[Service]
|
||||||
|
Type=simple
|
||||||
|
WorkingDirectory=${APP_DIR}/youtube-svc
|
||||||
|
Environment=YT_SVC_HOST=127.0.0.1
|
||||||
|
Environment=YT_SVC_PORT=${YT_PORT}
|
||||||
|
Environment=NODE_ENV=production
|
||||||
|
ExecStart=${NODE_BIN} src/server.mjs
|
||||||
|
Restart=always
|
||||||
|
RestartSec=3
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
||||||
|
EOF
|
||||||
|
|
||||||
|
cat >/etc/systemd/system/douyinweb-api.service <<EOF
|
||||||
|
[Unit]
|
||||||
|
Description=DouyinWEB FastAPI
|
||||||
|
After=network.target douyinweb-pb.service douyinweb-s3.service
|
||||||
|
[Service]
|
||||||
|
Type=simple
|
||||||
|
WorkingDirectory=${APP_DIR}/backend
|
||||||
|
Environment=TZ=Asia/Shanghai
|
||||||
|
Environment=DY_PB_URL=http://127.0.0.1:${PB_PORT}
|
||||||
|
Environment=DY_PB_ADMIN_EMAIL=${PB_ADMIN_EMAIL}
|
||||||
|
Environment=DY_PB_ADMIN_PASSWORD=${ADMIN_PASS}
|
||||||
|
Environment=DY_S3_ENABLED=true
|
||||||
|
Environment=DY_S3_ENDPOINT=http://127.0.0.1:${S3_PORT}
|
||||||
|
Environment=DY_S3_PUBLIC_BASE=${PUBLIC_BASE}
|
||||||
|
Environment=DY_S3_ACCESS_KEY=${S3_ACCESS}
|
||||||
|
Environment=DY_S3_SECRET_KEY=${S3_SECRET}
|
||||||
|
Environment=DY_S3_BUCKET=${S3_BUCKET}
|
||||||
|
Environment=DY_S3_REGION=us-east-1
|
||||||
|
Environment=DY_YOUTUBE_SVC_URL=http://127.0.0.1:${YT_PORT}
|
||||||
|
Environment=DY_PUBLIC_BASE_URL=${PUBLIC_BASE}
|
||||||
|
Environment=DY_CORS_ORIGINS=${PUBLIC_BASE},http://127.0.0.1:${WEB_PORT}
|
||||||
|
Environment=DY_AUTH_ENABLED=true
|
||||||
|
Environment=DY_ADMIN_USERNAME=${ADMIN_USER}
|
||||||
|
Environment=DY_ADMIN_PASSWORD=${ADMIN_PASS}
|
||||||
|
Environment=DY_SESSION_SECRET=${SESSION_SECRET}
|
||||||
|
ExecStart=${APP_DIR}/backend/.venv/bin/python -m uvicorn app.main:app --host 127.0.0.1 --port ${API_PORT}
|
||||||
|
Restart=always
|
||||||
|
RestartSec=3
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
||||||
|
EOF
|
||||||
|
|
||||||
|
cat >/etc/systemd/system/douyinweb-web.service <<EOF
|
||||||
|
[Unit]
|
||||||
|
Description=DouyinWEB Next.js
|
||||||
|
After=network.target douyinweb-api.service
|
||||||
|
[Service]
|
||||||
|
Type=simple
|
||||||
|
WorkingDirectory=${APP_DIR}/frontend
|
||||||
|
Environment=TZ=Asia/Shanghai
|
||||||
|
Environment=NODE_ENV=production
|
||||||
|
Environment=DY_INTERNAL_API_URL=http://127.0.0.1:${API_PORT}
|
||||||
|
Environment=DY_PUBLIC_BASE_URL=${PUBLIC_BASE}
|
||||||
|
Environment=PORT=${WEB_PORT}
|
||||||
|
Environment=HOSTNAME=127.0.0.1
|
||||||
|
ExecStart=${NPM_BIN} run start -- --hostname 127.0.0.1 --port ${WEB_PORT}
|
||||||
|
Restart=always
|
||||||
|
RestartSec=3
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
||||||
|
EOF
|
||||||
|
|
||||||
|
cat >/etc/systemd/system/douyinweb-sw-master.service <<EOF
|
||||||
|
[Unit]
|
||||||
|
Description=SeaweedFS master
|
||||||
|
After=network.target
|
||||||
|
[Service]
|
||||||
|
ExecStart=/opt/seaweedfs/weed master -ip=127.0.0.1 -port=${SW_MASTER_PORT} -mdir=/data/douyinweb-seaweed/master
|
||||||
|
Restart=always
|
||||||
|
RestartSec=2
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
||||||
|
EOF
|
||||||
|
|
||||||
|
cat >/etc/systemd/system/douyinweb-sw-volume.service <<EOF
|
||||||
|
[Unit]
|
||||||
|
Description=SeaweedFS volume
|
||||||
|
After=douyinweb-sw-master.service
|
||||||
|
Requires=douyinweb-sw-master.service
|
||||||
|
[Service]
|
||||||
|
ExecStart=/opt/seaweedfs/weed volume -mserver=127.0.0.1:${SW_MASTER_PORT} -ip=127.0.0.1 -port=${SW_VOLUME_PORT} -dir=/data/douyinweb-seaweed/volume -max=100
|
||||||
|
Restart=always
|
||||||
|
RestartSec=2
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
||||||
|
EOF
|
||||||
|
|
||||||
|
cat >/etc/systemd/system/douyinweb-sw-filer.service <<EOF
|
||||||
|
[Unit]
|
||||||
|
Description=SeaweedFS filer
|
||||||
|
After=douyinweb-sw-volume.service
|
||||||
|
[Service]
|
||||||
|
ExecStart=/opt/seaweedfs/weed filer -master=127.0.0.1:${SW_MASTER_PORT} -ip=127.0.0.1 -port=${SW_FILER_PORT} -defaultReplicaPlacement=000
|
||||||
|
Restart=always
|
||||||
|
RestartSec=2
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
||||||
|
EOF
|
||||||
|
|
||||||
|
cat >/etc/systemd/system/douyinweb-s3.service <<EOF
|
||||||
|
[Unit]
|
||||||
|
Description=SeaweedFS S3
|
||||||
|
After=douyinweb-sw-filer.service
|
||||||
|
[Service]
|
||||||
|
ExecStart=/opt/seaweedfs/weed s3 -filer=127.0.0.1:${SW_FILER_PORT} -ip.bind=127.0.0.1 -port=${S3_PORT} -config=/etc/seaweedfs/douyinweb-s3.json
|
||||||
|
Restart=always
|
||||||
|
RestartSec=2
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
||||||
|
EOF
|
||||||
|
|
||||||
|
systemctl daemon-reload
|
||||||
|
|
||||||
|
log "python + npm build"
|
||||||
|
python3 -m venv "$APP_DIR/backend/.venv"
|
||||||
|
"$APP_DIR/backend/.venv/bin/pip" install -U pip
|
||||||
|
"$APP_DIR/backend/.venv/bin/pip" install -r "$APP_DIR/backend/requirements.txt"
|
||||||
|
(cd "$APP_DIR/youtube-svc" && npm install --omit=dev --no-audit --no-fund)
|
||||||
|
(cd "$APP_DIR/frontend" && npm install --no-audit --no-fund && npm run build)
|
||||||
|
|
||||||
|
log "start stack"
|
||||||
|
systemctl enable --now \
|
||||||
|
douyinweb-sw-master douyinweb-sw-volume douyinweb-sw-filer douyinweb-s3 \
|
||||||
|
douyinweb-pb douyinweb-yt douyinweb-api douyinweb-web
|
||||||
|
sleep 6
|
||||||
|
|
||||||
|
"$APP_DIR/pb/pocketbase" superuser upsert "$PB_ADMIN_EMAIL" "$ADMIN_PASS" || true
|
||||||
|
export S3_PORT S3_ACCESS S3_SECRET S3_BUCKET
|
||||||
|
"$APP_DIR/backend/.venv/bin/python" - <<PY || true
|
||||||
|
import boto3, os
|
||||||
|
from botocore.client import Config
|
||||||
|
c=boto3.client("s3", endpoint_url=f"http://127.0.0.1:{os.environ.get('S3_PORT','8333')}",
|
||||||
|
aws_access_key_id=os.environ.get("S3_ACCESS","douyin"),
|
||||||
|
aws_secret_access_key=os.environ.get("S3_SECRET",""),
|
||||||
|
region_name="us-east-1", config=Config(signature_version="s3v4", s3={"addressing_style":"path"}))
|
||||||
|
try:
|
||||||
|
c.create_bucket(Bucket=os.environ.get("S3_BUCKET","douyin-covers"))
|
||||||
|
except Exception as e:
|
||||||
|
print("bucket", e)
|
||||||
|
PY
|
||||||
|
|
||||||
|
log "nginx vhost"
|
||||||
|
cat >/etc/nginx/conf.d/dy-nomadro-live.conf <<'NGX'
|
||||||
|
server {
|
||||||
|
listen 80;
|
||||||
|
server_name __DOMAIN__;
|
||||||
|
|
||||||
|
client_max_body_size 200m;
|
||||||
|
|
||||||
|
location ^~ /api/ {
|
||||||
|
proxy_pass http://127.0.0.1:__API_PORT__;
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
proxy_set_header Upgrade $http_upgrade;
|
||||||
|
proxy_set_header Connection "upgrade";
|
||||||
|
proxy_read_timeout 3600s;
|
||||||
|
}
|
||||||
|
location ^~ /covers/ {
|
||||||
|
proxy_pass http://127.0.0.1:__API_PORT__;
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
}
|
||||||
|
location ^~ /_/ {
|
||||||
|
proxy_pass http://127.0.0.1:__PB_PORT__;
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
}
|
||||||
|
location ^~ /douyin-covers/ {
|
||||||
|
proxy_pass http://127.0.0.1:__S3_PORT__;
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
client_max_body_size 200m;
|
||||||
|
}
|
||||||
|
location / {
|
||||||
|
proxy_pass http://127.0.0.1:__WEB_PORT__;
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
proxy_set_header Upgrade $http_upgrade;
|
||||||
|
proxy_set_header Connection "upgrade";
|
||||||
|
proxy_read_timeout 60s;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
NGX
|
||||||
|
sed -i "s/__DOMAIN__/${DOMAIN}/g; s/__API_PORT__/${API_PORT}/g; s/__PB_PORT__/${PB_PORT}/g; s/__S3_PORT__/${S3_PORT}/g; s/__WEB_PORT__/${WEB_PORT}/g" \
|
||||||
|
/etc/nginx/conf.d/dy-nomadro-live.conf
|
||||||
|
|
||||||
|
nginx -t
|
||||||
|
systemctl reload nginx
|
||||||
|
|
||||||
|
log "certbot ssl"
|
||||||
|
certbot --nginx -d "${DOMAIN}" --non-interactive --agree-tos --register-unsafely-without-email --redirect || \
|
||||||
|
certbot certonly --nginx -d "${DOMAIN}" --non-interactive --agree-tos --register-unsafely-without-email || true
|
||||||
|
|
||||||
|
if [ -f "/etc/letsencrypt/live/${DOMAIN}/fullchain.pem" ]; then
|
||||||
|
log "cert obtained"
|
||||||
|
systemctl reload nginx || true
|
||||||
|
fi
|
||||||
|
|
||||||
|
log "sync admin"
|
||||||
|
cd "$APP_DIR/backend"
|
||||||
|
.venv/bin/python -c "from app.session_auth import ensure_default_admin_credentials; ensure_default_admin_credentials(); from app.session_auth import get_admin_credentials; u,h=get_admin_credentials(); print('admin', u)"
|
||||||
|
|
||||||
|
log "verify"
|
||||||
|
sleep 3
|
||||||
|
systemctl is-active douyinweb-api douyinweb-web douyinweb-pb || true
|
||||||
|
curl -fsS "http://127.0.0.1:${API_PORT}/api/health" | head -c 300; echo
|
||||||
|
curl -sS -o /dev/null -w "web:%{http_code}\n" "http://127.0.0.1:${WEB_PORT}/login" || true
|
||||||
|
curl -sS -o /dev/null -w "pub:%{http_code}\n" --max-time 25 "${PUBLIC_BASE}/login" || true
|
||||||
|
echo "DONE ${PUBLIC_BASE}"
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
def run_remote_bootstrap(client: paramiko.SSHClient) -> int:
|
||||||
|
sh = (
|
||||||
|
BOOTSTRAP_SH.replace("__DOMAIN__", DOMAIN)
|
||||||
|
.replace("__ADMIN_USER__", ADMIN_USER)
|
||||||
|
.replace("__ADMIN_PASS__", ADMIN_PASS)
|
||||||
|
.replace("__APP_DIR__", APP_DIR)
|
||||||
|
.replace("__PUBLIC_BASE__", PUBLIC_BASE)
|
||||||
|
.replace("__WEB_PORT__", str(WEB_PORT))
|
||||||
|
.replace("__API_PORT__", str(API_PORT))
|
||||||
|
.replace("__PB_PORT__", str(PB_PORT))
|
||||||
|
.replace("__YT_PORT__", str(YT_PORT))
|
||||||
|
.replace("__S3_PORT__", str(S3_PORT))
|
||||||
|
)
|
||||||
|
remote_sh = "/tmp/bootstrap_dy_nomadro.sh"
|
||||||
|
sftp = client.open_sftp()
|
||||||
|
with sftp.file(remote_sh, "w") as f:
|
||||||
|
f.write(sh)
|
||||||
|
sftp.chmod(remote_sh, 0o755)
|
||||||
|
sftp.close()
|
||||||
|
|
||||||
|
chan = client.get_transport().open_session()
|
||||||
|
chan.settimeout(3600)
|
||||||
|
chan.get_pty(width=200, height=50)
|
||||||
|
chan.exec_command(f"bash {remote_sh}")
|
||||||
|
while True:
|
||||||
|
if chan.recv_ready():
|
||||||
|
print(chan.recv(65535).decode("utf-8", "replace"), end="", flush=True)
|
||||||
|
if chan.recv_stderr_ready():
|
||||||
|
print(chan.recv_stderr(65535).decode("utf-8", "replace"), end="", flush=True)
|
||||||
|
if chan.exit_status_ready() and not chan.recv_ready() and not chan.recv_stderr_ready():
|
||||||
|
break
|
||||||
|
time.sleep(0.3)
|
||||||
|
while chan.recv_ready():
|
||||||
|
print(chan.recv(65535).decode("utf-8", "replace"), end="", flush=True)
|
||||||
|
return chan.recv_exit_status()
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
tar_path = make_tarball()
|
||||||
|
client = paramiko.SSHClient()
|
||||||
|
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||||
|
print(f"connecting {HOST}...", flush=True)
|
||||||
|
client.connect(HOST, 22, USER, PASSWORD, timeout=45, allow_agent=False, look_for_keys=False)
|
||||||
|
|
||||||
|
print("[upload tarball]", flush=True)
|
||||||
|
sftp = client.open_sftp()
|
||||||
|
sftp.put(str(tar_path), "/tmp/douyinweb_deploy.tar.gz")
|
||||||
|
sftp.close()
|
||||||
|
os.unlink(tar_path)
|
||||||
|
|
||||||
|
code = run_remote_bootstrap(client)
|
||||||
|
client.close()
|
||||||
|
print(f"\n=== exit {code} ===", flush=True)
|
||||||
|
print(f"URL: {PUBLIC_BASE}/", flush=True)
|
||||||
|
print(f"Login: {ADMIN_USER} / {ADMIN_PASS}", flush=True)
|
||||||
|
return code
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
raise SystemExit(main())
|
||||||
102
scripts/_deploy_yt_neko.py
Normal file
102
scripts/_deploy_yt_neko.py
Normal file
@ -0,0 +1,102 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""Deploy YouTube Neko per-channel feature to dy.nomadro.live."""
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import paramiko
|
||||||
|
|
||||||
|
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||||
|
|
||||||
|
HOST = "108.174.50.68"
|
||||||
|
APP = "/opt/douyinWEB"
|
||||||
|
ROOT = Path(__file__).resolve().parents[1]
|
||||||
|
|
||||||
|
FILES = [
|
||||||
|
"backend/app/youtube_neko.py",
|
||||||
|
"backend/app/yt_assign_db.py",
|
||||||
|
"backend/app/main.py",
|
||||||
|
"backend/app/models.py",
|
||||||
|
"backend/app/config.py",
|
||||||
|
"frontend/src/components/YtRelayProStatusPanel.tsx",
|
||||||
|
"frontend/src/components/YtAssignPanel.tsx",
|
||||||
|
]
|
||||||
|
|
||||||
|
REMOTE_SH = r"""#!/usr/bin/env bash
|
||||||
|
set -euo pipefail
|
||||||
|
source /etc/douyinweb.env
|
||||||
|
|
||||||
|
echo "=== docker ==="
|
||||||
|
if ! command -v docker >/dev/null 2>&1; then
|
||||||
|
apt-get update -y
|
||||||
|
apt-get install -y docker.io docker-compose-plugin || apt-get install -y docker.io
|
||||||
|
systemctl enable --now docker
|
||||||
|
fi
|
||||||
|
docker --version
|
||||||
|
|
||||||
|
echo "=== restart api ==="
|
||||||
|
systemctl restart douyinweb-api
|
||||||
|
sleep 5
|
||||||
|
systemctl is-active douyinweb-api
|
||||||
|
|
||||||
|
echo "=== migrate neko ids ==="
|
||||||
|
cd /opt/douyinWEB/backend
|
||||||
|
.venv/bin/python - <<'PY'
|
||||||
|
from app import yt_assign_db
|
||||||
|
from app.db import init_db
|
||||||
|
init_db()
|
||||||
|
groups = yt_assign_db.list_groups(include_urls=False)
|
||||||
|
print("groups", len(groups), "neko_ids", [g.get("neko_instance_id") for g in groups])
|
||||||
|
PY
|
||||||
|
|
||||||
|
echo "=== build web ==="
|
||||||
|
cd /opt/douyinWEB/frontend && npm run build
|
||||||
|
systemctl restart douyinweb-web
|
||||||
|
sleep 4
|
||||||
|
systemctl is-active douyinweb-web
|
||||||
|
|
||||||
|
echo "=== neko status ==="
|
||||||
|
curl -sS http://127.0.0.1:${API_PORT:-8014}/api/youtube/neko/status | head -c 400
|
||||||
|
echo
|
||||||
|
echo DONE
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
c = paramiko.SSHClient()
|
||||||
|
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||||
|
c.connect(HOST, 22, "root", "Xiao4669805", timeout=45, allow_agent=False, look_for_keys=False)
|
||||||
|
|
||||||
|
sftp = c.open_sftp()
|
||||||
|
for rel in FILES:
|
||||||
|
local = ROOT / rel
|
||||||
|
remote = f"{APP}/{rel.replace(chr(92), '/')}"
|
||||||
|
print(f"upload {rel}")
|
||||||
|
sftp.put(str(local), remote)
|
||||||
|
with sftp.file("/tmp/deploy_yt_neko.sh", "w") as f:
|
||||||
|
f.write(REMOTE_SH)
|
||||||
|
sftp.chmod("/tmp/deploy_yt_neko.sh", 0o755)
|
||||||
|
sftp.close()
|
||||||
|
|
||||||
|
chan = c.get_transport().open_session()
|
||||||
|
chan.settimeout(900)
|
||||||
|
chan.get_pty(width=200, height=50)
|
||||||
|
chan.exec_command("bash /tmp/deploy_yt_neko.sh")
|
||||||
|
while True:
|
||||||
|
if chan.recv_ready():
|
||||||
|
print(chan.recv(65535).decode("utf-8", "replace"), end="", flush=True)
|
||||||
|
if chan.recv_stderr_ready():
|
||||||
|
print(chan.recv_stderr(65535).decode("utf-8", "replace"), end="", flush=True)
|
||||||
|
if chan.exit_status_ready() and not chan.recv_ready() and not chan.recv_stderr_ready():
|
||||||
|
break
|
||||||
|
time.sleep(0.3)
|
||||||
|
while chan.recv_ready():
|
||||||
|
print(chan.recv(65535).decode("utf-8", "replace"), end="", flush=True)
|
||||||
|
code = chan.recv_exit_status()
|
||||||
|
c.close()
|
||||||
|
print(f"\nexit {code}")
|
||||||
|
return code
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
raise SystemExit(main())
|
||||||
169
scripts/_finish_dy_deploy.py
Normal file
169
scripts/_finish_dy_deploy.py
Normal file
@ -0,0 +1,169 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""Finish dy.nomadro.live deploy: start services, nginx, certbot."""
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
import paramiko
|
||||||
|
|
||||||
|
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||||
|
|
||||||
|
HOST = "108.174.50.68"
|
||||||
|
DOMAIN = "dy.nomadro.live"
|
||||||
|
PUBLIC_BASE = f"https://{DOMAIN}"
|
||||||
|
|
||||||
|
FINISH_SH = r"""#!/usr/bin/env bash
|
||||||
|
set -euo pipefail
|
||||||
|
source /etc/douyinweb.env
|
||||||
|
APP_DIR=/opt/douyinWEB
|
||||||
|
ADMIN_PASS='Xiao4669805@'
|
||||||
|
API_PORT=${API_PORT:-8014}
|
||||||
|
WEB_PORT=${WEB_PORT:-4015}
|
||||||
|
PB_PORT=${PB_PORT:-8092}
|
||||||
|
S3_PORT=${S3_PORT:-8333}
|
||||||
|
S3_BUCKET=${S3_BUCKET:-douyin-covers}
|
||||||
|
S3_ACCESS=${S3_ACCESS:-douyin}
|
||||||
|
PB_ADMIN_EMAIL="${ADMIN_USER}@${DOMAIN}"
|
||||||
|
|
||||||
|
log() { printf '\n[%s] %s\n' "$(date '+%F %T')" "$*"; }
|
||||||
|
|
||||||
|
log "start all douyinweb units"
|
||||||
|
systemctl daemon-reload
|
||||||
|
systemctl enable --now \
|
||||||
|
douyinweb-sw-master douyinweb-sw-volume douyinweb-sw-filer douyinweb-s3 \
|
||||||
|
douyinweb-pb douyinweb-yt douyinweb-api douyinweb-web
|
||||||
|
sleep 8
|
||||||
|
systemctl is-active douyinweb-sw-master douyinweb-sw-volume douyinweb-sw-filer douyinweb-s3 \
|
||||||
|
douyinweb-pb douyinweb-yt douyinweb-api douyinweb-web || true
|
||||||
|
|
||||||
|
log "pb superuser + s3 bucket"
|
||||||
|
"$APP_DIR/pb/pocketbase" superuser upsert "$PB_ADMIN_EMAIL" "$ADMIN_PASS" || true
|
||||||
|
export S3_PORT S3_ACCESS S3_SECRET S3_BUCKET
|
||||||
|
"$APP_DIR/backend/.venv/bin/python" - <<PY || true
|
||||||
|
import boto3, os
|
||||||
|
from botocore.client import Config
|
||||||
|
c=boto3.client("s3", endpoint_url=f"http://127.0.0.1:{os.environ.get('S3_PORT','8333')}",
|
||||||
|
aws_access_key_id=os.environ.get("S3_ACCESS","douyin"),
|
||||||
|
aws_secret_access_key=os.environ.get("S3_SECRET",""),
|
||||||
|
region_name="us-east-1", config=Config(signature_version="s3v4", s3={"addressing_style":"path"}))
|
||||||
|
try:
|
||||||
|
c.create_bucket(Bucket=os.environ.get("S3_BUCKET","douyin-covers"))
|
||||||
|
print("bucket ok")
|
||||||
|
except Exception as e:
|
||||||
|
print("bucket", e)
|
||||||
|
PY
|
||||||
|
|
||||||
|
log "ensure frontend build"
|
||||||
|
if [ ! -f "$APP_DIR/frontend/.next/BUILD_ID" ]; then
|
||||||
|
(cd "$APP_DIR/frontend" && npm install --no-audit --no-fund && npm run build)
|
||||||
|
fi
|
||||||
|
|
||||||
|
log "sync admin"
|
||||||
|
cd "$APP_DIR/backend"
|
||||||
|
export DY_SESSION_SECRET="${SESSION_SECRET:-}"
|
||||||
|
.venv/bin/python -c "from app.session_auth import ensure_default_admin_credentials; ensure_default_admin_credentials(); from app.session_auth import get_admin_credentials; u,h=get_admin_credentials(); print('admin', u, h[:12])"
|
||||||
|
|
||||||
|
log "nginx vhost"
|
||||||
|
cat >/etc/nginx/conf.d/dy-nomadro-live.conf <<NGX
|
||||||
|
server {
|
||||||
|
listen 80;
|
||||||
|
server_name ${DOMAIN};
|
||||||
|
|
||||||
|
client_max_body_size 200m;
|
||||||
|
|
||||||
|
location ^~ /api/ {
|
||||||
|
proxy_pass http://127.0.0.1:${API_PORT};
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
proxy_set_header Host \$host;
|
||||||
|
proxy_set_header X-Real-IP \$remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto \$scheme;
|
||||||
|
proxy_set_header Upgrade \$http_upgrade;
|
||||||
|
proxy_set_header Connection "upgrade";
|
||||||
|
proxy_read_timeout 3600s;
|
||||||
|
}
|
||||||
|
location ^~ /covers/ {
|
||||||
|
proxy_pass http://127.0.0.1:${API_PORT};
|
||||||
|
proxy_set_header Host \$host;
|
||||||
|
proxy_set_header X-Forwarded-Proto \$scheme;
|
||||||
|
}
|
||||||
|
location ^~ /_/ {
|
||||||
|
proxy_pass http://127.0.0.1:${PB_PORT};
|
||||||
|
proxy_set_header Host \$host;
|
||||||
|
proxy_set_header X-Forwarded-Proto \$scheme;
|
||||||
|
}
|
||||||
|
location ^~ /${S3_BUCKET}/ {
|
||||||
|
proxy_pass http://127.0.0.1:${S3_PORT};
|
||||||
|
proxy_set_header Host \$host;
|
||||||
|
proxy_set_header X-Forwarded-Proto \$scheme;
|
||||||
|
client_max_body_size 200m;
|
||||||
|
}
|
||||||
|
location / {
|
||||||
|
proxy_pass http://127.0.0.1:${WEB_PORT};
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
proxy_set_header Host \$host;
|
||||||
|
proxy_set_header X-Real-IP \$remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto \$scheme;
|
||||||
|
proxy_set_header Upgrade \$http_upgrade;
|
||||||
|
proxy_set_header Connection "upgrade";
|
||||||
|
proxy_read_timeout 60s;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
NGX
|
||||||
|
|
||||||
|
nginx -t
|
||||||
|
systemctl reload nginx
|
||||||
|
|
||||||
|
log "certbot"
|
||||||
|
if [ ! -f "/etc/letsencrypt/live/${DOMAIN}/fullchain.pem" ]; then
|
||||||
|
certbot --nginx -d "${DOMAIN}" --non-interactive --agree-tos --register-unsafely-without-email --redirect || \
|
||||||
|
certbot certonly --nginx -d "${DOMAIN}" --non-interactive --agree-tos --register-unsafely-without-email || true
|
||||||
|
nginx -t && systemctl reload nginx || true
|
||||||
|
fi
|
||||||
|
|
||||||
|
log "verify"
|
||||||
|
sleep 2
|
||||||
|
curl -fsS "http://127.0.0.1:${API_PORT}/api/health" | head -c 300; echo
|
||||||
|
curl -sS -o /dev/null -w "web:%{http_code}\n" "http://127.0.0.1:${WEB_PORT}/login" || true
|
||||||
|
curl -sS -o /dev/null -w "login:%{http_code}\n" -X POST "http://127.0.0.1:${API_PORT}/api/auth/login" \
|
||||||
|
-H 'Content-Type: application/json' \
|
||||||
|
-d '{"username":"hackrobot","password":"Xiao4669805@"}' || true
|
||||||
|
curl -sS -o /dev/null -w "pub:%{http_code}\n" --max-time 25 "https://${DOMAIN}/login" || true
|
||||||
|
curl -sS -o /dev/null -w "pub_health:%{http_code}\n" --max-time 25 "https://${DOMAIN}/api/health" || true
|
||||||
|
echo "DONE https://${DOMAIN}/"
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
c = paramiko.SSHClient()
|
||||||
|
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||||
|
c.connect(HOST, 22, "root", "Xiao4669805", timeout=45, allow_agent=False, look_for_keys=False)
|
||||||
|
|
||||||
|
remote = "/tmp/finish_dy.sh"
|
||||||
|
sftp = c.open_sftp()
|
||||||
|
with sftp.file(remote, "w") as f:
|
||||||
|
f.write(FINISH_SH)
|
||||||
|
sftp.chmod(remote, 0o755)
|
||||||
|
sftp.close()
|
||||||
|
|
||||||
|
chan = c.get_transport().open_session()
|
||||||
|
chan.settimeout(600)
|
||||||
|
chan.get_pty(width=200, height=50)
|
||||||
|
chan.exec_command(f"bash {remote}")
|
||||||
|
while True:
|
||||||
|
if chan.recv_ready():
|
||||||
|
print(chan.recv(65535).decode("utf-8", "replace"), end="", flush=True)
|
||||||
|
if chan.recv_stderr_ready():
|
||||||
|
print(chan.recv_stderr(65535).decode("utf-8", "replace"), end="", flush=True)
|
||||||
|
if chan.exit_status_ready() and not chan.recv_ready() and not chan.recv_stderr_ready():
|
||||||
|
break
|
||||||
|
time.sleep(0.3)
|
||||||
|
while chan.recv_ready():
|
||||||
|
print(chan.recv(65535).decode("utf-8", "replace"), end="", flush=True)
|
||||||
|
code = chan.recv_exit_status()
|
||||||
|
c.close()
|
||||||
|
print(f"\nexit {code}")
|
||||||
|
return code
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
raise SystemExit(main())
|
||||||
Loading…
Reference in New Issue
Block a user