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>
353 lines
10 KiB
TypeScript
353 lines
10 KiB
TypeScript
import {
|
|
app,
|
|
BrowserWindow,
|
|
ipcMain,
|
|
Menu,
|
|
nativeImage,
|
|
Notification,
|
|
screen,
|
|
shell,
|
|
Tray,
|
|
} from "electron";
|
|
import path from "node:path";
|
|
import { getConfig, setConfig } from "./store";
|
|
import {
|
|
getResolvedFfmpeg,
|
|
listServicePids,
|
|
restartLocalServices,
|
|
setServiceStatusListener,
|
|
startLocalServices,
|
|
stopLocalServices,
|
|
} from "./services";
|
|
import { startUiServer } from "./uiServer";
|
|
|
|
let mainWindow: BrowserWindow | null = null;
|
|
let tray: Tray | null = null;
|
|
let serviceStatus: Record<string, string> = {};
|
|
let quitting = false;
|
|
let uiClose: (() => void) | null = null;
|
|
let uiUrl = "http://127.0.0.1:5173";
|
|
|
|
const isDev = !app.isPackaged;
|
|
const openDevtools = process.env.ELECTRON_OPEN_DEVTOOLS === "1";
|
|
|
|
function trayIcon(): Electron.NativeImage {
|
|
const png = Buffer.from(
|
|
"iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAPElEQVQ4T2NkYGD4z0ABYBzVMKoBBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGAAD+AQX5Yp1mAAAAAElFTkSuQmCC",
|
|
"base64",
|
|
);
|
|
const img = nativeImage.createFromBuffer(png);
|
|
return img.isEmpty() ? nativeImage.createFromDataURL("data:image/png;base64," + png.toString("base64")) : img;
|
|
}
|
|
|
|
function createTray() {
|
|
if (tray) return;
|
|
try {
|
|
tray = new Tray(trayIcon());
|
|
} catch (err) {
|
|
console.error("tray create failed", err);
|
|
return;
|
|
}
|
|
tray.setToolTip("抖音直播监控");
|
|
tray.setContextMenu(
|
|
Menu.buildFromTemplate([
|
|
{
|
|
label: "打开主窗口",
|
|
click: () => {
|
|
mainWindow?.show();
|
|
mainWindow?.focus();
|
|
},
|
|
},
|
|
{
|
|
label: "无人直播",
|
|
click: () => {
|
|
mainWindow?.show();
|
|
mainWindow?.focus();
|
|
navigateUi("/live");
|
|
},
|
|
},
|
|
{
|
|
label: "本地服务状态",
|
|
click: () => {
|
|
const lines = Object.entries(serviceStatus)
|
|
.map(([k, v]) => `${k}: ${v}`)
|
|
.join("\n");
|
|
if (Notification.isSupported()) {
|
|
new Notification({ title: "本地服务", body: lines || "未知" }).show();
|
|
}
|
|
},
|
|
},
|
|
{ type: "separator" },
|
|
{
|
|
label: "退出",
|
|
click: () => {
|
|
quitting = true;
|
|
app.quit();
|
|
},
|
|
},
|
|
]),
|
|
);
|
|
tray.on("double-click", () => {
|
|
mainWindow?.show();
|
|
mainWindow?.focus();
|
|
});
|
|
}
|
|
|
|
function resolveWindowBounds(): { width: number; height: number; x?: number; y?: number } {
|
|
const cfg = getConfig();
|
|
const saved = cfg.windowBounds;
|
|
const width = Math.max(1100, Number(saved?.width) || 1280);
|
|
const height = Math.max(700, Number(saved?.height) || 800);
|
|
const display = screen.getPrimaryDisplay().workArea;
|
|
const x = typeof saved?.x === "number" ? saved.x : undefined;
|
|
const y = typeof saved?.y === "number" ? saved.y : undefined;
|
|
if (
|
|
x == null ||
|
|
y == null ||
|
|
x + 80 < display.x ||
|
|
y + 80 < display.y ||
|
|
x > display.x + display.width - 80 ||
|
|
y > display.y + display.height - 80
|
|
) {
|
|
return {
|
|
width: Math.min(width, display.width),
|
|
height: Math.min(height, display.height),
|
|
x: display.x + Math.max(0, Math.floor((display.width - Math.min(width, display.width)) / 2)),
|
|
y: display.y + Math.max(0, Math.floor((display.height - Math.min(height, display.height)) / 2)),
|
|
};
|
|
}
|
|
return { width, height, x, y };
|
|
}
|
|
|
|
const SPLASH = `data:text/html;charset=utf-8,${encodeURIComponent(`<!doctype html>
|
|
<html><head><meta charset="utf-8"/><title>抖音直播监控</title>
|
|
<style>
|
|
body{margin:0;height:100vh;display:flex;align-items:center;justify-content:center;
|
|
font-family:Segoe UI,sans-serif;color:#edf3ff;background:#071018}
|
|
.box{text-align:center}
|
|
.h{font-size:22px;font-weight:700;margin:0 0 8px}
|
|
.p{color:#93a4bd;font-size:13px;margin:0}
|
|
.spin{width:28px;height:28px;margin:18px auto 0;border:2px solid #2dd4bf55;border-top-color:#2dd4bf;
|
|
border-radius:50%;animation:r .7s linear infinite}
|
|
@keyframes r{to{transform:rotate(360deg)}}
|
|
</style></head><body><div class="box"><p class="h">直播监控中心</p>
|
|
<p class="p">正在启动本地服务…</p><div class="spin"></div></div></body></html>`)}`;
|
|
|
|
function createWindow() {
|
|
const bounds = resolveWindowBounds();
|
|
mainWindow = new BrowserWindow({
|
|
width: bounds.width,
|
|
height: bounds.height,
|
|
x: bounds.x,
|
|
y: bounds.y,
|
|
minWidth: 1000,
|
|
minHeight: 640,
|
|
show: true,
|
|
backgroundColor: "#071018",
|
|
title: "抖音直播监控",
|
|
autoHideMenuBar: true,
|
|
webPreferences: {
|
|
preload: path.join(__dirname, "preload.js"),
|
|
contextIsolation: true,
|
|
nodeIntegration: false,
|
|
sandbox: false,
|
|
backgroundThrottling: true,
|
|
spellcheck: false,
|
|
},
|
|
});
|
|
|
|
mainWindow.webContents.on("did-fail-load", (_e, code, desc, url) => {
|
|
console.error("did-fail-load", code, desc, url);
|
|
});
|
|
mainWindow.webContents.on("did-finish-load", () => {
|
|
console.log("did-finish-load", mainWindow?.webContents.getURL());
|
|
});
|
|
|
|
mainWindow.on("close", (e) => {
|
|
if (!quitting && getConfig().minimizeToTray) {
|
|
e.preventDefault();
|
|
mainWindow?.hide();
|
|
}
|
|
});
|
|
|
|
mainWindow.on("resize", () => persistBounds());
|
|
mainWindow.on("move", () => persistBounds());
|
|
mainWindow.on("focus", () => mainWindow?.webContents.send("desktop:focus", true));
|
|
mainWindow.on("blur", () => mainWindow?.webContents.send("desktop:focus", false));
|
|
|
|
// Instant splash — do not wait for backends
|
|
void mainWindow.loadURL(SPLASH);
|
|
if (openDevtools) {
|
|
mainWindow.webContents.openDevTools({ mode: "detach" });
|
|
}
|
|
}
|
|
|
|
async function loadAppUi() {
|
|
if (!mainWindow || mainWindow.isDestroyed()) return;
|
|
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 || {}));
|
|
ipcMain.handle("desktop:getServiceStatus", () => ({
|
|
...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;
|
|
new Notification({ title: payload.title, body: payload.body }).show();
|
|
});
|
|
ipcMain.handle("desktop:openExternal", (_e, url: string) => {
|
|
if (typeof url === "string" && /^https?:\/\//i.test(url)) {
|
|
void shell.openExternal(url);
|
|
}
|
|
});
|
|
ipcMain.handle("desktop:openLogs", () => {
|
|
void shell.openPath(app.getPath("logs"));
|
|
});
|
|
ipcMain.handle("desktop:getDiagnostics", () => {
|
|
const cfg = getConfig();
|
|
return {
|
|
version: app.getVersion(),
|
|
electron: process.versions.electron,
|
|
chrome: process.versions.chrome,
|
|
platform: process.platform,
|
|
apiBase: cfg.apiBase,
|
|
services: serviceStatus,
|
|
ffmpeg: getResolvedFfmpeg() || serviceStatus.ffmpeg || "",
|
|
packaged: app.isPackaged,
|
|
};
|
|
});
|
|
ipcMain.handle("desktop:minimizeToTray", () => {
|
|
mainWindow?.hide();
|
|
});
|
|
}
|
|
|
|
const gotLock = app.requestSingleInstanceLock();
|
|
if (!gotLock) {
|
|
app.quit();
|
|
} else {
|
|
// Must be before ready
|
|
app.commandLine.appendSwitch("disable-features", "CalculateNativeWinOcclusion");
|
|
|
|
app.on("second-instance", () => {
|
|
if (mainWindow) {
|
|
if (mainWindow.isMinimized()) mainWindow.restore();
|
|
mainWindow.show();
|
|
mainWindow.focus();
|
|
}
|
|
});
|
|
|
|
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,
|
|
});
|
|
pushServiceStatus(started.status);
|
|
setConfig({ apiBase: started.apiBase });
|
|
|
|
if (isDev) {
|
|
uiUrl = "http://127.0.0.1:5173";
|
|
} else {
|
|
const ui = await startUiServer({
|
|
distDir: path.join(__dirname, "..", "dist"),
|
|
apiBase: started.apiBase,
|
|
port: 18574,
|
|
});
|
|
uiClose = ui.close;
|
|
uiUrl = ui.url;
|
|
}
|
|
} catch (err) {
|
|
pushServiceStatus({ boot: String((err as Error).message) });
|
|
console.error("Failed to start local services", err);
|
|
}
|
|
await loadAppUi();
|
|
})();
|
|
});
|
|
|
|
app.on("before-quit", () => {
|
|
quitting = true;
|
|
try {
|
|
uiClose?.();
|
|
} catch {
|
|
/* ignore */
|
|
}
|
|
stopLocalServices();
|
|
});
|
|
|
|
app.on("window-all-closed", () => {
|
|
if (process.platform !== "darwin") {
|
|
quitting = true;
|
|
app.quit();
|
|
}
|
|
});
|
|
}
|