feat(cameras): ‹ › through older/newer snapshots in the large view
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 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01RZgP5oMncSaVmKRKk1UvN4
This commit is contained in:
@@ -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", () => {
|
describe("WS /api/cameras/:id/live", () => {
|
||||||
const origin = "http://booth.local:8080";
|
const origin = "http://booth.local:8080";
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import type { FastifyInstance } from "fastify";
|
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 { isLiveStreamDevice } from "@parking/devices";
|
||||||
import { requirePermission, roleHasPermissions } from "../auth.js";
|
import { requirePermission, roleHasPermissions } from "../auth.js";
|
||||||
import { buildCamera } from "../snapshot.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
|
// - GET /api/cameras/:deviceId/latest-snapshot — the tile's default picture: the newest
|
||||||
// entry/exit evidence still this camera captured (metadata; bytes stay at
|
// entry/exit evidence still this camera captured (metadata; bytes stay at
|
||||||
// /api/snapshots/:id). Evidence → `session:read`, like every snapshot read.
|
// /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.
|
// - 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),
|
// Same handshake auth as /api/ws (Origin allowlist, then desktop ticket or cookie),
|
||||||
// then `device:read` (the footer's permission). Server → client: text JSON
|
// 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 })
|
.select({ id: snapshots.id, direction: snapshots.direction, capturedAt: snapshots.capturedAt })
|
||||||
.from(snapshots)
|
.from(snapshots)
|
||||||
.where(eq(snapshots.deviceId, req.params.deviceId))
|
.where(eq(snapshots.deviceId, req.params.deviceId))
|
||||||
.orderBy(desc(snapshots.capturedAt))
|
.orderBy(desc(snapshots.capturedAt), desc(snapshots.id))
|
||||||
.limit(1)
|
.limit(1)
|
||||||
.get();
|
.get();
|
||||||
if (!row) return reply.code(404).send({ error: "no snapshot for this camera yet" });
|
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 } }>(
|
app.get<{ Params: { deviceId: string } }>(
|
||||||
"/api/cameras/:deviceId/live",
|
"/api/cameras/:deviceId/live",
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -180,6 +180,14 @@ export async function fetchLatestCameraSnapshot(deviceId: string): Promise<Camer
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** The next older / newer snapshot of the same camera (the large view's ‹ ›). */
|
||||||
|
export function fetchCameraSnapshotNeighbors(
|
||||||
|
deviceId: string,
|
||||||
|
snapshotId: string,
|
||||||
|
): Promise<{ older: CameraSnapshotMeta | null; newer: CameraSnapshotMeta | null }> {
|
||||||
|
return apiFetch(`/api/cameras/${encodeURIComponent(deviceId)}/snapshots/${encodeURIComponent(snapshotId)}/neighbors`);
|
||||||
|
}
|
||||||
|
|
||||||
/** Snapshot bytes as an object URL. Fetched (not an <img src>) so it works in the
|
/** Snapshot bytes as an object URL. Fetched (not an <img src>) so it works in the
|
||||||
* desktop shell too, whose webview does not carry the session cookie. The caller
|
* desktop shell too, whose webview does not carry the session cookie. The caller
|
||||||
* revokes the URL. */
|
* revokes the URL. */
|
||||||
|
|||||||
@@ -272,7 +272,7 @@ export const en: Catalog = {
|
|||||||
camera: {
|
camera: {
|
||||||
expand: "Show larger",
|
expand: "Show larger",
|
||||||
snapshot: "Snapshot",
|
snapshot: "Snapshot",
|
||||||
liveOnDemand: "Live on request",
|
liveOnDemand: "Live on-demand",
|
||||||
live: "Live",
|
live: "Live",
|
||||||
showTile: "Show this camera",
|
showTile: "Show this camera",
|
||||||
hideTile: "Hide this camera",
|
hideTile: "Hide this camera",
|
||||||
@@ -281,6 +281,9 @@ export const en: Catalog = {
|
|||||||
connecting: "Connecting to live video…",
|
connecting: "Connecting to live video…",
|
||||||
liveUnavailable: "Live video unavailable",
|
liveUnavailable: "Live video unavailable",
|
||||||
vehicleInView: "Vehicle in view",
|
vehicleInView: "Vehicle in view",
|
||||||
|
older: "Older snapshot",
|
||||||
|
newer: "Newer snapshot",
|
||||||
|
snapshotUnavailable: "Snapshot unavailable",
|
||||||
},
|
},
|
||||||
booth: {
|
booth: {
|
||||||
processTicket: "Process ticket",
|
processTicket: "Process ticket",
|
||||||
|
|||||||
@@ -273,16 +273,19 @@ export const sq = {
|
|||||||
},
|
},
|
||||||
camera: {
|
camera: {
|
||||||
expand: "Shfaq më të madhe",
|
expand: "Shfaq më të madhe",
|
||||||
snapshot: "Foto",
|
snapshot: "Snapshot",
|
||||||
liveOnDemand: "Live me kërkesë",
|
liveOnDemand: "Live on-demand",
|
||||||
live: "Live",
|
live: "Live",
|
||||||
showTile: "Shfaq këtë kamerë",
|
showTile: "Shfaq këtë kamerë",
|
||||||
hideTile: "Fshih këtë kamerë",
|
hideTile: "Fshih këtë kamerë",
|
||||||
noSnapshot: "Ende pa foto",
|
noSnapshot: "Ende pa snapshot",
|
||||||
idle: "Videoja live nis kur vjen një automjet",
|
idle: "Videoja live nis kur vjen një automjet",
|
||||||
connecting: "Po lidhet videoja live…",
|
connecting: "Po lidhet videoja live…",
|
||||||
liveUnavailable: "Videoja live nuk është e disponueshme",
|
liveUnavailable: "Videoja live nuk është e disponueshme",
|
||||||
vehicleInView: "Automjet në pamje",
|
vehicleInView: "Automjet në pamje",
|
||||||
|
older: "Foto më e vjetër",
|
||||||
|
newer: "Foto më e re",
|
||||||
|
snapshotUnavailable: "Fotoja nuk është e disponueshme",
|
||||||
},
|
},
|
||||||
booth: {
|
booth: {
|
||||||
processTicket: "Proceso biletën",
|
processTicket: "Proceso biletën",
|
||||||
@@ -337,7 +340,7 @@ export const sq = {
|
|||||||
forgiveExitOk: "Dalja u hap manualisht, pa pagesë.",
|
forgiveExitOk: "Dalja u hap manualisht, pa pagesë.",
|
||||||
forgiveExitNotOpened: "U regjistrua, por barriera nuk u hap: {{reason}}",
|
forgiveExitNotOpened: "U regjistrua, por barriera nuk u hap: {{reason}}",
|
||||||
forgiveDialogTitle: "Hapje manuale",
|
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)",
|
forgiveDialogReason: "Arsyeja (opsionale)",
|
||||||
forgiveDialogReasonPlaceholder: "p.sh. hyri kur barrierat ishin të hapura…",
|
forgiveDialogReasonPlaceholder: "p.sh. hyri kur barrierat ishin të hapura…",
|
||||||
forgiveDialogConfirm: "Hap daljen — pa pagesë",
|
forgiveDialogConfirm: "Hap daljen — pa pagesë",
|
||||||
@@ -397,7 +400,7 @@ export const sq = {
|
|||||||
edSource: "Burimi",
|
edSource: "Burimi",
|
||||||
edIdentity: "Identiteti",
|
edIdentity: "Identiteti",
|
||||||
edReason: "Arsyeja",
|
edReason: "Arsyeja",
|
||||||
edSnapshots: "Fotot",
|
edSnapshots: "Snapshot-et",
|
||||||
edPayload: "Të dhënat e nënshkruara",
|
edPayload: "Të dhënat e nënshkruara",
|
||||||
edChain: "Zinxhiri",
|
edChain: "Zinxhiri",
|
||||||
edSignature: "Nënshkrimi",
|
edSignature: "Nënshkrimi",
|
||||||
@@ -533,7 +536,7 @@ export const sq = {
|
|||||||
// Category titles + the singular noun used in buttons/modal titles.
|
// Category titles + the singular noun used in buttons/modal titles.
|
||||||
catControllers: "Kontrollerat (barrierat + butoni i hyrjes)",
|
catControllers: "Kontrollerat (barrierat + butoni i hyrjes)",
|
||||||
catReaders: "Lexuesit (QR / RFID)",
|
catReaders: "Lexuesit (QR / RFID)",
|
||||||
catCameras: "Kamerat (foto + targë)",
|
catCameras: "Kamerat (snapshot + targë)",
|
||||||
catPrinters: "Printerat (bileta / vouchera)",
|
catPrinters: "Printerat (bileta / vouchera)",
|
||||||
nounController: "kontroller",
|
nounController: "kontroller",
|
||||||
nounReader: "lexues",
|
nounReader: "lexues",
|
||||||
@@ -874,7 +877,7 @@ export const sq = {
|
|||||||
reserveSubs: "Rezervo vendet e abonentëve",
|
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).",
|
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)",
|
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)",
|
parkDetails: "Të dhënat e parkimit (opsionale — shfaqen në bileta/fatura)",
|
||||||
save: "Ruaj",
|
save: "Ruaj",
|
||||||
saved: "U ruajt.",
|
saved: "U ruajt.",
|
||||||
@@ -1298,8 +1301,8 @@ export const sq = {
|
|||||||
exitForgiven: "Dalje manuale — {{amount}}, barriera u hap.",
|
exitForgiven: "Dalje manuale — {{amount}}, barriera u hap.",
|
||||||
exitForgivenNotOpened: "Dalje manuale — {{amount}}, barriera nuk u hap: {{reason}}",
|
exitForgivenNotOpened: "Dalje manuale — {{amount}}, barriera nuk u hap: {{reason}}",
|
||||||
// snapshots
|
// snapshots
|
||||||
noSnapshots: "asnjë foto",
|
noSnapshots: "asnjë snapshot",
|
||||||
loadingSnapshots: "duke ngarkuar fotot…",
|
loadingSnapshots: "duke ngarkuar snapshot-et…",
|
||||||
snapEntry: "hyrje",
|
snapEntry: "hyrje",
|
||||||
snapExit: "dalje",
|
snapExit: "dalje",
|
||||||
snapFailed: "kamera e paarritshme",
|
snapFailed: "kamera e paarritshme",
|
||||||
|
|||||||
+126
-31
@@ -2,8 +2,14 @@ import { useEffect, useMemo, useRef, useState, type ReactNode } from "react";
|
|||||||
import { createPortal } from "react-dom";
|
import { createPortal } from "react-dom";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { useQuery } from "@tanstack/react-query";
|
import { useQuery } from "@tanstack/react-query";
|
||||||
import { fetchLatestCameraSnapshot, fetchSnapshotObjectUrl, type DeviceStatus } from "../api.js";
|
import {
|
||||||
import { formatClock } from "../lib/format.js";
|
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 { useLiveStore } from "../lib/live-store.js";
|
||||||
import { wsUrl } from "../lib/origin.js";
|
import { wsUrl } from "../lib/origin.js";
|
||||||
import { createPlatformSocket } from "../lib/platform-ws.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
|
// 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
|
// 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
|
// 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 —
|
// shown, and the tile and the large view share that one socket. Advisory viewing —
|
||||||
// nothing here gates anything.
|
// nothing here gates anything.
|
||||||
|
|
||||||
@@ -83,6 +91,21 @@ function CameraTile({
|
|||||||
const live = useLiveFrames(deviceId, wantLive);
|
const live = useLiveFrames(deviceId, wantLive);
|
||||||
const snapshot = useLatestSnapshot(deviceId, canSeeSnapshots);
|
const snapshot = useLatestSnapshot(deviceId, canSeeSnapshots);
|
||||||
const showLive = wantLive && live.hasFrame;
|
const showLive = wantLive && live.hasFrame;
|
||||||
|
/** The snapshot the large view shows when the user has stepped away from the newest. */
|
||||||
|
const [browsed, setBrowsed] = useState<CameraSnapshotMeta | null>(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
|
const caption = wantLive
|
||||||
? showLive
|
? showLive
|
||||||
@@ -92,16 +115,33 @@ function CameraTile({
|
|||||||
: live.status.state === "unavailable" || live.status.state === "retrying"
|
: live.status.state === "unavailable" || live.status.state === "retrying"
|
||||||
? `${t("camera.liveUnavailable")}: ${live.status.reason}`
|
? `${t("camera.liveUnavailable")}: ${live.status.reason}`
|
||||||
: t("camera.connecting")
|
: t("camera.connecting")
|
||||||
: snapshot.meta
|
: snapshot.pic.meta
|
||||||
? `${snapshot.meta.direction === "entry" ? t("pay.snapEntry") : t("pay.snapExit")} · ${formatClock(snapshot.meta.capturedAt)}`
|
? `${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") => (
|
const view = (slot: "tile" | "modal") => (
|
||||||
<CameraView
|
<CameraView
|
||||||
imgRef={live.imgRefs[slot]}
|
imgRef={live.imgRefs[slot]}
|
||||||
showLive={showLive}
|
showLive={showLive}
|
||||||
snapshotUrl={snapshot.url}
|
snapshotUrl={slot === "modal" ? (browsed && browsedPic.failed ? null : modalPic.url) : snapshot.pic.url}
|
||||||
placeholder={canSeeSnapshots ? t("camera.noSnapshot") : t("camera.idle")}
|
placeholder={
|
||||||
caption={caption}
|
slot === "modal" && browsed && browsedPic.failed
|
||||||
|
? t("camera.snapshotUnavailable")
|
||||||
|
: canSeeSnapshots
|
||||||
|
? t("camera.noSnapshot")
|
||||||
|
: t("camera.idle")
|
||||||
|
}
|
||||||
|
caption={slot === "modal" ? modalCaption : caption}
|
||||||
large={slot === "modal"}
|
large={slot === "modal"}
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
@@ -136,7 +176,16 @@ function CameraTile({
|
|||||||
{view("tile")}
|
{view("tile")}
|
||||||
</button>
|
</button>
|
||||||
{expanded && (
|
{expanded && (
|
||||||
<CameraModal title={title} mode={modalMode} onMode={setModalMode} onClose={() => setExpanded(false)}>
|
<CameraModal
|
||||||
|
title={title}
|
||||||
|
mode={modalMode}
|
||||||
|
onMode={setModalMode}
|
||||||
|
nav={nav}
|
||||||
|
onClose={() => {
|
||||||
|
setExpanded(false);
|
||||||
|
setBrowsed(null);
|
||||||
|
}}
|
||||||
|
>
|
||||||
{view("modal")}
|
{view("modal")}
|
||||||
</CameraModal>
|
</CameraModal>
|
||||||
)}
|
)}
|
||||||
@@ -204,27 +253,56 @@ function LiveBadge({ large }: { large: boolean }) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Large view of one camera with a Live / Snapshot switch. Closes on ✕, Escape or a
|
type SnapshotNav = {
|
||||||
* backdrop click. */
|
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({
|
function CameraModal({
|
||||||
title,
|
title,
|
||||||
mode,
|
mode,
|
||||||
onMode,
|
onMode,
|
||||||
|
nav,
|
||||||
onClose,
|
onClose,
|
||||||
children,
|
children,
|
||||||
}: {
|
}: {
|
||||||
title: string;
|
title: string;
|
||||||
mode: "live" | "snapshot";
|
mode: "live" | "snapshot";
|
||||||
onMode: (m: "live" | "snapshot") => void;
|
onMode: (m: "live" | "snapshot") => void;
|
||||||
|
nav: SnapshotNav | null;
|
||||||
onClose: () => void;
|
onClose: () => void;
|
||||||
children: ReactNode;
|
children: ReactNode;
|
||||||
}) {
|
}) {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
useEffect(() => {
|
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);
|
document.addEventListener("keydown", onKey);
|
||||||
return () => document.removeEventListener("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 (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
disabled={!target}
|
||||||
|
onClick={() => target && nav?.go(target)}
|
||||||
|
aria-label={label}
|
||||||
|
title={label}
|
||||||
|
className={`absolute top-1/2 ${side === "left" ? "left-2" : "right-2"} flex h-12 w-12 -translate-y-1/2 items-center justify-center rounded-full bg-black/60 text-3xl leading-none text-term-text transition-opacity hover:bg-black/80 disabled:cursor-default disabled:opacity-25 disabled:hover:bg-black/60`}
|
||||||
|
>
|
||||||
|
{side === "left" ? "‹" : "›"}
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
};
|
||||||
const seg = (m: "live" | "snapshot", label: string) => (
|
const seg = (m: "live" | "snapshot", label: string) => (
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
@@ -267,14 +345,19 @@ function CameraModal({
|
|||||||
✕
|
✕
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
{children}
|
<div className="relative">
|
||||||
|
{children}
|
||||||
|
{nav && chevron("left")}
|
||||||
|
{nav && chevron("right")}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>,
|
</div>,
|
||||||
document.body,
|
document.body,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Newest snapshot for the tile's resting picture, as an object URL (revoked on change). */
|
/** Newest snapshot for the tile's resting picture: `meta` is the newest known, `pic` what
|
||||||
|
* is on screen (the previous picture until the newest has loaded). */
|
||||||
function useLatestSnapshot(deviceId: string, enabled: boolean) {
|
function useLatestSnapshot(deviceId: string, enabled: boolean) {
|
||||||
const meta = useQuery({
|
const meta = useQuery({
|
||||||
queryKey: ["camera-latest", deviceId],
|
queryKey: ["camera-latest", deviceId],
|
||||||
@@ -282,30 +365,42 @@ function useLatestSnapshot(deviceId: string, enabled: boolean) {
|
|||||||
enabled,
|
enabled,
|
||||||
staleTime: 60_000,
|
staleTime: 60_000,
|
||||||
});
|
});
|
||||||
const id = meta.data?.id ?? null;
|
const pic = useSnapshotPicture(meta.data ?? null);
|
||||||
const [url, setUrl] = useState<string | null>(null);
|
return { meta: meta.data ?? null, pic };
|
||||||
|
}
|
||||||
|
|
||||||
|
type SnapshotPicture = { meta: CameraSnapshotMeta | null; url: string | null; failed: boolean };
|
||||||
|
|
||||||
|
/** A snapshot's bytes as an object URL, paired with the meta it belongs to. On a change
|
||||||
|
* the previous picture (and its meta) stays until the next has loaded — no blank flash
|
||||||
|
* while stepping — then is revoked; `failed` when the last request failed (e.g. pruned
|
||||||
|
* by retention). Everything is revoked on unmount. */
|
||||||
|
function useSnapshotPicture(want: CameraSnapshotMeta | null): SnapshotPicture {
|
||||||
|
const [pic, setPic] = useState<SnapshotPicture>({ meta: null, url: null, failed: false });
|
||||||
|
const current = useRef<string | null>(null);
|
||||||
|
const replace = (next: SnapshotPicture) => {
|
||||||
|
if (current.current && current.current !== next.url) URL.revokeObjectURL(current.current);
|
||||||
|
current.current = next.url;
|
||||||
|
setPic(next);
|
||||||
|
};
|
||||||
|
const id = want?.id ?? null;
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!id) {
|
if (!want) {
|
||||||
setUrl(null);
|
replace({ meta: null, url: null, failed: false });
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
let cancelled = false;
|
let cancelled = false;
|
||||||
let made: string | null = null;
|
setPic((p) => ({ ...p, failed: false }));
|
||||||
fetchSnapshotObjectUrl(id)
|
fetchSnapshotObjectUrl(want.id)
|
||||||
.then((u) => {
|
.then((u) => (cancelled ? URL.revokeObjectURL(u) : replace({ meta: want, url: u, failed: false })))
|
||||||
if (cancelled) URL.revokeObjectURL(u);
|
.catch(() => !cancelled && setPic((p) => ({ ...p, failed: true })));
|
||||||
else {
|
|
||||||
made = u;
|
|
||||||
setUrl(u);
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.catch(() => !cancelled && setUrl(null));
|
|
||||||
return () => {
|
return () => {
|
||||||
cancelled = true;
|
cancelled = true;
|
||||||
if (made) URL.revokeObjectURL(made);
|
|
||||||
};
|
};
|
||||||
|
// Keyed by id only: a new `want` object for the same snapshot must not refetch.
|
||||||
}, [id]);
|
}, [id]);
|
||||||
return { meta: meta.data ?? null, url };
|
useEffect(() => () => replace({ meta: null, url: null, failed: false }), []);
|
||||||
|
return pic;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -29,6 +29,15 @@ verified end to end against the two park-lab cameras through the real server and
|
|||||||
is active (the same stream carries on, no reconnect), else on the Snapshot. The choice then
|
is active (the same stream carries on, no reconnect), else on the Snapshot. The choice then
|
||||||
holds while the view is open — a car leaving does not drop it to the snapshot, a car arriving
|
holds while the view is open — a car leaving does not drop it to the snapshot, a car arriving
|
||||||
does not switch it to live.
|
does not switch it to live.
|
||||||
|
- (2026-11-17, fourth round) On the Snapshot side the large view has **‹ ›** (and ← →) to step
|
||||||
|
through that camera's older / newer snapshots; a chevron is muted at either end. The caption
|
||||||
|
carries the date ("Dje 17:22:47"). The tile itself stays on the newest; closing the large view
|
||||||
|
drops the browse position, so it reopens on the newest. On Live there are no chevrons.
|
||||||
|
Server: `GET /api/cameras/:deviceId/snapshots/:snapshotId/neighbors` → `{ older, newer }`
|
||||||
|
(`session:read`; 404 for another camera's snapshot), ordered by (capturedAt, id) like
|
||||||
|
`latest-snapshot`, so equal timestamps neither skip nor loop. The caption always names the picture on screen:
|
||||||
|
while a stepped-to still loads, the previous picture and its date stay; if its bytes are gone
|
||||||
|
(retention), the view says *Snapshot unavailable* rather than show another still.
|
||||||
|
|
||||||
### When the stream stops
|
### When the stream stops
|
||||||
|
|
||||||
|
|||||||
@@ -3722,3 +3722,12 @@ adds nothing measurable, browser 1–2 ms; the 10 fps cap cut `.6` to 7 fps and
|
|||||||
was **removed** (`CAMERA_LIVE_MAX_FPS` unset = no cap). A viewer on a ~300 KB/s link runs 13–14 s
|
was **removed** (`CAMERA_LIVE_MAX_FPS` unset = no cap). A viewer on a ~300 KB/s link runs 13–14 s
|
||||||
behind (TCP buffering) — user judged the delay a non-issue; fix recorded on the page. Updated
|
behind (TCP buffering) — user judged the delay a non-issue; fix recorded on the page. Updated
|
||||||
[[camera-live-view]], [[passage-confirmation]] (rig table), [[lpr-camera]], index.
|
[[camera-live-view]], [[passage-confirmation]] (rig table), [[lpr-camera]], index.
|
||||||
|
|
||||||
|
## [2026-11-17] query | Booth camera large view — ‹ › through older snapshots
|
||||||
|
|
||||||
|
User asked for chevrons in the large view to step back and forth through snapshots, muted at
|
||||||
|
either end. Built: a neighbours route per camera snapshot (`{ older, newer }`, `session:read`,
|
||||||
|
(capturedAt, id) order shared with `latest-snapshot`) and ‹ › / ← → on the Snapshot side with
|
||||||
|
the date in the caption; the tile stays on the newest. Verified in headless Firefox with four
|
||||||
|
snapshots on one camera, including a slow load (caption keeps the shown picture's date) and a
|
||||||
|
missing still ("unavailable"). Updated [[camera-live-view]].
|
||||||
|
|||||||
Reference in New Issue
Block a user