Present: a remote, a phone at /remote/<code> drives a presenting screen
The screen shows a code on its setup and with its controls. Anyone with it can step, pause and jump through the slides, send the screen back to its setup, or change the setup and play it there. Server-sent events, held in memory (routes/present.js); X-Accel-Buffering: no, so nginx needs no block of its own. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
3aef3b1c34
commit
5eebc20c4e
10 changed files with 604 additions and 23 deletions
|
|
@ -214,11 +214,11 @@ const sectionsChild = {
|
|||
export const CORE_PAGES = { home: "/", give: "/give", feedback: "/feedback", request: "/request", qr: "/qr", privacy: "/privacy", terms: "/terms" };
|
||||
|
||||
/* Addresses a page can't take: the admin, the API, the uploads, the
|
||||
records' own pages and the account pages. */
|
||||
records' own pages, the account pages and the remote. */
|
||||
const RESERVED = [
|
||||
"admin", "api", "uploads", "assets", "pa", "go",
|
||||
"events", "regions", "groups", "partners", "organizations", "teams", "awards", "people", "blog", "directory",
|
||||
"sign-in", "account", "sitemap.xml", "robots.txt",
|
||||
"sign-in", "account", "remote", "sitemap.xml", "robots.txt",
|
||||
];
|
||||
|
||||
/* After a save: the address is one a page may have. */
|
||||
|
|
|
|||
|
|
@ -43,6 +43,7 @@ import imports from "./routes/import.js";
|
|||
import files from "./routes/files.js";
|
||||
import countdown from "./routes/countdown.js";
|
||||
import redirects from "./routes/redirects.js";
|
||||
import present from "./routes/present.js";
|
||||
import { CLIPS_DIR, startClipWorker } from "./clips.js";
|
||||
import { UPLOADS_DIR, writeMissingThumbs } from "./media.js";
|
||||
import { logSafe, requireStaff, startSessionSweeper } from "./auth.js";
|
||||
|
|
@ -137,7 +138,7 @@ app.use(
|
|||
so each is capped well above its longest real body (a 5000
|
||||
character message) and far below nginx's limit. */
|
||||
const smallBody = bodyLimit({ maxSize: 64 * 1024, onError: (c) => c.json({ error: "That's too long." }, 413) });
|
||||
for (const path of ["/api/csp-report", "/api/feedback", "/api/auth/login", "/api/account/accept", "/api/account/claim", "/api/account/profile"]) app.use(path, smallBody);
|
||||
for (const path of ["/api/csp-report", "/api/feedback", "/api/auth/login", "/api/account/accept", "/api/account/claim", "/api/account/profile", "/api/present/*"]) app.use(path, smallBody);
|
||||
|
||||
/* What the policy above would have blocked. Browsers post these on
|
||||
their own; a short line per report is plenty to go on. */
|
||||
|
|
@ -202,6 +203,11 @@ app.use("/api/countdown/*", rateLimit({ windowMs: 60_000, max: 600 }));
|
|||
app.route("/api", countdown);
|
||||
|
||||
// Tighter limit on the write path than anything else gets.
|
||||
// A presenting screen and its remotes, by the screen's code
|
||||
// (routes/present.js): a cap far above tapping, far below guessing.
|
||||
app.use("/api/present/*", rateLimit({ windowMs: 60_000, max: 300 }));
|
||||
app.route("/api", present);
|
||||
|
||||
app.use("/api/feedback", rateLimit({ windowMs: 60_000, max: 5 }));
|
||||
app.route("/api/feedback", feedback);
|
||||
// Requests carry files: fewer again.
|
||||
|
|
|
|||
|
|
@ -413,6 +413,9 @@ export function metaFor(db, rawPath, user = null) {
|
|||
// in particular, so never indexed or in the sitemap.
|
||||
if (ACCOUNT_PAGES[pathname]) return { ...meta, title: titled(site, ACCOUNT_PAGES[pathname]), noindex: true };
|
||||
|
||||
// A presenting screen's remote (src/pages/PresentRemote.tsx).
|
||||
if (/^\/remote(\/|$)/.test(pathname)) return { ...meta, title: titled(site, "Remote"), noindex: true };
|
||||
|
||||
// A page of the site (site_pages): hidden is Not found below
|
||||
// viewer; disabled stays out of search.
|
||||
const page = pageAt(db, pathname);
|
||||
|
|
|
|||
151
server/src/routes/present.js
Normal file
151
server/src/routes/present.js
Normal file
|
|
@ -0,0 +1,151 @@
|
|||
/* ═══════════════════════════════════════════════════════════════
|
||||
PRESENT REMOTE: a phone drives a presenting screen by its code
|
||||
|
||||
A screen (src/pages/EventPresent.tsx) opens /present/screen, a
|
||||
stream that first says its code and key, then carries commands.
|
||||
It posts what it shows (state) with the key. A remote
|
||||
(src/pages/PresentRemote.tsx) opens /present/:code, a stream of
|
||||
that state, and posts commands. Anyone with the code can drive
|
||||
the screen: the code is the only lock, so it's long enough not to
|
||||
guess at the rate limit set where this is mounted.
|
||||
|
||||
In memory only: one process, and a restart only makes each screen
|
||||
reconnect (keeping its code when no one took it) and post its
|
||||
state again. A screen gone for SWEEP_AFTER is forgotten.
|
||||
═══════════════════════════════════════════════════════════════ */
|
||||
|
||||
import { randomBytes, randomInt } from "node:crypto";
|
||||
import { Hono } from "hono";
|
||||
import { streamSSE } from "hono/streaming";
|
||||
|
||||
const present = new Hono();
|
||||
|
||||
// No 0/O, 1/I/L: read off a screen across a room.
|
||||
const LETTERS = "ABCDEFGHJKMNPQRSTUVWXYZ23456789";
|
||||
const CODE = /^[A-Z0-9]{6}$/;
|
||||
const PING_EVERY = 25_000; // under nginx's 60 second read timeout
|
||||
const SWEEP_AFTER = 10 * 60_000;
|
||||
const COMMANDS = ["next", "prev", "pause", "resume", "go", "setup", "start"];
|
||||
|
||||
// A screen's state before it first says.
|
||||
const NOTHING_YET = { event: "", title: "", query: "", playing: false, paused: false, index: 0, slides: [] };
|
||||
|
||||
// code → { key, state, screen (its stream, or null), gone (ms), remotes (streams) }
|
||||
const screens = new Map();
|
||||
|
||||
setInterval(() => {
|
||||
const now = Date.now();
|
||||
for (const [code, s] of screens) {
|
||||
if (!s.screen && s.remotes.size === 0 && now - s.gone > SWEEP_AFTER) screens.delete(code);
|
||||
}
|
||||
}, 60_000).unref();
|
||||
|
||||
function newCode() {
|
||||
for (;;) {
|
||||
const code = Array.from({ length: 6 }, () => LETTERS[randomInt(LETTERS.length)]).join("");
|
||||
// SCREEN would be the screen's own stream's address.
|
||||
if (!screens.has(code) && code !== "SCREEN") return code;
|
||||
}
|
||||
}
|
||||
|
||||
const send = (stream, event, data) => stream.writeSSE({ event, data: JSON.stringify(data) }).catch(() => {});
|
||||
|
||||
function tellRemotes(s) {
|
||||
for (const remote of s.remotes) send(remote, "state", { connected: !!s.screen, ...s.state });
|
||||
}
|
||||
|
||||
// Holds a stream open, pinging, until the other end goes.
|
||||
function hold(stream, onGone) {
|
||||
return new Promise((resolve) => {
|
||||
const ping = setInterval(() => stream.write(": ping\n\n").catch(() => {}), PING_EVERY);
|
||||
stream.onAbort(() => {
|
||||
clearInterval(ping);
|
||||
onGone();
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/* A screen's stream. It asks for the code it had (code and key) and
|
||||
gets it back unless that's wrong or another screen holds it now. */
|
||||
present.get("/present/screen", (c) => {
|
||||
let code = c.req.query("code");
|
||||
const key = c.req.query("key");
|
||||
let s = screens.get(code);
|
||||
if (!s || s.key !== key || s.screen) {
|
||||
code = newCode();
|
||||
s = { key: randomBytes(16).toString("hex"), state: NOTHING_YET, screen: null, gone: 0, remotes: new Set() };
|
||||
screens.set(code, s);
|
||||
}
|
||||
// Tells nginx to pass each event on as it's written.
|
||||
c.header("X-Accel-Buffering", "no");
|
||||
return streamSSE(c, async (stream) => {
|
||||
s.screen = stream;
|
||||
await send(stream, "hello", { code, key: s.key });
|
||||
tellRemotes(s);
|
||||
await hold(stream, () => {
|
||||
if (s.screen !== stream) return;
|
||||
s.screen = null;
|
||||
s.gone = Date.now();
|
||||
tellRemotes(s);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
/* What the screen shows, for its remotes: shown as text there, so
|
||||
only capped here. */
|
||||
present.post("/present/:code/state", async (c) => {
|
||||
const s = screens.get(c.req.param("code"));
|
||||
const body = await c.req.json().catch(() => null);
|
||||
if (!s || !body || body.key !== s.key) return c.json({ error: "Not found" }, 404);
|
||||
const text = (v, max) => (typeof v === "string" ? v.slice(0, max) : "");
|
||||
const count = (v) => (Number.isInteger(v) && v >= 0 ? v : 0);
|
||||
s.state = {
|
||||
event: text(body.event, 200),
|
||||
title: text(body.title, 300),
|
||||
query: text(body.query, 4000),
|
||||
playing: body.playing === true,
|
||||
paused: body.paused === true,
|
||||
index: count(body.index),
|
||||
slides: Array.isArray(body.slides) ? body.slides.slice(0, 500).map((name) => text(name, 150)) : [],
|
||||
};
|
||||
tellRemotes(s);
|
||||
return c.body(null, 204);
|
||||
});
|
||||
|
||||
// A remote's stream: the screen's state now and each time it changes.
|
||||
present.get("/present/:code", (c) => {
|
||||
const s = screens.get(c.req.param("code").toUpperCase());
|
||||
if (!s) return c.json({ error: "No screen has that code." }, 404);
|
||||
c.header("X-Accel-Buffering", "no");
|
||||
return streamSSE(c, async (stream) => {
|
||||
s.remotes.add(stream);
|
||||
await send(stream, "state", { connected: !!s.screen, ...s.state });
|
||||
await hold(stream, () => s.remotes.delete(stream));
|
||||
});
|
||||
});
|
||||
|
||||
/* A command for the screen: next, prev, pause, resume, go (to
|
||||
`index`), setup (back to its setup) or start (playing `query`, the
|
||||
setup's choices as EventPresent's address reads them). */
|
||||
present.post("/present/:code/command", async (c) => {
|
||||
const code = c.req.param("code").toUpperCase();
|
||||
const s = CODE.test(code) ? screens.get(code) : null;
|
||||
if (!s) return c.json({ error: "No screen has that code." }, 404);
|
||||
if (!s.screen) return c.json({ error: "The screen isn't connected right now." }, 409);
|
||||
const body = await c.req.json().catch(() => null);
|
||||
if (!body || !COMMANDS.includes(body.do)) return c.json({ error: "Unknown command." }, 400);
|
||||
const command = { do: body.do };
|
||||
if (body.do === "go") {
|
||||
if (!Number.isInteger(body.index) || body.index < 0) return c.json({ error: "Which slide?" }, 400);
|
||||
command.index = body.index;
|
||||
}
|
||||
if (body.do === "start") {
|
||||
if (typeof body.query !== "string" || body.query.length > 4000) return c.json({ error: "That setup is too long." }, 400);
|
||||
command.query = body.query;
|
||||
}
|
||||
await send(s.screen, "command", command);
|
||||
return c.body(null, 204);
|
||||
});
|
||||
|
||||
export default present;
|
||||
Loading…
Add table
Add a link
Reference in a new issue