483 lines
16 KiB
JavaScript
483 lines
16 KiB
JavaScript
"use strict";
|
|
var __create = Object.create;
|
|
var __defProp = Object.defineProperty;
|
|
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
var __getProtoOf = Object.getPrototypeOf;
|
|
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
var __copyProps = (to, from, except, desc) => {
|
|
if (from && typeof from === "object" || typeof from === "function") {
|
|
for (let key of __getOwnPropNames(from))
|
|
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
}
|
|
return to;
|
|
};
|
|
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
// If the importer is in node compatibility mode or this is not an ESM
|
|
// file that has been converted to a CommonJS file using a Babel-
|
|
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
mod
|
|
));
|
|
|
|
// src/server/index.ts
|
|
var import_express5 = __toESM(require("express"), 1);
|
|
var import_http_proxy_middleware = require("http-proxy-middleware");
|
|
var import_http = require("http");
|
|
var import_ws = require("ws");
|
|
var import_child_process2 = require("child_process");
|
|
var import_path3 = require("path");
|
|
|
|
// src/server/recorder.ts
|
|
var import_express = require("express");
|
|
var import_child_process = require("child_process");
|
|
var import_fs = require("fs");
|
|
var import_path = require("path");
|
|
var router = (0, import_express.Router)();
|
|
var MEDIA_DIR = process.env.MEDIA_DIR || "/media";
|
|
var CONFIG_DIR = process.env.CONFIG_DIR || "/config";
|
|
var GO2RTC_RTSP_URL = process.env.GO2RTC_RTSP_URL || "rtsp://kai-sa-go2rtc:8554/webcam";
|
|
var MAX_RECORDING_MINUTES = parseInt(process.env.MAX_RECORDING_MINUTES || "120", 10);
|
|
var DISK_MIN_FREE_GB = parseInt(process.env.DISK_MIN_FREE_GB || "2", 10);
|
|
var recordingProcess = null;
|
|
var recordingStartTime = null;
|
|
var currentRecordingFile = null;
|
|
if (!(0, import_fs.existsSync)(MEDIA_DIR)) {
|
|
(0, import_fs.mkdirSync)(MEDIA_DIR, { recursive: true });
|
|
}
|
|
function checkDiskSpace() {
|
|
try {
|
|
const stats = (0, import_fs.statSync)(MEDIA_DIR);
|
|
return true;
|
|
} catch {
|
|
return false;
|
|
}
|
|
}
|
|
function generateFilename(ext) {
|
|
const now = /* @__PURE__ */ new Date();
|
|
const timestamp = now.toISOString().replace(/[:.]/g, "-").split("T").join("_");
|
|
return `recording_${timestamp}.${ext}`;
|
|
}
|
|
function finalizeRecording(partPath) {
|
|
if (!partPath) return;
|
|
if (!(0, import_fs.existsSync)(partPath)) {
|
|
console.log("No part file to finalize");
|
|
return;
|
|
}
|
|
try {
|
|
const stats = (0, import_fs.statSync)(partPath);
|
|
if (stats.size < 1024) {
|
|
console.error(`Recording file too small (${stats.size} bytes), removing: ${partPath}`);
|
|
try {
|
|
(0, import_fs.unlinkSync)(partPath);
|
|
} catch {
|
|
}
|
|
return;
|
|
}
|
|
const finalPath = partPath.replace(/\.part$/, ".mp4");
|
|
(0, import_fs.renameSync)(partPath, finalPath);
|
|
console.log(`Recording saved: ${finalPath} (${stats.size} bytes)`);
|
|
} catch (e) {
|
|
console.error("Failed to finalize recording:", e);
|
|
}
|
|
}
|
|
router.post("/start", async (req, res) => {
|
|
if (recordingProcess) {
|
|
return res.status(409).json({ error: "Enregistrement d\xE9j\xE0 en cours" });
|
|
}
|
|
if (!checkDiskSpace()) {
|
|
return res.status(507).json({ error: "Espace disque insuffisant" });
|
|
}
|
|
const filename = generateFilename("part");
|
|
const filepath = (0, import_path.join)(MEDIA_DIR, filename);
|
|
currentRecordingFile = filepath;
|
|
recordingStartTime = Date.now();
|
|
const args = [
|
|
"-hide_banner",
|
|
"-loglevel",
|
|
"warning",
|
|
"-rtsp_transport",
|
|
"tcp",
|
|
"-fflags",
|
|
"+genpts",
|
|
"-use_wallclock_as_timestamps",
|
|
"1",
|
|
"-avoid_negative_ts",
|
|
"make_zero",
|
|
"-i",
|
|
GO2RTC_RTSP_URL,
|
|
"-c:v",
|
|
"libx264",
|
|
"-preset",
|
|
"ultrafast",
|
|
"-tune",
|
|
"zerolatency",
|
|
"-profile:v",
|
|
"baseline",
|
|
"-pix_fmt",
|
|
"yuv420p",
|
|
"-g",
|
|
"30",
|
|
"-an",
|
|
// no audio
|
|
"-f",
|
|
"mp4",
|
|
"-movflags",
|
|
"+frag_keyframe+empty_moov+default_base_moof",
|
|
"-t",
|
|
`${MAX_RECORDING_MINUTES * 60}`,
|
|
filepath
|
|
];
|
|
const ffmpegPath = process.env.FFMPEG_PATH || "ffmpeg";
|
|
console.log("Starting ffmpeg with args:", args.join(" "));
|
|
console.log("Working directory:", process.cwd());
|
|
console.log("User:", process.getuid?.() || "N/A");
|
|
recordingProcess = (0, import_child_process.spawn)(ffmpegPath, args, {
|
|
stdio: ["ignore", "pipe", "pipe"],
|
|
cwd: process.cwd()
|
|
});
|
|
recordingProcess.stdout?.on("data", (data) => {
|
|
console.log(`ffmpeg stdout: ${data}`);
|
|
});
|
|
recordingProcess.stderr?.on("data", (data) => {
|
|
const msg = data.toString();
|
|
if (msg.trim()) console.log(`ffmpeg stderr: ${msg}`);
|
|
});
|
|
recordingProcess.stdout?.resume();
|
|
recordingProcess.stderr?.resume();
|
|
recordingProcess.on("close", (code) => {
|
|
console.log(`Recording ffmpeg exited with code ${code}`);
|
|
const fileToFinalize = currentRecordingFile;
|
|
finalizeRecording(fileToFinalize);
|
|
recordingProcess = null;
|
|
currentRecordingFile = null;
|
|
recordingStartTime = null;
|
|
});
|
|
recordingProcess.on("error", (err) => {
|
|
console.error("Recording process error:", err);
|
|
const fileToFinalize = currentRecordingFile;
|
|
finalizeRecording(fileToFinalize);
|
|
recordingProcess = null;
|
|
currentRecordingFile = null;
|
|
recordingStartTime = null;
|
|
});
|
|
res.json({ status: "started", filename: currentRecordingFile.replace(/\.part$/, ".mp4") });
|
|
});
|
|
router.post("/stop", async (req, res) => {
|
|
if (!recordingProcess) {
|
|
return res.status(409).json({ error: "Aucun enregistrement en cours" });
|
|
}
|
|
const proc = recordingProcess;
|
|
const fileToFinalize = currentRecordingFile;
|
|
try {
|
|
proc.kill("SIGINT");
|
|
} catch (e) {
|
|
console.error("Error sending SIGINT:", e);
|
|
}
|
|
let waited = 0;
|
|
while (recordingProcess && waited < 15e3) {
|
|
await new Promise((r) => setTimeout(r, 100));
|
|
waited += 100;
|
|
}
|
|
if (recordingProcess) {
|
|
try {
|
|
recordingProcess.kill("SIGKILL");
|
|
} catch (e) {
|
|
console.error("Error sending SIGKILL:", e);
|
|
}
|
|
await new Promise((r) => setTimeout(r, 500));
|
|
recordingProcess = null;
|
|
currentRecordingFile = null;
|
|
recordingStartTime = null;
|
|
finalizeRecording(fileToFinalize);
|
|
return res.status(500).json({ error: "\xC9chec arr\xEAt enregistrement" });
|
|
}
|
|
res.json({ status: "stopped" });
|
|
});
|
|
router.get("/status", async (req, res) => {
|
|
res.json({
|
|
isRecording: !!recordingProcess,
|
|
startTime: recordingStartTime,
|
|
currentFile: currentRecordingFile?.replace(/\.part$/, ".mp4")
|
|
});
|
|
});
|
|
|
|
// src/server/media.ts
|
|
var import_express2 = require("express");
|
|
var import_fs2 = require("fs");
|
|
var import_path2 = require("path");
|
|
var import_archiver = __toESM(require("archiver"), 1);
|
|
var router2 = (0, import_express2.Router)();
|
|
var MEDIA_DIR2 = process.env.MEDIA_DIR || "/media";
|
|
var CONFIG_DIR2 = process.env.CONFIG_DIR || "/config";
|
|
if (!(0, import_fs2.existsSync)(MEDIA_DIR2)) {
|
|
require("fs").mkdirSync(MEDIA_DIR2, { recursive: true });
|
|
}
|
|
function getMediaType(filename) {
|
|
const ext = (0, import_path2.extname)(filename).toLowerCase();
|
|
if ([".mp4", ".webm", ".mov", ".mkv"].includes(ext)) return "video";
|
|
if ([".jpg", ".jpeg", ".png", ".webp", ".bmp"].includes(ext)) return "image";
|
|
return "other";
|
|
}
|
|
router2.get("/", async (req, res) => {
|
|
try {
|
|
const files = (0, import_fs2.readdirSync)(MEDIA_DIR2);
|
|
const media = files.filter((f) => getMediaType(f) !== "other").map((filename) => {
|
|
const filepath = (0, import_path2.join)(MEDIA_DIR2, filename);
|
|
const stats = (0, import_fs2.statSync)(filepath);
|
|
return {
|
|
filename,
|
|
type: getMediaType(filename),
|
|
size: stats.size,
|
|
mtime: stats.mtime.toISOString(),
|
|
url: `/api/media/${filename}`
|
|
};
|
|
}).sort((a, b) => new Date(b.mtime).getTime() - new Date(a.mtime).getTime());
|
|
res.json(media);
|
|
} catch (e) {
|
|
console.error("Media list error:", e);
|
|
res.status(500).json({ error: "Failed to list media" });
|
|
}
|
|
});
|
|
router2.get("/:filename", async (req, res) => {
|
|
const { filename } = req.params;
|
|
const filepath = (0, import_path2.join)(MEDIA_DIR2, filename);
|
|
if (!(0, import_fs2.existsSync)(filepath)) {
|
|
return res.status(404).json({ error: "File not found" });
|
|
}
|
|
const resolved = require("path").resolve(filepath);
|
|
if (!resolved.startsWith(require("path").resolve(MEDIA_DIR2))) {
|
|
return res.status(403).json({ error: "Forbidden" });
|
|
}
|
|
const stats = (0, import_fs2.statSync)(filepath);
|
|
const download = req.query.download === "1";
|
|
if (download) {
|
|
res.setHeader("Content-Disposition", `attachment; filename="${filename}"`);
|
|
}
|
|
res.setHeader("Content-Length", stats.size);
|
|
res.setHeader("Accept-Ranges", "bytes");
|
|
const range = req.headers.range;
|
|
if (range) {
|
|
const parts = range.replace(/bytes=/, "").split("-");
|
|
const start = parseInt(parts[0], 10);
|
|
const end = parts[1] ? parseInt(parts[1], 10) : stats.size - 1;
|
|
const chunksize = end - start + 1;
|
|
res.status(206);
|
|
res.setHeader("Content-Range", `bytes ${start}-${end}/${stats.size}`);
|
|
res.setHeader("Content-Length", chunksize);
|
|
const stream2 = (0, import_fs2.createReadStream)(filepath, { start, end });
|
|
return stream2.pipe(res);
|
|
}
|
|
const stream = (0, import_fs2.createReadStream)(filepath);
|
|
stream.pipe(res);
|
|
});
|
|
router2.post("/snapshots", async (req, res) => {
|
|
const { spawn: spawn3 } = await import("child_process");
|
|
const GO2RTC_RTSP_URL2 = process.env.GO2RTC_RTSP_URL || "rtsp://kai-sa-go2rtc:8554/webcam";
|
|
const MEDIA_DIR3 = process.env.MEDIA_DIR || "/media";
|
|
const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-").split("T").join("_");
|
|
const filename = `snapshot_${timestamp}.jpg`;
|
|
const filepath = (0, import_path2.join)(MEDIA_DIR3, filename);
|
|
const ffmpegPath = process.env.FFMPEG_PATH || "ffmpeg";
|
|
const args = [
|
|
"-hide_banner",
|
|
"-loglevel",
|
|
"warning",
|
|
"-rtsp_transport",
|
|
"tcp",
|
|
"-i",
|
|
GO2RTC_RTSP_URL2,
|
|
"-frames:v",
|
|
"1",
|
|
"-q:v",
|
|
"2",
|
|
"-update",
|
|
"1",
|
|
filepath
|
|
];
|
|
const child = spawn3(ffmpegPath, args);
|
|
return new Promise((resolve, reject) => {
|
|
let stderr = "";
|
|
child.stderr?.on("data", (data) => {
|
|
stderr += data.toString();
|
|
});
|
|
child.on("close", (code) => {
|
|
if (code === 0) {
|
|
res.json({ filename });
|
|
resolve();
|
|
} else {
|
|
console.error("Snapshot ffmpeg failed:", stderr);
|
|
res.status(500).json({ error: "Snapshot failed", details: stderr });
|
|
reject(new Error("Snapshot failed"));
|
|
}
|
|
});
|
|
child.on("error", (err) => {
|
|
res.status(500).json({ error: "Snapshot error", details: err.message });
|
|
reject(err);
|
|
});
|
|
});
|
|
});
|
|
router2.delete("/:filename", async (req, res) => {
|
|
const { filename } = req.params;
|
|
const filepath = (0, import_path2.join)(MEDIA_DIR2, filename);
|
|
if (!(0, import_fs2.existsSync)(filepath)) {
|
|
return res.status(404).json({ error: "File not found" });
|
|
}
|
|
const resolved = require("path").resolve(filepath);
|
|
if (!resolved.startsWith(require("path").resolve(MEDIA_DIR2))) {
|
|
return res.status(403).json({ error: "Forbidden" });
|
|
}
|
|
try {
|
|
(0, import_fs2.unlinkSync)(filepath);
|
|
res.json({ status: "deleted" });
|
|
} catch (e) {
|
|
console.error("Delete error:", e);
|
|
res.status(500).json({ error: "Failed to delete" });
|
|
}
|
|
});
|
|
router2.post("/export", async (req, res) => {
|
|
try {
|
|
const files = (0, import_fs2.readdirSync)(MEDIA_DIR2).filter((f) => getMediaType(f) !== "other");
|
|
if (files.length === 0) {
|
|
return res.status(404).json({ error: "No media to export" });
|
|
}
|
|
const archive = (0, import_archiver.default)("zip", { zlib: { level: 9 } });
|
|
let completed = false;
|
|
let aborted = false;
|
|
res.setHeader("Content-Type", "application/zip");
|
|
res.setHeader("Content-Disposition", `attachment; filename="kai-sa-cam-media-${(/* @__PURE__ */ new Date()).toISOString().split("T")[0]}.zip"`);
|
|
archive.on("error", (err) => {
|
|
console.error("Archive error:", err);
|
|
if (!completed) {
|
|
res.status(500).json({ error: "Archive creation failed" });
|
|
}
|
|
});
|
|
archive.on("end", () => {
|
|
completed = true;
|
|
console.log("Archive completed");
|
|
setTimeout(() => {
|
|
for (const file of files) {
|
|
try {
|
|
const filepath = (0, import_path2.join)(MEDIA_DIR2, file);
|
|
if ((0, import_fs2.existsSync)(filepath)) {
|
|
(0, import_fs2.unlinkSync)(filepath);
|
|
console.log(`Deleted after export: ${file}`);
|
|
}
|
|
} catch (e) {
|
|
console.error(`Failed to delete ${file}:`, e);
|
|
}
|
|
}
|
|
}, 100);
|
|
});
|
|
req.on("aborted", () => {
|
|
aborted = true;
|
|
console.log("Export aborted by client");
|
|
});
|
|
res.on("close", () => {
|
|
if (!res.writableFinished) {
|
|
aborted = true;
|
|
console.log("Export connection closed prematurely");
|
|
}
|
|
});
|
|
archive.pipe(res);
|
|
for (const file of files) {
|
|
const filepath = (0, import_path2.join)(MEDIA_DIR2, file);
|
|
if ((0, import_fs2.existsSync)(filepath)) {
|
|
archive.file(filepath, { name: file });
|
|
}
|
|
}
|
|
await archive.finalize();
|
|
} catch (e) {
|
|
console.error("Export error:", e);
|
|
if (!res.headersSent) {
|
|
res.status(500).json({ error: "Export failed" });
|
|
}
|
|
}
|
|
});
|
|
|
|
// src/server/talk.ts
|
|
var import_express3 = require("express");
|
|
var router3 = (0, import_express3.Router)();
|
|
router3.get("/status", async (req, res) => {
|
|
res.json({ status: "ok", message: "Talk endpoint available at /api/talk WebSocket" });
|
|
});
|
|
|
|
// src/server/health.ts
|
|
var import_express4 = require("express");
|
|
var router4 = (0, import_express4.Router)();
|
|
router4.get("/health", async (req, res) => {
|
|
res.json({ status: "ok", service: "kai-sa-cam", timestamp: (/* @__PURE__ */ new Date()).toISOString() });
|
|
});
|
|
|
|
// src/server/index.ts
|
|
var __dirname = process.cwd();
|
|
var app = (0, import_express5.default)();
|
|
var PORT = process.env.PORT || 8090;
|
|
app.use(import_express5.default.json({ limit: "10mb" }));
|
|
app.use(import_express5.default.urlencoded({ extended: true }));
|
|
app.use(import_express5.default.static((0, import_path3.join)(__dirname, "dist")));
|
|
var go2rtcProxy = (0, import_http_proxy_middleware.createProxyMiddleware)({
|
|
target: process.env.GO2RTC_URL || "http://kai-sa-go2rtc:1984",
|
|
changeOrigin: true,
|
|
ws: true,
|
|
pathRewrite: {
|
|
"^/go2rtc": ""
|
|
}
|
|
});
|
|
app.use("/go2rtc", go2rtcProxy);
|
|
app.use("/api/recordings", router);
|
|
app.use("/api/media", router2);
|
|
app.use("/api/talk", router3);
|
|
app.use("/api", router4);
|
|
app.get("*", (req, res, next) => {
|
|
if (req.path.startsWith("/api") || req.path.startsWith("/go2rtc")) {
|
|
return next();
|
|
}
|
|
res.sendFile((0, import_path3.join)(__dirname, "dist/index.html"));
|
|
});
|
|
var server = (0, import_http.createServer)(app);
|
|
server.on("upgrade", (req, socket, head) => {
|
|
if (req.url?.startsWith("/go2rtc")) {
|
|
go2rtcProxy.upgrade(req, socket, head);
|
|
}
|
|
});
|
|
var wss = new import_ws.WebSocketServer({ server, path: "/api/talk" });
|
|
wss.on("connection", (ws, _req) => {
|
|
console.log("Talk WS connection established");
|
|
let paplayProcess = null;
|
|
ws.on("message", (data, isBinary) => {
|
|
if (!isBinary) {
|
|
try {
|
|
const msg = JSON.parse(data.toString());
|
|
if (msg.rate && !paplayProcess) {
|
|
paplayProcess = (0, import_child_process2.spawn)("paplay", [
|
|
"--raw",
|
|
`--rate=${msg.rate}`,
|
|
"--format=s16le",
|
|
"--channels=1",
|
|
"--latency-msec=150"
|
|
]);
|
|
paplayProcess.on("error", (e) => console.error("paplay error:", e.message));
|
|
}
|
|
} catch (e) {
|
|
console.error("Talk WS message parse error:", e);
|
|
}
|
|
return;
|
|
}
|
|
if (paplayProcess?.stdin) {
|
|
paplayProcess.stdin.write(data);
|
|
}
|
|
});
|
|
ws.on("close", () => {
|
|
if (paplayProcess) {
|
|
paplayProcess.stdin.end();
|
|
paplayProcess = null;
|
|
}
|
|
});
|
|
});
|
|
server.listen(PORT, () => {
|
|
console.log(`kai-sa-cam server running on port ${PORT}`);
|
|
});
|