Add named wall displays: pages, order and speed per screen

An administrator can make named displays (Hall TV, Office monitor) under
Settings -> Share links, each with an address of its own (/wall/hall-tv), the
pages it rotates through in the board's order, and a rotation speed. The
signed-in wall opens one from its address and can switch between them, and a
wall share link can open one too. The address still wins over the display's
speed, then the browser's choice.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
bobbanandClaude Sonnet 5.5 committed 2026-11-12 23:04:22 +01:00
1 parent 639408c0d0
commit 333146e8e3
24 files changed
+10411 -22

No files matched your search

+2
View File
@@ -72,6 +72,7 @@ import { speedtestRouter } from "./routes/speedtest.js";
import { fragnetRouter } from "./routes/fragnet.js";
import { arrRouter } from "./routes/arr.js";
import { wallRouter } from "./routes/wall.js";
import { wallDisplaysRouter } from "./routes/wallDisplays.js";
import { adguardRouter } from "./routes/adguard.js";
import { technitiumRouter } from "./routes/technitium.js";
import { downloadsRouter } from "./routes/downloads.js";
@@ -229,6 +230,7 @@ export function createApp() {
app.use("/api/fragnet", fragnetRouter);
app.use("/api/arr", arrRouter);
app.use("/api/wall", wallRouter);
app.use("/api/wall-displays", wallDisplaysRouter);
app.use("/api/adguard", adguardRouter);
app.use("/api/technitium", technitiumRouter);
app.use("/api/downloads", downloadsRouter);
+15
View File
@@ -850,6 +850,19 @@ export type ShareLinkDetail = (typeof shareLinkDetails)[number];
export const shareLinkKinds = ["wall", "status", "calendar"] as const;
export type ShareLinkKind = (typeof shareLinkKinds)[number];
// Named wall displays ("Hall TV"): which pages the board rotates through, in which order, and how fast — services/wallDisplays.ts. A share link to a wall can open one.
export const wallDisplays = sqliteTable("wall_displays", {
id: integer("id").primaryKey({ autoIncrement: true }),
name: text("name").notNull(),
slug: text("slug").notNull().unique(), // the address: /wall/<slug>
pages: text("pages").notNull().default("[]"), // JSON: page ids in order ("overview", "alerts", "group:apps" …); empty = every page the board has
rotateSeconds: integer("rotate_seconds"), // how long each page stays; null = not set (the address or the browser decides, else the board does not rotate)
createdBy: text("created_by"),
createdAt: text("created_at")
.notNull()
.default(sql`(current_timestamp)`),
});
// A link to the wall display that needs no sign-in, for a TV in the hall or someone who only wants to know if things are up. Only a hash
// of the secret part of the address is kept (like an agent token), so it can't be read back out of the database or a backup.
export const shareLinks = sqliteTable("share_links", {
@@ -860,6 +873,8 @@ export const shareLinks = sqliteTable("share_links", {
// summary = how things are, in numbers; names = also the names of what is wrong, in maintenance, and the integrations
detail: text("detail").$type<ShareLinkDetail>().notNull().default("summary"),
kind: text("kind").$type<ShareLinkKind>().notNull().default("wall"),
// For a wall: the named display it opens (its pages and speed); null = the whole board. Taken away with the display.
displayId: integer("display_id").references(() => wallDisplays.id, { onDelete: "set null" }),
// A status page's own heading and an optional announcement under it ("Movies are being updated tonight"). Unused by a wall.
title: text("title"),
message: text("message"),
+3 -1
View File
@@ -1,6 +1,7 @@
import { Router } from "express";
import { NOT_FOUND, resolveShareLink } from "../services/shareLinks.js";
import { buildPublicWall } from "../services/publicWall.js";
import { displayForLink } from "../services/wallDisplays.js";
import { rateLimit } from "../utils/rateLimit.js";
import { asyncHandler } from "../utils/asyncHandler.js";
@@ -16,5 +17,6 @@ publicWallRouter.get("/:token", limiter, asyncHandler(async (req, res) => {
if (!link || link.kind !== "wall") return res.status(404).json(NOT_FOUND);
res.setHeader("Cache-Control", "no-store");
res.setHeader("X-Robots-Tag", "noindex, nofollow");
res.json(await buildPublicWall(link.detail));
// The named display this link opens, if any: which pages the board rotates through and how fast (the picture itself is the same).
res.json({ ...(await buildPublicWall(link.detail)), displayConfig: await displayForLink(link.displayId) });
}));
+8 -2
View File
@@ -2,7 +2,7 @@ import { Router } from "express";
import { eq } from "drizzle-orm";
import { z } from "zod";
import { db } from "../db/client.js";
import { shareLinkDetails, shareLinkKinds, shareLinks, statusItemKinds, statusItems } from "../db/schema.js";
import { shareLinkDetails, shareLinkKinds, shareLinks, statusItemKinds, statusItems, wallDisplays } from "../db/schema.js";
import { requireAuth, requireRole } from "../auth/middleware.js";
import { recordAudit } from "../services/audit.js";
import { createShareLink, publicShareLink } from "../services/shareLinks.js";
@@ -22,6 +22,8 @@ const createSchema = z.object({
kind: z.enum(shareLinkKinds).default("wall"),
// For a wall: how much it shows. A status page always shows only names and states, so this is ignored for it. For a calendar: summary leaves the names out of the events.
detail: z.enum(shareLinkDetails).default("summary"),
// For a wall: a named display (its pages and speed) instead of the whole board.
displayId: z.number().int().positive().nullable().optional(),
title: z.string().trim().max(MAX_TITLE).optional(),
message: z.string().trim().max(MAX_MESSAGE).optional(),
expiresInDays: z.number().int().min(1).max(365).nullable(),
@@ -49,6 +51,10 @@ shareLinksRouter.post("/", asyncHandler(async (req, res) => {
if (existing.length >= MAX_LINKS) {
return res.status(400).json({ error: "too_many", message: `There are already ${MAX_LINKS} share links. Remove one you no longer use first.` });
}
if (parsed.data.displayId != null) {
const [shown] = await db.select({ id: wallDisplays.id }).from(wallDisplays).where(eq(wallDisplays.id, parsed.data.displayId)).limit(1);
if (!shown) return res.status(400).json({ error: "no_such_display", message: "That wall display doesn't exist (any more)." });
}
const actor = req.currentUser!;
const { link, token } = await createShareLink({ ...parsed.data, createdBy: actor.name ?? actor.email ?? actor.oidcSub });
await recordAudit({
@@ -57,7 +63,7 @@ shareLinksRouter.post("/", asyncHandler(async (req, res) => {
action: "create",
targetType: "share_link",
targetId: link.id,
detail: { label: link.label, kind: link.kind, detail: link.detail, expiresAt: link.expiresAt },
detail: { label: link.label, kind: link.kind, detail: link.detail, expiresAt: link.expiresAt, ...(link.displayId !== null ? { displayId: link.displayId } : {}) },
});
res.status(201).json({ link: publicShareLink(link), token, path: link.kind === "calendar" ? `/api/public/calendar/${token}.ics` : `/share/${link.kind === "status" ? "status" : "wall"}/${token}` });
}));
+79
View File
@@ -0,0 +1,79 @@
import { Router } from "express";
import { eq } from "drizzle-orm";
import { z } from "zod";
import { db } from "../db/client.js";
import { shareLinks, wallDisplays } from "../db/schema.js";
import { requireAuth, requireRole } from "../auth/middleware.js";
import { recordAudit } from "../services/audit.js";
import { freeSlug, listDisplays, MAX_DISPLAYS, MAX_SLUG, PAGE_ID, ROTATE_MAX, ROTATE_MIN, shapeDisplay, SLUG, slugOf } from "../services/wallDisplays.js";
import { asyncHandler } from "../utils/asyncHandler.js";
export const wallDisplaysRouter = Router();
// Everyone signed in can see the list (the wall's own footer offers them); making, changing and removing one is an administrator's, like the share links they can be opened from.
wallDisplaysRouter.use(requireAuth);
const displaySchema = z.object({
name: z.string().trim().min(1).max(60),
// Left out: made from the name. Given: lower case letters, digits and hyphens.
slug: z.string().trim().max(MAX_SLUG).regex(SLUG, "Use lower case letters, digits and single hyphens, like hall-tv.").optional(),
// The pages in the order the board rotates through them; empty is every page it has.
pages: z.array(z.string().regex(PAGE_ID, "That is not a page of the board.")).max(20).default([]),
rotateSeconds: z.number().int().min(ROTATE_MIN).max(ROTATE_MAX).nullable().default(null),
});
const idOf = (v: string) => (/^\d+$/.test(v) ? Number(v) : NaN);
const addressOf = (slug: string) => `/wall/${slug}`;
wallDisplaysRouter.get("/", asyncHandler(async (_req, res) => {
res.json({ displays: (await listDisplays()).map(shapeDisplay) });
}));
wallDisplaysRouter.post("/", requireRole("admin"), asyncHandler(async (req, res) => {
const parsed = displaySchema.safeParse(req.body);
if (!parsed.success) return res.status(400).json({ error: "invalid_body", message: parsed.error.issues[0]?.message ?? "Give the display a name.", details: parsed.error.flatten() });
const all = await listDisplays();
if (all.length >= MAX_DISPLAYS) return res.status(409).json({ error: "too_many", message: `At most ${MAX_DISPLAYS} displays.` });
// A slug asked for that is taken is said to be; one made from the name is made free by a number.
if (parsed.data.slug && all.some((d) => d.slug === parsed.data.slug)) return res.status(409).json({ error: "slug_taken", message: `Another display already has the address ${addressOf(parsed.data.slug)}.` });
const slug = parsed.data.slug ?? freeSlug(slugOf(parsed.data.name), all.map((d) => d.slug));
const actor = req.currentUser!;
const [row] = await db
.insert(wallDisplays)
.values({ name: parsed.data.name, slug, pages: JSON.stringify([...new Set(parsed.data.pages)]), rotateSeconds: parsed.data.rotateSeconds, createdBy: actor.name ?? actor.email ?? actor.oidcSub })
.returning();
await recordAudit({ actor, category: "wall_display", action: "create", targetType: "wall_display", targetId: row.id, detail: { name: row.name, address: addressOf(row.slug) } });
res.status(201).json({ display: shapeDisplay(row) });
}));
wallDisplaysRouter.put("/:id", requireRole("admin"), asyncHandler(async (req, res) => {
const id = idOf(req.params.id);
const parsed = displaySchema.safeParse(req.body);
if (!Number.isInteger(id)) return res.status(400).json({ error: "invalid_id" });
if (!parsed.success) return res.status(400).json({ error: "invalid_body", message: parsed.error.issues[0]?.message ?? "Give the display a name.", details: parsed.error.flatten() });
const all = await listDisplays();
const before = all.find((d) => d.id === id);
if (!before) return res.status(404).json({ error: "not_found" });
// The address stays as it was unless it is changed on purpose, so a bookmark on a screen keeps working when the name is corrected.
const slug = parsed.data.slug ?? before.slug;
if (all.some((d) => d.id !== id && d.slug === slug)) return res.status(409).json({ error: "slug_taken", message: `Another display already has the address ${addressOf(slug)}.` });
const [row] = await db
.update(wallDisplays)
.set({ name: parsed.data.name, slug, pages: JSON.stringify([...new Set(parsed.data.pages)]), rotateSeconds: parsed.data.rotateSeconds })
.where(eq(wallDisplays.id, id))
.returning();
await recordAudit({ actor: req.currentUser!, category: "wall_display", action: "update", targetType: "wall_display", targetId: id, detail: { name: row.name, address: addressOf(row.slug) } });
res.json({ display: shapeDisplay(row) });
}));
wallDisplaysRouter.delete("/:id", requireRole("admin"), asyncHandler(async (req, res) => {
const id = idOf(req.params.id);
if (!Number.isInteger(id)) return res.status(400).json({ error: "invalid_id" });
const [before] = await db.select().from(wallDisplays).where(eq(wallDisplays.id, id)).limit(1);
if (!before) return res.status(404).json({ error: "not_found" });
// A share link that opened it goes on opening the whole board.
await db.update(shareLinks).set({ displayId: null }).where(eq(shareLinks.displayId, id));
await db.delete(wallDisplays).where(eq(wallDisplays.id, id));
await recordAudit({ actor: req.currentUser!, category: "wall_display", action: "delete", targetType: "wall_display", targetId: id, detail: { name: before.name } });
res.status(204).end();
}));
+7
View File
@@ -38,6 +38,7 @@ const KIND_OF_CATEGORY: Record<string, ChangeKind> = {
user: "settings",
push: "settings",
share_link: "settings",
wall_display: "settings",
metrics_token: "settings",
api_token: "settings",
alert_rule: "alerts",
@@ -259,6 +260,12 @@ export function describeChange(category: string, action: string, detail: Record<
return { title: `Alert settled${str(detail.message) ? `: ${str(detail.message)}` : ""}`, tone: detail.active === true ? "bad" : "good", detail: detail.active === true ? "steady for an hour, and still active" : "steady for an hour, and cleared" };
case "report/send_monthly":
return { title: `Monthly report sent${str(detail.month) ? ` (${str(detail.month)})` : ""}`, tone: "neutral", detail: null };
case "wall_display/create":
return { title: `Wall display added${name ? `: ${name}` : ""}`, tone: "neutral", detail: str(detail.address) };
case "wall_display/update":
return { title: `Wall display changed${name ? `: ${name}` : ""}`, tone: "neutral", detail: str(detail.address) };
case "wall_display/delete":
return { title: `Wall display removed${name ? `: ${name}` : ""}`, tone: "neutral", detail: null };
case "patch_plan/create":
return { title: `Patch plan added${name ? `: ${name}` : ""}`, tone: "neutral", detail: null };
case "patch_plan/update":
+3 -1
View File
@@ -17,7 +17,7 @@ const hash = (token: string) => createHash("sha256").update(token).digest("hex")
/** A link isn't recorded as used more than once in this time, so a screen refreshing every few seconds doesn't write the database each time. */
const USED_WRITE_GAP_MS = 60_000;
export async function createShareLink(params: { label: string; detail: ShareLinkDetail; kind?: ShareLinkKind; title?: string | null; message?: string | null; expiresInDays: number | null; createdBy: string; now?: Date }): Promise<{ link: ShareLinkRow; token: string }> {
export async function createShareLink(params: { label: string; detail: ShareLinkDetail; kind?: ShareLinkKind; displayId?: number | null; title?: string | null; message?: string | null; expiresInDays: number | null; createdBy: string; now?: Date }): Promise<{ link: ShareLinkRow; token: string }> {
const now = params.now ?? new Date();
const token = randomBytes(24).toString("base64url");
const [link] = await db
@@ -28,6 +28,7 @@ export async function createShareLink(params: { label: string; detail: ShareLink
tokenPrefix: token.slice(0, 6),
detail: params.detail,
kind: params.kind ?? "wall",
displayId: (params.kind ?? "wall") === "wall" ? (params.displayId ?? null) : null,
title: params.title?.trim() || null,
message: params.message?.trim() || null,
createdBy: params.createdBy,
@@ -57,6 +58,7 @@ export function publicShareLink(link: ShareLinkRow, now: Date = new Date()) {
tokenPrefix: link.tokenPrefix,
detail: link.detail,
kind: link.kind,
displayId: link.displayId,
title: link.title,
message: link.message,
createdBy: link.createdBy,
+71
View File
@@ -0,0 +1,71 @@
/**
* Named wall displays: "Hall TV", "Office monitor", "Rack tablet". Each is a saved choice of which pages the board rotates through (and in which order) and how fast, with an address of its own
* (`/wall/hall-tv`) that can be bookmarked on the screen it is for, and a share link can open one too. Nothing about what the board shows changes: a display only chooses among the pages the
* board has (the overview, what needs attention, and one for each group of integrations) — see web/src/utils/wallPages.ts.
*/
import { eq } from "drizzle-orm";
import { db } from "../db/client.js";
import { wallDisplays } from "../db/schema.js";
export type WallDisplayRow = typeof wallDisplays.$inferSelect;
/** More displays than there are screens in a house. */
export const MAX_DISPLAYS = 20;
export const ROTATE_MIN = 10;
export const ROTATE_MAX = 600;
/** A page of the board: "overview", "alerts", or "group:<id>" for a group of integrations (infrastructure, apps, backups, network, monitoring, automation, other …). */
export const PAGE_ID = /^(overview|alerts|group:[a-z0-9-]{1,40})$/;
/** The address part of a display: lower case letters, digits and single hyphens. */
export const SLUG = /^[a-z0-9]+(-[a-z0-9]+)*$/;
export const MAX_SLUG = 40;
/** Pure: a name as an address part — "Hall TV (upstairs)" → "hall-tv-upstairs"; Swedish letters are folded (å, ä → a, ö → o) so the address is plain. */
export function slugOf(name: string): string {
const folded = name
.toLowerCase()
.replace(/[åä]/g, "a")
.replace(/ö/g, "o")
.normalize("NFD")
.replace(/[̀-ͯ]/g, "");
const slug = folded.replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, MAX_SLUG).replace(/-+$/g, "");
return slug || "display";
}
/** Pure: a slug nobody else has, by adding -2, -3 … (the display being edited does not count against itself). */
export function freeSlug(wanted: string, taken: Iterable<string>): string {
const used = new Set(taken);
if (!used.has(wanted)) return wanted;
for (let n = 2; ; n++) {
const tail = `-${n}`;
const candidate = `${wanted.slice(0, MAX_SLUG - tail.length)}${tail}`;
if (!used.has(candidate)) return candidate;
}
}
/** What is stored for the pages, read back as a list of page ids; anything that is not one is none (which means every page). */
export function parsePages(stored: string | null | undefined): string[] {
if (!stored) return [];
try {
const v = JSON.parse(stored);
return Array.isArray(v) ? [...new Set(v.filter((p): p is string => typeof p === "string" && PAGE_ID.test(p)))] : [];
} catch {
return [];
}
}
/** A display as everyone signed in sees it. */
export function shapeDisplay(row: WallDisplayRow) {
return { id: row.id, name: row.name, slug: row.slug, pages: parsePages(row.pages), rotateSeconds: row.rotateSeconds, createdBy: row.createdBy, createdAt: row.createdAt };
}
export async function listDisplays(): Promise<WallDisplayRow[]> {
return db.select().from(wallDisplays).orderBy(wallDisplays.name);
}
/** The display a share link points at, as the public board needs it (name, pages, speed) — null when there is none or it was taken away. */
export async function displayForLink(displayId: number | null): Promise<{ name: string; pages: string[]; rotateSeconds: number | null } | null> {
if (displayId === null) return null;
const [row] = await db.select().from(wallDisplays).where(eq(wallDisplays.id, displayId)).limit(1);
return row ? { name: row.name, pages: parsePages(row.pages), rotateSeconds: row.rotateSeconds } : null;
}