fix: restore Access auth, add egress network, harden media routes
CD — Kai-Sa-Cam Deployment / deploy (push) Successful in 10s
CD — Kai-Sa-Cam Deployment / deploy (push) Successful in 10s
The app returned 401 on every request because jwtVerify could not fetch the Cloudflare Access signing keys (getaddrinfo EAI_AGAIN): kai-sa-cam was only attached to internal networks (kai-sa-cam-internal and the external kai-sa-cam-tunnel, which has Internal=true), so it had no DNS or route to the Internet. Network - add a dedicated kai-sa-cam-egress bridge network, attached to kai-sa-cam only - kai-sa-go2rtc stays on kai-sa-cam-internal only (no published ports, no outbound access); the video stream remains reachable solely through the authenticated /go2rtc proxy Auth (index.ts) - log the reason when an Access JWT is rejected instead of silently returning 401 - fail closed: exit at startup when CF_ACCESS_TEAM_DOMAIN or CF_ACCESS_AUD is missing, unless ALLOW_NO_AUTH=1 Media (media.ts) - replace inline require() calls with ESM imports (resolve, mkdirSync) - resolve the path first, then check it against MEDIA_DIR + path.sep (previous check ran after existsSync and accepted sibling prefixes) - on export, delete files only on the response "finish" event, not when the archive is finalized, so an interrupted download no longer loses media - snapshots: stop calling reject() after the response was sent, which caused unhandled rejections Recorder (recorder.ts) - enforce DISK_MIN_FREE_GB with statfsSync (was a stub returning true) - track the recording in a single state object and wait on an exit promise instead of polling; make cleanup idempotent - return 502 when ffmpeg exits right after start - recover orphaned .part files at startup - return file names instead of full paths from /start, /stop and /status
This commit is contained in:
@@ -22,6 +22,11 @@ const jwks =
|
||||
? createRemoteJWKSet(new URL(`${TEAM}/cdn-cgi/access/certs`))
|
||||
: null;
|
||||
|
||||
if (!jwks && process.env.ALLOW_NO_AUTH !== "1") {
|
||||
console.error("CF_ACCESS_TEAM_DOMAIN / CF_ACCESS_AUD manquants : arrêt.");
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
async function verifyAccess(headers: IncomingHttpHeaders): Promise<boolean> {
|
||||
if (!jwks) return true;
|
||||
const token = headers["cf-access-jwt-assertion"];
|
||||
|
||||
+191
-209
@@ -1,240 +1,222 @@
|
||||
import { Router, Request, Response } from 'express'
|
||||
import { readdirSync, statSync, unlinkSync, createReadStream, existsSync } from 'fs'
|
||||
import { join, extname } from 'path'
|
||||
import { pipeline } from 'stream/promises'
|
||||
import archiver from 'archiver'
|
||||
import { Router, Request, Response } from "express";
|
||||
import { readdirSync, statSync, unlinkSync, existsSync, mkdirSync } from "fs";
|
||||
import { join, extname, resolve, dirname } from "path";
|
||||
import { spawn } from "child_process";
|
||||
import archiver from "archiver";
|
||||
|
||||
const router = Router()
|
||||
const router = Router();
|
||||
|
||||
const MEDIA_DIR = process.env.MEDIA_DIR || '/media'
|
||||
const CONFIG_DIR = process.env.CONFIG_DIR || '/config'
|
||||
const MEDIA_DIR = process.env.MEDIA_DIR || "/media";
|
||||
const MEDIA_ROOT = resolve(MEDIA_DIR);
|
||||
const GO2RTC_RTSP_URL =
|
||||
process.env.GO2RTC_RTSP_URL || "rtsp://kai-sa-go2rtc:8554/webcam";
|
||||
const FFMPEG_PATH = process.env.FFMPEG_PATH || "ffmpeg";
|
||||
|
||||
// Ensure media directory exists
|
||||
if (!existsSync(MEDIA_DIR)) {
|
||||
require('fs').mkdirSync(MEDIA_DIR, { recursive: true })
|
||||
if (!existsSync(MEDIA_ROOT)) {
|
||||
mkdirSync(MEDIA_ROOT, { recursive: true });
|
||||
}
|
||||
|
||||
function getMediaType(filename: string): 'video' | 'image' | 'other' {
|
||||
const ext = extname(filename).toLowerCase()
|
||||
if (['.mp4', '.webm', '.mov', '.mkv'].includes(ext)) return 'video'
|
||||
if (['.jpg', '.jpeg', '.png', '.webp', '.bmp'].includes(ext)) return 'image'
|
||||
return 'other'
|
||||
function getMediaType(filename: string): "video" | "image" | "other" {
|
||||
const ext = extname(filename).toLowerCase();
|
||||
if ([".mp4", ".webm", ".mov", ".mkv"].includes(ext)) return "video";
|
||||
if ([".jpg", ".jpeg", ".png", ".webp", ".bmp"].includes(ext)) return "image";
|
||||
return "other";
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a user-supplied filename inside MEDIA_ROOT.
|
||||
* Returns null if it escapes the directory (../, encoded slashes, sibling
|
||||
* directories sharing the same prefix) or is not a media file.
|
||||
*/
|
||||
function safeMediaPath(filename: string): string | null {
|
||||
const full = resolve(MEDIA_ROOT, filename);
|
||||
if (dirname(full) !== MEDIA_ROOT) return null;
|
||||
if (getMediaType(full) === "other") return null;
|
||||
return full;
|
||||
}
|
||||
|
||||
// GET /api/media
|
||||
router.get('/', async (req: Request, res: Response) => {
|
||||
router.get("/", async (_req: Request, res: Response) => {
|
||||
try {
|
||||
const files = readdirSync(MEDIA_DIR)
|
||||
const files = readdirSync(MEDIA_ROOT);
|
||||
const media = files
|
||||
.filter(f => getMediaType(f) !== 'other')
|
||||
.map(filename => {
|
||||
const filepath = join(MEDIA_DIR, filename)
|
||||
const stats = statSync(filepath)
|
||||
.filter((f) => getMediaType(f) !== "other")
|
||||
.map((filename) => {
|
||||
const stats = statSync(join(MEDIA_ROOT, filename));
|
||||
return {
|
||||
filename,
|
||||
type: getMediaType(filename),
|
||||
size: stats.size,
|
||||
mtime: stats.mtime.toISOString(),
|
||||
url: `/api/media/${filename}`,
|
||||
}
|
||||
url: `/api/media/${encodeURIComponent(filename)}`,
|
||||
};
|
||||
})
|
||||
.sort((a, b) => new Date(b.mtime).getTime() - new Date(a.mtime).getTime())
|
||||
|
||||
res.json(media)
|
||||
.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' })
|
||||
console.error("Media list error:", e);
|
||||
res.status(500).json({ error: "Failed to list media" });
|
||||
}
|
||||
})
|
||||
});
|
||||
|
||||
// GET /api/media/:filename
|
||||
router.get('/:filename', async (req: Request, res: Response) => {
|
||||
const { filename } = req.params
|
||||
const filepath = join(MEDIA_DIR, filename)
|
||||
|
||||
if (!existsSync(filepath)) {
|
||||
return res.status(404).json({ error: 'File not found' })
|
||||
}
|
||||
|
||||
// Security: prevent directory traversal
|
||||
const resolved = require('path').resolve(filepath)
|
||||
if (!resolved.startsWith(require('path').resolve(MEDIA_DIR))) {
|
||||
return res.status(403).json({ error: 'Forbidden' })
|
||||
}
|
||||
|
||||
const stats = 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')
|
||||
|
||||
// Handle range requests for video seeking
|
||||
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 stream = createReadStream(filepath, { start, end })
|
||||
return stream.pipe(res)
|
||||
}
|
||||
|
||||
const stream = createReadStream(filepath)
|
||||
stream.pipe(res)
|
||||
})
|
||||
// POST /api/media/snapshots
|
||||
router.post("/snapshots", (_req: Request, res: Response) => {
|
||||
const timestamp = new Date()
|
||||
.toISOString()
|
||||
.replace(/[:.]/g, "-")
|
||||
.split("T")
|
||||
.join("_");
|
||||
const filename = `snapshot_${timestamp}.jpg`;
|
||||
const filepath = join(MEDIA_ROOT, filename);
|
||||
|
||||
// POST /api/snapshots
|
||||
router.post('/snapshots', async (req: Request, res: Response) => {
|
||||
const { spawn } = await import('child_process')
|
||||
|
||||
const GO2RTC_RTSP_URL = process.env.GO2RTC_RTSP_URL || 'rtsp://kai-sa-go2rtc:8554/webcam'
|
||||
const MEDIA_DIR = process.env.MEDIA_DIR || '/media'
|
||||
|
||||
const timestamp = new Date().toISOString().replace(/[:.]/g, '-').split('T').join('_')
|
||||
const filename = `snapshot_${timestamp}.jpg`
|
||||
const filepath = join(MEDIA_DIR, filename)
|
||||
|
||||
const ffmpegPath = process.env.FFMPEG_PATH || 'ffmpeg'
|
||||
const args = [
|
||||
'-hide_banner',
|
||||
'-loglevel', 'warning',
|
||||
'-rtsp_transport', 'tcp',
|
||||
'-i', GO2RTC_RTSP_URL,
|
||||
'-frames:v', '1',
|
||||
'-q:v', '2',
|
||||
'-update', '1',
|
||||
"-hide_banner",
|
||||
"-loglevel",
|
||||
"warning",
|
||||
"-rtsp_transport",
|
||||
"tcp",
|
||||
"-i",
|
||||
GO2RTC_RTSP_URL,
|
||||
"-frames:v",
|
||||
"1",
|
||||
"-q:v",
|
||||
"2",
|
||||
"-update",
|
||||
"1",
|
||||
filepath,
|
||||
]
|
||||
|
||||
const child = spawn(ffmpegPath, args)
|
||||
|
||||
return new Promise<void>((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'))
|
||||
];
|
||||
|
||||
const child = spawn(FFMPEG_PATH, args);
|
||||
let stderr = "";
|
||||
let replied = false;
|
||||
|
||||
const reply = (status: number, body: object) => {
|
||||
if (replied) return;
|
||||
replied = true;
|
||||
clearTimeout(timer);
|
||||
res.status(status).json(body);
|
||||
};
|
||||
|
||||
// Do not hang forever if the stream is unavailable
|
||||
const timer = setTimeout(() => {
|
||||
child.kill("SIGKILL");
|
||||
reply(504, { error: "Snapshot timeout" });
|
||||
}, 15_000);
|
||||
|
||||
child.stderr?.on("data", (d) => {
|
||||
stderr += d.toString();
|
||||
});
|
||||
child.on("error", (err) => {
|
||||
console.error("Snapshot spawn error:", err);
|
||||
reply(500, { error: "Snapshot error" });
|
||||
});
|
||||
child.on("close", (code) => {
|
||||
if (code === 0) {
|
||||
reply(200, { filename });
|
||||
} else {
|
||||
console.error("Snapshot ffmpeg failed:", stderr);
|
||||
try {
|
||||
unlinkSync(filepath);
|
||||
} catch {}
|
||||
reply(500, { error: "Snapshot failed" });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// POST /api/media/export - ZIP of all media; files are deleted only once the
|
||||
// response has been fully written, never if the download is interrupted.
|
||||
router.post("/export", (req: Request, res: Response) => {
|
||||
let files: string[];
|
||||
try {
|
||||
files = readdirSync(MEDIA_ROOT).filter((f) => getMediaType(f) !== "other");
|
||||
} catch (e) {
|
||||
console.error("Export error:", e);
|
||||
return res.status(500).json({ error: "Export failed" });
|
||||
}
|
||||
|
||||
if (files.length === 0) {
|
||||
return res.status(404).json({ error: "No media to export" });
|
||||
}
|
||||
|
||||
// Videos/images are already compressed: store instead of deflating.
|
||||
const archive = archiver("zip", { store: true });
|
||||
|
||||
res.setHeader("Content-Type", "application/zip");
|
||||
res.setHeader(
|
||||
"Content-Disposition",
|
||||
`attachment; filename="kai-sa-cam-media-${new Date().toISOString().split("T")[0]}.zip"`,
|
||||
);
|
||||
|
||||
archive.on("warning", (err) => console.warn("Archive warning:", err));
|
||||
archive.on("error", (err) => {
|
||||
console.error("Archive error:", err);
|
||||
if (!res.headersSent)
|
||||
res.status(500).json({ error: "Archive creation failed" });
|
||||
else res.destroy();
|
||||
});
|
||||
|
||||
// 'finish' = the whole ZIP was handed to the connection. 'close' without
|
||||
// 'finish' = client aborted: keep the files.
|
||||
res.on("finish", () => {
|
||||
console.log("Export sent, deleting exported files");
|
||||
for (const file of files) {
|
||||
try {
|
||||
unlinkSync(join(MEDIA_ROOT, file));
|
||||
console.log(`Deleted after export: ${file}`);
|
||||
} catch (e) {
|
||||
console.error(`Failed to delete ${file}:`, e);
|
||||
}
|
||||
})
|
||||
child.on('error', (err) => {
|
||||
res.status(500).json({ error: 'Snapshot error', details: err.message })
|
||||
reject(err)
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
});
|
||||
res.on("close", () => {
|
||||
if (!res.writableFinished) {
|
||||
console.log("Export interrupted, files kept");
|
||||
archive.abort();
|
||||
}
|
||||
});
|
||||
|
||||
archive.pipe(res);
|
||||
for (const file of files) {
|
||||
archive.file(join(MEDIA_ROOT, file), { name: file });
|
||||
}
|
||||
void archive.finalize();
|
||||
});
|
||||
|
||||
// GET /api/media/:filename (Express handles Range requests, Content-Type, etc.)
|
||||
router.get("/:filename", (req: Request, res: Response) => {
|
||||
const filepath = safeMediaPath(req.params.filename);
|
||||
if (!filepath) return res.status(403).json({ error: "Forbidden" });
|
||||
if (!existsSync(filepath))
|
||||
return res.status(404).json({ error: "File not found" });
|
||||
|
||||
if (req.query.download === "1") {
|
||||
res.attachment(req.params.filename);
|
||||
}
|
||||
res.sendFile(filepath, { dotfiles: "deny" }, (err) => {
|
||||
if (err && !res.headersSent) {
|
||||
res.status(500).json({ error: "Failed to read file" });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// DELETE /api/media/:filename
|
||||
router.delete('/:filename', async (req: Request, res: Response) => {
|
||||
const { filename } = req.params
|
||||
const filepath = join(MEDIA_DIR, filename)
|
||||
|
||||
if (!existsSync(filepath)) {
|
||||
return res.status(404).json({ error: 'File not found' })
|
||||
}
|
||||
|
||||
// Security check
|
||||
const resolved = require('path').resolve(filepath)
|
||||
if (!resolved.startsWith(require('path').resolve(MEDIA_DIR))) {
|
||||
return res.status(403).json({ error: 'Forbidden' })
|
||||
}
|
||||
|
||||
try {
|
||||
unlinkSync(filepath)
|
||||
res.json({ status: 'deleted' })
|
||||
} catch (e) {
|
||||
console.error('Delete error:', e)
|
||||
res.status(500).json({ error: 'Failed to delete' })
|
||||
}
|
||||
})
|
||||
router.delete("/:filename", (req: Request, res: Response) => {
|
||||
const filepath = safeMediaPath(req.params.filename);
|
||||
if (!filepath) return res.status(403).json({ error: "Forbidden" });
|
||||
if (!existsSync(filepath))
|
||||
return res.status(404).json({ error: "File not found" });
|
||||
|
||||
// POST /api/media/export - Create ZIP of all media and stream it
|
||||
router.post('/export', async (req: Request, res: Response) => {
|
||||
try {
|
||||
const files = readdirSync(MEDIA_DIR)
|
||||
.filter(f => getMediaType(f) !== 'other')
|
||||
|
||||
if (files.length === 0) {
|
||||
return res.status(404).json({ error: 'No media to export' })
|
||||
}
|
||||
|
||||
const archive = archiver('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-${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')
|
||||
// Delete files after successful archive completion
|
||||
setTimeout(() => {
|
||||
for (const file of files) {
|
||||
try {
|
||||
const filepath = join(MEDIA_DIR, file)
|
||||
if (existsSync(filepath)) {
|
||||
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 = join(MEDIA_DIR, file)
|
||||
if (existsSync(filepath)) {
|
||||
archive.file(filepath, { name: file })
|
||||
}
|
||||
}
|
||||
|
||||
await archive.finalize()
|
||||
unlinkSync(filepath);
|
||||
res.json({ status: "deleted" });
|
||||
} catch (e) {
|
||||
console.error('Export error:', e)
|
||||
if (!res.headersSent) {
|
||||
res.status(500).json({ error: 'Export failed' })
|
||||
}
|
||||
console.error("Delete error:", e);
|
||||
res.status(500).json({ error: "Failed to delete" });
|
||||
}
|
||||
})
|
||||
});
|
||||
|
||||
export { router as mediaRouter }
|
||||
export { router as mediaRouter };
|
||||
|
||||
@@ -1,43 +1,69 @@
|
||||
import { Router, Request, Response } from "express";
|
||||
import { spawn, ChildProcess } from "child_process";
|
||||
import { existsSync, mkdirSync, renameSync, statSync, unlinkSync } from "fs";
|
||||
import { join } from "path";
|
||||
import {
|
||||
existsSync,
|
||||
mkdirSync,
|
||||
readdirSync,
|
||||
renameSync,
|
||||
statSync,
|
||||
statfsSync,
|
||||
unlinkSync,
|
||||
} from "fs";
|
||||
import { join, basename } from "path";
|
||||
|
||||
const router = Router();
|
||||
|
||||
// Get config from environment
|
||||
function envInt(name: string, fallback: number): number {
|
||||
const n = Number.parseInt(process.env[name] ?? "", 10);
|
||||
return Number.isFinite(n) && n >= 0 ? n : fallback;
|
||||
}
|
||||
|
||||
const MEDIA_DIR = process.env.MEDIA_DIR || "/media";
|
||||
const CONFIG_DIR = process.env.CONFIG_DIR || "/config";
|
||||
const GO2RTC_RTSP_URL =
|
||||
process.env.GO2RTC_RTSP_URL || "rtsp://kai-sa-go2rtc:8554/webcam";
|
||||
const MAX_RECORDING_MINUTES = parseInt(
|
||||
process.env.MAX_RECORDING_MINUTES || "120",
|
||||
10,
|
||||
);
|
||||
const DISK_MIN_FREE_GB = parseInt(process.env.DISK_MIN_FREE_GB || "2", 10);
|
||||
const FFMPEG_PATH = process.env.FFMPEG_PATH || "ffmpeg";
|
||||
const MAX_RECORDING_MINUTES = envInt("MAX_RECORDING_MINUTES", 120);
|
||||
const DISK_MIN_FREE_GB = envInt("DISK_MIN_FREE_GB", 2);
|
||||
|
||||
let recordingProcess: ChildProcess | null = null;
|
||||
let recordingStartTime: number | null = null;
|
||||
let currentRecordingFile: string | null = null;
|
||||
type Recording = {
|
||||
proc: ChildProcess;
|
||||
partPath: string;
|
||||
startTime: number;
|
||||
exited: Promise<void>; // resolves once ffmpeg is gone and the file is finalized
|
||||
};
|
||||
|
||||
let current: Recording | null = null;
|
||||
|
||||
// Ensure media directory exists
|
||||
if (!existsSync(MEDIA_DIR)) {
|
||||
mkdirSync(MEDIA_DIR, { recursive: true });
|
||||
}
|
||||
|
||||
function checkDiskSpace(): boolean {
|
||||
const finalPathOf = (partPath: string) => partPath.replace(/\.part$/, ".mp4");
|
||||
const publicName = (partPath: string) => basename(finalPathOf(partPath));
|
||||
|
||||
/** Resolves true if `p` settles within `ms`, false otherwise. */
|
||||
function settledWithin(p: Promise<void>, ms: number): Promise<boolean> {
|
||||
return new Promise((resolve) => {
|
||||
const t = setTimeout(() => resolve(false), ms);
|
||||
void p.then(() => {
|
||||
clearTimeout(t);
|
||||
resolve(true);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function hasEnoughDisk(): boolean {
|
||||
try {
|
||||
const stats = statSync(MEDIA_DIR);
|
||||
// Simple check - in production you'd use df
|
||||
const s = statfsSync(MEDIA_DIR);
|
||||
return (s.bavail * s.bsize) / 1024 ** 3 >= DISK_MIN_FREE_GB;
|
||||
} catch (e) {
|
||||
console.warn("Disk space check unavailable:", e);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function generateFilename(ext: string): string {
|
||||
const now = new Date();
|
||||
const timestamp = now
|
||||
const timestamp = new Date()
|
||||
.toISOString()
|
||||
.replace(/[:.]/g, "-")
|
||||
.split("T")
|
||||
@@ -45,47 +71,44 @@ function generateFilename(ext: string): string {
|
||||
return `recording_${timestamp}.${ext}`;
|
||||
}
|
||||
|
||||
function finalizeRecording(partPath: string | null): void {
|
||||
if (!partPath) return;
|
||||
if (!existsSync(partPath)) {
|
||||
console.log("No part file to finalize");
|
||||
return;
|
||||
}
|
||||
/** Rename a .part file to .mp4, or delete it if it is empty/too small. */
|
||||
function finalizeRecording(partPath: string): void {
|
||||
if (!existsSync(partPath)) return;
|
||||
try {
|
||||
const stats = statSync(partPath);
|
||||
if (stats.size < 1024) {
|
||||
const { size } = statSync(partPath);
|
||||
if (size < 1024) {
|
||||
console.error(
|
||||
`Recording file too small (${stats.size} bytes), removing: ${partPath}`,
|
||||
`Recording too small (${size} bytes), removing: ${partPath}`,
|
||||
);
|
||||
try {
|
||||
unlinkSync(partPath);
|
||||
} catch {}
|
||||
unlinkSync(partPath);
|
||||
return;
|
||||
}
|
||||
const finalPath = partPath.replace(/\.part$/, ".mp4");
|
||||
const finalPath = finalPathOf(partPath);
|
||||
renameSync(partPath, finalPath);
|
||||
console.log(`Recording saved: ${finalPath} (${stats.size} bytes)`);
|
||||
console.log(`Recording saved: ${finalPath} (${size} bytes)`);
|
||||
} catch (e) {
|
||||
console.error("Failed to finalize recording:", e);
|
||||
}
|
||||
}
|
||||
|
||||
// A crash or restart mid-recording leaves a .part file behind. The MP4 is
|
||||
// fragmented, so it is still playable: recover it at startup.
|
||||
for (const f of readdirSync(MEDIA_DIR)) {
|
||||
if (f.endsWith(".part")) finalizeRecording(join(MEDIA_DIR, f));
|
||||
}
|
||||
|
||||
// POST /api/recordings/start
|
||||
router.post("/start", async (req: Request, res: Response) => {
|
||||
if (recordingProcess) {
|
||||
router.post("/start", async (_req: Request, res: Response) => {
|
||||
if (current) {
|
||||
return res.status(409).json({ error: "Enregistrement déjà en cours" });
|
||||
}
|
||||
|
||||
if (!checkDiskSpace()) {
|
||||
if (!hasEnoughDisk()) {
|
||||
return res.status(507).json({ error: "Espace disque insuffisant" });
|
||||
}
|
||||
|
||||
const filename = generateFilename("part");
|
||||
const filepath = join(MEDIA_DIR, filename);
|
||||
currentRecordingFile = filepath;
|
||||
recordingStartTime = Date.now();
|
||||
const partPath = join(MEDIA_DIR, generateFilename("part"));
|
||||
|
||||
// ffmpeg command for recording (video only, no audio in RTSP stream)
|
||||
// Video only: the RTSP stream carries no audio.
|
||||
const args = [
|
||||
"-hide_banner",
|
||||
"-loglevel",
|
||||
@@ -112,109 +135,90 @@ router.post("/start", async (req: Request, res: Response) => {
|
||||
"yuv420p",
|
||||
"-g",
|
||||
"30",
|
||||
"-an", // no audio
|
||||
"-an",
|
||||
"-f",
|
||||
"mp4",
|
||||
"-movflags",
|
||||
"+frag_keyframe+empty_moov+default_base_moof",
|
||||
"-t",
|
||||
`${MAX_RECORDING_MINUTES * 60}`,
|
||||
filepath,
|
||||
...(MAX_RECORDING_MINUTES > 0
|
||||
? ["-t", `${MAX_RECORDING_MINUTES * 60}`]
|
||||
: []),
|
||||
partPath,
|
||||
];
|
||||
|
||||
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 = spawn(ffmpegPath, args, {
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
cwd: process.cwd(),
|
||||
console.log("Starting ffmpeg:", args.join(" "));
|
||||
const proc = spawn(FFMPEG_PATH, args, {
|
||||
stdio: ["ignore", "ignore", "pipe"],
|
||||
});
|
||||
|
||||
recordingProcess.stdout?.on("data", (data) => {
|
||||
console.log(`ffmpeg stdout: ${data}`);
|
||||
proc.stderr?.on("data", (d: Buffer) => {
|
||||
const msg = d.toString().trim();
|
||||
if (msg) console.log(`ffmpeg: ${msg}`);
|
||||
});
|
||||
|
||||
recordingProcess.stderr?.on("data", (data) => {
|
||||
const msg = data.toString();
|
||||
if (msg.trim()) console.log(`ffmpeg stderr: ${msg}`);
|
||||
// 'close' and 'error' can both fire: make the cleanup idempotent.
|
||||
const exited = new Promise<void>((resolve) => {
|
||||
let ended = false;
|
||||
const end = (reason: string) => {
|
||||
if (ended) return;
|
||||
ended = true;
|
||||
console.log(`Recording ended (${reason})`);
|
||||
finalizeRecording(partPath);
|
||||
if (current?.proc === proc) current = null;
|
||||
resolve();
|
||||
};
|
||||
proc.on("close", (code, signal) => end(`code=${code} signal=${signal}`));
|
||||
proc.on("error", (err) => {
|
||||
console.error("Recording process error:", err);
|
||||
end("process error");
|
||||
});
|
||||
});
|
||||
|
||||
// Consume stdout/stderr to prevent blocking
|
||||
recordingProcess.stdout?.resume();
|
||||
recordingProcess.stderr?.resume();
|
||||
current = { proc, partPath, startTime: Date.now(), exited };
|
||||
|
||||
recordingProcess.on("close", (code) => {
|
||||
console.log(`Recording ffmpeg exited with code ${code}`);
|
||||
const fileToFinalize = currentRecordingFile;
|
||||
// Try to finalize regardless of exit code (SIGINT often gives non-zero)
|
||||
finalizeRecording(fileToFinalize);
|
||||
recordingProcess = null;
|
||||
currentRecordingFile = null;
|
||||
recordingStartTime = null;
|
||||
});
|
||||
// If ffmpeg dies right away (stream down, bad args), tell the client
|
||||
// instead of reporting a recording that does not exist.
|
||||
if (await settledWithin(exited, 1500)) {
|
||||
return res.status(502).json({
|
||||
error: "Échec du démarrage de l'enregistrement (flux indisponible ?)",
|
||||
});
|
||||
}
|
||||
|
||||
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"),
|
||||
});
|
||||
res.json({ status: "started", filename: publicName(partPath) });
|
||||
});
|
||||
|
||||
// POST /api/recordings/stop
|
||||
router.post("/stop", async (req: Request, res: Response) => {
|
||||
if (!recordingProcess) {
|
||||
router.post("/stop", async (_req: Request, res: Response) => {
|
||||
const rec = current;
|
||||
if (!rec) {
|
||||
return res.status(409).json({ error: "Aucun enregistrement en cours" });
|
||||
}
|
||||
|
||||
const proc = recordingProcess;
|
||||
const fileToFinalize = currentRecordingFile;
|
||||
|
||||
try {
|
||||
// Try graceful shutdown first
|
||||
proc.kill("SIGINT");
|
||||
rec.proc.kill("SIGINT"); // graceful: lets ffmpeg flush the last fragment
|
||||
} catch (e) {
|
||||
console.error("Error sending SIGINT:", e);
|
||||
}
|
||||
|
||||
// Wait for process to exit (max 15 seconds)
|
||||
let waited = 0;
|
||||
while (recordingProcess && waited < 15000) {
|
||||
await new Promise((r) => setTimeout(r, 100));
|
||||
waited += 100;
|
||||
if (await settledWithin(rec.exited, 15_000)) {
|
||||
return res.json({ status: "stopped", filename: publicName(rec.partPath) });
|
||||
}
|
||||
|
||||
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: "Échec arrêt enregistrement" });
|
||||
try {
|
||||
rec.proc.kill("SIGKILL");
|
||||
} catch (e) {
|
||||
console.error("Error sending SIGKILL:", e);
|
||||
}
|
||||
|
||||
res.json({ status: "stopped" });
|
||||
await settledWithin(rec.exited, 2000);
|
||||
res.status(500).json({ error: "Échec arrêt enregistrement" });
|
||||
});
|
||||
|
||||
// GET /api/recordings/status
|
||||
router.get("/status", async (req: Request, res: Response) => {
|
||||
router.get("/status", (_req: Request, res: Response) => {
|
||||
res.json({
|
||||
isRecording: !!recordingProcess,
|
||||
startTime: recordingStartTime,
|
||||
currentFile: currentRecordingFile?.replace(/\.part$/, ".mp4"),
|
||||
isRecording: !!current,
|
||||
startTime: current?.startTime ?? null,
|
||||
currentFile: current ? publicName(current.partPath) : undefined,
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
Reference in New Issue
Block a user