refactor: move app from apps/kai-sa-cam to the repository root
CD — Kai-Sa-Cam Deployment / deploy (push) Successful in 9s
CD — Kai-Sa-Cam Deployment / deploy (push) Successful in 9s
- move sources, Dockerfile and build config (src, public, package.json, vite/tailwind/postcss/tsconfig, index.html) to the repo root - docker-compose: build context is now "." instead of ./apps/kai-sa-cam - add a .dockerignore (node_modules, dist, media, config, .env, ...) so the larger build context does not ship media, secrets or local node_modules into the image - deploy workflow: replace the apps/kai-sa-cam/** paths filter with paths-ignore so pushes keep triggering deployments - remove the Renovate workflow
This commit is contained in:
+151
@@ -0,0 +1,151 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import { VideoPlayer } from "./components/VideoPlayer";
|
||||
import { Controls } from "./components/Controls";
|
||||
import { MediaGallery } from "./components/MediaGallery";
|
||||
import { useRecorder } from "./hooks/useRecorder";
|
||||
import { useTalk } from "./hooks/useTalk";
|
||||
import {
|
||||
apiFetch,
|
||||
onSessionChange,
|
||||
reauthenticate,
|
||||
startSessionMonitor,
|
||||
} from "./lib/api";
|
||||
|
||||
export function App() {
|
||||
const [activeTab, setActiveTab] = useState<"live" | "media">("live");
|
||||
const [isRecording, setIsRecording] = useState(false);
|
||||
const [gain, setGain] = useState(1);
|
||||
const [recordingTime, setRecordingTime] = useState(0);
|
||||
const [snapshots, setSnapshots] = useState<string[]>([]);
|
||||
const [sessionExpired, setSessionExpired] = useState(false);
|
||||
const [streamKey, setStreamKey] = useState(0);
|
||||
|
||||
const {
|
||||
startRecording,
|
||||
stopRecording,
|
||||
error: recError,
|
||||
} = useRecorder({
|
||||
onStart: () => {
|
||||
setIsRecording(true);
|
||||
setRecordingTime(0);
|
||||
},
|
||||
onStop: () => {
|
||||
setIsRecording(false);
|
||||
setRecordingTime(0);
|
||||
},
|
||||
onTimeUpdate: (t) => setRecordingTime(t),
|
||||
});
|
||||
|
||||
const {
|
||||
isTalking,
|
||||
startTalk,
|
||||
stopTalk,
|
||||
error: talkError,
|
||||
} = useTalk({ gain });
|
||||
|
||||
// Surveillance de la session Cloudflare Access + bandeau de reconnexion
|
||||
useEffect(() => {
|
||||
const off = onSessionChange((expired) => {
|
||||
setSessionExpired(expired);
|
||||
if (!expired) setStreamKey((k) => k + 1); // recharge le flux vidéo après reconnexion
|
||||
});
|
||||
const stop = startSessionMonitor();
|
||||
return () => {
|
||||
off();
|
||||
stop();
|
||||
};
|
||||
}, []);
|
||||
|
||||
const handleRecord = async () => {
|
||||
if (isRecording) {
|
||||
await stopRecording();
|
||||
} else {
|
||||
await startRecording();
|
||||
}
|
||||
};
|
||||
|
||||
const handleSnapshot = async () => {
|
||||
try {
|
||||
const res = await apiFetch("/api/media/snapshots", { method: "POST" });
|
||||
if (!res.ok) throw new Error("Snapshot failed");
|
||||
const data = await res.json();
|
||||
setSnapshots((prev) => [data.filename, ...prev]);
|
||||
} catch (e) {
|
||||
console.error("Snapshot error:", e);
|
||||
}
|
||||
};
|
||||
|
||||
const handleTalk = async () => {
|
||||
if (isTalking) stopTalk();
|
||||
else await startTalk();
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-900 text-white flex flex-col">
|
||||
<header className="bg-gray-800 border-b border-gray-700 px-4 py-3 flex items-center justify-between">
|
||||
<h1 className="text-xl font-semibold flex items-center gap-3">
|
||||
<img src="/logo.png" alt="Logo" className="w-8 h-8 object-contain" />
|
||||
Kai-Sa-Cam
|
||||
</h1>
|
||||
</header>
|
||||
|
||||
{sessionExpired && (
|
||||
<div className="bg-amber-600 text-white text-sm px-4 py-2 flex items-center justify-between">
|
||||
<span>Session expirée.</span>
|
||||
<button
|
||||
className="underline font-medium"
|
||||
onClick={() => reauthenticate().catch(() => {})}
|
||||
>
|
||||
Se reconnecter
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<main className="flex-1 flex flex-col">
|
||||
<nav className="flex border-b border-gray-700 bg-gray-800">
|
||||
<button
|
||||
className={`flex-1 py-3 text-center font-medium ${activeTab === "live" ? "text-blue-400 border-b-2 border-blue-400" : "text-gray-400"}`}
|
||||
onClick={() => setActiveTab("live")}
|
||||
>
|
||||
Live
|
||||
</button>
|
||||
<button
|
||||
className={`flex-1 py-3 text-center font-medium ${activeTab === "media" ? "text-blue-400 border-b-2 border-blue-400" : "text-gray-400"}`}
|
||||
onClick={() => setActiveTab("media")}
|
||||
>
|
||||
Médias
|
||||
</button>
|
||||
</nav>
|
||||
|
||||
{activeTab === "live" ? (
|
||||
<div className="flex-1 flex flex-col p-4 gap-4 overflow-hidden">
|
||||
{/* Même origine => même session Access, plus de stream.esiah.dev.
|
||||
Le key force le rechargement du flux après une reconnexion. */}
|
||||
<VideoPlayer
|
||||
key={streamKey}
|
||||
streamUrl="/go2rtc/stream.html?src=webcam&mode=mse"
|
||||
/>
|
||||
<Controls
|
||||
isRecording={isRecording}
|
||||
recordingTime={recordingTime}
|
||||
isTalking={isTalking}
|
||||
gain={gain}
|
||||
onGainChange={setGain}
|
||||
onRecord={handleRecord}
|
||||
onSnapshot={handleSnapshot}
|
||||
onTalk={handleTalk}
|
||||
disabled={Boolean(recError || talkError)}
|
||||
/>
|
||||
{(recError || talkError) && (
|
||||
<div className="text-red-400 text-sm text-center px-4">
|
||||
{recError || talkError}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<MediaGallery />
|
||||
)}
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
interface ControlsProps {
|
||||
isRecording: boolean;
|
||||
recordingTime: number;
|
||||
isTalking: boolean;
|
||||
gain: number;
|
||||
onGainChange: (gain: number) => void;
|
||||
onRecord: () => void;
|
||||
onSnapshot: () => void;
|
||||
onTalk: () => void;
|
||||
disabled?: boolean;
|
||||
}
|
||||
|
||||
export function Controls({
|
||||
isRecording,
|
||||
recordingTime,
|
||||
isTalking,
|
||||
gain,
|
||||
onGainChange,
|
||||
onRecord,
|
||||
onSnapshot,
|
||||
onTalk,
|
||||
disabled,
|
||||
}: ControlsProps) {
|
||||
const formatTime = (seconds: number) => {
|
||||
const mins = Math.floor(seconds / 60);
|
||||
const secs = seconds % 60;
|
||||
return `${mins.toString().padStart(2, "0")}:${secs.toString().padStart(2, "0")}`;
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="glass-card p-4 rounded-2xl flex flex-col md:flex-row items-center justify-between gap-4">
|
||||
<div className="flex items-center gap-3">
|
||||
<button
|
||||
onClick={onRecord}
|
||||
disabled={disabled}
|
||||
className={`px-4 py-2 rounded-xl text-sm font-medium transition-all ${
|
||||
isRecording
|
||||
? "bg-red-500/20 text-red-400 border border-red-500/30"
|
||||
: "glass-button text-zinc-200"
|
||||
}`}
|
||||
>
|
||||
{isRecording
|
||||
? `Arrêter (${formatTime(recordingTime)})`
|
||||
: "Enregistrer"}
|
||||
</button>
|
||||
<button
|
||||
onClick={onSnapshot}
|
||||
disabled={disabled}
|
||||
className="px-4 py-2 rounded-xl text-sm font-medium glass-button text-zinc-200 hover:text-white"
|
||||
>
|
||||
Capture
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-xs text-zinc-400">Gain micro</span>
|
||||
<input
|
||||
type="range"
|
||||
min="0.2"
|
||||
max="5"
|
||||
step="0.1"
|
||||
value={gain}
|
||||
onChange={(e) => onGainChange(Number(e.target.value))}
|
||||
className="w-28 accent-blue-500"
|
||||
/>
|
||||
</div>
|
||||
<button
|
||||
onClick={onTalk}
|
||||
disabled={disabled}
|
||||
className={`px-4 py-2 rounded-xl text-sm font-medium transition-all ${
|
||||
isTalking
|
||||
? "bg-blue-500/20 text-blue-400 border border-blue-500/30"
|
||||
: "glass-button text-zinc-200"
|
||||
}`}
|
||||
>
|
||||
{isTalking ? "Parler (Actif)" : "Parler"}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import { apiFetch, SessionExpiredError } from "../lib/api";
|
||||
|
||||
interface MediaItem {
|
||||
filename: string;
|
||||
type: "video" | "image";
|
||||
size: number;
|
||||
mtime: string;
|
||||
url: string;
|
||||
}
|
||||
|
||||
export function MediaGallery() {
|
||||
const [media, setMedia] = useState<MediaItem[]>([]);
|
||||
const [selectedItem, setSelectedItem] = useState<MediaItem | null>(null);
|
||||
const [itemToDelete, setItemToDelete] = useState<string | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const fetchMedia = async () => {
|
||||
try {
|
||||
const res = await apiFetch("/api/media");
|
||||
if (!res.ok) throw new Error();
|
||||
const data = await res.json();
|
||||
setMedia(data);
|
||||
} catch (e) {
|
||||
setError(
|
||||
e instanceof SessionExpiredError
|
||||
? "Session expirée, reconnecte-toi"
|
||||
: "Erreur chargement médias",
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
fetchMedia();
|
||||
}, []);
|
||||
|
||||
const handleDelete = async (filename: string) => {
|
||||
try {
|
||||
const res = await apiFetch(`/api/media/${encodeURIComponent(filename)}`, {
|
||||
method: "DELETE",
|
||||
});
|
||||
if (!res.ok) throw new Error();
|
||||
setMedia((prev) => prev.filter((m) => m.filename !== filename));
|
||||
setItemToDelete(null);
|
||||
} catch (e) {
|
||||
setError(
|
||||
e instanceof SessionExpiredError
|
||||
? "Session expirée, reconnecte-toi"
|
||||
: "Erreur suppression",
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const handleExportAll = async () => {
|
||||
try {
|
||||
const res = await apiFetch("/api/media/export", { method: "POST" });
|
||||
if (!res.ok) throw new Error();
|
||||
const blob = await res.blob();
|
||||
const url = window.URL.createObjectURL(blob);
|
||||
const a = document.createElement("a");
|
||||
a.href = url;
|
||||
a.download = "kai-sa-cam-media.zip";
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
a.remove();
|
||||
window.URL.revokeObjectURL(url);
|
||||
fetchMedia();
|
||||
} catch (e) {
|
||||
setError(
|
||||
e instanceof SessionExpiredError
|
||||
? "Session expirée, reconnecte-toi"
|
||||
: "Erreur export",
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex-1 flex flex-col p-4 gap-4 overflow-y-auto">
|
||||
<div className="flex justify-between items-center">
|
||||
<span className="text-sm text-zinc-400">{media.length} fichiers</span>
|
||||
<div className="flex gap-2">
|
||||
<button
|
||||
onClick={fetchMedia}
|
||||
className="px-3 py-2 text-xs glass-button rounded-xl text-zinc-200 hover:text-white"
|
||||
>
|
||||
Actualiser
|
||||
</button>
|
||||
{media.length > 0 && (
|
||||
<button
|
||||
onClick={handleExportAll}
|
||||
className="px-4 py-2 text-xs glass-button rounded-xl text-zinc-200 hover:text-white"
|
||||
>
|
||||
Tout télécharger et vider
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{error && <div className="text-red-400 text-sm text-center">{error}</div>}
|
||||
<div className="grid grid-cols-2 md:grid-cols-4 gap-4">
|
||||
{media.map((item) => (
|
||||
<div
|
||||
key={item.filename}
|
||||
className="glass-card rounded-xl overflow-hidden flex flex-col"
|
||||
>
|
||||
<div
|
||||
className="relative aspect-video bg-black/40 flex items-center justify-center cursor-pointer"
|
||||
onClick={() => setSelectedItem(item)}
|
||||
>
|
||||
{item.type === "video" ? (
|
||||
<video src={item.url} className="w-full h-full object-cover" />
|
||||
) : (
|
||||
<img
|
||||
src={item.url}
|
||||
alt={item.filename}
|
||||
className="w-full h-full object-cover"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
<div className="p-3 flex items-center justify-between gap-2">
|
||||
<span className="text-xs truncate text-zinc-300">
|
||||
{item.filename}
|
||||
</span>
|
||||
<div className="flex gap-1">
|
||||
<a
|
||||
href={item.url}
|
||||
download={item.filename}
|
||||
className="px-2 py-1 text-xs glass-button rounded-lg text-zinc-300 hover:text-white"
|
||||
>
|
||||
DL
|
||||
</a>
|
||||
<button
|
||||
onClick={() => setItemToDelete(item.filename)}
|
||||
className="px-2 py-1 text-xs bg-red-500/20 text-red-400 rounded-lg hover:bg-red-500/30 transition-colors"
|
||||
>
|
||||
Supprimer
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{itemToDelete && (
|
||||
<div className="fixed inset-0 bg-black/60 backdrop-blur-sm flex items-center justify-center z-50 p-4">
|
||||
<div className="glass-card p-6 rounded-2xl max-w-sm w-full flex flex-col gap-4 border border-white/10">
|
||||
<h3 className="text-lg font-semibold text-white">
|
||||
Confirmer la suppression
|
||||
</h3>
|
||||
<p className="text-sm text-zinc-400">
|
||||
Voulez-vous vraiment supprimer ce fichier ?
|
||||
</p>
|
||||
<div className="flex gap-2 justify-end">
|
||||
<button
|
||||
onClick={() => setItemToDelete(null)}
|
||||
className="px-4 py-2 text-sm glass-button rounded-xl text-zinc-300"
|
||||
>
|
||||
Annuler
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleDelete(itemToDelete)}
|
||||
className="px-4 py-2 text-sm bg-red-500 text-white rounded-xl hover:bg-red-600 transition-colors"
|
||||
>
|
||||
Confirmer
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{selectedItem && (
|
||||
<div
|
||||
className="fixed inset-0 bg-black/80 backdrop-blur-md flex items-center justify-center z-50 p-4"
|
||||
onClick={() => setSelectedItem(null)}
|
||||
>
|
||||
<div
|
||||
className="relative max-w-4xl w-full max-h-[90vh] flex items-center justify-center"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
{selectedItem.type === "video" ? (
|
||||
<video
|
||||
src={selectedItem.url}
|
||||
controls
|
||||
autoPlay
|
||||
className="max-w-full max-h-[85vh] rounded-2xl"
|
||||
/>
|
||||
) : (
|
||||
<img
|
||||
src={selectedItem.url}
|
||||
alt={selectedItem.filename}
|
||||
className="max-w-full max-h-[85vh] rounded-2xl object-contain"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
interface VideoPlayerProps {
|
||||
streamUrl: string; // chemin same-origin, ex: /go2rtc/stream.html?src=webcam&mode=mse
|
||||
}
|
||||
|
||||
export function VideoPlayer({ streamUrl }: VideoPlayerProps) {
|
||||
return (
|
||||
<div className="flex-1 min-h-[300px] relative bg-black rounded-lg overflow-hidden flex items-center justify-center">
|
||||
<iframe
|
||||
src={streamUrl}
|
||||
className="w-full h-full border-none absolute inset-0"
|
||||
allow="autoplay; encrypted-media; fullscreen"
|
||||
title="Flux caméra"
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
import { useState, useCallback, useRef, useEffect } from "react";
|
||||
import { apiFetch, SessionExpiredError } from "../lib/api";
|
||||
|
||||
interface UseRecorderOptions {
|
||||
onStart?: () => void;
|
||||
onStop?: () => void;
|
||||
onTimeUpdate?: (seconds: number) => void;
|
||||
}
|
||||
|
||||
const errMsg = (e: unknown, fallback: string) =>
|
||||
e instanceof SessionExpiredError
|
||||
? "Session expirée, reconnecte-toi"
|
||||
: e instanceof Error
|
||||
? e.message
|
||||
: fallback;
|
||||
|
||||
async function readError(res: Response, fallback: string) {
|
||||
try {
|
||||
return (await res.json()).error || fallback;
|
||||
} catch {
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
|
||||
export function useRecorder({
|
||||
onStart,
|
||||
onStop,
|
||||
onTimeUpdate,
|
||||
}: UseRecorderOptions) {
|
||||
const [isRecording, setIsRecording] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const intervalRef = useRef<number>();
|
||||
const isRecordingRef = useRef(false);
|
||||
isRecordingRef.current = isRecording;
|
||||
|
||||
// Callbacks toujours à jour sans recréer les fonctions
|
||||
const cb = useRef({ onStart, onStop, onTimeUpdate });
|
||||
cb.current = { onStart, onStop, onTimeUpdate };
|
||||
|
||||
const clearTimer = () => {
|
||||
if (intervalRef.current) clearInterval(intervalRef.current);
|
||||
intervalRef.current = undefined;
|
||||
};
|
||||
|
||||
const beginTimer = (startedAt: number) => {
|
||||
clearTimer();
|
||||
const tick = () =>
|
||||
cb.current.onTimeUpdate?.(Math.floor((Date.now() - startedAt) / 1000));
|
||||
tick();
|
||||
intervalRef.current = window.setInterval(tick, 1000);
|
||||
};
|
||||
|
||||
const markStopped = () => {
|
||||
clearTimer();
|
||||
setIsRecording(false);
|
||||
cb.current.onStop?.();
|
||||
};
|
||||
|
||||
// Récupère un enregistrement déjà en cours côté serveur (reload, autre onglet, 409)
|
||||
const adoptRunning = useCallback(async (): Promise<boolean> => {
|
||||
const res = await apiFetch("/api/recordings/status");
|
||||
const s = await res.json();
|
||||
if (!s.isRecording) return false;
|
||||
setIsRecording(true);
|
||||
cb.current.onStart?.();
|
||||
beginTimer(s.startTime ?? Date.now());
|
||||
return true;
|
||||
}, []);
|
||||
|
||||
const startRecording = useCallback(async () => {
|
||||
setError(null);
|
||||
try {
|
||||
const res = await apiFetch("/api/recordings/start", { method: "POST" });
|
||||
if (res.status === 409 && (await adoptRunning())) return;
|
||||
if (!res.ok)
|
||||
throw new Error(await readError(res, "Failed to start recording"));
|
||||
setIsRecording(true);
|
||||
cb.current.onStart?.();
|
||||
beginTimer(Date.now());
|
||||
} catch (e) {
|
||||
setError(errMsg(e, "Erreur démarrage enregistrement"));
|
||||
}
|
||||
}, [adoptRunning]);
|
||||
|
||||
const stopRecording = useCallback(async () => {
|
||||
setError(null);
|
||||
try {
|
||||
const res = await apiFetch("/api/recordings/stop", { method: "POST" });
|
||||
// 409 = plus rien en cours côté serveur : l'UI doit juste se resynchroniser
|
||||
if (!res.ok && res.status !== 409)
|
||||
throw new Error(await readError(res, "Failed to stop recording"));
|
||||
markStopped();
|
||||
} catch (e) {
|
||||
setError(errMsg(e, "Erreur arrêt enregistrement"));
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
adoptRunning().catch(() => {});
|
||||
const handleBeforeUnload = () => {
|
||||
if (isRecordingRef.current) navigator.sendBeacon("/api/recordings/stop");
|
||||
};
|
||||
window.addEventListener("beforeunload", handleBeforeUnload);
|
||||
return () => {
|
||||
window.removeEventListener("beforeunload", handleBeforeUnload);
|
||||
clearTimer();
|
||||
};
|
||||
}, [adoptRunning]);
|
||||
|
||||
return { isRecording, error, startRecording, stopRecording };
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
import { useState, useCallback, useRef, useEffect } from "react";
|
||||
import { checkSession, reauthenticate, wsUrl } from "../lib/api";
|
||||
|
||||
interface UseTalkOptions {
|
||||
gain?: number;
|
||||
}
|
||||
|
||||
const WORKLET = `
|
||||
class Processor extends AudioWorkletProcessor {
|
||||
process(inputs) {
|
||||
const input = inputs[0]
|
||||
if (input && input.length > 0) {
|
||||
const f = input[0]
|
||||
const i16 = new Int16Array(f.length)
|
||||
for (let i = 0; i < f.length; i++) {
|
||||
const s = Math.max(-1, Math.min(1, f[i]))
|
||||
i16[i] = s < 0 ? s * 0x8000 : s * 0x7FFF
|
||||
}
|
||||
this.port.postMessage(i16.buffer, [i16.buffer])
|
||||
}
|
||||
return true
|
||||
}
|
||||
}
|
||||
registerProcessor('pcm-processor', Processor)
|
||||
`;
|
||||
|
||||
const MAX_ATTEMPTS = 10;
|
||||
|
||||
export function useTalk({ gain = 1 }: UseTalkOptions = {}) {
|
||||
const [isTalking, setIsTalking] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const wsRef = useRef<WebSocket | null>(null);
|
||||
const streamRef = useRef<MediaStream | null>(null);
|
||||
const ctxRef = useRef<AudioContext | null>(null);
|
||||
const gainNodeRef = useRef<GainNode | null>(null);
|
||||
const nodeRef = useRef<AudioWorkletNode | null>(null);
|
||||
const wantRef = useRef(false); // l'utilisateur veut parler
|
||||
const attemptsRef = useRef(0);
|
||||
const retryRef = useRef<number>();
|
||||
|
||||
useEffect(() => {
|
||||
if (gainNodeRef.current) gainNodeRef.current.gain.value = gain;
|
||||
}, [gain]);
|
||||
|
||||
const stopTalk = useCallback((reason?: string) => {
|
||||
wantRef.current = false;
|
||||
clearTimeout(retryRef.current);
|
||||
const ws = wsRef.current;
|
||||
wsRef.current = null;
|
||||
ws?.close();
|
||||
streamRef.current?.getTracks().forEach((t) => t.stop());
|
||||
streamRef.current = null;
|
||||
ctxRef.current?.close().catch(() => {});
|
||||
ctxRef.current = null;
|
||||
gainNodeRef.current = null;
|
||||
nodeRef.current = null;
|
||||
setIsTalking(false);
|
||||
if (typeof reason === "string") setError(reason);
|
||||
}, []);
|
||||
|
||||
// Ouvre (ou rouvre) UNIQUEMENT le WebSocket ; micro + AudioContext restent en place.
|
||||
const connect = useCallback(() => {
|
||||
const ctx = ctxRef.current;
|
||||
const node = nodeRef.current;
|
||||
if (!ctx || !node || !wantRef.current) return;
|
||||
|
||||
const ws = new WebSocket(wsUrl("/api/talk"));
|
||||
ws.binaryType = "arraybuffer";
|
||||
wsRef.current = ws;
|
||||
|
||||
ws.onopen = () => {
|
||||
attemptsRef.current = 0;
|
||||
setError(null);
|
||||
ws.send(JSON.stringify({ rate: ctx.sampleRate }));
|
||||
};
|
||||
|
||||
node.port.onmessage = (e) => {
|
||||
const cur = wsRef.current;
|
||||
if (cur && cur.readyState === WebSocket.OPEN) cur.send(e.data);
|
||||
};
|
||||
|
||||
ws.onclose = async (ev) => {
|
||||
if (wsRef.current !== ws) return; // fermeture volontaire / ancienne socket
|
||||
wsRef.current = null;
|
||||
if (!wantRef.current) return;
|
||||
if (ev.code === 4001)
|
||||
return stopTalk("Micro repris par un autre appareil");
|
||||
|
||||
if (++attemptsRef.current > MAX_ATTEMPTS)
|
||||
return stopTalk("Connexion micro perdue");
|
||||
|
||||
// Cause probable : session Access expirée (le handshake WS est redirigé)
|
||||
if (!(await checkSession())) {
|
||||
try {
|
||||
await reauthenticate(); // popup ; peut être bloquée hors geste utilisateur
|
||||
} catch {
|
||||
return stopTalk("Session expirée, reconnecte-toi puis réessaie");
|
||||
}
|
||||
}
|
||||
const delay = Math.min(500 * 2 ** (attemptsRef.current - 1), 5000);
|
||||
retryRef.current = window.setTimeout(connect, delay);
|
||||
};
|
||||
// onerror est toujours suivi de onclose : la logique de reconnexion y est centralisée.
|
||||
}, [stopTalk]);
|
||||
|
||||
const startTalk = useCallback(async () => {
|
||||
setError(null);
|
||||
if (wantRef.current) return;
|
||||
try {
|
||||
// Valide la session AVANT de demander le micro (évite un état à moitié initialisé)
|
||||
if (!(await checkSession())) await reauthenticate();
|
||||
|
||||
const stream = await navigator.mediaDevices.getUserMedia({
|
||||
audio: { echoCancellation: true, noiseSuppression: true },
|
||||
});
|
||||
streamRef.current = stream;
|
||||
stream.getAudioTracks()[0].onended = () => stopTalk("Micro déconnecté");
|
||||
|
||||
const ctx = new AudioContext();
|
||||
ctxRef.current = ctx;
|
||||
await ctx.resume();
|
||||
|
||||
const url = URL.createObjectURL(
|
||||
new Blob([WORKLET], { type: "application/javascript" }),
|
||||
);
|
||||
try {
|
||||
await ctx.audioWorklet.addModule(url);
|
||||
} finally {
|
||||
URL.revokeObjectURL(url);
|
||||
}
|
||||
|
||||
const node = new AudioWorkletNode(ctx, "pcm-processor");
|
||||
nodeRef.current = node;
|
||||
const source = ctx.createMediaStreamSource(stream);
|
||||
const gainNode = ctx.createGain();
|
||||
gainNode.gain.value = gain;
|
||||
gainNodeRef.current = gainNode;
|
||||
source.connect(gainNode);
|
||||
gainNode.connect(node);
|
||||
node.connect(ctx.destination); // le worklet ne produit aucun son en sortie
|
||||
|
||||
wantRef.current = true;
|
||||
attemptsRef.current = 0;
|
||||
setIsTalking(true);
|
||||
connect();
|
||||
} catch (e) {
|
||||
stopTalk(
|
||||
e instanceof Error ? e.message : "Impossible d'accéder au microphone",
|
||||
);
|
||||
}
|
||||
}, [gain, connect, stopTalk]);
|
||||
|
||||
// Mobile : l'AudioContext est suspendu quand l'onglet passe en arrière-plan
|
||||
useEffect(() => {
|
||||
const onVis = () => {
|
||||
if (document.visibilityState === "visible")
|
||||
ctxRef.current?.resume().catch(() => {});
|
||||
};
|
||||
document.addEventListener("visibilitychange", onVis);
|
||||
return () => document.removeEventListener("visibilitychange", onVis);
|
||||
}, []);
|
||||
|
||||
useEffect(() => () => stopTalk(), [stopTalk]);
|
||||
|
||||
return { isTalking, error, startTalk, stopTalk: () => stopTalk() };
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
@tailwind base;
|
||||
@tailwind components;
|
||||
@tailwind utilities;
|
||||
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
font-family:
|
||||
-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue",
|
||||
Arial, sans-serif;
|
||||
background: #09090b;
|
||||
color: #f4f4f5;
|
||||
}
|
||||
|
||||
@layer utilities {
|
||||
.glass {
|
||||
background: rgba(255, 255, 255, 0.03);
|
||||
backdrop-filter: blur(16px);
|
||||
-webkit-backdrop-filter: blur(16px);
|
||||
border: 1px solid rgba(255, 255, 255, 0.08);
|
||||
}
|
||||
.glass-card {
|
||||
background: rgba(24, 24, 27, 0.6);
|
||||
backdrop-filter: blur(20px);
|
||||
-webkit-backdrop-filter: blur(20px);
|
||||
border: 1px solid rgba(255, 255, 255, 0.1);
|
||||
}
|
||||
.glass-button {
|
||||
background: rgba(255, 255, 255, 0.05);
|
||||
backdrop-filter: blur(10px);
|
||||
border: 1px solid rgba(255, 255, 255, 0.1);
|
||||
transition: all 0.2s ease;
|
||||
}
|
||||
.glass-button:hover {
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
border-color: rgba(255, 255, 255, 0.2);
|
||||
}
|
||||
.no-scrollbar::-webkit-scrollbar {
|
||||
display: none;
|
||||
}
|
||||
.no-scrollbar {
|
||||
-ms-overflow-style: none;
|
||||
scrollbar-width: none;
|
||||
}
|
||||
}
|
||||
+133
@@ -0,0 +1,133 @@
|
||||
// Client API avec gestion de l'expiration de session Cloudflare Access.
|
||||
// Principe : fetch avec redirect:"manual" -> une redirection vers cloudflareaccess.com
|
||||
// donne une réponse "opaqueredirect" (au lieu du "NetworkError" CORS). On rouvre alors
|
||||
// une popup /auth/done (protégée par Access) qui se ferme seule, puis on rejoue la requête.
|
||||
|
||||
export class SessionExpiredError extends Error {
|
||||
constructor() {
|
||||
super("Session Cloudflare Access expirée");
|
||||
}
|
||||
}
|
||||
|
||||
type Listener = (expired: boolean) => void;
|
||||
const listeners = new Set<Listener>();
|
||||
let expired = false;
|
||||
|
||||
function setExpired(v: boolean) {
|
||||
if (expired !== v) {
|
||||
expired = v;
|
||||
listeners.forEach((l) => l(v));
|
||||
}
|
||||
}
|
||||
|
||||
export function onSessionChange(l: Listener): () => void {
|
||||
listeners.add(l);
|
||||
return () => listeners.delete(l);
|
||||
}
|
||||
|
||||
function isExpiredResponse(r: Response): boolean {
|
||||
return r.type === "opaqueredirect" || r.status === 0 || r.status === 401;
|
||||
}
|
||||
|
||||
async function probe(): Promise<"ok" | "expired" | "offline"> {
|
||||
try {
|
||||
const r = await fetch("/api/health", {
|
||||
credentials: "same-origin",
|
||||
redirect: "manual",
|
||||
cache: "no-store",
|
||||
});
|
||||
return isExpiredResponse(r) ? "expired" : "ok";
|
||||
} catch {
|
||||
return "offline";
|
||||
}
|
||||
}
|
||||
|
||||
/** true si la session est valide (ou si on est simplement hors-ligne). */
|
||||
export async function checkSession(): Promise<boolean> {
|
||||
const s = await probe();
|
||||
setExpired(s === "expired");
|
||||
return s !== "expired";
|
||||
}
|
||||
|
||||
let pending: Promise<void> | null = null;
|
||||
|
||||
/** Ouvre la popup de reconnexion. À appeler depuis un clic si possible (anti-popup-blocker). */
|
||||
export function reauthenticate(): Promise<void> {
|
||||
pending ??= new Promise<void>((resolve, reject) => {
|
||||
const w = window.open(
|
||||
"/auth/done",
|
||||
"kaisa-auth",
|
||||
"popup,width=480,height=680",
|
||||
);
|
||||
if (!w) return reject(new SessionExpiredError());
|
||||
|
||||
let done = false;
|
||||
const finish = async () => {
|
||||
if (done) return;
|
||||
done = true;
|
||||
clearInterval(poll);
|
||||
window.removeEventListener("message", onMsg);
|
||||
(await checkSession()) ? resolve() : reject(new SessionExpiredError());
|
||||
};
|
||||
const onMsg = (e: MessageEvent) => {
|
||||
if (e.origin === location.origin && e.data === "kaisa-auth-ok")
|
||||
void finish();
|
||||
};
|
||||
window.addEventListener("message", onMsg);
|
||||
const poll = setInterval(() => {
|
||||
if (w.closed) void finish();
|
||||
}, 500);
|
||||
}).finally(() => {
|
||||
pending = null;
|
||||
});
|
||||
return pending!;
|
||||
}
|
||||
|
||||
export async function apiFetch(
|
||||
input: string,
|
||||
init: RequestInit = {},
|
||||
): Promise<Response> {
|
||||
const run = () =>
|
||||
fetch(input, { ...init, credentials: "same-origin", redirect: "manual" });
|
||||
|
||||
let res: Response | null = null;
|
||||
let err: unknown;
|
||||
try {
|
||||
res = await run();
|
||||
} catch (e) {
|
||||
err = e;
|
||||
}
|
||||
|
||||
if (res && !isExpiredResponse(res)) {
|
||||
setExpired(false);
|
||||
return res;
|
||||
}
|
||||
// Erreur réseau : vraie panne, ou session expirée ? On teste.
|
||||
if (!res && (await probe()) !== "expired") throw err;
|
||||
|
||||
setExpired(true);
|
||||
await reauthenticate(); // lève SessionExpiredError si annulé / popup bloquée
|
||||
const retry = await run();
|
||||
if (isExpiredResponse(retry)) throw new SessionExpiredError();
|
||||
setExpired(false);
|
||||
return retry;
|
||||
}
|
||||
|
||||
export function wsUrl(path: string): string {
|
||||
return `${location.protocol === "https:" ? "wss" : "ws"}://${location.host}${path}`;
|
||||
}
|
||||
|
||||
/** Vérifie la session toutes les minutes, au retour sur l'onglet et au retour du réseau. */
|
||||
export function startSessionMonitor(): () => void {
|
||||
const tick = () => void checkSession();
|
||||
const id = setInterval(tick, 60_000);
|
||||
const onVis = () => document.visibilityState === "visible" && tick();
|
||||
document.addEventListener("visibilitychange", onVis);
|
||||
window.addEventListener("online", tick);
|
||||
tick();
|
||||
return () => {
|
||||
clearInterval(id);
|
||||
document.removeEventListener("visibilitychange", onVis);
|
||||
window.removeEventListener("online", tick);
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import React from 'react'
|
||||
import ReactDOM from 'react-dom/client'
|
||||
import { App } from './App'
|
||||
import './index.css'
|
||||
|
||||
ReactDOM.createRoot(document.getElementById('root')!).render(
|
||||
<React.StrictMode>
|
||||
<App />
|
||||
</React.StrictMode>
|
||||
)
|
||||
@@ -0,0 +1,9 @@
|
||||
import { Router, Response } from 'express'
|
||||
|
||||
const router = Router()
|
||||
|
||||
router.get('/health', async (req, res: Response) => {
|
||||
res.json({ status: 'ok', service: 'kai-sa-cam', timestamp: new Date().toISOString() })
|
||||
})
|
||||
|
||||
export { router as healthRouter }
|
||||
@@ -0,0 +1,205 @@
|
||||
import express from "express";
|
||||
import { createProxyMiddleware } from "http-proxy-middleware";
|
||||
import { createServer } from "http";
|
||||
import type { IncomingHttpHeaders } from "http";
|
||||
import { WebSocketServer, WebSocket } from "ws";
|
||||
import { spawn, ChildProcessWithoutNullStreams } from "child_process";
|
||||
import { join } from "path";
|
||||
import { createRemoteJWKSet, jwtVerify } from "jose";
|
||||
import { recorderRouter } from "./recorder.js";
|
||||
import { mediaRouter } from "./media.js";
|
||||
import { talkRouter } from "./talk.js";
|
||||
import { healthRouter } from "./health.js";
|
||||
|
||||
const __dirname = process.cwd();
|
||||
const app = express();
|
||||
const PORT = process.env.PORT || 8090;
|
||||
|
||||
const TEAM = process.env.CF_ACCESS_TEAM_DOMAIN;
|
||||
const AUD = process.env.CF_ACCESS_AUD;
|
||||
const jwks =
|
||||
TEAM && AUD
|
||||
? 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"];
|
||||
if (typeof token !== "string") return false;
|
||||
try {
|
||||
await jwtVerify(token, jwks, { issuer: TEAM, audience: AUD });
|
||||
return true;
|
||||
} catch (e) {
|
||||
console.error("Access JWT rejected:", (e as Error).message);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
app.use(async (req, res, next) => {
|
||||
if (req.path === "/api/health") return next(); // sondes locales
|
||||
if (await verifyAccess(req.headers)) return next();
|
||||
res.status(401).json({ error: "unauthorized" });
|
||||
});
|
||||
|
||||
app.use(express.json({ limit: "10mb" }));
|
||||
app.use(express.urlencoded({ extended: true }));
|
||||
|
||||
// Page chargée dans la popup de reconnexion (déjà derrière Access).
|
||||
app.get("/auth/done", (_req, res) => {
|
||||
res.setHeader("Cache-Control", "no-store");
|
||||
res
|
||||
.type("html")
|
||||
.send(
|
||||
`<!doctype html><meta charset="utf-8"><title>OK</title><body style="font-family:sans-serif;background:#111827;color:#fff;text-align:center;padding-top:30vh">Connecté ✔<script>try{window.opener&&window.opener.postMessage("kaisa-auth-ok",location.origin)}catch(e){}window.close()</script>`,
|
||||
);
|
||||
});
|
||||
|
||||
app.use(express.static(join(__dirname, "dist")));
|
||||
|
||||
// go2rtc : uniquement via ce proxy (même origine que l'app => même session Access).
|
||||
// ws:false car l'upgrade est routé à la main plus bas (sinon le proxy
|
||||
// intercepterait aussi /api/talk).
|
||||
const go2rtcProxy = createProxyMiddleware({
|
||||
target: process.env.GO2RTC_URL || "http://kai-sa-go2rtc:1984",
|
||||
changeOrigin: true,
|
||||
ws: false,
|
||||
pathRewrite: { "^/go2rtc": "" },
|
||||
});
|
||||
app.use("/go2rtc", go2rtcProxy);
|
||||
|
||||
app.use("/api/recordings", recorderRouter);
|
||||
app.use("/api/media", mediaRouter);
|
||||
app.use("/api/talk", talkRouter);
|
||||
app.use("/api", healthRouter);
|
||||
|
||||
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);
|
||||
const wss = new WebSocketServer({ noServer: true, maxPayload: 1 << 20 });
|
||||
|
||||
server.on("upgrade", async (req, socket, head) => {
|
||||
if (!(await verifyAccess(req.headers))) {
|
||||
socket.write("HTTP/1.1 401 Unauthorized\r\nConnection: close\r\n\r\n");
|
||||
return socket.destroy();
|
||||
}
|
||||
const path = (req.url ?? "").split("?")[0];
|
||||
if (path.startsWith("/go2rtc/")) {
|
||||
return (go2rtcProxy as any).upgrade(req, socket, head);
|
||||
}
|
||||
if (path === "/api/talk") {
|
||||
return wss.handleUpgrade(req, socket, head, (ws) =>
|
||||
wss.emit("connection", ws, req),
|
||||
);
|
||||
}
|
||||
socket.destroy();
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Talkback : micro navigateur -> paplay -> enceinte BT
|
||||
// ---------------------------------------------------------------------------
|
||||
type Talk = {
|
||||
ws: WebSocket;
|
||||
player: ChildProcessWithoutNullStreams | null;
|
||||
cleanup: () => void;
|
||||
};
|
||||
let activeTalk: Talk | null = null;
|
||||
|
||||
wss.on("connection", (ws: WebSocket) => {
|
||||
// Un seul "speaker" : une nouvelle connexion remplace l'ancienne (évite le blocage
|
||||
// après un onglet mort / une coupure réseau).
|
||||
const old = activeTalk;
|
||||
if (old) {
|
||||
old.cleanup(); // coupe paplay tout de suite
|
||||
old.ws.close(4001, "replaced"); // le client n'essaie pas de se reconnecter
|
||||
setTimeout(() => old.ws.terminate(), 1000);
|
||||
}
|
||||
|
||||
const me: Talk = { ws, player: null, cleanup: () => {} };
|
||||
activeTalk = me;
|
||||
|
||||
let alive = true;
|
||||
ws.on("pong", () => (alive = true));
|
||||
const heartbeat = setInterval(() => {
|
||||
if (!alive) return ws.terminate();
|
||||
alive = false;
|
||||
ws.ping();
|
||||
}, 15_000);
|
||||
|
||||
const cleanup = () => {
|
||||
clearInterval(heartbeat);
|
||||
const p = me.player;
|
||||
me.player = null;
|
||||
if (p) {
|
||||
try {
|
||||
p.stdin.destroy();
|
||||
} catch {}
|
||||
try {
|
||||
p.kill("SIGKILL");
|
||||
} catch {}
|
||||
}
|
||||
if (activeTalk === me) activeTalk = null;
|
||||
};
|
||||
me.cleanup = cleanup;
|
||||
|
||||
ws.on("message", (data: Buffer, isBinary: boolean) => {
|
||||
if (!isBinary) {
|
||||
if (me.player) return;
|
||||
let rate = 48000;
|
||||
try {
|
||||
const r = Number(JSON.parse(data.toString()).rate);
|
||||
if (r >= 8000 && r <= 96000) rate = r;
|
||||
} catch {}
|
||||
|
||||
const p = spawn("paplay", [
|
||||
"--raw",
|
||||
`--rate=${rate}`,
|
||||
"--format=s16le",
|
||||
"--channels=1",
|
||||
"--latency-msec=150",
|
||||
]);
|
||||
// Sans ces handlers, un EPIPE sur stdin ou un paplay introuvable
|
||||
// = exception non gérée = crash du serveur Node.
|
||||
p.on("error", (e) => {
|
||||
console.error("paplay error:", e.message);
|
||||
ws.close(1011, "paplay error");
|
||||
});
|
||||
p.on("exit", () => {
|
||||
if (me.player === p) {
|
||||
me.player = null;
|
||||
ws.close(1011, "paplay exited");
|
||||
}
|
||||
});
|
||||
p.stdin.on("error", () => {});
|
||||
p.stdout.resume();
|
||||
p.stderr.resume();
|
||||
me.player = p;
|
||||
return;
|
||||
}
|
||||
|
||||
const p = me.player;
|
||||
// Backpressure : on jette l'audio plutôt que d'accumuler de la latence.
|
||||
if (p && p.stdin.writable && p.stdin.writableLength < 256 * 1024)
|
||||
p.stdin.write(data);
|
||||
});
|
||||
|
||||
ws.on("close", cleanup);
|
||||
ws.on("error", cleanup);
|
||||
});
|
||||
|
||||
process.on("uncaughtException", (e) => console.error("uncaughtException:", e));
|
||||
process.on("unhandledRejection", (e) =>
|
||||
console.error("unhandledRejection:", e),
|
||||
);
|
||||
|
||||
server.listen(PORT, () =>
|
||||
console.log(`kai-sa-cam server running on port ${PORT}`),
|
||||
);
|
||||
@@ -0,0 +1,222 @@
|
||||
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 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_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";
|
||||
}
|
||||
|
||||
/**
|
||||
* 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) => {
|
||||
try {
|
||||
const files = readdirSync(MEDIA_ROOT);
|
||||
const media = files
|
||||
.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/${encodeURIComponent(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" });
|
||||
}
|
||||
});
|
||||
|
||||
// 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);
|
||||
|
||||
const args = [
|
||||
"-hide_banner",
|
||||
"-loglevel",
|
||||
"warning",
|
||||
"-rtsp_transport",
|
||||
"tcp",
|
||||
"-i",
|
||||
GO2RTC_RTSP_URL,
|
||||
"-frames:v",
|
||||
"1",
|
||||
"-q:v",
|
||||
"2",
|
||||
"-update",
|
||||
"1",
|
||||
filepath,
|
||||
];
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
});
|
||||
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", (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" });
|
||||
|
||||
try {
|
||||
unlinkSync(filepath);
|
||||
res.json({ status: "deleted" });
|
||||
} catch (e) {
|
||||
console.error("Delete error:", e);
|
||||
res.status(500).json({ error: "Failed to delete" });
|
||||
}
|
||||
});
|
||||
|
||||
export { router as mediaRouter };
|
||||
@@ -0,0 +1,233 @@
|
||||
import { Router, Request, Response } from "express";
|
||||
import { spawn, ChildProcess } from "child_process";
|
||||
import {
|
||||
existsSync,
|
||||
mkdirSync,
|
||||
readdirSync,
|
||||
renameSync,
|
||||
statSync,
|
||||
statfsSync,
|
||||
unlinkSync,
|
||||
} from "fs";
|
||||
import { join, basename } from "path";
|
||||
|
||||
const router = Router();
|
||||
|
||||
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 GO2RTC_RTSP_URL =
|
||||
process.env.GO2RTC_RTSP_URL || "rtsp://kai-sa-go2rtc:8554/webcam";
|
||||
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);
|
||||
|
||||
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;
|
||||
|
||||
if (!existsSync(MEDIA_DIR)) {
|
||||
mkdirSync(MEDIA_DIR, { recursive: true });
|
||||
}
|
||||
|
||||
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 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;
|
||||
}
|
||||
}
|
||||
|
||||
function generateFilename(ext: string): string {
|
||||
const timestamp = new Date()
|
||||
.toISOString()
|
||||
.replace(/[:.]/g, "-")
|
||||
.split("T")
|
||||
.join("_");
|
||||
return `recording_${timestamp}.${ext}`;
|
||||
}
|
||||
|
||||
/** 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 { size } = statSync(partPath);
|
||||
if (size < 1024) {
|
||||
console.error(
|
||||
`Recording too small (${size} bytes), removing: ${partPath}`,
|
||||
);
|
||||
unlinkSync(partPath);
|
||||
return;
|
||||
}
|
||||
const finalPath = finalPathOf(partPath);
|
||||
renameSync(partPath, finalPath);
|
||||
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 (current) {
|
||||
return res.status(409).json({ error: "Enregistrement déjà en cours" });
|
||||
}
|
||||
if (!hasEnoughDisk()) {
|
||||
return res.status(507).json({ error: "Espace disque insuffisant" });
|
||||
}
|
||||
|
||||
const partPath = join(MEDIA_DIR, generateFilename("part"));
|
||||
|
||||
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,
|
||||
"-map",
|
||||
"0:v:0",
|
||||
"-map",
|
||||
"0:a:0?",
|
||||
"-c:v",
|
||||
"libx264",
|
||||
"-preset",
|
||||
"ultrafast",
|
||||
"-tune",
|
||||
"zerolatency",
|
||||
"-profile:v",
|
||||
"baseline",
|
||||
"-pix_fmt",
|
||||
"yuv420p",
|
||||
"-g",
|
||||
"30",
|
||||
"-c:a",
|
||||
"aac",
|
||||
"-b:a",
|
||||
"96k",
|
||||
"-af",
|
||||
"aresample=async=1",
|
||||
"-f",
|
||||
"mp4",
|
||||
"-movflags",
|
||||
"+frag_keyframe+empty_moov+default_base_moof",
|
||||
...(MAX_RECORDING_MINUTES > 0
|
||||
? ["-t", `${MAX_RECORDING_MINUTES * 60}`]
|
||||
: []),
|
||||
partPath,
|
||||
];
|
||||
|
||||
console.log("Starting ffmpeg:", args.join(" "));
|
||||
const proc = spawn(FFMPEG_PATH, args, {
|
||||
stdio: ["ignore", "ignore", "pipe"],
|
||||
});
|
||||
|
||||
proc.stderr?.on("data", (d: Buffer) => {
|
||||
const msg = d.toString().trim();
|
||||
if (msg) console.log(`ffmpeg: ${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");
|
||||
});
|
||||
});
|
||||
|
||||
current = { proc, partPath, startTime: Date.now(), exited };
|
||||
|
||||
// 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 ?)",
|
||||
});
|
||||
}
|
||||
|
||||
res.json({ status: "started", filename: publicName(partPath) });
|
||||
});
|
||||
|
||||
// POST /api/recordings/stop
|
||||
router.post("/stop", async (_req: Request, res: Response) => {
|
||||
const rec = current;
|
||||
if (!rec) {
|
||||
return res.status(409).json({ error: "Aucun enregistrement en cours" });
|
||||
}
|
||||
|
||||
try {
|
||||
rec.proc.kill("SIGINT"); // graceful: lets ffmpeg flush the last fragment
|
||||
} catch (e) {
|
||||
console.error("Error sending SIGINT:", e);
|
||||
}
|
||||
|
||||
if (await settledWithin(rec.exited, 15_000)) {
|
||||
return res.json({ status: "stopped", filename: publicName(rec.partPath) });
|
||||
}
|
||||
|
||||
try {
|
||||
rec.proc.kill("SIGKILL");
|
||||
} catch (e) {
|
||||
console.error("Error sending SIGKILL:", e);
|
||||
}
|
||||
await settledWithin(rec.exited, 2000);
|
||||
res.status(500).json({ error: "Échec arrêt enregistrement" });
|
||||
});
|
||||
|
||||
// GET /api/recordings/status
|
||||
router.get("/status", (_req: Request, res: Response) => {
|
||||
res.json({
|
||||
isRecording: !!current,
|
||||
startTime: current?.startTime ?? null,
|
||||
currentFile: current ? publicName(current.partPath) : undefined,
|
||||
});
|
||||
});
|
||||
|
||||
export { router as recorderRouter };
|
||||
@@ -0,0 +1,10 @@
|
||||
import { Router, Response } from 'express'
|
||||
|
||||
const router = Router()
|
||||
|
||||
// GET /api/talk/status
|
||||
router.get('/status', async (req, res: Response) => {
|
||||
res.json({ status: 'ok', message: 'Talk endpoint available at /api/talk WebSocket' })
|
||||
})
|
||||
|
||||
export { router as talkRouter }
|
||||
Reference in New Issue
Block a user