Files
Homelab-manager/server/src/routes/wallDisplays.ts
T
bobbanandClaude Sonnet 5.5 333146e8e3 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>
2026-11-12 23:04:22 +01:00

80 lines
5.2 KiB
TypeScript

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();
}));