feat(control): Race Controller Master, one browser runs the race and others follow or take over (1.77.0)

This commit is contained in:
larssand committed 2026-11-07 17:36:15 +01:00
1 parent 54989d8597
commit cf3a4c5fdb
16 files changed
+316 -9

No files matched your search

+30
View File
@@ -439,6 +439,36 @@ app.get("/api/state", (_req, res) => {
}
});
// Race Controller Master: one browser tab runs the race (decoder, start, pause, finish).
// Kept in memory; the master renews it every 5 s and it lapses after 15 s of silence.
// Claiming is a POST, so with the admin PIN on only a logged-in browser can take over.
const CONTROLLER_LEASE_MS = 15000;
let raceController = null;
const liveController = () => (raceController && Date.now() - raceController.seenAt < CONTROLLER_LEASE_MS ? raceController : null);
const controllerView = () => {
const live = liveController();
return { master: live ? { clientId: live.clientId, name: live.name || live.ip, since: live.since } : null };
};
app.get("/api/controller", (_req, res) => res.json(controllerView()));
app.post("/api/controller/claim", (req, res) => {
const clientId = String(req.body?.clientId || "").trim().slice(0, 64);
if (!clientId) return res.status(400).json({ error: "clientId required" });
const live = liveController();
const renewing = live?.clientId === clientId;
if (!renewing && !auth.isIpAllowed(req.ip)) return res.status(403).json({ error: "ip_not_allowed" });
// Taking over always needs the PIN (when one is set): the client shows the PIN dialog on
// auth_required. A quiet claim on page load gets login_needed and the tab just follows.
if (!renewing && auth.isEnabled() && !auth.isAuthenticated(req)) return res.status(401).json({ error: req.body?.force === true ? "auth_required" : "login_needed", ...controllerView() });
if (live && !renewing && req.body?.force !== true) return res.status(409).json(controllerView());
const since = renewing ? live.since : Date.now();
raceController = { clientId, name: String(req.body?.name || "").trim().slice(0, 60), ip: String(req.ip || "").replace(/^::ffff:/, ""), since, seenAt: Date.now() };
return res.json(controllerView());
});
app.post("/api/controller/release", (req, res) => {
if (liveController()?.clientId === String(req.body?.clientId || "")) raceController = null;
res.json(controllerView());
});
app.post("/api/state", (req, res) => {
if (!req.body || typeof req.body !== "object") {
res.status(400).json({ error: "Expected JSON body" });