From cb43ad78cae6bf3f312a239e9549f4fad380e1b4 Mon Sep 17 00:00:00 2001 From: Julian Cuni Date: Tue, 17 Nov 2026 17:31:58 +0100 Subject: [PATCH] =?UTF-8?q?feat(cameras):=20=E2=80=B9=20=E2=80=BA=20throug?= =?UTF-8?q?h=20older/newer=20snapshots=20in=20the=20large=20view?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit On the Snapshot side the large view steps through that camera's snapshots (‹ older, › newer, also ← →), muted at either end; the caption carries the date and always names the picture on screen (the previous one stays while the next loads; a pruned still says "unavailable"). The tile stays on the newest; closing resets. New read-only route GET /api/cameras/:deviceId/snapshots/:snapshotId/neighbors (session:read), ordered by (capturedAt, id) like latest-snapshot, bounded to seek the device/time index. Also carries the user's own label edits in en.ts / sq.ts. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RZgP5oMncSaVmKRKk1UvN4 --- apps/server/src/routes/cameras.test.ts | 49 ++++++++ apps/server/src/routes/cameras.ts | 52 +++++++- apps/web/src/api.ts | 8 ++ apps/web/src/lib/i18n/en.ts | 5 +- apps/web/src/lib/i18n/sq.ts | 21 ++-- apps/web/src/ui/CameraDock.tsx | 157 ++++++++++++++++++++----- wiki/decisions/camera-live-view.md | 9 ++ wiki/log.md | 9 ++ 8 files changed, 267 insertions(+), 43 deletions(-) diff --git a/apps/server/src/routes/cameras.test.ts b/apps/server/src/routes/cameras.test.ts index 46fd887..2185362 100644 --- a/apps/server/src/routes/cameras.test.ts +++ b/apps/server/src/routes/cameras.test.ts @@ -60,6 +60,55 @@ describe("GET /api/cameras/:id/latest-snapshot", () => { }); }); +describe("GET /api/cameras/:id/snapshots/:snapshotId/neighbors", () => { + const url = (cam: string, id: string) => `/api/cameras/${cam}/snapshots/${id}/neighbors`; + + it("steps through one camera's snapshots by time, ties broken by id", async () => { + await seedUser(db, { username: "admin", password: "pw" }); + const { cookie } = await login(app, "admin", "pw"); + shot("a", "cam-dahua", "2026-11-17T10:00:00.000Z"); + shot("b", "cam-dahua", "2026-11-17T11:00:00.000Z"); + shot("c", "cam-dahua", "2026-11-17T11:00:00.000Z"); // same instant as b + shot("d", "cam-dahua", "2026-11-17T12:00:00.000Z"); + shot("x", "other", "2026-11-17T11:30:00.000Z"); // another camera: never a neighbour + const get = async (id: string) => (await app.inject({ url: url("cam-dahua", id), headers: { cookie } })).json(); + const ids = (r: { older: { id: string } | null; newer: { id: string } | null }) => [r.older?.id ?? null, r.newer?.id ?? null]; + expect(ids(await get("a"))).toEqual([null, "b"]); + expect(ids(await get("b"))).toEqual(["a", "c"]); + expect(ids(await get("c"))).toEqual(["b", "d"]); + expect(ids(await get("d"))).toEqual(["c", null]); + expect(await get("b")).toMatchObject({ older: { id: "a", direction: "entry", capturedAt: "2026-11-17T10:00:00.000Z" } }); + // latest-snapshot uses the same tie-break, so "newer" is never offered from the latest + const latest = await app.inject({ url: "/api/cameras/cam-dahua/latest-snapshot", headers: { cookie } }); + expect(latest.json().id).toBe("d"); + }); + + it("a tie at the newest end: latest-snapshot is the one with no newer", async () => { + await seedUser(db, { username: "admin", password: "pw" }); + const { cookie } = await login(app, "admin", "pw"); + shot("p", "cam-dahua", "2026-11-17T10:00:00.000Z"); + shot("q", "cam-dahua", "2026-11-17T12:00:00.000Z"); + shot("r", "cam-dahua", "2026-11-17T12:00:00.000Z"); + const latest = (await app.inject({ url: "/api/cameras/cam-dahua/latest-snapshot", headers: { cookie } })).json(); + const n = (await app.inject({ url: url("cam-dahua", latest.id), headers: { cookie } })).json(); + expect(latest.id).toBe("r"); + expect(n).toMatchObject({ older: { id: "q" }, newer: null }); + }); + + it("404s another camera's snapshot, 403s without session:read", async () => { + await seedUser(db, { username: "admin", password: "pw" }); + const admin = await login(app, "admin", "pw"); + shot("x", "other", "2026-11-17T11:30:00.000Z"); + const foreign = await app.inject({ url: url("cam-dahua", "x"), headers: { cookie: admin.cookie } }); + expect(foreign.statusCode).toBe(404); + + await seedUser(db, { username: "dev", password: "pw", roleId: "devonly", permissions: ["device:read"] }); + const dev = await login(app, "dev", "pw"); + const res = await app.inject({ url: url("other", "x"), headers: { cookie: dev.cookie } }); + expect(res.statusCode).toBe(403); + }); +}); + describe("WS /api/cameras/:id/live", () => { const origin = "http://booth.local:8080"; diff --git a/apps/server/src/routes/cameras.ts b/apps/server/src/routes/cameras.ts index 78e17fb..3aca4ed 100644 --- a/apps/server/src/routes/cameras.ts +++ b/apps/server/src/routes/cameras.ts @@ -1,5 +1,5 @@ import type { FastifyInstance } from "fastify"; -import { desc, devices, eq, snapshots, type Db } from "@parking/db"; +import { and, asc, desc, devices, eq, gt, gte, lt, lte, or, snapshots, type Db } from "@parking/db"; import { isLiveStreamDevice } from "@parking/devices"; import { requirePermission, roleHasPermissions } from "../auth.js"; import { buildCamera } from "../snapshot.js"; @@ -10,6 +10,9 @@ import { authenticateWsHandshake } from "./ws.js"; // - GET /api/cameras/:deviceId/latest-snapshot — the tile's default picture: the newest // entry/exit evidence still this camera captured (metadata; bytes stay at // /api/snapshots/:id). Evidence → `session:read`, like every snapshot read. +// - GET /api/cameras/:deviceId/snapshots/:snapshotId/neighbors — the large view's ‹ ›: +// this camera's next older and next newer snapshot ({ older, newer }, each meta or +// null). Same permission. Order is (capturedAt, id) everywhere so ties are stable. // - WS /api/cameras/:deviceId/live — live video while the camera sees a vehicle. // Same handshake auth as /api/ws (Origin allowlist, then desktop ticket or cookie), // then `device:read` (the footer's permission). Server → client: text JSON @@ -42,7 +45,7 @@ export async function cameraRoutes(app: FastifyInstance, db: Db, hub: CameraLive .select({ id: snapshots.id, direction: snapshots.direction, capturedAt: snapshots.capturedAt }) .from(snapshots) .where(eq(snapshots.deviceId, req.params.deviceId)) - .orderBy(desc(snapshots.capturedAt)) + .orderBy(desc(snapshots.capturedAt), desc(snapshots.id)) .limit(1) .get(); if (!row) return reply.code(404).send({ error: "no snapshot for this camera yet" }); @@ -50,6 +53,51 @@ export async function cameraRoutes(app: FastifyInstance, db: Db, hub: CameraLive }, ); + app.get<{ Params: { deviceId: string; snapshotId: string } }>( + "/api/cameras/:deviceId/snapshots/:snapshotId/neighbors", + { preHandler: requirePermission("session:read") }, + async (req, reply) => { + const { deviceId, snapshotId } = req.params; + const at = db + .select({ capturedAt: snapshots.capturedAt }) + .from(snapshots) + .where(and(eq(snapshots.id, snapshotId), eq(snapshots.deviceId, deviceId))) + .get(); + if (!at) return reply.code(404).send({ error: "no such snapshot for this camera" }); + const meta = { id: snapshots.id, direction: snapshots.direction, capturedAt: snapshots.capturedAt }; + // capturedAt is always toISOString() (UTC, fixed width), so string order = time order. + // The plain lte/gte bound next to the OR lets SQLite seek snapshots_device_time_idx + // from this snapshot instead of walking the camera's index from one end. + const older = db + .select(meta) + .from(snapshots) + .where( + and( + eq(snapshots.deviceId, deviceId), + lte(snapshots.capturedAt, at.capturedAt), + or(lt(snapshots.capturedAt, at.capturedAt), and(eq(snapshots.capturedAt, at.capturedAt), lt(snapshots.id, snapshotId))), + ), + ) + .orderBy(desc(snapshots.capturedAt), desc(snapshots.id)) + .limit(1) + .get(); + const newer = db + .select(meta) + .from(snapshots) + .where( + and( + eq(snapshots.deviceId, deviceId), + gte(snapshots.capturedAt, at.capturedAt), + or(gt(snapshots.capturedAt, at.capturedAt), and(eq(snapshots.capturedAt, at.capturedAt), gt(snapshots.id, snapshotId))), + ), + ) + .orderBy(asc(snapshots.capturedAt), asc(snapshots.id)) + .limit(1) + .get(); + return { older: older ?? null, newer: newer ?? null }; + }, + ); + app.get<{ Params: { deviceId: string } }>( "/api/cameras/:deviceId/live", { diff --git a/apps/web/src/api.ts b/apps/web/src/api.ts index cd2e2a8..45427ac 100644 --- a/apps/web/src/api.ts +++ b/apps/web/src/api.ts @@ -180,6 +180,14 @@ export async function fetchLatestCameraSnapshot(deviceId: string): Promise { + return apiFetch(`/api/cameras/${encodeURIComponent(deviceId)}/snapshots/${encodeURIComponent(snapshotId)}/neighbors`); +} + /** Snapshot bytes as an object URL. Fetched (not an ) so it works in the * desktop shell too, whose webview does not carry the session cookie. The caller * revokes the URL. */ diff --git a/apps/web/src/lib/i18n/en.ts b/apps/web/src/lib/i18n/en.ts index cdbe555..8456439 100644 --- a/apps/web/src/lib/i18n/en.ts +++ b/apps/web/src/lib/i18n/en.ts @@ -272,7 +272,7 @@ export const en: Catalog = { camera: { expand: "Show larger", snapshot: "Snapshot", - liveOnDemand: "Live on request", + liveOnDemand: "Live on-demand", live: "Live", showTile: "Show this camera", hideTile: "Hide this camera", @@ -281,6 +281,9 @@ export const en: Catalog = { connecting: "Connecting to live video…", liveUnavailable: "Live video unavailable", vehicleInView: "Vehicle in view", + older: "Older snapshot", + newer: "Newer snapshot", + snapshotUnavailable: "Snapshot unavailable", }, booth: { processTicket: "Process ticket", diff --git a/apps/web/src/lib/i18n/sq.ts b/apps/web/src/lib/i18n/sq.ts index 60b4431..4078bec 100644 --- a/apps/web/src/lib/i18n/sq.ts +++ b/apps/web/src/lib/i18n/sq.ts @@ -273,16 +273,19 @@ export const sq = { }, camera: { expand: "Shfaq më të madhe", - snapshot: "Foto", - liveOnDemand: "Live me kërkesë", + snapshot: "Snapshot", + liveOnDemand: "Live on-demand", live: "Live", showTile: "Shfaq këtë kamerë", hideTile: "Fshih këtë kamerë", - noSnapshot: "Ende pa foto", + noSnapshot: "Ende pa snapshot", idle: "Videoja live nis kur vjen një automjet", connecting: "Po lidhet videoja live…", liveUnavailable: "Videoja live nuk është e disponueshme", vehicleInView: "Automjet në pamje", + older: "Foto më e vjetër", + newer: "Foto më e re", + snapshotUnavailable: "Fotoja nuk është e disponueshme", }, booth: { processTicket: "Proceso biletën", @@ -337,7 +340,7 @@ export const sq = { forgiveExitOk: "Dalja u hap manualisht, pa pagesë.", forgiveExitNotOpened: "U regjistrua, por barriera nuk u hap: {{reason}}", forgiveDialogTitle: "Hapje manuale", - forgiveDialogBody: "Hap barrierën e DALJES manualisht. Nuk merret asnjë pagesë dhe nuk printohet asgjë; hapja nënshkruhet me emrin tënd bashkë me foton e kamerës së daljes dhe shfaqet në raportin e turnit tënd.", + forgiveDialogBody: "Hap barrierën e DALJES manualisht. Nuk merret asnjë pagesë dhe nuk printohet asgjë; hapja nënshkruhet me emrin tënd bashkë me snapshot-in e kamerës së daljes dhe shfaqet në raportin e turnit tënd.", forgiveDialogReason: "Arsyeja (opsionale)", forgiveDialogReasonPlaceholder: "p.sh. hyri kur barrierat ishin të hapura…", forgiveDialogConfirm: "Hap daljen — pa pagesë", @@ -397,7 +400,7 @@ export const sq = { edSource: "Burimi", edIdentity: "Identiteti", edReason: "Arsyeja", - edSnapshots: "Fotot", + edSnapshots: "Snapshot-et", edPayload: "Të dhënat e nënshkruara", edChain: "Zinxhiri", edSignature: "Nënshkrimi", @@ -533,7 +536,7 @@ export const sq = { // Category titles + the singular noun used in buttons/modal titles. catControllers: "Kontrollerat (barrierat + butoni i hyrjes)", catReaders: "Lexuesit (QR / RFID)", - catCameras: "Kamerat (foto + targë)", + catCameras: "Kamerat (snapshot + targë)", catPrinters: "Printerat (bileta / vouchera)", nounController: "kontroller", nounReader: "lexues", @@ -874,7 +877,7 @@ export const sq = { reserveSubs: "Rezervo vendet e abonentëve", reserveSubsHint: "Mban një vend për makinat e çdo abonenti aktiv edhe kur nuk janë të parkuar — kalimtarët e shohin 'plot' më shpejt. Joaktiv: numërohen vetëm makinat brenda (mbingarkesa menaxhohet me parkim manual).", anprEntry: "Hapje automatike për targat e abonentëve (ANPR)", - anprEntryHint: "Kur është aktiv, targa e një abonenti e lexuar nga kamera e korsisë hap barrierën përmes portës normale të abonimit. Joaktiv: abonentët duhet të përdorin kartën/QR-në. Fotot e targave regjistrohen gjithsesi.", + anprEntryHint: "Kur është aktiv, targa e një abonenti e lexuar nga kamera e korsisë hap barrierën përmes portës normale të abonimit. Joaktiv: abonentët duhet të përdorin kartën/QR-në. Snapshot-et e targave regjistrohen gjithsesi.", parkDetails: "Të dhënat e parkimit (opsionale — shfaqen në bileta/fatura)", save: "Ruaj", saved: "U ruajt.", @@ -1298,8 +1301,8 @@ export const sq = { exitForgiven: "Dalje manuale — {{amount}}, barriera u hap.", exitForgivenNotOpened: "Dalje manuale — {{amount}}, barriera nuk u hap: {{reason}}", // snapshots - noSnapshots: "asnjë foto", - loadingSnapshots: "duke ngarkuar fotot…", + noSnapshots: "asnjë snapshot", + loadingSnapshots: "duke ngarkuar snapshot-et…", snapEntry: "hyrje", snapExit: "dalje", snapFailed: "kamera e paarritshme", diff --git a/apps/web/src/ui/CameraDock.tsx b/apps/web/src/ui/CameraDock.tsx index 2bbb768..69686ed 100644 --- a/apps/web/src/ui/CameraDock.tsx +++ b/apps/web/src/ui/CameraDock.tsx @@ -2,8 +2,14 @@ import { useEffect, useMemo, useRef, useState, type ReactNode } from "react"; import { createPortal } from "react-dom"; import { useTranslation } from "react-i18next"; import { useQuery } from "@tanstack/react-query"; -import { fetchLatestCameraSnapshot, fetchSnapshotObjectUrl, type DeviceStatus } from "../api.js"; -import { formatClock } from "../lib/format.js"; +import { + fetchCameraSnapshotNeighbors, + fetchLatestCameraSnapshot, + fetchSnapshotObjectUrl, + type CameraSnapshotMeta, + type DeviceStatus, +} from "../api.js"; +import { formatClock, formatRelativeDateTime } from "../lib/format.js"; import { useLiveStore } from "../lib/live-store.js"; import { wsUrl } from "../lib/origin.js"; import { createPlatformSocket } from "../lib/platform-ws.js"; @@ -15,7 +21,9 @@ import { createPlatformSocket } from "../lib/platform-ws.js"; // activity, pushed over /api/ws). Clicking the picture opens a large view in the // tile's state (live if the tile is live, else the snapshot), with a Live / Snapshot // switch that streams LIVE ON DEMAND, car or no car; closing it returns the tile to -// automatic — a stream the user started stops, one the camera started carries on. Live frames come over their own socket as JPEG binaries; only the newest frame is +// automatic — a stream the user started stops, one the camera started carries on. On +// the Snapshot side, ‹ › step through this camera's older / newer snapshots (the tile +// itself always rests on the newest; the large view reopens on it). Live frames come over their own socket as JPEG binaries; only the newest frame is // shown, and the tile and the large view share that one socket. Advisory viewing — // nothing here gates anything. @@ -83,6 +91,21 @@ function CameraTile({ const live = useLiveFrames(deviceId, wantLive); const snapshot = useLatestSnapshot(deviceId, canSeeSnapshots); const showLive = wantLive && live.hasFrame; + /** The snapshot the large view shows when the user has stepped away from the newest. */ + const [browsed, setBrowsed] = useState(null); + const browsedPic = useSnapshotPicture(browsed); + /** What the ‹ › step from: the snapshot asked for (its picture may still be loading). */ + const modalShot = browsed ?? snapshot.meta; + const browsing = expanded && modalMode === "snapshot" && canSeeSnapshots && modalShot !== null; + const neighbors = useQuery({ + // Under "camera-latest" so a new snapshot's invalidation refreshes "newer" too. + queryKey: ["camera-latest", deviceId, "neighbors", modalShot?.id], + queryFn: () => fetchCameraSnapshotNeighbors(deviceId, modalShot!.id), + enabled: browsing, + }); + const nav = browsing + ? { older: neighbors.data?.older ?? null, newer: neighbors.data?.newer ?? null, go: setBrowsed } + : null; const caption = wantLive ? showLive @@ -92,16 +115,33 @@ function CameraTile({ : live.status.state === "unavailable" || live.status.state === "retrying" ? `${t("camera.liveUnavailable")}: ${live.status.reason}` : t("camera.connecting") - : snapshot.meta - ? `${snapshot.meta.direction === "entry" ? t("pay.snapEntry") : t("pay.snapExit")} · ${formatClock(snapshot.meta.capturedAt)}` + : snapshot.pic.meta + ? `${snapshot.pic.meta.direction === "entry" ? t("pay.snapEntry") : t("pay.snapExit")} · ${formatClock(snapshot.pic.meta.capturedAt)}` : ""; + // The large view's picture: a stepped-to snapshot once its bytes are in, the previous + // picture until then. The caption always names the picture SHOWN (these are evidence + // stills — a date must never sit under another snapshot's picture). + const modalPic = browsed ? (browsedPic.meta ? browsedPic : snapshot.pic) : snapshot.pic; + const modalCaption = wantLive + ? caption + : browsed && browsedPic.failed + ? t("camera.snapshotUnavailable") + : modalPic.meta + ? `${modalPic.meta.direction === "entry" ? t("pay.snapEntry") : t("pay.snapExit")} · ${formatRelativeDateTime(modalPic.meta.capturedAt, t, { seconds: true })}` + : caption; const view = (slot: "tile" | "modal") => ( ); @@ -136,7 +176,16 @@ function CameraTile({ {view("tile")} {expanded && ( - setExpanded(false)}> + { + setExpanded(false); + setBrowsed(null); + }} + > {view("modal")} )} @@ -204,27 +253,56 @@ function LiveBadge({ large }: { large: boolean }) { ); } -/** Large view of one camera with a Live / Snapshot switch. Closes on ✕, Escape or a - * backdrop click. */ +type SnapshotNav = { + older: CameraSnapshotMeta | null; + newer: CameraSnapshotMeta | null; + go: (shot: CameraSnapshotMeta) => void; +}; + +/** Large view of one camera with a Live / Snapshot switch and, on the Snapshot side, + * ‹ › (also ← →) to step through older / newer snapshots — muted at either end. + * Closes on ✕, Escape or a backdrop click. */ function CameraModal({ title, mode, onMode, + nav, onClose, children, }: { title: string; mode: "live" | "snapshot"; onMode: (m: "live" | "snapshot") => void; + nav: SnapshotNav | null; onClose: () => void; children: ReactNode; }) { const { t } = useTranslation(); useEffect(() => { - const onKey = (e: KeyboardEvent) => e.key === "Escape" && onClose(); + const onKey = (e: KeyboardEvent) => { + if (e.key === "Escape") onClose(); + else if (e.key === "ArrowLeft" && nav?.older) nav.go(nav.older); + else if (e.key === "ArrowRight" && nav?.newer) nav.go(nav.newer); + }; document.addEventListener("keydown", onKey); return () => document.removeEventListener("keydown", onKey); - }, [onClose]); + }, [onClose, nav]); + const chevron = (side: "left" | "right") => { + const target = side === "left" ? nav?.older : nav?.newer; + const label = t(side === "left" ? "camera.older" : "camera.newer"); + return ( + + ); + }; const seg = (m: "live" | "snapshot", label: string) => (