Camera pictures without an object-storage bucket
Head office shows a camera's latest frame rather than live video, for a
reason that has not changed: the engine serves MJPEG on 127.0.0.1 on a PC
behind a shop's router with no inbound route, and relaying it needs
WebRTC/TURN. Pointing a browser straight at the shop PC is not the escape
either - the engine's API is Basic-authenticated with a credential it
generates locally and never sends anywhere, and shipping that to the
cloud so a web page could use it would put the key to the biometric API
and the live face feed in the server's database.
But that picture only worked if you had an S3 bucket. Without one,
attachSnapshots reported "This system is not storing images" for every
camera forever - on the two screens whose whole job is to show the
camera. Making them picture-led turned a missing feature into a wall of
empty tiles, on every local install and any self-hosted customer who does
not want a bucket.
migrations/009 adds camera_snapshots and the agent falls back to
PUT /api/agent/cameras/{camera}/snapshot when the presigned route answers
images_disabled - chosen by sentinel, never by matching the message, since
it picks between two routes. One row per camera is what makes this safe in
the database when face images are not: the key IS the camera, so storage
is (cameras x ~100 KB) and does not grow with footfall.
The read is session-authenticated rather than a signed link, which an
<img> cannot use - hence Shot.jsx and useAuthedImage, keyed on the URL
string rather than the snapshot object so a poll does not re-fetch 90 KB
per camera every few seconds, and revoking the object URL on cleanup.
Verified against the real office camera with no bucket configured: 90,587
bytes stored in Postgres, served as image/jpeg to a signed-in user, 401
without a session, rendered on both the Cameras and Shops cards.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HViLj9gYNRtSr7YVZmW5sn
This commit is contained in:
@@ -91,6 +91,37 @@ async function send(method, path, body, retry = true) {
|
||||
parsed?.message || `Something went wrong (${res.status}).`)
|
||||
}
|
||||
|
||||
// fetchImage loads a picture this server holds itself, with the session's
|
||||
// bearer token, and returns an object URL an <img> can use.
|
||||
//
|
||||
// It exists because an <img src> cannot carry an Authorization header. The
|
||||
// object-storage path returns a presigned absolute URL that needs no auth,
|
||||
// which is why it worked with a plain src; a picture served from our own
|
||||
// database has no such link, and minting an unauthenticated one so that <img>
|
||||
// could use it would add a way to reach a photograph of somebody's shop floor
|
||||
// without a session - the opposite of what this path is for.
|
||||
//
|
||||
// The caller MUST revoke the returned URL when it is finished with it, or the
|
||||
// browser keeps every blob it has ever loaded for the life of the page.
|
||||
async function fetchImage(path, retry = true) {
|
||||
const { access } = tokens()
|
||||
const res = await fetch(path, {
|
||||
headers: access ? { Authorization: 'Bearer ' + access } : {},
|
||||
})
|
||||
if (res.ok) return URL.createObjectURL(await res.blob())
|
||||
|
||||
let parsed = null
|
||||
try { parsed = await res.json() } catch { /* an image endpoint may not answer json */ }
|
||||
const code = parsed?.error || ''
|
||||
if (code === 'token_expired' && retry) {
|
||||
await refresh()
|
||||
return fetchImage(path, false)
|
||||
}
|
||||
if (res.status === 401) clearTokens()
|
||||
throw new ApiError(res.status, code,
|
||||
parsed?.message || `That picture could not be loaded (${res.status}).`)
|
||||
}
|
||||
|
||||
const qs = (params) => {
|
||||
const p = new URLSearchParams()
|
||||
for (const [k, v] of Object.entries(params || {})) {
|
||||
@@ -138,6 +169,9 @@ export const api = {
|
||||
conversion: (params) => send('GET', '/api/reports/conversion' + qs(params)),
|
||||
|
||||
cameras: () => send('GET', '/api/cameras'),
|
||||
// A camera picture this server holds itself. Returns an object URL the
|
||||
// caller must revoke; see fetchImage.
|
||||
cameraSnapshot: (url) => fetchImage(url),
|
||||
createCamera: (siteID, cam) =>
|
||||
send('POST', `/api/sites/${encodeURIComponent(siteID)}/cameras`, cam),
|
||||
updateCamera: (id, cam) => send('PATCH', `/api/cameras/${encodeURIComponent(id)}`, cam),
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
|
||||
import { api } from './api.js'
|
||||
|
||||
// usePolled runs `fn` now and every `everyMs`, and is careful about the two
|
||||
// things every screen would otherwise get wrong on its own: overlapping
|
||||
// requests when the server is slower than the interval, and setting state
|
||||
@@ -40,3 +42,40 @@ export function usePolled(fn, everyMs, deps = []) {
|
||||
|
||||
return { data, error, loading, reload: run }
|
||||
}
|
||||
|
||||
|
||||
// useAuthedImage loads a picture that needs the session's bearer token and
|
||||
// hands back a URL an <img> can use.
|
||||
//
|
||||
// Two things it has to get right, and both were bugs the first time something
|
||||
// like it was written elsewhere in this app:
|
||||
//
|
||||
// * REVOKE. An object URL pins the blob in memory until it is revoked, and
|
||||
// this component re-renders on every poll. Without the cleanup a camera
|
||||
// screen left open for an afternoon holds hundreds of copies of the same
|
||||
// photograph.
|
||||
// * Key on the URL, not on the object. `snapshot` is a fresh object on every
|
||||
// poll, so an effect depending on it would re-fetch 90 KB per camera every
|
||||
// few seconds; the URL only changes when the picture actually does.
|
||||
export function useAuthedImage(url) {
|
||||
const [src, setSrc] = useState(null)
|
||||
|
||||
useEffect(() => {
|
||||
if (!url) { setSrc(null); return }
|
||||
let alive = true
|
||||
let objectURL = null
|
||||
api.cameraSnapshot(url)
|
||||
.then(u => {
|
||||
if (!alive) { URL.revokeObjectURL(u); return }
|
||||
objectURL = u
|
||||
setSrc(u)
|
||||
})
|
||||
.catch(() => { if (alive) setSrc(null) })
|
||||
return () => {
|
||||
alive = false
|
||||
if (objectURL) URL.revokeObjectURL(objectURL)
|
||||
}
|
||||
}, [url])
|
||||
|
||||
return src
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useState } from 'react'
|
||||
import { api } from '../api.js'
|
||||
import { usePolled } from '../hooks.js'
|
||||
import Shot from './Shot.jsx'
|
||||
import { ago, Loading, Problem } from './Sites.jsx'
|
||||
import CameraSetup from './CameraSetup.jsx'
|
||||
|
||||
@@ -114,7 +115,7 @@ function CameraCard({ cam, canEdit, onEdit }) {
|
||||
onKeyDown={e => canEdit && e.key === 'Enter' && onEdit()}>
|
||||
<div className="shot">
|
||||
{cam.snapshot?.available
|
||||
? <img src={cam.snapshot.url} alt={`View from ${cam.label}`} loading="lazy" />
|
||||
? <Shot url={cam.snapshot.url} alt={`View from ${cam.label}`} />
|
||||
: <div className="noshot">
|
||||
<span className="lens" aria-hidden="true" />
|
||||
{cam.snapshot?.reason || 'No picture yet.'}
|
||||
|
||||
24
web/src/views/Shot.jsx
Normal file
24
web/src/views/Shot.jsx
Normal file
@@ -0,0 +1,24 @@
|
||||
import { useAuthedImage } from '../hooks.js'
|
||||
|
||||
// One camera picture, however this deployment stores them.
|
||||
//
|
||||
// Two shapes arrive here and they need different handling, which is exactly
|
||||
// why it is one component rather than an <img> repeated on each screen:
|
||||
//
|
||||
// * An ABSOLUTE url is a presigned link to object storage. It carries its
|
||||
// own signature, so a plain <img src> loads it.
|
||||
// * A RELATIVE url is served by this server from its own database, for a
|
||||
// deployment with no bucket. An <img> cannot send an Authorization header,
|
||||
// so it has to be fetched with the session and handed over as an object
|
||||
// URL. Minting an unauthenticated link instead would put a photograph of
|
||||
// somebody's shop floor behind no session at all, which is the thing this
|
||||
// path exists to avoid.
|
||||
export default function Shot({ url, alt }) {
|
||||
const local = typeof url === 'string' && url.startsWith('/')
|
||||
// Hooks cannot be called conditionally, so this always runs and simply has
|
||||
// nothing to do when the URL is already usable.
|
||||
const fetched = useAuthedImage(local ? url : null)
|
||||
const src = local ? fetched : url
|
||||
if (!src) return null
|
||||
return <img src={src} alt={alt} loading="lazy" />
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useState } from 'react'
|
||||
import { api } from '../api.js'
|
||||
import { usePolled } from '../hooks.js'
|
||||
import Shot from './Shot.jsx'
|
||||
import SiteCheck from './SiteCheck.jsx'
|
||||
|
||||
// The estate at a glance.
|
||||
@@ -134,7 +135,7 @@ function SiteCard({ site, cams, verdict, onCheck }) {
|
||||
tabIndex={0} onKeyDown={e => e.key === 'Enter' && onCheck()}>
|
||||
<div className="shot">
|
||||
{view.url
|
||||
? <img src={view.url} alt={`View inside ${site.name}`} loading="lazy" />
|
||||
? <Shot url={view.url} alt={`View inside ${site.name}`} />
|
||||
: <div className="noshot">
|
||||
<ShopMark />
|
||||
{view.reason && <span>{view.reason}</span>}
|
||||
|
||||
Reference in New Issue
Block a user