diff --git a/README.md b/README.md index 822e2dc..293788a 100644 --- a/README.md +++ b/README.md @@ -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`。 diff --git a/backend/requirements.txt b/backend/requirements.txt index 65f729d..57448d2 100644 --- a/backend/requirements.txt +++ b/backend/requirements.txt @@ -12,4 +12,5 @@ requests-auth-aws-sigv4>=0.7 requests>=2.31 PySocks>=1.7.1 python-dotenv>=1.0 +tzdata>=2024.1 diff --git a/desktop/README.md b/desktop/README.md index 9571085..15b4b8c 100644 --- a/desktop/README.md +++ b/desktop/README.md @@ -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 + 抖音直播间 → 保存 → **一键武装推流** diff --git a/desktop/electron/main.ts b/desktop/electron/main.ts index c634573..70842cb 100644 --- a/desktop/electron/main.ts +++ b/desktop/electron/main.ts @@ -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) { + 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(); diff --git a/desktop/electron/preload.ts b/desktop/electron/preload.ts index f276688..fe91fbb 100644 --- a/desktop/electron/preload.ts +++ b/desktop/electron/preload.ts @@ -4,11 +4,13 @@ export type DesktopBridge = { getConfig: () => Promise>; setConfig: (patch: Record) => Promise>; getServiceStatus: () => Promise>; + restartServices: () => Promise>; notify: (title: string, body: string) => Promise; openExternal: (url: string) => Promise; openLogs: () => Promise; getDiagnostics: () => Promise>; onWindowFocus: (cb: (focused: boolean) => void) => () => void; + onServiceStatus: (cb: (status: Record) => void) => () => void; minimizeToTray: () => Promise; }; @@ -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) => cb(status); + ipcRenderer.on("desktop:services", handler); + return () => ipcRenderer.removeListener("desktop:services", handler); + }, minimizeToTray: () => ipcRenderer.invoke("desktop:minimizeToTray"), }; diff --git a/desktop/electron/services.ts b/desktop/electron/services.ts index 856be56..63c34eb 100644 --- a/desktop/electron/services.ts +++ b/desktop/electron/services.ts @@ -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; +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 { }); } -function probeHttp(url: string, timeoutMs = 1000): Promise { +function probeHttp(url: string, timeoutMs = 1200): Promise { 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 { }); } -function waitPort(port: number, timeoutMs = 45000, host = "127.0.0.1"): Promise { - const start = Date.now(); - return new Promise((resolve, reject) => { - let settled = false; - let timer: ReturnType | 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((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 { + 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 { + 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, + status: ServiceStatus, +): Promise { + 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, + status: ServiceStatus, +): Promise { + 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 }> { +}): Promise<{ apiBase: string; status: ServiceStatus }> { const paths = resolvePaths(); - const status: Record = {}; + 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 = { + ...(process.env as Record), 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 })); } diff --git a/desktop/electron/uiServer.ts b/desktop/electron/uiServer.ts index b743e1e..ba6a423 100644 --- a/desktop/electron/uiServer.ts +++ b/desktop/electron/uiServer.ts @@ -40,29 +40,56 @@ function proxy(req: http.IncomingMessage, res: http.ServerResponse, apiBase: str req.pipe(preq); } +function cacheHeaders(urlPath: string, ext: string): Record { + // 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 = { + "Content-Type": MIME[ext] || "application/octet-stream", + ...cacheHeaders(rawPath, ext), + }; + res.writeHead(200, headers); fs.createReadStream(filePath).pipe(res); }); diff --git a/desktop/package.json b/desktop/package.json index afc5531..4244265 100644 --- a/desktop/package.json +++ b/desktop/package.json @@ -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": { diff --git a/desktop/runtime/ffmpeg/.gitkeep b/desktop/runtime/ffmpeg/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/desktop/scripts/ensure-python.ps1 b/desktop/scripts/ensure-python.ps1 new file mode 100644 index 0000000..de65151 --- /dev/null +++ b/desktop/scripts/ensure-python.ps1 @@ -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')" diff --git a/desktop/scripts/fetch-ffmpeg.ps1 b/desktop/scripts/fetch-ffmpeg.ps1 new file mode 100644 index 0000000..b2b8252 --- /dev/null +++ b/desktop/scripts/fetch-ffmpeg.ps1 @@ -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 diff --git a/desktop/scripts/fetch-pocketbase.ps1 b/desktop/scripts/fetch-pocketbase.ps1 new file mode 100644 index 0000000..8a5cd0c --- /dev/null +++ b/desktop/scripts/fetch-pocketbase.ps1 @@ -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 diff --git a/desktop/src/App.tsx b/desktop/src/App.tsx index 69f0cab..5ab34e4 100644 --- a/desktop/src/App.tsx +++ b/desktop/src/App.tsx @@ -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 ( - - }> - - } /> - }> - } /> - } /> - } /> - } /> - } /> - } /> - } /> - } /> - } /> - } /> - } /> - } /> - - } /> - - + + + + }> + + } /> + }> + } /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> + + } /> + + + ); diff --git a/desktop/src/components/LazyMount.tsx b/desktop/src/components/LazyMount.tsx new file mode 100644 index 0000000..92ce4c4 --- /dev/null +++ b/desktop/src/components/LazyMount.tsx @@ -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(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 ( +
+ {show ? children : fallback} +
+ ); +} diff --git a/desktop/src/components/ServiceBanner.tsx b/desktop/src/components/ServiceBanner.tsx index ff13d2c..f0027aa 100644 --- a/desktop/src/components/ServiceBanner.tsx +++ b/desktop/src/components/ServiceBanner.tsx @@ -1,28 +1,55 @@ import { useEffect, useState } from "react"; +function statusLine(st: Record | 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 | 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 (
diff --git a/desktop/src/components/SessionCharts.tsx b/desktop/src/components/SessionCharts.tsx index 739adbc..01af940 100644 --- a/desktop/src/components/SessionCharts.tsx +++ b/desktop/src/components/SessionCharts.tsx @@ -40,10 +40,11 @@ function useEchart(option: Record | 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); diff --git a/desktop/src/components/Shell.tsx b/desktop/src/components/Shell.tsx index 9381305..0dce98d 100644 --- a/desktop/src/components/Shell.tsx +++ b/desktop/src/components/Shell.tsx @@ -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 ( - - {children} - + {children} ); } +export function Shell({ children }: { children: React.ReactNode }) { + return {children}; +} + 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 }) { 直播监控中心

- 抖音 + YouTube · 开播捕捉 · 停播结场 · 时长统计 · 截图存证 · Windows 客户端 + 抖音 + YouTube · 无人直播 · 开播捕捉 · Shorts · Windows 唯一客户端

{(dyLiveCount > 0 || ytLiveCount > 0) ? (
diff --git a/desktop/src/components/ui.tsx b/desktop/src/components/ui.tsx index 07fd845..648bf3a 100644 --- a/desktop/src/components/ui.tsx +++ b/desktop/src/components/ui.tsx @@ -121,6 +121,31 @@ export function EmptyState({ ); } +export function SectionCard({ + title, + emoji, + children, + action, +}: { + title: string; + emoji?: string; + children: ReactNode; + action?: ReactNode; +}) { + return ( +
+
+

+ {emoji ? {emoji} : null} + {title} +

+ {action} +
+ {children} +
+ ); +} + export function PlatformBadge({ platform, className = "", diff --git a/desktop/src/lib/api.ts b/desktop/src/lib/api.ts index 9a0066a..c41ca9a 100644 --- a/desktop/src/lib/api.ts +++ b/desktop/src/lib/api.ts @@ -14,11 +14,13 @@ declare global { getConfig: () => Promise>; setConfig: (patch: Record) => Promise>; getServiceStatus: () => Promise>; + restartServices: () => Promise>; notify: (title: string, body: string) => Promise; openExternal: (url: string) => Promise; openLogs: () => Promise; getDiagnostics: () => Promise>; onWindowFocus: (cb: (focused: boolean) => void) => () => void; + onServiceStatus: (cb: (status: Record) => void) => () => void; minimizeToTray: () => Promise; }; } diff --git a/desktop/src/lib/douyinLive.ts b/desktop/src/lib/douyinLive.ts index 4fbfc1f..58c33e0 100644 --- a/desktop/src/lib/douyinLive.ts +++ b/desktop/src/lib/douyinLive.ts @@ -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(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, diff --git a/desktop/src/lib/echartsSlim.ts b/desktop/src/lib/echartsSlim.ts new file mode 100644 index 0000000..222765c --- /dev/null +++ b/desktop/src/lib/echartsSlim.ts @@ -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; diff --git a/desktop/src/lib/realtime.ts b/desktop/src/lib/realtime.ts index bc03d41..189dd04 100644 --- a/desktop/src/lib/realtime.ts +++ b/desktop/src/lib/realtime.ts @@ -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; } diff --git a/desktop/src/main.tsx b/desktop/src/main.tsx index b572a8a..cdd89bf 100644 --- a/desktop/src/main.tsx +++ b/desktop/src/main.tsx @@ -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( @@ -16,7 +14,6 @@ createRoot(document.getElementById("root")!).render( , ); -// Optional: refresh apiBase from Electron store (non-blocking) void window.desktop?.getConfig?.() .then((cfg) => { const base = String(cfg?.apiBase || "").trim(); diff --git a/desktop/src/pages/EventsPage.tsx b/desktop/src/pages/EventsPage.tsx index 3ff843d..1401d4a 100644 --- a/desktop/src/pages/EventsPage.tsx +++ b/desktop/src/pages/EventsPage.tsx @@ -120,7 +120,7 @@ export default function EventsPage() { }, [tick, last, kind, platform, q]); const liveHint = useMemo( - () => (connected ? "SSE 实时推送中" : "SSE 重连中 · 可手动刷新"), + () => (connected ? "实时推送中" : "轮询模式 · 可手动刷新"), [connected], ); diff --git a/desktop/src/pages/GroupsPage.tsx b/desktop/src/pages/GroupsPage.tsx index 79e0691..fe4c460 100644 --- a/desktop/src/pages/GroupsPage.tsx +++ b/desktop/src/pages/GroupsPage.tsx @@ -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() {

可视化分析

- + 图表进入视口后加载…
} + > + 加载图表…
}> + + +
diff --git a/desktop/src/pages/LiveUnmannedPage.tsx b/desktop/src/pages/LiveUnmannedPage.tsx new file mode 100644 index 0000000..9c1ae87 --- /dev/null +++ b/desktop/src/pages/LiveUnmannedPage.tsx @@ -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 = { + streaming: "推流中", + waiting_source: "等待直播", + source_live: "源已开播", + relay_starting: "转推启动中", + ready: "已配置", + inactive: "未运行", + misconfigured: "密钥异常", + error: "异常", +}; + +export default function LiveUnmannedPage() { + const toast = useToast(); + const [group, setGroup] = useState(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(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("/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 | null = null; + const tick = () => { + void fetchJson("/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("/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 ( + +
+
+
+
+
+ {pushing ? : null} + + 无人直播 + +
+

+ {LABEL[biz] || biz || (showArmed ? "已武装" : "空闲")} +

+

+ Studio 先点「开始直播」→ 本页保存 Key 与抖音源 → 一键武装。下播自动停,开播自动推。 +

+ {phase ? ( +

+ + {phase} +

+ ) : null} +
+
+ + + +
+
+ {(row as any)?.recent_error || (row as any)?.error ? ( +

+ {String((row as any).recent_error || (row as any).error)} +

+ ) : null} + {ffmpegHint ?

{ffmpegHint}

: null} + {!streamKey.trim() || !urlsText.trim() ? ( +

+ 尚未配置完整:需要 Stream Key + 至少一行抖音地址,再点「一键武装推流」。 +

+ ) : null} + {(row as any)?.recent_log ? ( +
+ FFmpeg 最近日志 +
+                {String((row as any).recent_log)}
+              
+
+ ) : null} +
+ +
+ + + + +
+ + +
+ + +