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; proc: ChildProcess; cwd: string; }; 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; } export function resolveRuntimeRoot(): string { if (isPackaged()) { return path.join(process.resourcesPath, "runtime"); } return path.resolve(__dirname, "..", ".."); } export function resolvePaths() { const root = resolveRuntimeRoot(); if (isPackaged()) { return { root, backend: path.join(root, "backend"), pb: path.join(root, "pb"), youtube: path.join(root, "youtube-svc"), }; } return { root, backend: path.join(root, "backend"), pb: path.join(root, "pb"), youtube: path.join(root, "youtube-svc"), }; } function spawnLogged( name: ServiceName, command: string, args: string[], opts: SpawnOptions, ): ChildProcess { const proc = spawn(command, args, { ...opts, stdio: ["ignore", "pipe", "pipe"], windowsHide: true, }); const prefix = `[${name}]`; let lines = 0; const onChunk = (buf: Buffer, isErr: boolean) => { if (lines > 40) return; const line = String(buf).trim(); if (!line) return; lines += 1; if (isErr || lines <= 8) { (isErr ? console.error : console.log)(prefix, line.slice(0, 220)); } }; proc.stdout?.on("data", (b) => onChunk(b, false)); proc.stderr?.on("data", (b) => onChunk(b, true)); proc.on("exit", (code, signal) => { console.log(prefix, `exited code=${code} signal=${signal}`); }); children.push({ name, proc, cwd: String(opts.cwd || "") }); return proc; } function portOpen(port: number, host = "127.0.0.1"): Promise { return new Promise((resolve) => { const sock = net.connect({ port, host }); sock.setTimeout(500); sock.on("connect", () => { sock.destroy(); resolve(true); }); sock.on("timeout", () => { sock.destroy(); resolve(false); }); sock.on("error", () => resolve(false)); }); } function probeHttp(url: string, timeoutMs = 1200): Promise { return new Promise((resolve) => { const req = http.get(url, { timeout: timeoutMs }, (res) => { res.resume(); resolve((res.statusCode || 500) < 500); }); req.on("timeout", () => { req.destroy(); resolve(false); }); req.on("error", () => resolve(false)); }); } function sleep(ms: number) { return new Promise((r) => setTimeout(r, ms)); } 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: ServiceStatus }> { const paths = resolvePaths(); const status: ServiceStatus = { boot: "starting" }; const apiBase = `http://127.0.0.1:${ports.apiPort}`; emitStatus(status); 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"; status.boot = "ok"; console.log("[boot] reuse healthy API", status); emitStatus(status); return { apiBase, status }; } // PocketBase + youtube-svc in parallel await Promise.all([ ensurePocketbase(ports, paths, status), ensureYoutube(ports, paths, status), ]); // 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(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", // 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", "http://127.0.0.1:18574", "http://localhost:18574", ].join(","), DY_S3_ENABLED: process.env.DY_S3_ENABLED || "false", TZ: "Asia/Shanghai", PYTHONUTF8: "1", }; 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 waitHttp(`${apiBase}/api/ping`, 45000); status.api = "ok"; } catch (e) { status.api = spawnFailed ? "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 }; } export function stopLocalServices(): void { for (const child of [...children].reverse()) { try { if (process.platform === "win32" && child.proc.pid) { spawn("taskkill", ["/pid", String(child.proc.pid), "/T", "/F"], { stdio: "ignore", windowsHide: true, }); } else { child.proc.kill("SIGTERM"); } } catch { /* ignore */ } } 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 })); }