Make desktop the sole Windows client with unmanned live and boot/poll hardening.

Consolidate Douyin→YouTube RTMPS into /live, parallel local service boot, poll-only realtime, slimmer packs/charts, and deprecate youtube-live-win.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Eric 2026-10-23 14:10:07 +01:00
parent bee143c47d
commit 960a268fa2
31 changed files with 1518 additions and 267 deletions

View File

@ -8,7 +8,7 @@
## Windows 客户端(本地独立运行)
仓库 [`desktop/`](desktop/) 为 Electron + React 桌面端:启动时在本机拉起 **PocketBase + FastAPI + youtube-svc**,不依赖线上服务器。
仓库 [`desktop/`](desktop/) 为 **唯一 Windows 客户端**(Electron + React):本机拉起 PocketBase + FastAPI + youtube-svc,含监控 / 分组 / Shorts / **无人直播(抖音→YouTube RTMPS)** 全功能。勿再使用已废弃的 `youtube-live-win/`。
```bat
scripts\start-desktop.bat
@ -17,7 +17,7 @@ scripts\start-desktop.bat
或:
```bat
cd desktop && npm install && npm run electron:dev
cd desktop && npm install && npm run fetch-ffmpeg && npm run electron:dev
```
默认本机端口:API `8014` · PB `8090` · youtube-svc `8020` · UI `5173`。说明见 [desktop/README.md](desktop/README.md)。打包:`cd desktop && npm run pack`。

View File

@ -12,4 +12,5 @@ requests-auth-aws-sigv4>=0.7
requests>=2.31
PySocks>=1.7.1
python-dotenv>=1.0
tzdata>=2024.1

View File

@ -1,60 +1,57 @@
# Windows 桌面客户端(Electron + React)
# Windows 桌面客户端(唯一)
本目录是 **独立 Windows 客户端**:启动时在本机拉起 **PocketBase + FastAPI + youtube-svc**,UI 连本地 API,**不依赖** `dylive.nomadro.com`。
本目录是 **douyinWEB 唯一 Windows 客户端**:本地拉起 PocketBase + FastAPI + youtube-svc,UI 为 Electron + React。
> 已废弃独立目录 `youtube-live-win/`。无人直播请用本客户端导航 **「无人直播」**。
## 要求
- Windows 10/11 x64
- Node.js 20+
- Python 3.10+(已 `pip install -r ../backend/requirements.txt`)
- 仓库内 `pb/pocketbase.exe`
- (可选)`ffmpeg` 在 PATH,用于封面/Shorts
- Python 3.10+(Windows 需 `tzdata`:`npm run ensure-python` 或 `pip install -r ../backend/requirements.txt`)
- PocketBase:`npm run fetch-pocketbase` → `../pb/pocketbase.exe`
- FFmpeg:系统 PATH,或 `npm run fetch-ffmpeg` → `runtime/ffmpeg/`
- `youtube-svc`:`cd ../youtube-svc && npm install`(`start-desktop.bat` 会自动装)
## 开发
```bat
cd desktop
npm install
npm run prepare:runtime
npm run electron:dev
```
流程:
1. Electron main 启动本地 PB `:8090`、API `:8014`、youtube-svc `:8020`
2. Vite `:5173`(代理 `/api`、`/covers` → API)
3. 打开桌面窗口加载 UI
仅预览 UI(需你已手动起后端):
```bat
npm run dev
```
## 打包
```bat
npm run pack
```
产物在 `desktop/release/`(NSIS 安装包 + portable)。打包会把 `backend/`、`pb/`、`youtube-svc/` 打进 `extraResources`(不含 `pocketbase.exe` 时需自行放入 runtime/pb)。
## 端口
或仓库根目录:`scripts\start-desktop.bat`(自动补齐 PB / ffmpeg / Python / youtube-svc)。
| 服务 | 默认 |
|------|------|
| FastAPI | `127.0.0.1:8014` |
| PocketBase | `127.0.0.1:8090` |
| youtube-svc | `127.0.0.1:8020` |
| Vite / UI | `127.0.0.1:5173`(开发)或 `:18574`(打包) |
| Vite UI | `127.0.0.1:5173` |
## 客户端能力
启动时 **关闭 `DY_DESKTOP_LIGHT`**,会自动拉起 monitor / youtube_relay / Shorts 等 worker(Neko 默认关,无需 Docker)。
- 系统托盘(关闭窗口可托盘驻留)
- 开播/风控等 **Windows 原生通知**
- 单实例锁;外链用系统浏览器
- 设置页「Windows 客户端 · 本地后端」:服务状态、日志目录、诊断复制
- 窗口失焦时降低轮询频率(SSE 仍保持以便通知)
桌面端默认 **轮询模式**(不开 SSE),避免 Windows 本机 API 被 EventSource 打满。
## 登录
## 功能
与 Web 相同:本地 API 的站点登录(默认见后端 `DY_ADMIN_*` / 设置页改密)。
- 概览 / 时段 / 场次 / 主播 / 截图 / 事件
- 直播间 / 分组 / YouTube 管理与探测 / Shorts / 黑名单 / 设置
- **无人直播**:单频道 Stream Key + 抖音源 → 一键武装 RTMPS 推流
## 打包
```bat
npm run fetch-ffmpeg
npm run pack
```
产物在 `desktop/release/`(NSIS + portable)。
## 无人直播用法
1. YouTube Studio → 开始直播(进入收流)
2. 客户端打开 **无人直播**
3. 填 Stream Key + 抖音直播间 → 保存 → **一键武装推流**

View File

@ -11,7 +11,14 @@ import {
} from "electron";
import path from "node:path";
import { getConfig, setConfig } from "./store";
import { listServicePids, startLocalServices, stopLocalServices } from "./services";
import {
getResolvedFfmpeg,
listServicePids,
restartLocalServices,
setServiceStatusListener,
startLocalServices,
stopLocalServices,
} from "./services";
import { startUiServer } from "./uiServer";
let mainWindow: BrowserWindow | null = null;
@ -51,6 +58,14 @@ function createTray() {
mainWindow?.focus();
},
},
{
label: "无人直播",
click: () => {
mainWindow?.show();
mainWindow?.focus();
navigateUi("/live");
},
},
{
label: "本地服务状态",
click: () => {
@ -172,12 +187,51 @@ async function loadAppUi() {
void mainWindow.loadURL(uiUrl);
}
function navigateUi(routePath: string) {
if (!mainWindow || mainWindow.isDestroyed()) return;
const pathOnly = routePath.startsWith("/") ? routePath : `/${routePath}`;
const base = uiUrl.replace(/\/$/, "");
const target = `${base}${pathOnly}`;
const current = mainWindow.webContents.getURL();
if (current.startsWith("data:")) {
void mainWindow.loadURL(target);
return;
}
void mainWindow.webContents
.executeJavaScript(
`(() => { const p=${JSON.stringify(pathOnly)}; if (location.pathname !== p) { window.history.pushState({}, "", p); window.dispatchEvent(new PopStateEvent("popstate")); } })()`,
)
.catch(() => {
void mainWindow?.loadURL(target);
});
}
function persistBounds() {
if (!mainWindow) return;
const b = mainWindow.getBounds();
setConfig({ windowBounds: b });
}
function pushServiceStatus(next: Record<string, string>) {
serviceStatus = { ...next };
if (mainWindow && !mainWindow.isDestroyed()) {
mainWindow.webContents.send("desktop:services", serviceStatus);
const url = mainWindow.webContents.getURL();
if (url.startsWith("data:")) {
const line = [
`PB ${serviceStatus.pocketbase || "…"}`,
`API ${serviceStatus.api || "…"}`,
`YT ${serviceStatus.youtube || "…"}`,
].join(" · ");
void mainWindow.webContents
.executeJavaScript(
`(() => { const p=document.querySelector('.p'); if(p) p.textContent=${JSON.stringify(line)}; })()`,
)
.catch(() => undefined);
}
}
}
function registerIpc() {
ipcMain.handle("desktop:getConfig", () => getConfig());
ipcMain.handle("desktop:setConfig", (_e, patch) => setConfig(patch || {}));
@ -185,6 +239,17 @@ function registerIpc() {
...serviceStatus,
pids: listServicePids(),
}));
ipcMain.handle("desktop:restartServices", async () => {
const cfg = getConfig();
const started = await restartLocalServices({
apiPort: cfg.apiPort,
pbPort: cfg.pbPort,
ytPort: cfg.ytPort,
});
pushServiceStatus(started.status);
setConfig({ apiBase: started.apiBase });
return { ...started.status, pids: listServicePids() };
});
ipcMain.handle("desktop:notify", (_e, payload: { title: string; body: string }) => {
if (!getConfig().nativeNotify) return;
if (!Notification.isSupported()) return;
@ -207,6 +272,7 @@ function registerIpc() {
platform: process.platform,
apiBase: cfg.apiBase,
services: serviceStatus,
ffmpeg: getResolvedFfmpeg() || serviceStatus.ffmpeg || "",
packaged: app.isPackaged,
};
});
@ -232,18 +298,20 @@ if (!gotLock) {
app.whenReady().then(() => {
registerIpc();
setServiceStatusListener((st) => pushServiceStatus(st));
createTray();
createWindow(); // instant splash
const cfg = getConfig();
void (async () => {
try {
pushServiceStatus({ boot: "starting" });
const started = await startLocalServices({
apiPort: cfg.apiPort,
pbPort: cfg.pbPort,
ytPort: cfg.ytPort,
});
serviceStatus = started.status;
pushServiceStatus(started.status);
setConfig({ apiBase: started.apiBase });
if (isDev) {
@ -258,7 +326,7 @@ if (!gotLock) {
uiUrl = ui.url;
}
} catch (err) {
serviceStatus = { boot: String((err as Error).message) };
pushServiceStatus({ boot: String((err as Error).message) });
console.error("Failed to start local services", err);
}
await loadAppUi();

View File

@ -4,11 +4,13 @@ export type DesktopBridge = {
getConfig: () => Promise<Record<string, unknown>>;
setConfig: (patch: Record<string, unknown>) => Promise<Record<string, unknown>>;
getServiceStatus: () => Promise<Record<string, unknown>>;
restartServices: () => Promise<Record<string, unknown>>;
notify: (title: string, body: string) => Promise<void>;
openExternal: (url: string) => Promise<void>;
openLogs: () => Promise<void>;
getDiagnostics: () => Promise<Record<string, unknown>>;
onWindowFocus: (cb: (focused: boolean) => void) => () => void;
onServiceStatus: (cb: (status: Record<string, unknown>) => void) => () => void;
minimizeToTray: () => Promise<void>;
};
@ -16,6 +18,7 @@ const bridge: DesktopBridge = {
getConfig: () => ipcRenderer.invoke("desktop:getConfig"),
setConfig: (patch) => ipcRenderer.invoke("desktop:setConfig", patch),
getServiceStatus: () => ipcRenderer.invoke("desktop:getServiceStatus"),
restartServices: () => ipcRenderer.invoke("desktop:restartServices"),
notify: (title, body) => ipcRenderer.invoke("desktop:notify", { title, body }),
openExternal: (url) => ipcRenderer.invoke("desktop:openExternal", url),
openLogs: () => ipcRenderer.invoke("desktop:openLogs"),
@ -25,6 +28,11 @@ const bridge: DesktopBridge = {
ipcRenderer.on("desktop:focus", handler);
return () => ipcRenderer.removeListener("desktop:focus", handler);
},
onServiceStatus: (cb) => {
const handler = (_: Electron.IpcRendererEvent, status: Record<string, unknown>) => cb(status);
ipcRenderer.on("desktop:services", handler);
return () => ipcRenderer.removeListener("desktop:services", handler);
},
minimizeToTray: () => ipcRenderer.invoke("desktop:minimizeToTray"),
};

View File

@ -1,11 +1,17 @@
import { ChildProcess, spawn, SpawnOptions } from "node:child_process";
import { ChildProcess, execFileSync, spawn, SpawnOptions } from "node:child_process";
import fs from "node:fs";
import http from "node:http";
import net from "node:net";
import path from "node:path";
import { app } from "electron";
/** Resolved ffmpeg used for youtube_relay / Shorts (env or disk). */
let resolvedFfmpeg = "";
let resolvedPython = "";
export type ServiceName = "pocketbase" | "api" | "youtube";
export type ServiceStatus = Record<string, string>;
export type StatusListener = (status: ServiceStatus) => void;
type Running = {
name: ServiceName;
@ -14,6 +20,19 @@ type Running = {
};
const children: Running[] = [];
let statusListener: StatusListener | null = null;
export function setServiceStatusListener(cb: StatusListener | null) {
statusListener = cb;
}
function emitStatus(status: ServiceStatus) {
try {
statusListener?.({ ...status });
} catch {
/* ignore */
}
}
function isPackaged(): boolean {
return app.isPackaged;
@ -58,11 +77,11 @@ function spawnLogged(
const prefix = `[${name}]`;
let lines = 0;
const onChunk = (buf: Buffer, isErr: boolean) => {
if (lines > 30) return;
if (lines > 40) return;
const line = String(buf).trim();
if (!line) return;
lines += 1;
if (isErr || lines <= 6) {
if (isErr || lines <= 8) {
(isErr ? console.error : console.log)(prefix, line.slice(0, 220));
}
};
@ -91,7 +110,7 @@ function portOpen(port: number, host = "127.0.0.1"): Promise<boolean> {
});
}
function probeHttp(url: string, timeoutMs = 1000): Promise<boolean> {
function probeHttp(url: string, timeoutMs = 1200): Promise<boolean> {
return new Promise((resolve) => {
const req = http.get(url, { timeout: timeoutMs }, (res) => {
res.resume();
@ -105,140 +124,271 @@ function probeHttp(url: string, timeoutMs = 1000): Promise<boolean> {
});
}
function waitPort(port: number, timeoutMs = 45000, host = "127.0.0.1"): Promise<void> {
const start = Date.now();
return new Promise((resolve, reject) => {
let settled = false;
let timer: ReturnType<typeof setTimeout> | null = null;
let sock: net.Socket | null = null;
const finish = (err?: Error) => {
if (settled) return;
settled = true;
if (timer) clearTimeout(timer);
try {
sock?.destroy();
} catch {
/* ignore */
}
if (err) reject(err);
else resolve();
};
const tick = () => {
if (settled) return;
if (Date.now() - start > timeoutMs) {
finish(new Error(`timeout waiting port ${host}:${port}`));
return;
}
try {
sock?.destroy();
} catch {
/* ignore */
}
sock = net.connect({ port, host });
sock.setTimeout(800);
sock.once("connect", () => finish());
sock.once("timeout", () => {
try {
sock?.destroy();
} catch {
/* ignore */
}
timer = setTimeout(tick, 400);
});
sock.once("error", () => {
timer = setTimeout(tick, 400);
});
};
tick();
});
function sleep(ms: number) {
return new Promise<void>((r) => setTimeout(r, ms));
}
function findPython(): string {
return process.platform === "win32" ? "python" : "python3";
async function waitPort(port: number, timeoutMs = 45000, host = "127.0.0.1"): Promise<void> {
const start = Date.now();
while (Date.now() - start < timeoutMs) {
if (await portOpen(port, host)) return;
await sleep(350);
}
throw new Error(`timeout waiting port ${host}:${port}`);
}
async function waitHttp(url: string, timeoutMs = 45000): Promise<void> {
const start = Date.now();
while (Date.now() - start < timeoutMs) {
if (await probeHttp(url, 1500)) return;
await sleep(400);
}
throw new Error(`timeout waiting ${url}`);
}
function whichOnPath(bin: string): string {
try {
if (process.platform === "win32") {
const out = execFileSync("where.exe", [bin], {
encoding: "utf8",
windowsHide: true,
timeout: 3000,
});
const lines = String(out)
.split(/\r?\n/)
.map((s) => s.trim())
.filter(Boolean);
for (const line of lines) {
// Skip Windows Store python stubs
if (/WindowsApps\\python/i.test(line)) continue;
if (fs.existsSync(line)) return line;
}
return "";
}
const out = execFileSync("which", [bin], { encoding: "utf8", timeout: 3000 });
const first = String(out).trim().split(/\r?\n/)[0] || "";
return first && fs.existsSync(first) ? first : "";
} catch {
return "";
}
}
function pythonLooksGood(bin: string): boolean {
try {
execFileSync(
bin,
["-c", "from zoneinfo import ZoneInfo; ZoneInfo('Asia/Shanghai'); import fastapi"],
{ encoding: "utf8", windowsHide: true, timeout: 8000, stdio: ["ignore", "pipe", "pipe"] },
);
return true;
} catch {
return false;
}
}
export function findPython(backendDir?: string): string {
if (resolvedPython && fs.existsSync(resolvedPython) && pythonLooksGood(resolvedPython)) {
return resolvedPython;
}
const paths = resolvePaths();
const backend = backendDir || paths.backend;
const candidates: string[] = [];
if (process.env.DY_PYTHON_BIN) candidates.push(process.env.DY_PYTHON_BIN);
if (process.platform === "win32") {
candidates.push(path.join(backend, ".venv", "Scripts", "python.exe"));
candidates.push(path.join(paths.root, "backend", ".venv", "Scripts", "python.exe"));
try {
const py = execFileSync("py", ["-3", "-c", "import sys; print(sys.executable)"], {
encoding: "utf8",
windowsHide: true,
timeout: 5000,
})
.trim()
.split(/\r?\n/)[0];
if (py) candidates.push(py);
} catch {
/* ignore */
}
const fromWhere = whichOnPath("python");
if (fromWhere) candidates.push(fromWhere);
candidates.push("python");
} else {
candidates.push(path.join(backend, ".venv", "bin", "python"));
candidates.push("python3");
candidates.push("python");
}
for (const cand of candidates) {
if (!cand) continue;
if (cand.includes(path.sep) && !fs.existsSync(cand)) continue;
if (pythonLooksGood(cand)) {
resolvedPython = cand;
return cand;
}
}
// Last resort: return something spawnable so status can report failure
const fallback = process.platform === "win32" ? "python" : "python3";
resolvedPython = fallback;
return fallback;
}
export function resolveFfmpegBin(): string {
if (resolvedFfmpeg && fs.existsSync(resolvedFfmpeg)) return resolvedFfmpeg;
const exe = process.platform === "win32" ? "ffmpeg.exe" : "ffmpeg";
const candidates = [
process.env.DY_FFMPEG_BIN || "",
path.join(path.resolve(__dirname, ".."), "runtime", "ffmpeg", exe),
isPackaged() ? path.join(process.resourcesPath, "runtime", "ffmpeg", exe) : "",
whichOnPath("ffmpeg"),
].filter(Boolean);
for (const cand of candidates) {
if (fs.existsSync(cand)) {
resolvedFfmpeg = cand;
return cand;
}
}
resolvedFfmpeg = "";
return "";
}
export function getResolvedFfmpeg(): string {
return resolvedFfmpeg || resolveFfmpegBin();
}
async function ensurePocketbase(
ports: { pbPort: number },
paths: ReturnType<typeof resolvePaths>,
status: ServiceStatus,
): Promise<void> {
if (await portOpen(ports.pbPort)) {
status.pocketbase = "ok";
emitStatus(status);
return;
}
const pbExe = path.join(paths.pb, process.platform === "win32" ? "pocketbase.exe" : "pocketbase");
if (!fs.existsSync(pbExe)) {
status.pocketbase = `missing: ${pbExe}`;
emitStatus(status);
return;
}
status.pocketbase = "starting";
emitStatus(status);
spawnLogged("pocketbase", pbExe, ["serve", `--http=127.0.0.1:${ports.pbPort}`], {
cwd: paths.pb,
env: { ...process.env },
});
try {
await waitPort(ports.pbPort, 20000);
status.pocketbase = "ok";
} catch (e) {
status.pocketbase = String((e as Error).message);
}
emitStatus(status);
}
async function ensureYoutube(
ports: { ytPort: number },
paths: ReturnType<typeof resolvePaths>,
status: ServiceStatus,
): Promise<void> {
if (await portOpen(ports.ytPort)) {
status.youtube = "ok";
emitStatus(status);
return;
}
const ytPkg = path.join(paths.youtube, "package.json");
if (!fs.existsSync(ytPkg)) {
status.youtube = "skipped";
emitStatus(status);
return;
}
const nm = path.join(paths.youtube, "node_modules");
if (!fs.existsSync(nm)) {
status.youtube = "missing node_modules (cd youtube-svc && npm install)";
emitStatus(status);
return;
}
status.youtube = "starting";
emitStatus(status);
const npmCmd = process.platform === "win32" ? "npm.cmd" : "npm";
spawnLogged("youtube", npmCmd, ["start"], {
cwd: paths.youtube,
env: { ...process.env, YT_SVC_PORT: String(ports.ytPort) },
shell: process.platform === "win32",
});
try {
await waitPort(ports.ytPort, 20000);
status.youtube = "ok";
} catch {
status.youtube = "optional";
}
emitStatus(status);
}
export async function startLocalServices(ports: {
apiPort: number;
pbPort: number;
ytPort: number;
}): Promise<{ apiBase: string; status: Record<string, string> }> {
}): Promise<{ apiBase: string; status: ServiceStatus }> {
const paths = resolvePaths();
const status: Record<string, string> = {};
const status: ServiceStatus = { boot: "starting" };
const apiBase = `http://127.0.0.1:${ports.apiPort}`;
emitStatus(status);
// Fast path: ports already open (avoid HTTP probes that can hang a wedged stack)
if (await portOpen(ports.apiPort)) {
const ffEarly = resolveFfmpegBin();
status.ffmpeg = ffEarly || "missing (npm run fetch-ffmpeg or install PATH)";
emitStatus(status);
// Reuse only if API answers HTTP (not just TCP)
if (await probeHttp(`${apiBase}/api/ping`, 800)) {
status.api = "ok";
status.pocketbase = (await portOpen(ports.pbPort)) ? "ok" : "down";
status.youtube = (await portOpen(ports.ytPort)) ? "ok" : "optional";
console.log("[boot] reuse open ports", status);
status.boot = "ok";
console.log("[boot] reuse healthy API", status);
emitStatus(status);
return { apiBase, status };
}
// --- PocketBase ---
if (!(await portOpen(ports.pbPort))) {
const pbExe = path.join(paths.pb, process.platform === "win32" ? "pocketbase.exe" : "pocketbase");
if (!fs.existsSync(pbExe)) {
status.pocketbase = `missing: ${pbExe}`;
} else {
spawnLogged("pocketbase", pbExe, ["serve", `--http=127.0.0.1:${ports.pbPort}`], {
cwd: paths.pb,
env: { ...process.env },
});
try {
await waitPort(ports.pbPort, 20000);
status.pocketbase = "ok";
} catch (e) {
status.pocketbase = String((e as Error).message);
}
}
} else {
status.pocketbase = "ok";
}
// PocketBase + youtube-svc in parallel
await Promise.all([
ensurePocketbase(ports, paths, status),
ensureYoutube(ports, paths, status),
]);
// --- youtube-svc (optional) ---
if (!(await portOpen(ports.ytPort))) {
const ytPkg = path.join(paths.youtube, "package.json");
if (!fs.existsSync(ytPkg)) {
status.youtube = "skipped";
} else {
const npmCmd = process.platform === "win32" ? "npm.cmd" : "npm";
spawnLogged("youtube", npmCmd, ["start"], {
cwd: paths.youtube,
env: { ...process.env, YT_SVC_PORT: String(ports.ytPort) },
shell: process.platform === "win32",
});
status.youtube = "optional";
void waitPort(ports.ytPort, 20000)
.then(() => {
status.youtube = "ok";
})
.catch(() => {
status.youtube = "optional";
});
}
} else {
status.youtube = "ok";
}
// --- FastAPI ---
if (await portOpen(ports.apiPort)) {
// FastAPI
if (await probeHttp(`${apiBase}/api/ping`, 600)) {
status.api = "ok";
} else if (await portOpen(ports.apiPort)) {
// Port open but ping failing — wait briefly for readiness
status.api = "warming";
emitStatus(status);
try {
await waitHttp(`${apiBase}/api/ping`, 20000);
status.api = "ok";
} catch (e) {
status.api = String((e as Error).message);
}
} else {
const python = findPython();
const env = {
...process.env,
const python = findPython(paths.backend);
status.python = python;
if (!pythonLooksGood(python)) {
status.api = "python missing deps (npm run ensure-python)";
status.boot = "failed";
emitStatus(status);
console.error("[boot] python not ready", python);
return { apiBase, status };
}
const env: Record<string, string> = {
...(process.env as Record<string, string>),
DY_PB_URL: `http://127.0.0.1:${ports.pbPort}`,
DY_YOUTUBE_SVC_URL: `http://127.0.0.1:${ports.ytPort}`,
DY_API_HOST: "127.0.0.1",
DY_API_PORT: String(ports.apiPort),
DY_AUTH_ENABLED: "false",
DY_DISABLE_LIVE_MAP_LOOP: "true",
// Keep event loop free for UI clicks on Windows desktop
DY_DESKTOP_LIGHT: "true",
// Full Windows client: start monitor / youtube_relay / shorts workers.
DY_DESKTOP_LIGHT: "false",
DY_DISABLE_LIVE_MAP_LOOP: "false",
DY_NEKO_ENABLED: process.env.DY_NEKO_ENABLED || "false",
DY_CORS_ORIGINS: [
"http://127.0.0.1:5173",
"http://localhost:5173",
@ -249,27 +399,36 @@ export async function startLocalServices(ports: {
TZ: "Asia/Shanghai",
PYTHONUTF8: "1",
};
const proc = spawnLogged(
"api",
python,
["run_desktop_api.py"],
{ cwd: paths.backend, env },
);
const ffmpegBin = resolveFfmpegBin();
if (ffmpegBin) {
env.DY_FFMPEG_BIN = ffmpegBin;
status.ffmpeg = ffmpegBin;
} else {
status.ffmpeg = "missing (npm run fetch-ffmpeg or install PATH)";
}
status.api = "starting";
emitStatus(status);
const proc = spawnLogged("api", python, ["run_desktop_api.py"], {
cwd: paths.backend,
env,
});
let spawnFailed = false;
proc.once("exit", (code) => {
if (code && code !== 0) spawnFailed = true;
});
try {
await waitPort(ports.apiPort, 45000);
await waitHttp(`${apiBase}/api/ping`, 45000);
status.api = "ok";
} catch (e) {
status.api = spawnFailed
? "api process exited (port busy?)"
? "api process exited (deps? port busy?)"
: String((e as Error).message);
}
}
status.boot = status.api === "ok" ? "ok" : "degraded";
console.log("[boot] services", status);
emitStatus(status);
return { apiBase, status };
}
@ -291,6 +450,16 @@ export function stopLocalServices(): void {
children.length = 0;
}
export async function restartLocalServices(ports: {
apiPort: number;
pbPort: number;
ytPort: number;
}): Promise<{ apiBase: string; status: ServiceStatus }> {
stopLocalServices();
await sleep(800);
return startLocalServices(ports);
}
export function listServicePids(): { name: ServiceName; pid?: number }[] {
return children.map((c) => ({ name: c.name, pid: c.proc.pid }));
}

View File

@ -40,29 +40,56 @@ function proxy(req: http.IncomingMessage, res: http.ServerResponse, apiBase: str
req.pipe(preq);
}
function cacheHeaders(urlPath: string, ext: string): Record<string, string> {
// Vite hashed assets under /assets/
if (urlPath.startsWith("/assets/") || /\.[a-f0-9]{8,}\.(js|css)$/i.test(urlPath)) {
return { "Cache-Control": "public, max-age=31536000, immutable" };
}
if (ext === ".html") {
return { "Cache-Control": "no-cache" };
}
if (ext === ".woff2" || ext === ".png" || ext === ".jpg" || ext === ".svg" || ext === ".ico") {
return { "Cache-Control": "public, max-age=86400" };
}
return { "Cache-Control": "public, max-age=3600" };
}
export function startUiServer(opts: {
distDir: string;
apiBase: string;
port?: number;
}): Promise<{ port: number; url: string; close: () => void }> {
const port = opts.port ?? 18574;
const distDir = path.resolve(opts.distDir);
const server = http.createServer((req, res) => {
const url = req.url || "/";
if (url.startsWith("/api") || url.startsWith("/covers")) {
// Renderer talks to API directly; only proxy media that may be relative.
if (url.startsWith("/covers")) {
proxy(req, res, opts.apiBase);
return;
}
let filePath = path.join(opts.distDir, url === "/" ? "index.html" : decodeURIComponent(url.split("?")[0]));
if (!filePath.startsWith(opts.distDir)) {
const rawPath = decodeURIComponent(url.split("?")[0] || "/");
let filePath = path.join(distDir, rawPath === "/" ? "index.html" : rawPath);
if (!filePath.startsWith(distDir)) {
res.writeHead(403);
res.end("forbidden");
return;
}
if (!fs.existsSync(filePath) || fs.statSync(filePath).isDirectory()) {
filePath = path.join(opts.distDir, "index.html");
let st: fs.Stats | null = null;
try {
st = fs.statSync(filePath);
} catch {
st = null;
}
if (!st || st.isDirectory()) {
filePath = path.join(distDir, "index.html");
}
const ext = path.extname(filePath).toLowerCase();
res.writeHead(200, { "Content-Type": MIME[ext] || "application/octet-stream" });
const headers: Record<string, string> = {
"Content-Type": MIME[ext] || "application/octet-stream",
...cacheHeaders(rawPath, ext),
};
res.writeHead(200, headers);
fs.createReadStream(filePath).pipe(res);
});

View File

@ -2,7 +2,7 @@
"name": "douyinweb-desktop",
"version": "0.1.0",
"private": true,
"description": "抖音直播监控 Windows 客户端(本地 FastAPI + PocketBase)",
"description": "抖音直播监控 + YouTube 无人直播 · 唯一 Windows 客户端",
"main": "dist-electron/main.js",
"author": "douyinWEB",
"scripts": {
@ -12,7 +12,12 @@
"build": "npm run build:renderer && npm run build:electron",
"start": "npm run build:electron && electron .",
"electron:dev": "npm run build:electron && concurrently -k \"vite\" \"wait-on http://127.0.0.1:5173 && electron .\"",
"pack": "npm run build && electron-builder --win",
"fetch-ffmpeg": "powershell -ExecutionPolicy Bypass -File scripts/fetch-ffmpeg.ps1",
"fetch-pocketbase": "powershell -ExecutionPolicy Bypass -File scripts/fetch-pocketbase.ps1",
"ensure-python": "powershell -ExecutionPolicy Bypass -File scripts/ensure-python.ps1",
"prepare:runtime": "npm run fetch-pocketbase && npm run fetch-ffmpeg && npm run ensure-python",
"prepare:pack": "npm run prepare:runtime && npm --prefix ../youtube-svc install --omit=dev",
"pack": "npm run prepare:pack && npm run build && electron-builder --win",
"dist": "npm run pack"
},
"dependencies": {
@ -53,17 +58,38 @@
{
"from": "../backend",
"to": "runtime/backend",
"filter": ["**/*", "!**/__pycache__/**", "!**/.venv/**", "!**/venv/**"]
"filter": [
"**/*",
"!**/__pycache__/**",
"!**/.venv/**",
"!**/venv/**",
"!**/data/**/*.db",
"!**/data/**/*.db-*",
"!**/data/covers/**",
"!**/data/clips/**",
"!**/*.pyc"
]
},
{
"from": "../pb",
"to": "runtime/pb",
"filter": ["**/*"]
"filter": [
"**/*",
"!pb_data/**",
"!**/*.exe~",
"!CHANGELOG.md",
"!LICENSE.md"
]
},
{
"from": "../youtube-svc",
"to": "runtime/youtube-svc",
"filter": ["**/*", "!node_modules/**"]
"filter": ["**/*", "!**/.git/**", "!**/*.md"]
},
{
"from": "runtime/ffmpeg",
"to": "runtime/ffmpeg",
"filter": ["ffmpeg.exe", "ffprobe.exe", "*.dll"]
}
],
"win": {

View File

View File

@ -0,0 +1,19 @@
# Ensure Windows Python can import backend (tzdata for Asia/Shanghai, etc.)
$ErrorActionPreference = "Stop"
$RepoRoot = Split-Path -Parent (Split-Path -Parent $PSScriptRoot)
$Req = Join-Path $RepoRoot "backend\requirements.txt"
Write-Host "Checking Python backend deps..."
python -c "from zoneinfo import ZoneInfo; ZoneInfo('Asia/Shanghai'); import fastapi" 2>$null
if ($LASTEXITCODE -eq 0) {
Write-Host "Python deps OK (skip pip)"
exit 0
}
Write-Host "Installing backend requirements..."
if (Test-Path $Req) {
python -m pip install -r $Req
} else {
python -m pip install "tzdata>=2024.1" "fastapi==0.115.6" "uvicorn[standard]==0.34.0"
}
python -c "from zoneinfo import ZoneInfo; ZoneInfo('Asia/Shanghai'); import fastapi; print('Python deps OK')"

View File

@ -0,0 +1,46 @@
# Download static ffmpeg into desktop/runtime/ffmpeg/ (Windows x64 essentials)
$ErrorActionPreference = "Stop"
$Root = Split-Path -Parent $PSScriptRoot
$Dest = Join-Path $Root "runtime\ffmpeg"
$DestExe = Join-Path $Dest "ffmpeg.exe"
New-Item -ItemType Directory -Force -Path $Dest | Out-Null
if ((Test-Path $DestExe) -and -not $env:DY_FFMPEG_FORCE) {
Write-Host "OK (exists) -> $DestExe"
& $DestExe -version | Select-Object -First 1
exit 0
}
$Zip = Join-Path $env:TEMP "dy-desktop-ffmpeg.zip"
# Smaller essentials build (enough for RTMPS relay / Shorts)
$Url = "https://github.com/BtbN/FFmpeg-Builds/releases/download/latest/ffmpeg-master-latest-win64-gpl-shared.zip"
# Fallback to full static gpl if essentials URL shape changes — prefer shared/essentials when available
$UrlStatic = "https://github.com/BtbN/FFmpeg-Builds/releases/download/latest/ffmpeg-master-latest-win64-gpl.zip"
Write-Host "Downloading ffmpeg..."
try {
Invoke-WebRequest -Uri $Url -OutFile $Zip -UseBasicParsing
} catch {
Write-Host "shared build failed, trying full static..."
Invoke-WebRequest -Uri $UrlStatic -OutFile $Zip -UseBasicParsing
}
$Extract = Join-Path $env:TEMP "dy-desktop-ffmpeg-extract"
if (Test-Path $Extract) { Remove-Item -Recurse -Force $Extract }
Expand-Archive -Path $Zip -DestinationPath $Extract -Force
$Bin = Get-ChildItem -Path $Extract -Recurse -Filter "ffmpeg.exe" | Select-Object -First 1
if (-not $Bin) { throw "ffmpeg.exe not found in archive" }
Copy-Item $Bin.FullName $DestExe -Force
$Probe = Get-ChildItem -Path $Extract -Recurse -Filter "ffprobe.exe" | Select-Object -First 1
if ($Probe) {
Copy-Item $Probe.FullName (Join-Path $Dest "ffprobe.exe") -Force
}
# Copy sibling DLLs if shared build
Get-ChildItem -Path $Bin.Directory.FullName -Filter "*.dll" -ErrorAction SilentlyContinue |
ForEach-Object { Copy-Item $_.FullName (Join-Path $Dest $_.Name) -Force }
Write-Host "OK -> $DestExe"
& $DestExe -version | Select-Object -First 1

View File

@ -0,0 +1,28 @@
# Download PocketBase Windows x64 into repo pb/pocketbase.exe
$ErrorActionPreference = "Stop"
$RepoRoot = Split-Path -Parent (Split-Path -Parent $PSScriptRoot)
$DestDir = Join-Path $RepoRoot "pb"
$DestExe = Join-Path $DestDir "pocketbase.exe"
$Ver = if ($env:PB_VER) { $env:PB_VER } else { "0.25.8" }
New-Item -ItemType Directory -Force -Path $DestDir | Out-Null
if (Test-Path $DestExe) {
Write-Host "OK (exists) -> $DestExe"
& $DestExe --version
exit 0
}
$Zip = Join-Path $env:TEMP "dy-desktop-pocketbase.zip"
$Url = "https://github.com/pocketbase/pocketbase/releases/download/v$Ver/pocketbase_${Ver}_windows_amd64.zip"
Write-Host "Downloading PocketBase $Ver ..."
Invoke-WebRequest -Uri $Url -OutFile $Zip -UseBasicParsing
$Extract = Join-Path $env:TEMP "dy-desktop-pocketbase-extract"
if (Test-Path $Extract) { Remove-Item -Recurse -Force $Extract }
Expand-Archive -Path $Zip -DestinationPath $Extract -Force
$Bin = Get-ChildItem -Path $Extract -Recurse -Filter "pocketbase.exe" | Select-Object -First 1
if (-not $Bin) { throw "pocketbase.exe not found in archive" }
Copy-Item $Bin.FullName $DestExe -Force
Write-Host "OK -> $DestExe"
& $DestExe --version

View File

@ -1,15 +1,16 @@
import { Suspense, lazy } from "react";
import { Suspense, lazy, useEffect } from "react";
import { BrowserRouter, Navigate, Route, Routes } from "react-router-dom";
import { Loader2 } from "lucide-react";
import { Providers } from "@/components/Providers";
import { AuthGate } from "@/components/AuthGate";
import { LiveRadarProviders } from "@/components/Shell";
import { ServiceBanner } from "@/components/ServiceBanner";
import LoginPage from "@/pages/LoginPage";
import OverviewPage from "@/pages/OverviewPage";
import ShortsPage from "@/pages/ShortsPage";
import SettingsPage from "@/pages/SettingsPage";
const OverviewPage = lazy(() => import("@/pages/OverviewPage"));
const ShortsPage = lazy(() => import("@/pages/ShortsPage"));
const SettingsPage = lazy(() => import("@/pages/SettingsPage"));
const SlotsPage = lazy(() => import("@/pages/SlotsPage"));
const SessionsPage = lazy(() => import("@/pages/SessionsPage"));
const AnchorsPage = lazy(() => import("@/pages/AnchorsPage"));
@ -18,6 +19,7 @@ const EventsPage = lazy(() => import("@/pages/EventsPage"));
const RoomsPage = lazy(() => import("@/pages/RoomsPage"));
const GroupsPage = lazy(() => import("@/pages/GroupsPage"));
const YoutubePage = lazy(() => import("@/pages/YoutubePage"));
const LiveUnmannedPage = lazy(() => import("@/pages/LiveUnmannedPage"));
const BlacklistPage = lazy(() => import("@/pages/BlacklistPage"));
function PageFallback() {
@ -28,31 +30,47 @@ function PageFallback() {
);
}
function PrefetchHotRoutes() {
useEffect(() => {
const t = window.setTimeout(() => {
void import("@/pages/LiveUnmannedPage");
void import("@/pages/OverviewPage");
void import("@/pages/RoomsPage");
}, 900);
return () => window.clearTimeout(t);
}, []);
return null;
}
export default function App() {
return (
<Providers>
<BrowserRouter>
<ServiceBanner />
<Suspense fallback={<PageFallback />}>
<Routes>
<Route path="/login" element={<LoginPage />} />
<Route element={<AuthGate />}>
<Route path="/" element={<OverviewPage />} />
<Route path="/slots" element={<SlotsPage />} />
<Route path="/sessions" element={<SessionsPage />} />
<Route path="/anchors" element={<AnchorsPage />} />
<Route path="/covers" element={<CoversPage />} />
<Route path="/events" element={<EventsPage />} />
<Route path="/rooms" element={<RoomsPage />} />
<Route path="/groups" element={<GroupsPage />} />
<Route path="/youtube" element={<YoutubePage />} />
<Route path="/shorts" element={<ShortsPage />} />
<Route path="/blacklist" element={<BlacklistPage />} />
<Route path="/settings" element={<SettingsPage />} />
</Route>
<Route path="*" element={<Navigate to="/" replace />} />
</Routes>
</Suspense>
<LiveRadarProviders>
<ServiceBanner />
<PrefetchHotRoutes />
<Suspense fallback={<PageFallback />}>
<Routes>
<Route path="/login" element={<LoginPage />} />
<Route element={<AuthGate />}>
<Route path="/" element={<OverviewPage />} />
<Route path="/slots" element={<SlotsPage />} />
<Route path="/sessions" element={<SessionsPage />} />
<Route path="/anchors" element={<AnchorsPage />} />
<Route path="/covers" element={<CoversPage />} />
<Route path="/events" element={<EventsPage />} />
<Route path="/rooms" element={<RoomsPage />} />
<Route path="/groups" element={<GroupsPage />} />
<Route path="/youtube" element={<YoutubePage />} />
<Route path="/live" element={<LiveUnmannedPage />} />
<Route path="/shorts" element={<ShortsPage />} />
<Route path="/blacklist" element={<BlacklistPage />} />
<Route path="/settings" element={<SettingsPage />} />
</Route>
<Route path="*" element={<Navigate to="/" replace />} />
</Routes>
</Suspense>
</LiveRadarProviders>
</BrowserRouter>
</Providers>
);

View File

@ -0,0 +1,43 @@
import { useEffect, useRef, useState, type ReactNode } from "react";
/** Mount children only when the sentinel enters the viewport (or after idle). */
export function LazyMount({
children,
rootMargin = "200px",
fallback = null,
minHeight = 120,
}: {
children: ReactNode;
rootMargin?: string;
fallback?: ReactNode;
minHeight?: number;
}) {
const ref = useRef<HTMLDivElement>(null);
const [show, setShow] = useState(false);
useEffect(() => {
const el = ref.current;
if (!el || show) return;
if (typeof IntersectionObserver === "undefined") {
setShow(true);
return;
}
const io = new IntersectionObserver(
(entries) => {
if (entries.some((e) => e.isIntersecting)) {
setShow(true);
io.disconnect();
}
},
{ rootMargin },
);
io.observe(el);
return () => io.disconnect();
}, [rootMargin, show]);
return (
<div ref={ref} style={{ minHeight: show ? undefined : minHeight }}>
{show ? children : fallback}
</div>
);
}

View File

@ -1,28 +1,55 @@
import { useEffect, useState } from "react";
function statusLine(st: Record<string, unknown> | null): string {
if (!st) return "";
const pb = String(st.pocketbase || "");
const api = String(st.api || "");
const ff = String(st.ffmpeg || "");
const boot = String(st.boot || "");
if (pb.startsWith("missing")) {
return "缺少 PocketBase:在 desktop 执行 npm run fetch-pocketbase";
}
if (ff.startsWith("missing") && api === "ok") {
return "FFmpeg 未就绪:无人直播/Shorts 不可用 — npm run fetch-ffmpeg";
}
if (api === "ok" || boot === "ok") return "";
if (api.includes("python missing")) return api;
if (api.includes("exited") || api.includes("timeout")) {
return `本地 API 异常:${api}`;
}
if (boot === "starting" || api === "starting" || api === "warming" || pb === "starting") {
return `正在启动本地服务… PB ${pb || "…"} · API ${api || "…"} · YT ${String(st.youtube || "…")}`;
}
if (String(st.boot || "").trim() && boot !== "ok" && boot !== "degraded") {
return "正在启动本地服务…";
}
return "";
}
export function ServiceBanner() {
const [msg, setMsg] = useState("");
const [booting, setBooting] = useState(true);
useEffect(() => {
let cancelled = false;
const check = async () => {
const apply = (st: Record<string, unknown> | null) => {
if (cancelled) return;
const line = statusLine(st);
setMsg(line);
const apiOk = String(st?.api || "") === "ok";
setBooting(!apiOk);
};
const checkHttp = async () => {
if (window.desktop?.getServiceStatus) {
try {
const st = await window.desktop.getServiceStatus();
if (cancelled) return;
const apiOk = String(st?.api || "") === "ok";
if (apiOk) {
setMsg("");
return;
}
if (String(st?.boot || "").trim()) {
setMsg("正在启动本地服务…");
return;
}
apply(st);
if (String(st?.api || "") === "ok") return;
} catch {
/* fall through */
}
}
const ctrl = new AbortController();
const t = window.setTimeout(() => ctrl.abort(), 2500);
try {
@ -33,20 +60,29 @@ export function ServiceBanner() {
cache: "no-store",
});
if (cancelled) return;
setMsg(res.ok ? "" : `API 异常 HTTP ${res.status}`);
if (res.ok) {
setMsg("");
setBooting(false);
} else {
setMsg(`API 异常 HTTP ${res.status}`);
}
} catch {
if (!cancelled) setMsg("正在连接本地 API…");
if (!cancelled && !window.desktop) setMsg("正在连接本地 API…");
} finally {
window.clearTimeout(t);
}
};
void check();
const id = window.setInterval(() => void check(), 12000);
void checkHttp();
const unsub = window.desktop?.onServiceStatus?.((st) => apply(st));
const id = window.setInterval(() => void checkHttp(), booting ? 2500 : 15000);
return () => {
cancelled = true;
window.clearInterval(id);
unsub?.();
};
}, []);
}, [booting]);
if (!msg) return null;
return (
<div className="pointer-events-none fixed left-0 right-0 top-0 z-[100] bg-amber-500/90 px-4 py-2 text-center text-xs text-black">

View File

@ -40,10 +40,11 @@ function useEchart(option: Record<string, unknown> | null, height: number) {
const el = ref.current;
if (!el || !option) return;
let disposed = false;
let chart: import("echarts").ECharts | null = null;
let chart: import("@/lib/echartsSlim").EChartsType | null = null;
const onResize = () => chart?.resize();
import("echarts").then((echarts) => {
void import("@/lib/echartsSlim").then((mod) => {
if (disposed || !ref.current) return;
const echarts = mod.default;
chart = echarts.init(ref.current, undefined, { renderer: "canvas" });
chart.setOption(option, true);
window.addEventListener("resize", onResize);

View File

@ -10,6 +10,7 @@ import { Link } from "react-router-dom";
const NAV = [
{ href: "/", label: "概览", emoji: "📡" },
{ href: "/live", label: "无人直播", emoji: "🔴" },
{ href: "/slots", label: "时段", emoji: "🕐" },
{ href: "/sessions", label: "场次", emoji: "🎬" },
{ href: "/anchors", label: "主播", emoji: "👤" },
@ -23,20 +24,23 @@ const NAV = [
{ href: "/settings", label: "设置", emoji: "⚙️" },
];
const MOBILE_PRIMARY = ["/", "/groups", "/shorts", "/youtube", "/settings"];
const MOBILE_PRIMARY = ["/", "/live", "/rooms", "/youtube", "/settings"];
export function Shell({ children }: { children: React.ReactNode }) {
/** App-level singleton providers — avoid remounting live-map polls on every page. */
export function LiveRadarProviders({ children }: { children: React.ReactNode }) {
const ytCtx = useYouTubeLiveProviderValue();
const dyCtx = useDouyinLiveProviderValue();
return (
<YouTubeLiveContextProvider value={ytCtx}>
<DouyinLiveContextProvider value={dyCtx}>
<ShellFrame>{children}</ShellFrame>
</DouyinLiveContextProvider>
<DouyinLiveContextProvider value={dyCtx}>{children}</DouyinLiveContextProvider>
</YouTubeLiveContextProvider>
);
}
export function Shell({ children }: { children: React.ReactNode }) {
return <ShellFrame>{children}</ShellFrame>;
}
function ShellFrame({ children }: { children: React.ReactNode }) {
const pathname = useLocation().pathname;
const navigate = useNavigate();
@ -49,7 +53,7 @@ function ShellFrame({ children }: { children: React.ReactNode }) {
void fetchJson("/api/auth/status")
.then((d) => setUsername(String(d.username || "")))
.catch(() => setUsername(""));
}, [pathname]);
}, []);
async function logout() {
try {
@ -77,7 +81,7 @@ function ShellFrame({ children }: { children: React.ReactNode }) {
直播监控中心
</h1>
<p className="mt-1 max-w-2xl text-sm text-slate-400">
抖音 + YouTube · 开播捕捉 · 停播结场 · 时长统计 · 截图存证 · Windows 客户端
抖音 + YouTube · 无人直播 · 开播捕捉 · Shorts · Windows 唯一客户端
</p>
{(dyLiveCount > 0 || ytLiveCount > 0) ? (
<div className="mt-2 flex flex-wrap items-center gap-2">

View File

@ -121,6 +121,31 @@ export function EmptyState({
);
}
export function SectionCard({
title,
emoji,
children,
action,
}: {
title: string;
emoji?: string;
children: ReactNode;
action?: ReactNode;
}) {
return (
<section className="glass-panel animate-fade-up rounded-3xl p-5 sm:p-6">
<div className="mb-4 flex flex-wrap items-center justify-between gap-2">
<h3 className="flex items-center gap-2 font-display text-lg font-semibold text-white">
{emoji ? <span>{emoji}</span> : null}
{title}
</h3>
{action}
</div>
{children}
</section>
);
}
export function PlatformBadge({
platform,
className = "",

View File

@ -14,11 +14,13 @@ declare global {
getConfig: () => Promise<Record<string, unknown>>;
setConfig: (patch: Record<string, unknown>) => Promise<Record<string, unknown>>;
getServiceStatus: () => Promise<Record<string, unknown>>;
restartServices: () => Promise<Record<string, unknown>>;
notify: (title: string, body: string) => Promise<void>;
openExternal: (url: string) => Promise<void>;
openLogs: () => Promise<void>;
getDiagnostics: () => Promise<Record<string, unknown>>;
onWindowFocus: (cb: (focused: boolean) => void) => () => void;
onServiceStatus: (cb: (status: Record<string, unknown>) => void) => () => void;
minimizeToTray: () => Promise<void>;
};
}

View File

@ -1,7 +1,6 @@
import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from "react";
import { fetchJson } from "@/lib/api";
import { useEventStream } from "@/lib/realtime";
export type DouyinLiveEntry = {
is_live?: boolean;
@ -33,7 +32,6 @@ const DouyinLiveContext = createContext<{
export function useDouyinLiveProviderValue(intervalMs = 25000) {
const [map, setMap] = useState<DouyinLiveMap | null>(null);
const [loading, setLoading] = useState(false);
const { tick, last } = useEventStream(true);
const inFlight = useRef(false);
const refresh = useCallback(async (silent = false) => {
@ -67,14 +65,6 @@ export function useDouyinLiveProviderValue(intervalMs = 25000) {
};
}, [intervalMs, refresh]);
useEffect(() => {
if (!last?.kind) return;
if (!["live", "offline", "risk"].includes(String(last.kind))) return;
if (document.hidden) return;
void refresh(true);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [tick]);
return useMemo(
() => ({
map,

View File

@ -0,0 +1,25 @@
/** Tree-shaken echarts — only charts used by SessionCharts. */
import * as echarts from "echarts/core";
import { BarChart, HeatmapChart, LineChart, PieChart } from "echarts/charts";
import {
GridComponent,
LegendComponent,
TooltipComponent,
VisualMapComponent,
} from "echarts/components";
import { CanvasRenderer } from "echarts/renderers";
echarts.use([
BarChart,
LineChart,
HeatmapChart,
PieChart,
GridComponent,
TooltipComponent,
LegendComponent,
VisualMapComponent,
CanvasRenderer,
]);
export type EChartsType = echarts.ECharts;
export default echarts;

View File

@ -15,6 +15,12 @@ export type StreamEvent = {
export type RefreshOpts = { silent?: boolean };
/**
* Windows desktop sole-client: poll only.
* SSE EventSource historically wedged the local FastAPI connection pool.
*/
export const DESKTOP_POLL_ONLY = true;
function useDesktopFocused(defaultFocused = true) {
const [focused, setFocused] = useState(defaultFocused);
useEffect(() => {
@ -29,16 +35,20 @@ function useDesktopFocused(defaultFocused = true) {
return focused;
}
/** One shared EventSource — avoid reconnect storms starving fetch. */
/** One shared EventSource — unused when DESKTOP_POLL_ONLY. */
let sharedEs: EventSource | null = null;
let sharedEsUrl = "";
let sharedEsRefCount = 0;
const sharedListeners = new Set<(ev: StreamEvent) => void>();
const sharedOpenListeners = new Set<(ok: boolean) => void>();
let sharedEsPaused = false;
let sharedEsPaused = DESKTOP_POLL_ONLY;
/** Pause SSE while API is wedged (desktop boot / health fail). */
/** Pause SSE while API is wedged (kept for non-desktop / restore). */
export function setEventStreamPaused(paused: boolean) {
if (DESKTOP_POLL_ONLY) {
sharedEsPaused = true;
return;
}
sharedEsPaused = Boolean(paused);
if (sharedEsPaused && sharedEs) {
try {
@ -54,6 +64,7 @@ export function setEventStreamPaused(paused: boolean) {
}
function acquireSharedEventSource() {
if (DESKTOP_POLL_ONLY) return null;
sharedEsRefCount += 1;
if (sharedEsPaused) return null;
const url = apiUrl("/api/events/stream");
@ -80,7 +91,6 @@ function acquireSharedEventSource() {
sharedEs = null;
window.setTimeout(() => {
if (!sharedEsPaused && sharedEsRefCount > 0 && !sharedEs) {
// reconnect without bumping refcount
sharedEsRefCount = Math.max(0, sharedEsRefCount - 1);
acquireSharedEventSource();
}
@ -98,6 +108,7 @@ function acquireSharedEventSource() {
}
function releaseSharedEventSource() {
if (DESKTOP_POLL_ONLY) return;
sharedEsRefCount = Math.max(0, sharedEsRefCount - 1);
if (sharedEsRefCount === 0 && sharedEs) {
try {
@ -117,7 +128,10 @@ export function useEventStream(enabled = true) {
const focused = useDesktopFocused(true);
useEffect(() => {
if (!enabled) return;
if (DESKTOP_POLL_ONLY || !enabled) {
setConnected(false);
return;
}
const onMsg = (data: StreamEvent) => {
setLast(data);
setTick((n) => n + 1);
@ -146,7 +160,11 @@ export function useAutoRefresh(
) {
const intervalMs = opts?.intervalMs ?? 30000;
const enabled = opts?.enabled !== false;
const eventKinds = opts?.eventKinds === false ? null : opts?.eventKinds ?? ["live", "offline", "risk"];
// Desktop: never open SSE for refresh kicks
const eventKinds =
DESKTOP_POLL_ONLY || opts?.eventKinds === false
? null
: opts?.eventKinds ?? ["live", "offline", "risk"];
const { connected, last, tick, focused } = useEventStream(Boolean(eventKinds) && enabled);
const loadRef = useRef(load);
loadRef.current = load;
@ -156,7 +174,10 @@ export function useAutoRefresh(
void loadRef.current({ silent: false });
if (!intervalMs || intervalMs <= 0) return;
const ms = focused ? intervalMs : Math.max(intervalMs * 3, 60000);
const t = window.setInterval(() => void loadRef.current({ silent: true }), ms);
const t = window.setInterval(() => {
if (document.hidden) return;
void loadRef.current({ silent: true });
}, ms);
return () => window.clearInterval(t);
}, [load, intervalMs, enabled, focused]);
@ -172,10 +193,12 @@ export function useAutoRefresh(
export function useNow(intervalMs = 1000) {
const [now, setNow] = useState(() => Date.now());
const focused = useDesktopFocused(true);
useEffect(() => {
if (!focused) return;
const t = setInterval(() => setNow(Date.now()), intervalMs);
return () => clearInterval(t);
}, [intervalMs]);
}, [intervalMs, focused]);
return now;
}

View File

@ -7,8 +7,6 @@ import "./styles/globals.css";
// Never block first paint on IPC
setApiBase("http://127.0.0.1:8014");
// Hold SSE until /api/health succeeds (avoids wedging API on boot)
void import("./lib/realtime").then((m) => m.setEventStreamPaused(true));
createRoot(document.getElementById("root")!).render(
<StrictMode>
@ -16,7 +14,6 @@ createRoot(document.getElementById("root")!).render(
</StrictMode>,
);
// Optional: refresh apiBase from Electron store (non-blocking)
void window.desktop?.getConfig?.()
.then((cfg) => {
const base = String(cfg?.apiBase || "").trim();

View File

@ -120,7 +120,7 @@ export default function EventsPage() {
}, [tick, last, kind, platform, q]);
const liveHint = useMemo(
() => (connected ? "SSE 实时推送中" : "SSE 重连中 · 可手动刷新"),
() => (connected ? "实时推送中" : "轮询模式 · 可手动刷新"),
[connected],
);

View File

@ -1,4 +1,4 @@
import { useCallback, useEffect, useMemo, useState } from "react";
import { lazy, Suspense, useCallback, useEffect, useMemo, useState } from "react";
import { Link } from "react-router-dom";
import { Loader2, Pencil, Plus, Trash2, Download, Zap } from "lucide-react";
@ -6,12 +6,17 @@ import { Shell } from "@/components/Shell";
import { useConfirm } from "@/components/ConfirmDialog";
import { useToast } from "@/components/Toast";
import { Modal } from "@/components/Modal";
import { SessionCharts, type RelayStats } from "@/components/SessionCharts";
import { LazyMount } from "@/components/LazyMount";
import { type RelayStats } from "@/components/SessionCharts";
import { YouTubeLiveBadge } from "@/components/YouTubeLiveBadge";
import { fetchJson, fmtDuration, fmtTs, todayBeijingISO, shiftBeijingISO } from "@/lib/api";
import { groupLiveRef } from "@/lib/youtubeLive";
import { useAutoRefresh, type RefreshOpts } from "@/lib/realtime";
const SessionCharts = lazy(() =>
import("@/components/SessionCharts").then((m) => ({ default: m.SessionCharts })),
);
type Group = {
id: string;
name: string;
@ -489,7 +494,14 @@ export default function GroupsPage() {
<section className="rounded-2xl border border-white/10 bg-black/25 p-4">
<h3 className="mb-3 font-display text-sm font-medium text-slate-100">可视化分析</h3>
<SessionCharts stats={ytStats} />
<LazyMount
minHeight={240}
fallback={<div className="py-12 text-center text-xs text-slate-600">图表进入视口后加载…</div>}
>
<Suspense fallback={<div className="py-12 text-center text-xs text-slate-600">加载图表…</div>}>
<SessionCharts stats={ytStats} />
</Suspense>
</LazyMount>
</section>
<section className="overflow-hidden rounded-2xl border border-white/10 bg-black/25">

View File

@ -0,0 +1,542 @@
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
ClipboardPaste,
ExternalLink,
Eye,
EyeOff,
Loader2,
Power,
RefreshCw,
Save,
Search,
} from "lucide-react";
import { Shell } from "@/components/Shell";
import { LivePulse, SectionCard, StatTile } from "@/components/ui";
import { useToast } from "@/components/Toast";
import { fetchJson } from "@/lib/api";
type AssignGroup = {
id: string;
name?: string;
stream_key?: string;
has_stream_key?: boolean;
enabled?: boolean;
featured?: Array<{ id?: string; url?: string; pool_url_id?: string }>;
pool?: Array<{ id: string; url?: string }>;
};
type RelayStatus = {
running?: boolean;
youtube_relay_enabled?: boolean;
groups?: Array<{
group_id?: string;
business_status?: string;
is_pushing?: boolean;
ffmpeg_pid?: number;
ffmpeg_speed?: number;
ffmpeg_frame?: number;
source_url?: string;
error?: string;
recent_log?: string;
}>;
process_monitor?: Array<{
group_id?: string;
business_status?: string;
is_pushing?: boolean;
ffmpeg_pid?: number;
ffmpeg_speed?: number | null;
ffmpeg_frame?: number | null;
source_display?: string;
recent_error?: string;
}>;
};
const LABEL: Record<string, string> = {
streaming: "推流中",
waiting_source: "等待直播",
source_live: "源已开播",
relay_starting: "转推启动中",
ready: "已配置",
inactive: "未运行",
misconfigured: "密钥异常",
error: "异常",
};
export default function LiveUnmannedPage() {
const toast = useToast();
const [group, setGroup] = useState<AssignGroup | null>(null);
const [streamKey, setStreamKey] = useState("");
const [keyVisible, setKeyVisible] = useState(false);
const [urlsText, setUrlsText] = useState("");
const [name, setName] = useState("Windows 无人直播");
const [busy, setBusy] = useState(false);
const [phase, setPhase] = useState("");
const [probeMsg, setProbeMsg] = useState("");
const [relay, setRelay] = useState<RelayStatus | null>(null);
const [armed, setArmed] = useState(false);
const [ffmpegHint, setFfmpegHint] = useState("");
const dirtyRef = useRef(false);
const lastNotifyRef = useRef("");
const row = useMemo(() => {
const gid = group?.id;
const list = relay?.process_monitor || relay?.groups || [];
return list.find((g: any) => g.group_id === gid) || list[0] || null;
}, [relay, group?.id]);
const biz = String((row as any)?.business_status || "");
const pushing = Boolean((row as any)?.is_pushing || biz === "streaming");
const showArmed = armed || pushing || biz === "waiting_source" || biz === "relay_starting";
const markDirty = () => {
dirtyRef.current = true;
};
const applyGroupFields = useCallback((g: AssignGroup, force: boolean) => {
if (!force && dirtyRef.current) return;
setName(String(g.name || "Windows 无人直播"));
setStreamKey(String(g.stream_key || ""));
const featured = (g.featured || []).map((f) => f.url).filter(Boolean) as string[];
const pool = (g.pool || []).map((p) => p.url).filter(Boolean) as string[];
setUrlsText((featured.length ? featured : pool).join("\n"));
}, []);
const load = useCallback(
async (opts?: { forceFields?: boolean }) => {
const [gData, rData] = await Promise.all([
fetchJson<{ groups: AssignGroup[] }>("/api/youtube/assign/groups"),
fetchJson<RelayStatus>("/api/youtube/relay/status").catch(() => null),
]);
const groups = gData.groups || [];
let g =
groups.find((x) => /无人|windows|lazy/i.test(String(x.name || ""))) ||
groups.find((x) => x.has_stream_key) ||
groups[0] ||
null;
if (!g) {
const created = await fetchJson<{ group: AssignGroup }>("/api/youtube/assign/groups", {
method: "POST",
body: JSON.stringify({
name: "Windows 无人直播",
enabled: true,
category: "normal",
}),
});
g = created.group;
}
setGroup(g);
applyGroupFields(g, Boolean(opts?.forceFields));
setRelay(rData);
const list = rData?.process_monitor || rData?.groups || [];
const mine = list.find((x: any) => x.group_id === g.id);
const localPush = Boolean(
(mine as any)?.is_pushing || (mine as any)?.business_status === "streaming",
);
setArmed(Boolean(rData?.youtube_relay_enabled || rData?.running || localPush));
},
[applyGroupFields],
);
useEffect(() => {
void load({ forceFields: true }).catch((e) => toast.push((e as Error).message, "err"));
void window.desktop?.getServiceStatus?.()
.then((st) => {
const ff = String(st?.ffmpeg || "");
if (!ff || ff.startsWith("missing")) {
setFfmpegHint("未检测到 FFmpeg:请 npm run fetch-ffmpeg,或把 ffmpeg 加入 PATH");
} else {
setFfmpegHint("");
}
})
.catch(() => undefined);
const unsub = window.desktop?.onServiceStatus?.((st) => {
const ff = String(st?.ffmpeg || "");
if (!ff || ff.startsWith("missing")) {
setFfmpegHint("未检测到 FFmpeg:请 npm run fetch-ffmpeg,或把 ffmpeg 加入 PATH");
} else {
setFfmpegHint("");
}
});
let timer: ReturnType<typeof setInterval> | null = null;
const tick = () => {
void fetchJson<RelayStatus>("/api/youtube/relay/status")
.then(setRelay)
.catch(() => undefined);
};
const schedule = () => {
if (timer) clearInterval(timer);
const hidden = document.hidden;
const ms = hidden ? 15000 : 2500;
timer = setInterval(tick, ms);
};
schedule();
tick();
const onVis = () => {
schedule();
if (!document.hidden) tick();
};
document.addEventListener("visibilitychange", onVis);
const unFocus = window.desktop?.onWindowFocus?.((f) => {
if (f) tick();
});
return () => {
if (timer) clearInterval(timer);
document.removeEventListener("visibilitychange", onVis);
unFocus?.();
unsub?.();
};
}, [load, toast]);
useEffect(() => {
if (!pushing && biz !== "error") return;
const key = `${biz}:${(row as any)?.recent_error || (row as any)?.error || ""}`;
if (key === lastNotifyRef.current) return;
lastNotifyRef.current = key;
if (pushing) {
void window.desktop?.notify?.("无人直播", "正在推流到 YouTube");
} else if (biz === "error") {
void window.desktop?.notify?.(
"无人直播异常",
String((row as any)?.recent_error || (row as any)?.error || "推流失败"),
);
}
}, [pushing, biz, row]);
async function persistConfig(opts?: { quiet?: boolean }) {
if (!group?.id) return;
await fetchJson(`/api/youtube/assign/groups/${group.id}`, {
method: "PATCH",
body: JSON.stringify({
name,
stream_key: streamKey,
enabled: true,
}),
});
const urls = urlsText
.split(/\r?\n/)
.map((s) => s.trim())
.filter(Boolean);
if (urls.length) {
await fetchJson(`/api/youtube/assign/groups/${group.id}/pool`, {
method: "POST",
body: JSON.stringify({ urls }),
});
const fresh = await fetchJson<{ group: AssignGroup }>(
`/api/youtube/assign/groups/${group.id}`,
);
const poolIds = (fresh.group?.pool || [])
.filter((p) => urls.includes(String(p.url || "")))
.map((p) => p.id);
if (poolIds.length) {
await fetchJson(`/api/youtube/assign/groups/${group.id}/featured`, {
method: "PUT",
body: JSON.stringify({ pool_url_ids: poolIds }),
});
}
}
dirtyRef.current = false;
if (!opts?.quiet) toast.push("已保存频道与片源", "ok");
await load({ forceFields: true });
}
async function save() {
if (!group?.id) return;
setBusy(true);
setPhase("保存中…");
try {
await persistConfig();
} catch (e) {
toast.push((e as Error).message, "err");
} finally {
setBusy(false);
setPhase("");
}
}
async function toggleArm(on: boolean) {
if (on) {
if (ffmpegHint) {
toast.push(ffmpegHint, "err");
return;
}
if (!streamKey.trim()) {
toast.push("请先填写 YouTube Stream Key", "err");
return;
}
if (!urlsText.split(/\r?\n/).map((s) => s.trim()).some(Boolean)) {
toast.push("请先填写至少一个抖音直播间", "err");
return;
}
}
setBusy(true);
try {
setPhase("保存配置…");
await persistConfig({ quiet: true });
if (on) {
setPhase("启动全局中继…");
await fetchJson("/api/youtube/relay/start", { method: "POST", body: "{}" });
if (group?.id) {
setPhase("武装本频道…");
await fetchJson(`/api/youtube/relay/groups/${group.id}/start`, {
method: "POST",
body: "{}",
});
}
setArmed(true);
toast.push("已武装自动推流", "ok");
void window.desktop?.notify?.("无人直播", "已武装:开播将自动推流");
} else {
setPhase("停止推流…");
if (group?.id) {
await fetchJson(`/api/youtube/relay/groups/${group.id}/stop`, {
method: "POST",
body: "{}",
}).catch(() => undefined);
}
await fetchJson("/api/youtube/relay/stop", { method: "POST", body: "{}" });
setArmed(false);
toast.push("已停止推流", "warn");
}
await load({ forceFields: true });
} catch (e) {
toast.push((e as Error).message, "err");
} finally {
setBusy(false);
setPhase("");
}
}
async function pasteKey() {
try {
const t = (await navigator.clipboard.readText()).trim();
if (t) {
setStreamKey(t);
markDirty();
toast.push("已粘贴 Key", "ok");
}
} catch {
toast.push("无法读取剪贴板", "err");
}
}
async function probe() {
const first = urlsText.split(/\r?\n/).map((s) => s.trim()).find(Boolean);
if (!first) {
setProbeMsg("请先填写抖音地址");
return;
}
setBusy(true);
setPhase("探测片源…");
try {
const r = await fetchJson<any>("/api/rooms/probe", {
method: "POST",
body: JSON.stringify({ url: first }),
});
setProbeMsg(
r.is_live
? `在播 · ${r.anchor_name || ""} · ${r.title || ""}`
: `未开播${r.error ? ` · ${r.error}` : ""}`,
);
} catch (e) {
setProbeMsg((e as Error).message);
} finally {
setBusy(false);
setPhase("");
}
}
function openStudio() {
const open = window.desktop?.openExternal;
const url = "https://studio.youtube.com/";
if (open) void open(url);
else window.open(url, "_blank");
}
return (
<Shell>
<div className="space-y-5">
<section
className={`glass-panel relative overflow-hidden rounded-3xl p-5 sm:p-6 ${
pushing ? "ring-1 ring-rose-400/30" : ""
}`}
>
<div className="relative flex flex-wrap items-start justify-between gap-4">
<div>
<div className="flex items-center gap-2">
{pushing ? <LivePulse label="LIVE PUSH" /> : null}
<span className="text-[11px] uppercase tracking-[0.2em] text-slate-500">
无人直播
</span>
</div>
<h2 className="mt-2 font-display text-3xl font-semibold text-white">
{LABEL[biz] || biz || (showArmed ? "已武装" : "空闲")}
</h2>
<p className="mt-2 max-w-xl text-sm text-slate-400">
Studio 先点「开始直播」→ 本页保存 Key 与抖音源 → 一键武装。下播自动停,开播自动推。
</p>
{phase ? (
<p className="mt-2 inline-flex items-center gap-2 text-sm text-teal-300">
<Loader2 className="h-3.5 w-3.5 animate-spin" />
{phase}
</p>
) : null}
</div>
<div className="flex flex-wrap gap-2">
<button
type="button"
disabled={busy}
onClick={() => void toggleArm(!showArmed)}
className={`btn-glow inline-flex items-center gap-2 rounded-2xl px-4 py-2.5 text-sm font-semibold ${
showArmed
? "bg-rose-500 text-white"
: "bg-gradient-to-r from-rose-500 to-teal-400 text-slate-950"
}`}
>
{busy ? <Loader2 className="h-4 w-4 animate-spin" /> : <Power className="h-4 w-4" />}
{showArmed ? "解除武装" : "一键武装推流"}
</button>
<button
type="button"
onClick={() => openStudio()}
className="inline-flex items-center gap-2 rounded-2xl border border-white/10 bg-white/5 px-3 py-2.5 text-sm text-slate-300"
>
<ExternalLink className="h-4 w-4" />
Studio
</button>
<button
type="button"
disabled={busy}
onClick={() => void load({ forceFields: true }).catch((e) => toast.push((e as Error).message, "err"))}
className="inline-flex items-center gap-2 rounded-2xl border border-white/10 bg-white/5 px-3 py-2.5 text-sm text-slate-300"
>
{busy ? <Loader2 className="h-4 w-4 animate-spin" /> : <RefreshCw className="h-4 w-4" />}
</button>
</div>
</div>
{(row as any)?.recent_error || (row as any)?.error ? (
<p className="mt-3 text-sm text-rose-300">
{String((row as any).recent_error || (row as any).error)}
</p>
) : null}
{ffmpegHint ? <p className="mt-3 text-sm text-amber-200/90">{ffmpegHint}</p> : null}
{!streamKey.trim() || !urlsText.trim() ? (
<p className="mt-3 text-sm text-slate-500">
尚未配置完整:需要 Stream Key + 至少一行抖音地址,再点「一键武装推流」。
</p>
) : null}
{(row as any)?.recent_log ? (
<details className="mt-3 rounded-xl border border-white/10 bg-black/25 p-3">
<summary className="cursor-pointer text-xs text-slate-400">FFmpeg 最近日志</summary>
<pre className="mt-2 max-h-36 overflow-auto whitespace-pre-wrap font-mono text-[11px] text-slate-400">
{String((row as any).recent_log)}
</pre>
</details>
) : null}
</section>
<div className="stagger grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
<StatTile
emoji="🎬"
label="FFmpeg"
value={(row as any)?.ffmpeg_pid ? `PID ${(row as any).ffmpeg_pid}` : "未推"}
accent={pushing ? "rose" : "teal"}
/>
<StatTile
emoji="⚡"
label="速度"
value={
(row as any)?.ffmpeg_speed != null
? `${Number((row as any).ffmpeg_speed).toFixed(2)}x`
: "—"
}
/>
<StatTile emoji="🎞️" label="帧" value={(row as any)?.ffmpeg_frame ?? "—"} />
<StatTile
emoji="🏠"
label="片源"
value={(row as any)?.source_display || (row as any)?.source_url || "—"}
accent="amber"
/>
</div>
<SectionCard title="单频道配置" emoji="📡">
<div className="grid gap-4 lg:grid-cols-2">
<label className="block space-y-1.5 lg:col-span-2">
<span className="text-xs text-slate-400">频道备注名</span>
<input
className="w-full rounded-xl border border-white/10 bg-black/30 px-3 py-2.5 text-sm outline-none focus:ring-2 focus:ring-teal-400/20"
value={name}
onChange={(e) => {
markDirty();
setName(e.target.value);
}}
/>
</label>
<label className="block space-y-1.5 lg:col-span-2">
<span className="text-xs text-slate-400">YouTube Stream Key</span>
<div className="flex gap-2">
<input
type={keyVisible ? "text" : "password"}
className="w-full rounded-xl border border-white/10 bg-black/30 px-3 py-2.5 font-mono text-sm outline-none focus:ring-2 focus:ring-teal-400/20"
value={streamKey}
onChange={(e) => {
markDirty();
setStreamKey(e.target.value);
}}
/>
<button
type="button"
className="rounded-xl border border-white/10 bg-white/5 px-3"
onClick={() => void pasteKey()}
>
<ClipboardPaste className="h-4 w-4" />
</button>
<button
type="button"
className="rounded-xl border border-white/10 bg-white/5 px-3"
onClick={() => setKeyVisible((v) => !v)}
>
{keyVisible ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
</button>
</div>
</label>
<label className="block space-y-1.5 lg:col-span-2">
<span className="text-xs text-slate-400">抖音直播间(每行一个,写入精选源)</span>
<textarea
className="min-h-[110px] w-full rounded-xl border border-white/10 bg-black/30 px-3 py-2.5 font-mono text-sm outline-none focus:ring-2 focus:ring-teal-400/20"
value={urlsText}
onChange={(e) => {
markDirty();
setUrlsText(e.target.value);
}}
placeholder="https://live.douyin.com/xxxxx"
/>
</label>
</div>
<div className="mt-5 flex flex-wrap gap-2">
<button
type="button"
disabled={busy}
onClick={() => void save()}
className="btn-glow inline-flex items-center gap-2 rounded-2xl bg-white px-4 py-2.5 text-sm font-semibold text-slate-900"
>
{busy ? <Loader2 className="h-4 w-4 animate-spin" /> : <Save className="h-4 w-4" />}
保存
</button>
<button
type="button"
disabled={busy}
onClick={() => void probe()}
className="inline-flex items-center gap-2 rounded-2xl border border-white/10 bg-white/5 px-4 py-2.5 text-sm text-slate-200"
>
<Search className="h-4 w-4" />
探测首个源
</button>
</div>
{probeMsg ? <p className="mt-3 text-sm text-slate-400">{probeMsg}</p> : null}
</SectionCard>
</div>
</Shell>
);
}

View File

@ -1,9 +1,10 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { lazy, Suspense, useCallback, useEffect, useRef, useState } from "react";
import { Link } from "react-router-dom";
import { Loader2, RefreshCw, ArrowRight, ShieldOff } from "lucide-react";
import { Shell } from "@/components/Shell";
import { SessionCharts, type RelayStats } from "@/components/SessionCharts";
import { LazyMount } from "@/components/LazyMount";
import { type RelayStats } from "@/components/SessionCharts";
import { SessionDetailModal, type SessionDetail } from "@/components/SessionDetailModal";
import { AnimatedNumber, LivePulse, StatTile, PlatformBadge } from "@/components/ui";
import { DouyinLiveBadge } from "@/components/DouyinLiveBadge";
@ -17,6 +18,10 @@ import { fetchJson, fmtTs, sessionCoverSrc, todayBeijingISO, beijingHourFromTs,
import { liveElapsed, useEventStream, useNow, type RefreshOpts } from "@/lib/realtime";
import { channelLiveRef, useYouTubeLiveCount } from "@/lib/youtubeLive";
const SessionCharts = lazy(() =>
import("@/components/SessionCharts").then((m) => ({ default: m.SessionCharts })),
);
type MonitorStatus = {
running: boolean;
monitor_enabled: boolean;
@ -355,8 +360,8 @@ export default function HomePage() {
▶ YT 已暂停
</Link>
)}
<span className={`rounded-md border px-2 py-1 text-[11px] ${connected ? "border-teal-500/30 bg-teal-500/10 text-teal-100" : "border-slate-500/30 bg-slate-500/10 text-slate-400"}`}>
{connected ? "🟢 SSE 已连接" : "⚪ SSE 重连中"}
<span className="rounded-md border border-teal-500/30 bg-teal-500/10 px-2 py-1 text-[11px] text-teal-100">
轮询模式
</span>
{riskActive ? (
<span className="rounded-md border border-amber-500/30 bg-amber-500/10 px-2 py-1 text-[11px] text-amber-100">⚠️ 风控熔断中</span>
@ -429,6 +434,12 @@ export default function HomePage() {
<p className="mt-1 text-sm text-slate-400">抖音 + YouTube 双平台开播态势 · 时段规律 · 事件回放</p>
</div>
<div className="flex flex-wrap gap-2">
<Link
to="/live"
className="btn-glow inline-flex items-center gap-2 rounded-xl border border-rose-500/35 bg-rose-500/15 px-3 py-2 text-sm font-medium text-rose-100 hover:bg-rose-500/25"
>
无人直播 <ArrowRight className="h-3.5 w-3.5" />
</Link>
<button
type="button"
onClick={() => setFocusOnly((v) => !v)}
@ -741,7 +752,14 @@ export default function HomePage() {
</Link>
</div>
</div>
<SessionCharts stats={stats} />
<LazyMount
minHeight={280}
fallback={<div className="py-16 text-center text-xs text-slate-600">图表进入视口后加载…</div>}
>
<Suspense fallback={<div className="py-16 text-center text-xs text-slate-600">加载图表…</div>}>
<SessionCharts stats={stats} />
</Suspense>
</LazyMount>
{ytStats?.overview ? (
<div className="mt-4 rounded-xl border border-amber-500/20 bg-amber-500/5 px-3 py-2 text-xs text-amber-100/90">
YouTube 单独:场次 {ytStats.overview.sessions ?? 0} · 在播 {ytStats.overview.active_sessions ?? 0} · 累计{" "}

View File

@ -1,4 +1,5 @@
import { useCallback, useEffect, useState } from "react";
import { Link } from "react-router-dom";
import { Loader2, Save, ShieldOff } from "lucide-react";
import { Shell } from "@/components/Shell";
@ -916,11 +917,13 @@ function DesktopLocalPanel() {
const [svc, setSvc] = useState<Record<string, unknown> | null>(null);
const [diag, setDiag] = useState("");
const [msg, setMsg] = useState("");
const [restarting, setRestarting] = useState(false);
useEffect(() => {
if (!window.desktop) return;
void window.desktop.getConfig().then(setCfg);
void window.desktop.getServiceStatus().then(setSvc);
return window.desktop.onServiceStatus?.((st) => setSvc(st));
}, []);
if (!window.desktop) {
@ -938,7 +941,7 @@ function DesktopLocalPanel() {
nativeNotify: Boolean(cfg.nativeNotify),
});
setCfg(next);
setMsg("已保存客户端偏好(本地服务端口需重启生效)");
setMsg("已保存客户端偏好");
}
async function copyDiag() {
@ -953,13 +956,43 @@ function DesktopLocalPanel() {
}
}
async function restart() {
setRestarting(true);
setMsg("正在重启本地服务…");
try {
const st = await window.desktop!.restartServices();
setSvc(st);
setMsg(String(st.api) === "ok" ? "本地服务已重启" : `重启完成:API ${String(st.api)}`);
} catch (e) {
setMsg((e as Error).message);
} finally {
setRestarting(false);
}
}
const rows = [
["PocketBase", String(svc?.pocketbase || "—")],
["FastAPI", String(svc?.api || "—")],
["youtube-svc", String(svc?.youtube || "—")],
["FFmpeg", String(svc?.ffmpeg || "—")],
["Python", String(svc?.python || "—")],
];
return (
<div className="space-y-3 rounded-2xl border border-teal-500/20 bg-teal-500/5 p-4">
<div>
<h2 className="font-display text-lg text-white">Windows 客户端 · 本地后端</h2>
<p className="mt-1 text-xs text-slate-400">
启动时自动拉起本机 PocketBase / FastAPI / youtube-svc,不依赖远程服务器。
</p>
<div className="flex flex-wrap items-start justify-between gap-2">
<div>
<h2 className="font-display text-lg text-white">Windows 客户端 · 本地后端</h2>
<p className="mt-1 text-xs text-slate-400">
本机 PocketBase / FastAPI / youtube-svc · 全量 worker · 无人直播 RTMPS
</p>
</div>
<Link
to="/live"
className="rounded-lg border border-rose-500/30 bg-rose-500/10 px-3 py-1.5 text-xs text-rose-100 hover:bg-rose-500/20"
>
打开无人直播 →
</Link>
</div>
<div className="grid gap-2 text-xs text-slate-300 sm:grid-cols-2">
<div className="rounded-xl border border-white/10 bg-black/30 p-3">
@ -973,9 +1006,13 @@ function DesktopLocalPanel() {
</div>
</div>
</div>
<div className="rounded-xl border border-white/10 bg-black/30 p-3 text-xs">
<div className="mb-2 text-slate-500">服务状态</div>
<pre className="whitespace-pre-wrap text-slate-300">{JSON.stringify(svc || {}, null, 2)}</pre>
<div className="grid gap-1.5 rounded-xl border border-white/10 bg-black/30 p-3 text-xs">
{rows.map(([k, v]) => (
<div key={k} className="flex gap-2">
<span className="w-24 shrink-0 text-slate-500">{k}</span>
<span className="break-all font-mono text-slate-300">{v}</span>
</div>
))}
</div>
<label className="flex items-center gap-2 text-sm text-slate-300">
<input
@ -991,7 +1028,7 @@ function DesktopLocalPanel() {
checked={cfg?.nativeNotify !== false}
onChange={(e) => setCfg((c) => ({ ...(c || {}), nativeNotify: e.target.checked }))}
/>
系统原生通知(开播/风控等)
系统原生通知(开播/风控/推流)
</label>
<div className="flex flex-wrap gap-2">
<button
@ -1001,6 +1038,21 @@ function DesktopLocalPanel() {
>
保存客户端偏好
</button>
<button
type="button"
disabled={restarting}
onClick={() => void restart()}
className="rounded-lg border border-amber-500/30 bg-amber-500/10 px-3 py-1.5 text-xs text-amber-100 hover:bg-amber-500/20 disabled:opacity-50"
>
{restarting ? "重启中…" : "重启本地服务"}
</button>
<button
type="button"
onClick={() => void window.desktop?.getServiceStatus().then(setSvc)}
className="rounded-lg border border-white/10 bg-white/5 px-3 py-1.5 text-xs hover:bg-white/10"
>
刷新状态
</button>
<button
type="button"
onClick={() => void window.desktop?.openLogs()}

View File

@ -25,9 +25,17 @@ export default defineConfig({
emptyOutDir: true,
rollupOptions: {
output: {
manualChunks: {
echarts: ["echarts"],
vendor: ["react", "react-dom", "react-router-dom"],
manualChunks(id) {
if (id.includes("node_modules/echarts") || id.includes("lib/echartsSlim")) {
return "echarts";
}
if (
id.includes("node_modules/react-dom") ||
id.includes("node_modules/react-router") ||
id.includes("node_modules/react/")
) {
return "vendor";
}
},
},
},

View File

@ -1,10 +1,56 @@
@echo off
setlocal
cd /d %~dp0\..\desktop
if not exist node_modules (
echo Installing desktop dependencies...
call npm install
if errorlevel 1 goto :fail
)
echo Starting Electron desktop (local FastAPI + PocketBase)...
if not exist ..\youtube-svc\node_modules (
echo Installing youtube-svc dependencies...
pushd ..\youtube-svc
call npm install
if errorlevel 1 (
popd
goto :fail
)
popd
)
if not exist runtime\ffmpeg\ffmpeg.exe (
where ffmpeg >nul 2>&1
if errorlevel 1 (
echo Fetching bundled ffmpeg...
call npm run fetch-ffmpeg
if errorlevel 1 echo WARN: ffmpeg fetch failed — install ffmpeg or retry npm run fetch-ffmpeg
) else (
echo System ffmpeg found on PATH.
)
)
if not exist ..\pb\pocketbase.exe (
echo Fetching PocketBase...
call npm run fetch-pocketbase
if errorlevel 1 (
echo ERROR: pb\pocketbase.exe missing. Run: cd desktop ^&^& npm run fetch-pocketbase
goto :fail
)
)
echo Ensuring Python deps ^(tzdata / requirements^)...
call npm run ensure-python
if errorlevel 1 (
echo WARN: ensure-python failed — API may not start. Run: pip install -r ..\backend\requirements.txt
)
echo Starting Electron desktop ^(local FastAPI + PocketBase + youtube-svc^)...
call npm run electron:dev
goto :eof
:fail
echo.
echo Desktop start aborted.
exit /b 1
endlocal

View File

@ -0,0 +1,20 @@
# 已合并到 desktop
请只用仓库唯一 Windows 客户端:
```bat
scripts\start-desktop.bat
```
或:
```bat
cd desktop
npm install
npm run prepare:runtime
npm run electron:dev
```
应用内打开 **无人直播**(`/live`)。
本目录若还残留 `node_modules`(旧 Electron 文件锁),重启电脑后可整夹删除。