98 lines
2.6 KiB
TypeScript
98 lines
2.6 KiB
TypeScript
import express from "express";
|
|
import { createProxyMiddleware } from "http-proxy-middleware";
|
|
import { createServer } from "http";
|
|
import { WebSocketServer, WebSocket } from "ws";
|
|
import { spawn, ChildProcessWithoutNullStreams } from "child_process";
|
|
import { join } from "path";
|
|
import { recorderRouter } from "./recorder.js";
|
|
import { mediaRouter } from "./media.js";
|
|
import { talkRouter } from "./talk.js";
|
|
import { healthRouter } from "./health.js";
|
|
|
|
// Use process.cwd() instead of import.meta.url for bundled compatibility
|
|
const __dirname = process.cwd();
|
|
|
|
const app = express();
|
|
const PORT = process.env.PORT || 8090;
|
|
|
|
// Middleware
|
|
app.use(express.json({ limit: "10mb" }));
|
|
app.use(express.urlencoded({ extended: true }));
|
|
|
|
// Serve static files (built React app)
|
|
app.use(express.static(join(__dirname, "dist")));
|
|
|
|
// Proxy go2rtc requests
|
|
const go2rtcProxy = createProxyMiddleware({
|
|
target: process.env.GO2RTC_URL || "http://kai-sa-go2rtc:1984",
|
|
changeOrigin: true,
|
|
ws: true,
|
|
pathRewrite: {
|
|
"^/go2rtc": "",
|
|
},
|
|
});
|
|
|
|
app.use("/go2rtc", go2rtcProxy);
|
|
|
|
// API routes
|
|
app.use("/api/recordings", recorderRouter);
|
|
app.use("/api/media", mediaRouter);
|
|
app.use("/api/talk", talkRouter);
|
|
app.use("/api", healthRouter);
|
|
|
|
// SPA fallback - serve index.html for non-API routes
|
|
app.get("*", (req, res, next) => {
|
|
if (req.path.startsWith("/api") || req.path.startsWith("/go2rtc")) {
|
|
return next();
|
|
}
|
|
res.sendFile(join(__dirname, "dist/index.html"));
|
|
});
|
|
|
|
const server = createServer(app);
|
|
|
|
server.on("upgrade", (req: any, socket: any, head: any) => {
|
|
if (req.url?.startsWith("/go2rtc")) {
|
|
go2rtcProxy.upgrade(req, socket, head);
|
|
}
|
|
});
|
|
|
|
// WebSocket server for talk
|
|
const wss = new WebSocketServer({ server, path: "/api/talk" });
|
|
|
|
wss.on("connection", (ws: WebSocket) => {
|
|
let paplayProcess: ChildProcessWithoutNullStreams | null = null;
|
|
|
|
ws.on("message", (data: Buffer | string, isBinary: boolean) => {
|
|
if (!isBinary) {
|
|
try {
|
|
const msg = JSON.parse(data.toString());
|
|
if (msg.rate && !paplayProcess) {
|
|
paplayProcess = spawn("paplay", [
|
|
"--raw",
|
|
`--rate=${msg.rate}`,
|
|
"--format=s16le",
|
|
"--channels=1",
|
|
"--latency-msec=150",
|
|
]);
|
|
}
|
|
} catch (e) {}
|
|
return;
|
|
}
|
|
|
|
if (paplayProcess?.stdin) {
|
|
paplayProcess.stdin.write(data);
|
|
}
|
|
});
|
|
|
|
ws.on("close", () => {
|
|
if (paplayProcess) {
|
|
paplayProcess.kill("SIGKILL");
|
|
paplayProcess = null;
|
|
}
|
|
});
|
|
});
|
|
|
|
server.listen(PORT, () => {
|
|
console.log(`kai-sa-cam server running on port ${PORT}`);
|
|
});
|