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

+12
View File
@@ -0,0 +1,12 @@
CREATE TABLE `wall_displays` (
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
`name` text NOT NULL,
`slug` text NOT NULL,
`pages` text DEFAULT '[]' NOT NULL,
`rotate_seconds` integer,
`created_by` text,
`created_at` text DEFAULT (current_timestamp) NOT NULL
);
--> statement-breakpoint
CREATE UNIQUE INDEX `wall_displays_slug_unique` ON `wall_displays` (`slug`);--> statement-breakpoint
ALTER TABLE `share_links` ADD `display_id` integer REFERENCES wall_displays(id);
File diff suppressed because it is too large. Load diff
+7
View File
@@ -673,6 +673,13 @@
"when": 1794514473426,
"tag": "0095_user_language",
"breakpoints": true
},
{
"idx": 96,
"version": "6",
"when": 1794520424972,
"tag": "0096_wall_displays",
"breakpoints": true
}
]
}
+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;
}
+229
View File
@@ -0,0 +1,229 @@
/**
* Named wall displays: the address made from a name, which pages a display rotates through and in what order, how fast (and who wins: the address, the display, or the browser), the admin routes, the share
* link that opens one, and what the public board is told.
*
* Run with: npm test --workspace server
*/
import { test, describe, before, after } from "node:test";
import assert from "node:assert/strict";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import type { AddressInfo } from "node:net";
import type { Server } from "node:http";
const dir = mkdtempSync(join(tmpdir(), "hm-walls-"));
process.env.DATABASE_PATH = join(dir, "test.sqlite");
process.env.SESSION_DIR = join(dir, "sessions");
process.env.CREDENTIALS_ENCRYPTION_KEY = "ab".repeat(32);
process.env.HEALTH_STARTUP_GRACE_MS = "0";
const express = (await import("express")).default;
const { db } = await import("../src/db/client.js");
const { users, shareLinks, auditLog } = await import("../src/db/schema.js");
const { runMigrations } = await import("../src/db/migrate.js");
const W = await import("../src/services/wallDisplays.js");
const { createShareLink } = await import("../src/services/shareLinks.js");
const { wallDisplaysRouter } = await import("../src/routes/wallDisplays.js");
const { shareLinksRouter } = await import("../src/routes/shareLinks.js");
const { publicWallRouter } = await import("../src/routes/publicWall.js");
const { describeChange } = await import("../src/services/changeLog.js");
const P = await import("../../web/src/utils/wallPages.js");
const { eq } = await import("drizzle-orm");
await runMigrations();
describe("the address", () => {
test("a name becomes an address of lower case letters, digits and single hyphens; Swedish letters are folded", () => {
assert.equal(W.slugOf("Hall TV"), "hall-tv");
assert.equal(W.slugOf(" Office monitor (upstairs)! "), "office-monitor-upstairs");
assert.equal(W.slugOf("Köket & Vardagsrummet"), "koket-vardagsrummet");
assert.equal(W.slugOf("Åke"), "ake");
assert.equal(W.slugOf("!!!"), "display", "nothing to make one from");
assert.ok(W.slugOf("x".repeat(100)).length <= W.MAX_SLUG);
for (const s of [W.slugOf("Hall TV"), W.slugOf("Köket"), W.slugOf("a b")]) assert.match(s, W.SLUG);
});
test("one that is taken gets a number", () => {
assert.equal(W.freeSlug("hall-tv", []), "hall-tv");
assert.equal(W.freeSlug("hall-tv", ["hall-tv"]), "hall-tv-2");
assert.equal(W.freeSlug("hall-tv", ["hall-tv", "hall-tv-2", "hall-tv-3"]), "hall-tv-4");
assert.ok(W.freeSlug("y".repeat(40), ["y".repeat(40)]).length <= W.MAX_SLUG);
});
test("a stored list of pages is read back as ids of pages that exist, once each; anything else is none", () => {
assert.deepEqual(W.parsePages(JSON.stringify(["overview", "group:apps", "overview", "bogus", 5, "group:Bad"])), ["overview", "group:apps"]);
for (const odd of [null, undefined, "", "{", "{}", '"overview"']) assert.deepEqual(W.parsePages(odd as string), []);
});
});
describe("what a display shows, and how fast", () => {
const board: import("../../web/src/utils/wallPages.js").WallPage[] = [
{ id: "overview", label: "Overview", kind: "overview" },
{ id: "alerts", label: "Needs attention", kind: "alerts" },
{ id: "group:apps", label: "Apps", kind: "group", groupId: "apps" },
{ id: "group:network", label: "Network", kind: "group", groupId: "network" },
];
test("the pages it lists, in its order, that the board has now; none listed is every page", () => {
assert.deepEqual(P.applyDisplay(board, []).map((p) => p.id), ["overview", "alerts", "group:apps", "group:network"]);
assert.deepEqual(P.applyDisplay(board, ["group:network", "overview"]).map((p) => p.id), ["group:network", "overview"], "its order, not the board's");
assert.deepEqual(P.applyDisplay(board, ["overview", "overview", "group:apps"]).map((p) => p.id), ["overview", "group:apps"]);
});
test("a page the board has not got just now is left out, and a display with none of its pages shows the overview", () => {
const quiet = board.filter((p) => p.id !== "alerts");
assert.deepEqual(P.applyDisplay(quiet, ["alerts", "group:apps"]).map((p) => p.id), ["group:apps"]);
assert.deepEqual(P.applyDisplay(quiet, ["alerts"]).map((p) => p.id), ["overview"]);
assert.deepEqual(P.applyDisplay(quiet, ["group:nothing"]).map((p) => p.id), ["overview"]);
});
test("the pages a display may be given are the board's, in its order", () => {
const ids = P.displayPageChoices().map((c) => c.id);
assert.deepEqual(ids.slice(0, 2), ["overview", "alerts"]);
assert.ok(ids.includes("group:infrastructure") && ids.includes("group:other"));
for (const id of ids) assert.match(id, W.PAGE_ID, `${id} is a page the server accepts`);
});
test("the address wins, then what the display says, then what the browser last chose", () => {
assert.equal(P.rotateSeconds("45", "off", 60), 45, "the address");
assert.equal(P.rotateSeconds("off", "30", 60), null, "the address may switch it off");
assert.equal(P.rotateSeconds(null, "off", 60), 60, "the display, over the browser");
assert.equal(P.rotateSeconds(null, "30", null), 30, "the browser, when the display says nothing");
assert.equal(P.rotateSeconds(null, null, null), null);
assert.equal(P.rotateSeconds(null, null, 5), P.ROTATE_MIN, "a speed out of range is brought into it");
assert.equal(P.rotateSeconds(null, "30"), 30, "existing callers are unchanged");
});
});
describe("the routes", () => {
let app: Server;
let base = "";
let who = "root";
const call = (method: string, path: string, body?: unknown) => fetch(`${base}${path}`, { method, headers: { "content-type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body) });
before(async () => {
await db.insert(users).values([
{ oidcSub: "root", name: "Rut", role: "admin" },
{ oidcSub: "viewer", name: "Vera", role: "viewer" },
]);
const a = express();
a.use(express.json());
a.use((req, _res, next) => {
(req as unknown as { session: unknown }).session = { user: { sub: who } };
next();
});
a.use("/api/wall-displays", wallDisplaysRouter);
a.use("/api/share-links", shareLinksRouter);
a.use("/api/public/wall", publicWallRouter);
app = await new Promise<Server>((resolve) => {
const x = a.listen(0, "127.0.0.1", () => resolve(x));
});
base = `http://127.0.0.1:${(app.address() as AddressInfo).port}/api`;
});
after(() => {
app.close();
try {
rmSync(dir, { recursive: true, force: true });
} catch {
// Windows keeps the database file locked until the process exits.
}
});
test("an administrator makes one, the address is made from the name, and anyone signed in can see the list", async () => {
const res = await call("POST", "/wall-displays", { name: "Hall TV", pages: ["overview", "group:apps"], rotateSeconds: 30 });
assert.equal(res.status, 201);
const { display } = await res.json();
assert.deepEqual([display.name, display.slug, display.pages, display.rotateSeconds], ["Hall TV", "hall-tv", ["overview", "group:apps"], 30]);
assert.equal(display.createdBy, "Rut");
who = "viewer";
const list = await (await call("GET", "/wall-displays")).json();
assert.deepEqual(list.displays.map((d: { slug: string }) => d.slug), ["hall-tv"]);
who = "root";
});
test("a viewer can not make, change or remove one", async () => {
who = "viewer";
assert.equal((await call("POST", "/wall-displays", { name: "No" })).status, 403);
const id = (await (await call("GET", "/wall-displays")).json()).displays[0].id;
assert.equal((await call("PUT", `/wall-displays/${id}`, { name: "No" })).status, 403);
assert.equal((await call("DELETE", `/wall-displays/${id}`)).status, 403);
who = "root";
});
test("a second with the same name gets a number; an address asked for that is taken is refused; a bad one is refused with a reason", async () => {
const second = (await (await call("POST", "/wall-displays", { name: "Hall TV" })).json()).display;
assert.equal(second.slug, "hall-tv-2");
assert.deepEqual([second.pages, second.rotateSeconds], [[], null], "no pages is every page");
const taken = await call("POST", "/wall-displays", { name: "Other", slug: "hall-tv" });
assert.equal(taken.status, 409);
assert.equal((await taken.json()).error, "slug_taken");
for (const bad of [{ name: "" }, { name: "x", slug: "Has Spaces" }, { name: "x", slug: "-lead" }, { name: "x", pages: ["nonsense"] }, { name: "x", pages: ["group:UPPER"] }, { name: "x", rotateSeconds: 3 }, { name: "x", rotateSeconds: 9999 }, { name: "x", pages: Array(25).fill("overview") }]) {
assert.equal((await call("POST", "/wall-displays", bad)).status, 400, JSON.stringify(bad).slice(0, 50));
}
assert.match((await (await call("POST", "/wall-displays", { name: "x", pages: ["nonsense"] })).json()).message, /not a page of the board/);
await call("DELETE", `/wall-displays/${second.id}`);
});
test("changing it keeps its address unless that is changed on purpose, so a bookmark on a screen survives a corrected name", async () => {
const id = (await (await call("GET", "/wall-displays")).json()).displays.find((d: { slug: string }) => d.slug === "hall-tv").id;
const renamed = (await (await call("PUT", `/wall-displays/${id}`, { name: "Hallway TV", pages: ["group:network"], rotateSeconds: null })).json()).display;
assert.deepEqual([renamed.name, renamed.slug, renamed.pages, renamed.rotateSeconds], ["Hallway TV", "hall-tv", ["group:network"], null]);
const moved = (await (await call("PUT", `/wall-displays/${id}`, { name: "Hallway TV", slug: "hallway" })).json()).display;
assert.equal(moved.slug, "hallway");
assert.equal((await call("PUT", "/wall-displays/9999", { name: "x" })).status, 404);
assert.equal((await call("PUT", "/wall-displays/abc", { name: "x" })).status, 400);
await call("PUT", `/wall-displays/${id}`, { name: "Hall TV", slug: "hall-tv", pages: ["overview", "group:apps"], rotateSeconds: 30 });
});
test("a wall share link can open one; the public board is told its name, pages and speed; one that is gone opens the whole board", async () => {
const id = (await (await call("GET", "/wall-displays")).json()).displays[0].id;
const made = await call("POST", "/share-links", { label: "Hall screen", kind: "wall", detail: "summary", displayId: id, expiresInDays: null });
assert.equal(made.status, 201);
const { link, token } = await made.json();
assert.equal(link.displayId, id);
const board = await (await call("GET", `/public/wall/${token}`)).json();
assert.deepEqual(board.displayConfig, { name: "Hall TV", pages: ["overview", "group:apps"], rotateSeconds: 30 });
// a link with no display says none
const plain = (await (await call("POST", "/share-links", { label: "Whole board", kind: "wall", expiresInDays: null })).json()).token;
assert.equal((await (await call("GET", `/public/wall/${plain}`)).json()).displayConfig, null);
// taking the display away leaves the link working, on the whole board
assert.equal((await call("DELETE", `/wall-displays/${id}`)).status, 204);
const after = await (await call("GET", `/public/wall/${token}`)).json();
assert.equal(after.displayConfig, null);
const [row] = await db.select().from(shareLinks).where(eq(shareLinks.label, "Hall screen"));
assert.equal(row.displayId, null);
});
test("a link can only open a display that exists, only a wall can, and the rest of what it needs is unchanged", async () => {
const refused = await call("POST", "/share-links", { label: "x", kind: "wall", displayId: 9999, expiresInDays: null });
assert.equal(refused.status, 400);
assert.equal((await refused.json()).error, "no_such_display");
const display = (await (await call("POST", "/wall-displays", { name: "For status" })).json()).display;
const calendar = (await (await call("POST", "/share-links", { label: "cal", kind: "calendar", detail: "summary", displayId: display.id, expiresInDays: null })).json()).link;
assert.equal(calendar.displayId, null, "a calendar has no display");
void createShareLink;
});
test("it is in the audit log and the change log", async () => {
const audit = (await db.select().from(auditLog)).filter((a) => a.category === "wall_display");
assert.deepEqual([...new Set(audit.map((a) => a.action))].sort(), ["create", "delete", "update"]);
assert.deepEqual(describeChange("wall_display", "create", { name: "Hall TV", address: "/wall/hall-tv" }), { title: "Wall display added: Hall TV", tone: "neutral", detail: "/wall/hall-tv" });
assert.equal(describeChange("wall_display", "update", { name: "Hall TV" }).title, "Wall display changed: Hall TV");
assert.equal(describeChange("wall_display", "delete", { name: "Hall TV" }).title, "Wall display removed: Hall TV");
});
test("no more than twenty", async () => {
for (let i = 0; i < 25; i++) {
const r = await call("POST", "/wall-displays", { name: `Screen ${i}` });
if (r.status === 409) {
assert.equal((await r.json()).error, "too_many");
return;
}
}
assert.fail("never refused");
});
});