From a4236e3dd225534ac704407583de7f3cf174029e Mon Sep 17 00:00:00 2001 From: prsmith777 Date: Wed, 4 Nov 2026 00:00:17 -0700 Subject: [PATCH 1/2] Add camera input deletion while preserving plate history --- app/api/camera-inputs/route.js | 19 ++++ components/settings/CameraInputs.jsx | 86 +++++++++++++- docs/CAMERA_INPUTS.md | 15 +++ lib/camera-inputs/processor.mjs | 7 +- lib/camera-inputs/repository.mjs | 83 ++++++++++++-- lib/camera-inputs/runtime.mjs | 19 +++- lib/help-manual.mjs | 6 +- lib/plate-read-ingestion.js | 5 +- lib/settings-help-coverage.mjs | 2 +- migrations.sql | 31 +++++ .../0077_2026110301_camera_input_deletion.sql | 9 ++ scripts/test-camera-inputs-postgres.mjs | 106 +++++++++++++++++- test/camera-inputs.test.mjs | 9 ++ test/help-manual.test.mjs | 2 +- test/release-info.test.mjs | 4 +- 15 files changed, 379 insertions(+), 24 deletions(-) create mode 100644 migrations/0077_2026110301_camera_input_deletion.sql diff --git a/app/api/camera-inputs/route.js b/app/api/camera-inputs/route.js index acc4f3a..01b983b 100644 --- a/app/api/camera-inputs/route.js +++ b/app/api/camera-inputs/route.js @@ -2,6 +2,7 @@ import { getPool } from "@/lib/db"; import { denyUnlessRoutePermission } from "@/lib/route-permission.mjs"; import { CameraInputRepository } from "@/lib/camera-inputs/repository.mjs"; import { InputError, readAxisRequest } from "@/lib/camera-inputs/axis.mjs"; +import { refreshCameraInputs } from "@/lib/camera-inputs/runtime.mjs"; export async function GET() { const denied = await denyUnlessRoutePermission("system.manage_settings"); @@ -59,3 +60,21 @@ export async function POST(request) { ); } } + +export async function DELETE(request) { + const denied = await denyUnlessRoutePermission("system.manage_settings"); + if (denied) return denied; + try { + const data = await readAxisRequest(request, 64 * 1024); + if (!data || Array.isArray(data) || typeof data !== "object") + throw new InputError("Expected a camera input to delete"); + const result = await new CameraInputRepository(await getPool()).remove(data); + refreshCameraInputs(); + return Response.json(result, { headers: { "Cache-Control": "no-store" } }); + } catch (error) { + return Response.json( + { error: error instanceof InputError ? error.message : "Unable to delete camera input" }, + { status: error instanceof InputError ? error.status : 503 }, + ); + } +} diff --git a/components/settings/CameraInputs.jsx b/components/settings/CameraInputs.jsx index e59b22a..adb3bd4 100644 --- a/components/settings/CameraInputs.jsx +++ b/components/settings/CameraInputs.jsx @@ -2,9 +2,13 @@ import Link from "next/link"; import Image from "next/image"; -import { useCallback, useEffect, useState } from "react"; +import { useCallback, useEffect, useRef, useState } from "react"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; +import { + AlertDialog, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, + AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, +} from "@/components/ui/alert-dialog"; import { Card, CardContent, @@ -30,13 +34,13 @@ const blank = { }; const selectClass = "h-10 w-full rounded-md border border-input bg-background px-3 text-sm"; -async function api(url, data) { +async function api(url, data, method = "POST") { const response = await fetch( url, data === undefined ? { cache: "no-store" } : { - method: "POST", + method, headers: { "Content-Type": "application/json" }, body: JSON.stringify(data), }, @@ -69,6 +73,10 @@ export function CameraInputs() { const [brokerDraft, setBrokerDraft] = useState(null); const [origin, setOrigin] = useState(""); const [loaded, setLoaded] = useState(false); + const [deleteTarget, setDeleteTarget] = useState(null); + const [deleteError, setDeleteError] = useState(""); + const deleteTrigger = useRef(null); + const addCameraButton = useRef(null); const load = useCallback(async () => { const result = await api("/api/camera-inputs"); setInputs(result.inputs); @@ -169,6 +177,35 @@ export function CameraInputs() { setBusy(false); } } + async function remove() { + const target = deleteTarget; + if (!target || busy) return; + setBusy(true); + setDeleteError(""); + try { + await api("/api/camera-inputs", { id: target.id, camera_name: target.camera_name }, "DELETE"); + setInputs((current) => current.filter((input) => input.camera_name !== target.camera_name)); + if (draft?.camera_name === target.camera_name) { + setDraft(null); + setBrokerDraft(null); + } + setCredential((current) => current?.id === target.id ? null : current); + setListening(null); + setEvents([]); + setDeleteTarget(null); + setMessage("Camera input deleted. Saved plate history and images are kept."); + await load().catch(() => setMessage("Camera input deleted. Refresh the page to reload the list.")); + } catch (error) { + setDeleteError(error.message); + } finally { + setBusy(false); + } + } + const confirmDelete = (input) => { + deleteTrigger.current = document.activeElement; + setDeleteError(""); + setDeleteTarget(input); + }; return (
@@ -181,7 +218,7 @@ export function CameraInputs() { Existing Blue Iris cameras work automatically.
- + @@ -259,6 +296,15 @@ export function CameraInputs() { ) : null} ) : null} + @@ -270,6 +316,7 @@ export function CameraInputs() {

Connect your first camera using Add camera input. Existing Blue Iris feeds also appear automatically after their first read. + To reconnect a deleted camera, use Add camera input.

) : null}
@@ -633,10 +680,15 @@ export function CameraInputs() { /> Enable this input -
+
+ {draft.id || draft.legacy ? ( + + ) : null} + + +
); } diff --git a/docs/CAMERA_INPUTS.md b/docs/CAMERA_INPUTS.md index fceb827..1a40cc8 100644 --- a/docs/CAMERA_INPUTS.md +++ b/docs/CAMERA_INPUTS.md @@ -4,6 +4,21 @@ Open **Settings > Integrations > Camera Inputs**. Select a recognition source fo Recognition and recording are independent. An Axis camera may supply recognition directly while Blue Iris continues recording it. This integration does not manufacture Blue Iris alert/clip pointers for Axis events; playback pointers require an actual Blue Iris alert association. The existing Blue Iris recording setup remains available independently. +## Delete a camera input + +Select **Delete input** in the camera's Actions column or configuration form, +then confirm the named camera. Deletion stops new imports, revokes the input's +HTTP credential and disconnects its MQTT subscription. Queued detections and +unfinished passages are cancelled. Saved plate reads, direction observations, +and saved plate/scene images are preserved, so the camera can still appear in +historical data filters. + +Deleted inputs stay out of this settings list, including Blue Iris cameras +discovered from history. Blue Iris recognition for a deleted camera name is +ignored until you explicitly add that name again. **Add camera input** can +reuse the name and device identity with a fresh input ID and HTTP credential. +The camera's own publishing setup and a shared MQTT broker are managed separately. + ## Blue Iris Use the exact camera name sent in the Blue Iris alert JSON. Send the existing alert body to `/api/plate-reads`, authenticated with the existing integration API key in `x-api-key` or `Authorization: Bearer`. Existing unregistered camera names continue to be accepted automatically. diff --git a/lib/camera-inputs/processor.mjs b/lib/camera-inputs/processor.mjs index 332fb2f..a2628bf 100644 --- a/lib/camera-inputs/processor.mjs +++ b/lib/camera-inputs/processor.mjs @@ -59,6 +59,7 @@ export class AxisEventProcessor { const client = await this.pool.connect(); let lockKey; let locked = false; + let inputLocked = false; let transaction = false; let committed = false; const files = []; @@ -72,12 +73,14 @@ export class AxisEventProcessor { ) ).rows[0].locked; if (!locked) return false; + await client.query("SELECT pg_advisory_lock_shared(hashtextextended($1,2))", [receipt.input_id]); + inputLocked = true; const input = ( await client.query("SELECT * FROM public.camera_inputs WHERE id=$1", [ receipt.input_id, ]) ).rows[0]; - if (!input?.enabled || input.source !== "axis") return false; + if (!input?.enabled || input.deleted_at || input.source !== "axis") return false; const current = ( await client.query( "SELECT * FROM public.camera_input_events WHERE id=$1", @@ -351,6 +354,8 @@ export class AxisEventProcessor { ); throw error; } finally { + if (inputLocked) + await client.query("SELECT pg_advisory_unlock_shared(hashtextextended($1,2))", [receipt.input_id]).catch(() => {}); if (locked) await client .query("SELECT pg_advisory_unlock(hashtextextended($1,0))", [lockKey]) diff --git a/lib/camera-inputs/repository.mjs b/lib/camera-inputs/repository.mjs index 42c0a5d..b3f0665 100644 --- a/lib/camera-inputs/repository.mjs +++ b/lib/camera-inputs/repository.mjs @@ -5,7 +5,7 @@ import { publicInput, validateInput, } from "./config.mjs"; -import { InputError, normalizeAxisEvent } from "./axis.mjs"; +import { InputError, normalizeAxisEvent, text } from "./axis.mjs"; export class CameraInputRepository { constructor(pool) { @@ -15,7 +15,7 @@ export class CameraInputRepository { return ( ( await this.pool.query( - "SELECT * FROM public.camera_inputs WHERE id = $1", + "SELECT * FROM public.camera_inputs WHERE id = $1 AND deleted_at IS NULL", [id], ) ).rows[0] ?? null @@ -37,7 +37,7 @@ export class CameraInputRepository { configured.map((input) => input.camera_name.trim().toLowerCase()), ); return [ - ...configured, + ...configured.filter((input) => !input.deleted_at), ...legacy .filter((row) => !names.has(row.camera_name.trim().toLowerCase())) .map((row) => ({ @@ -65,7 +65,7 @@ export class CameraInputRepository { const previous = id ? ( await client.query( - "SELECT * FROM public.camera_inputs WHERE id=$1 FOR UPDATE", + "SELECT * FROM public.camera_inputs WHERE id=$1 AND deleted_at IS NULL FOR UPDATE", [id], ) ).rows[0] @@ -139,6 +139,75 @@ export class CameraInputRepository { client.release(); } } + async remove(data) { + let id = data.id == null ? null : text(data.id, 36); + if (id && !/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(id)) + throw new InputError("Invalid camera input ID"); + const initial = id + ? (await this.pool.query("SELECT id,camera_name FROM public.camera_inputs WHERE id=$1", [id])).rows[0] + : null; + if (id && !initial) throw new InputError("Camera input not found", 404); + const name = initial?.camera_name ?? text(data.camera_name, 30); + if (!name) throw new InputError("Camera name is required"); + if (initial && data.camera_name != null && text(data.camera_name, 30) !== name) + throw new InputError("Camera input changed; reload before deleting it", 409); + // PostgreSQL normalizes UUID spelling; use that same identity for locks. + id = initial?.id ?? null; + const client = await this.pool.connect(); + try { + await client.query("BEGIN"); + await client.query("SELECT pg_advisory_xact_lock(hashtextextended(LOWER(BTRIM($1)),1))", [name]); + // Workers hold a shared session lock across their ingestion transaction. + // Wait before locking the input row so their completion cannot deadlock. + if (id) + await client.query("SELECT pg_advisory_xact_lock(hashtextextended($1,2))", [id]); + let input = (await client.query( + id + ? "SELECT * FROM public.camera_inputs WHERE id=$1 FOR UPDATE" + : `SELECT * FROM public.camera_inputs WHERE LOWER(BTRIM(camera_name))=LOWER(BTRIM($1)) + ORDER BY (deleted_at IS NULL) DESC,deleted_at DESC LIMIT 1 FOR UPDATE`, + [id ?? name], + )).rows[0]; + if (id && !input) throw new InputError("Camera input not found", 404); + if (!id && input && !input.deleted_at) + throw new InputError("Camera input changed; reload before deleting it", 409); + if (input?.deleted_at) { + await client.query("COMMIT"); + return { deleted: true, id: input.id, camera_name: name, already_deleted: true }; + } + if (!input) { + const legacy = await client.query( + "SELECT 1 FROM public.plate_reads WHERE LOWER(BTRIM(camera_name))=LOWER(BTRIM($1)) LIMIT 1", [name], + ); + if (!legacy.rows.length) throw new InputError("Camera input not found", 404); + input = (await client.query( + `INSERT INTO public.camera_inputs(id,camera_name,source,transport,enabled) + VALUES ($1,$2,'blue_iris','http',FALSE) RETURNING *`, [randomUUID(), name], + )).rows[0]; + } + const pending = (await client.query( + "SELECT COUNT(*)::int AS count FROM public.camera_input_events WHERE input_id=$1 AND status='pending'", [input.id], + )).rows[0].count; + await client.query( + `UPDATE public.camera_input_events SET status=CASE WHEN status='pending' THEN 'ignored' ELSE status END, + payload=payload - 'image' - 'sceneImage',leased_until=NULL,lease_token=NULL, + processed_at=COALESCE(processed_at,CURRENT_TIMESTAMP) WHERE input_id=$1`, [input.id], + ); + await client.query("UPDATE public.camera_input_passages SET finalized=TRUE WHERE input_id=$1", [input.id]); + await client.query( + `UPDATE public.camera_inputs SET deleted_at=CURRENT_TIMESTAMP,updated_at=CURRENT_TIMESTAMP, + enabled=FALSE,credential_hash=NULL,broker_id=NULL,topic_filter=NULL,transport='http', + connection_status='deleted',last_error=NULL WHERE id=$1`, [input.id], + ); + await client.query("COMMIT"); + return { deleted: true, id: input.id, camera_name: name, discarded_events: pending }; + } catch (error) { + await client.query("ROLLBACK").catch(() => {}); + throw error; + } finally { + client.release(); + } + } async receive(input, payload, transport, { retained = false } = {}) { if ( !input?.enabled || @@ -160,7 +229,7 @@ export class CameraInputRepository { throw new InputError("Event is too large", 413); const result = await this.pool.query( `WITH active AS ( - SELECT * FROM public.camera_inputs WHERE id=$1 AND enabled AND source='axis' + SELECT * FROM public.camera_inputs WHERE id=$1 AND enabled AND deleted_at IS NULL AND source='axis' AND device_id=$5 AND transport IN ($4,'both') AND (roi_filter IS NULL OR roi_filter=$6) FOR UPDATE ), event AS ( INSERT INTO public.camera_input_events(input_id,fingerprint,payload,transport) @@ -199,7 +268,7 @@ export class CameraInputRepository { async status(id, status, error = null) { await this.pool.query( - "UPDATE public.camera_inputs SET connection_status=$2, last_error=$3 WHERE id=$1", + "UPDATE public.camera_inputs SET connection_status=$2, last_error=$3 WHERE id=$1 AND deleted_at IS NULL", [id, status, error], ); } @@ -208,7 +277,7 @@ export class CameraInputRepository { await this.pool .query(`SELECT inputs.*, brokers.broker, brokers.port, brokers.username, brokers.password, brokers.use_tls, brokers.enabled AS broker_enabled FROM public.camera_inputs inputs JOIN public.mqttbrokers brokers ON brokers.id = inputs.broker_id - WHERE inputs.source='axis' AND inputs.enabled AND inputs.transport IN ('mqtt','both')`) + WHERE inputs.source='axis' AND inputs.enabled AND inputs.deleted_at IS NULL AND inputs.transport IN ('mqtt','both')`) ).rows; } async claim() { diff --git a/lib/camera-inputs/runtime.mjs b/lib/camera-inputs/runtime.mjs index 1a90342..7463def 100644 --- a/lib/camera-inputs/runtime.mjs +++ b/lib/camera-inputs/runtime.mjs @@ -145,7 +145,7 @@ export class CameraInputRuntime { ); continue; } - this.clients.set(input.id, { client, identity }); + this.clients.set(input.id, { client, identity, topicFilter: input.topic_filter }); // MQTT.js invokes handleMessage before PUBACK for QoS 1. Persist before // acknowledging; disconnect on transient failures so the broker can retry. client.handleMessage = (packet, callback) => { @@ -202,6 +202,17 @@ export class CameraInputRuntime { } for (const [id, entry] of this.clients) if (!wanted.has(id)) { + if (entry.client.connected && entry.topicFilter) { + // Retire this subscription, while keeping ordinary app shutdown + // persistent so the broker can still queue events during outages. + await new Promise((resolve) => { + const timer = setTimeout(resolve, 2000); + entry.client.unsubscribe(entry.topicFilter, () => { + clearTimeout(timer); + resolve(); + }); + }); + } await new Promise((resolve) => entry.client.end(true, {}, resolve)); this.clients.delete(id); } @@ -294,6 +305,12 @@ const STATE = Symbol.for("alpr.camera-input-runtime.v1"); export function wakeCameraInputs(stateHost = globalThis) { stateHost[STATE]?.then((runtime) => runtime.wake()).catch(() => {}); } +export function refreshCameraInputs(stateHost = globalThis) { + stateHost[STATE]?.then((runtime) => { + runtime.lastSync = 0; + runtime.wake(); + }).catch(() => {}); +} export async function startCameraInputRuntime({ loadDependencies, stateHost = globalThis, diff --git a/lib/help-manual.mjs b/lib/help-manual.mjs index f6ba59e..6e70d78 100644 --- a/lib/help-manual.mjs +++ b/lib/help-manual.mjs @@ -12,8 +12,8 @@ export const HELP_MANUAL = Object.freeze({ title: "ALPR Database Community User Guide", shortTitle: "User Guide", description: "A practical guide to using, configuring, and safely administering the portable Community application.", - manualVersion: "3.29", - updatedAt: "November 2, 2026", + manualVersion: "3.30", + updatedAt: "November 3, 2026", coverageBaseline: "Published clean-history Community release with portable configuration and no private deployment controls.", filename: "ALPR-Database-Community-User-Guide.pdf", sections: [ @@ -426,7 +426,7 @@ export const HELP_MANUAL = Object.freeze({ "For MQTT, select or add a broker, enter its incoming AllPlates topic filter, and use QoS 1 on both the camera publication and ALPR subscription. Keep Retain set to None. ALPR uses a separate persistent client ID and checks the camera identity in every event.", "Choose immediate processing for fast initial reads and later corrections, or finalized processing to wait for Lost with a 30-second inactivity fallback. Immediate alerts use the first recognition and are not repeated for corrections. Optional ROI ID filtering and in/out direction labels apply per camera.", "Save and use Test MQTT to verify broker access, then Listen for event to inspect a real or camera-generated test event, plate image, time, direction, and processing state. Camera test events are real imports. Keep sample plate values out of production when testing.", - ] },{ type: "note", tone: "info", title: "Delivery and evidence", text: "HTTP success and MQTT QoS 1 acknowledgment follow durable receipt. Broker persistence is needed for ALPR disconnects; MQTT cannot recover events never delivered to the broker. Original plate observations and later corrections are retained separately, and human corrections remain authoritative. Event observations are retained for seven days; saved images use application storage. Source credentials are shown only when generated; rotating one requires updating the camera." }], + ] },{ type: "paragraph", text: "Use Delete input in a camera's Actions or configuration form, then confirm its name. ALPR stops new imports, revokes its HTTP credential and disconnects MQTT. Queued detections and unfinished passages are cancelled; saved plate history, direction observations and images are kept. Deleted inputs do not reappear automatically from history. Add camera input can reuse the name and device identity with fresh credentials; a deleted Blue Iris name stays blocked until explicitly added again." },{ type: "note", tone: "info", title: "Delivery and evidence", text: "HTTP success and MQTT QoS 1 acknowledgment follow durable receipt. Broker persistence is needed for ALPR disconnects; MQTT cannot recover events never delivered to the broker. Original plate observations and later corrections are retained separately, and human corrections remain authoritative. Event observations are retained for seven days; saved images use application storage. Source credentials are shown only when generated; rotating one requires updating the camera." }], }, { id: "mqtt", diff --git a/lib/plate-read-ingestion.js b/lib/plate-read-ingestion.js index af530d6..4924c9c 100644 --- a/lib/plate-read-ingestion.js +++ b/lib/plate-read-ingestion.js @@ -321,7 +321,8 @@ export async function processPlateRead(data, _request, context = {}) { ); const source = ( await dbClient.query( - "SELECT source,enabled FROM public.camera_inputs WHERE LOWER(BTRIM(camera_name))=LOWER(BTRIM($1)) FOR UPDATE", + `SELECT source,enabled FROM public.camera_inputs WHERE LOWER(BTRIM(camera_name))=LOWER(BTRIM($1)) + ORDER BY (deleted_at IS NULL) DESC,deleted_at DESC LIMIT 1 FOR UPDATE`, [camera], ) ).rows[0]; @@ -335,7 +336,7 @@ export async function processPlateRead(data, _request, context = {}) { } if (source) await dbClient.query( - "UPDATE public.camera_inputs SET last_received_at=CURRENT_TIMESTAMP,connection_status='receiving',last_error=NULL WHERE LOWER(BTRIM(camera_name))=LOWER(BTRIM($1))", + "UPDATE public.camera_inputs SET last_received_at=CURRENT_TIMESTAMP,connection_status='receiving',last_error=NULL WHERE LOWER(BTRIM(camera_name))=LOWER(BTRIM($1)) AND deleted_at IS NULL", [camera], ); } diff --git a/lib/settings-help-coverage.mjs b/lib/settings-help-coverage.mjs index 03a9b2c..74c6f8c 100644 --- a/lib/settings-help-coverage.mjs +++ b/lib/settings-help-coverage.mjs @@ -1,5 +1,5 @@ export const SETTINGS_HELP_COVERAGE = Object.freeze([ - { sectionId: "camera-inputs", routes: ["/settings/integrations/camera-inputs"], requiredTerms: ["Blue Iris", "Axis", "HTTP push", "MQTT", "source credential", "QoS 1", "30-second inactivity", "seven days"] }, + { sectionId: "camera-inputs", routes: ["/settings/integrations/camera-inputs"], requiredTerms: ["Blue Iris", "Axis", "HTTP push", "MQTT", "source credential", "QoS 1", "30-second inactivity", "seven days", "Delete input"] }, { sectionId: "general-settings", routes: ["/settings/general"], diff --git a/migrations.sql b/migrations.sql index 5d99df5..6745c37 100644 --- a/migrations.sql +++ b/migrations.sql @@ -9542,3 +9542,34 @@ $source_ae7c8a94fcbe92b3$; END IF; END; $migration$; + +-- 0077_2026110301_camera_input_deletion.sql +DO $migration$ +DECLARE recorded_hash TEXT; +BEGIN + SELECT sql_sha256 INTO recorded_hash FROM public.schema_migrations WHERE version = '2026110301_camera_input_deletion'; + IF FOUND THEN + IF recorded_hash IS NOT NULL AND recorded_hash <> 'b9f84473098bb46f9c93f7f71eb46efe53aedd5d0b69fab9b8a974189cd5a199' THEN + RAISE EXCEPTION 'Applied migration checksum differs: 2026110301_camera_input_deletion'; + END IF; + IF recorded_hash IS NULL THEN + UPDATE public.schema_migrations SET sql_sha256 = 'b9f84473098bb46f9c93f7f71eb46efe53aedd5d0b69fab9b8a974189cd5a199' WHERE version = '2026110301_camera_input_deletion'; + END IF; + ELSE + EXECUTE $source_b9f84473098bb46f$-- migration: 2026110301_camera_input_deletion +-- Keep source identity and passage/image references after removing an input. +ALTER TABLE public.camera_inputs ADD COLUMN deleted_at TIMESTAMPTZ; +DROP INDEX public.uq_camera_inputs_name; +CREATE UNIQUE INDEX uq_camera_inputs_name ON public.camera_inputs(LOWER(BTRIM(camera_name))) WHERE deleted_at IS NULL; +DROP INDEX public.uq_camera_inputs_device; +CREATE UNIQUE INDEX uq_camera_inputs_device ON public.camera_inputs(device_id) WHERE source='axis' AND deleted_at IS NULL; +INSERT INTO public.schema_migrations(version,description) VALUES + ('2026110301_camera_input_deletion','Remove camera inputs while preserving imported reads, images and archived source identity.'); +$source_b9f84473098bb46f$; + IF NOT EXISTS (SELECT 1 FROM public.schema_migrations WHERE version = '2026110301_camera_input_deletion') THEN + RAISE EXCEPTION 'Migration did not record completion: 2026110301_camera_input_deletion'; + END IF; + UPDATE public.schema_migrations SET sql_sha256 = 'b9f84473098bb46f9c93f7f71eb46efe53aedd5d0b69fab9b8a974189cd5a199' WHERE version = '2026110301_camera_input_deletion'; + END IF; +END; +$migration$; diff --git a/migrations/0077_2026110301_camera_input_deletion.sql b/migrations/0077_2026110301_camera_input_deletion.sql new file mode 100644 index 0000000..72ae549 --- /dev/null +++ b/migrations/0077_2026110301_camera_input_deletion.sql @@ -0,0 +1,9 @@ +-- migration: 2026110301_camera_input_deletion +-- Keep source identity and passage/image references after removing an input. +ALTER TABLE public.camera_inputs ADD COLUMN deleted_at TIMESTAMPTZ; +DROP INDEX public.uq_camera_inputs_name; +CREATE UNIQUE INDEX uq_camera_inputs_name ON public.camera_inputs(LOWER(BTRIM(camera_name))) WHERE deleted_at IS NULL; +DROP INDEX public.uq_camera_inputs_device; +CREATE UNIQUE INDEX uq_camera_inputs_device ON public.camera_inputs(device_id) WHERE source='axis' AND deleted_at IS NULL; +INSERT INTO public.schema_migrations(version,description) VALUES + ('2026110301_camera_input_deletion','Remove camera inputs while preserving imported reads, images and archived source identity.'); diff --git a/scripts/test-camera-inputs-postgres.mjs b/scripts/test-camera-inputs-postgres.mjs index 0f5f48d..adf98fe 100644 --- a/scripts/test-camera-inputs-postgres.mjs +++ b/scripts/test-camera-inputs-postgres.mjs @@ -43,7 +43,20 @@ try { new URL("../migrations.sql", import.meta.url), "utf8", ); + const deletionMigration = migrations.indexOf("-- 0077_2026110301_camera_input_deletion.sql"); + assert.ok(deletionMigration > 0); + await pool.query(migrations.slice(0, deletionMigration)); + const upgradeId = "77777777-0000-4000-8000-000000000077"; + const beforeUpgrade = (await pool.query( + `INSERT INTO public.camera_inputs(id,camera_name,source,transport,device_id,credential_hash) + VALUES ($1,'Upgrade Existing','axis','http','EE0000000077',repeat('a',64)) RETURNING *`, [upgradeId], + )).rows[0]; await pool.query(migrations); + const { deleted_at: upgradeDeletedAt, ...afterUpgrade } = (await pool.query( + "SELECT * FROM public.camera_inputs WHERE id=$1", [upgradeId], + )).rows[0]; + assert.equal(upgradeDeletedAt, null); + assert.deepEqual(afterUpgrade, beforeUpgrade, "Upgrading a populated installation preserves existing camera configuration"); const [ { processPlateRead, processCameraDirection }, { default: storage }, @@ -670,8 +683,99 @@ try { timestamp: "2026-10-29T15:01:00.000Z", }); assert.equal(after.status, 201); + // Removal preserves accepted history and image references, but cancels work + // that has not been imported. It must wait for an already-running ingestion. + const removable = await repository.get((await repository.save({ + camera_name: "Delete Input", source: "axis", transport: "both", + device_id: "DD0000000001", processing_mode: "final", + broker_id: input.broker_id, topic_filter: "axis/delete/#", + })).input.id); + await deliver(removable, body(removable, { + plateText: "KEEP123", carID: "kept", carState: "lost", capture_timestamp: "1793294994000", + ImageArray: [{ ImageType: "plate", BinaryImage: image }, { ImageType: "scene", BinaryImage: image }], + })); + const kept = (await pool.query("SELECT * FROM public.plate_reads WHERE camera_name=$1", [removable.camera_name])).rows[0]; + const scene = (await pool.query("SELECT * FROM public.camera_input_passages WHERE read_id=$1", [kept.id])).rows[0]; + const buffered = await deliver(removable, body(removable, { + carID: "buffered", plateText: "DROP123", capture_timestamp: "1793295994000", + })); + const queued = await repository.receive(removable, body(removable, { + carID: "queued", plateText: "DROP456", capture_timestamp: "1793296994000", + }), "http"); + const inflight = await repository.receive(removable, body(removable, { + carID: "inflight", plateText: "FLIGHT1", carState: "lost", capture_timestamp: "1793297994000", + }), "http"); + let entered, proceed; + const enteredGate = new Promise((resolve) => { entered = resolve; }); + const proceedGate = new Promise((resolve) => { proceed = resolve; }); + const activeProcessor = new AxisEventProcessor({ pool, storage, ingest: async (...args) => { + entered(); await proceedGate; return processPlateRead(...args); + }}); + const active = activeProcessor.process((await pool.query("SELECT * FROM public.camera_input_events WHERE id=$1", [inflight.eventId])).rows[0]); + let removal; + try { + await enteredGate; + let removed = false; + removal = repository.remove({ id: removable.id.toUpperCase(), camera_name: removable.camera_name }).then((result) => { removed = true; return result; }); + let waiting = false; + const deadline = Date.now() + 3000; + while (!waiting && Date.now() < deadline) { + waiting = (await pool.query("SELECT EXISTS(SELECT 1 FROM pg_locks WHERE locktype='advisory' AND mode='ExclusiveLock' AND NOT granted) AS waiting")).rows[0].waiting; + if (!waiting) await new Promise((resolve) => setTimeout(resolve, 10)); + } + assert.equal(waiting, true, "Deletion waits for in-flight passage processing"); + assert.equal(removed, false); + proceed(); + assert.equal(await active, true); + assert.equal((await removal).discarded_events, 1); + } finally { + proceed(); + await Promise.allSettled([active, removal]); + } + assert.deepEqual((await pool.query("SELECT * FROM public.plate_reads WHERE id=$1", [kept.id])).rows[0], kept); + assert.ok(await storage.resolveExistingImagePath(kept.image_path)); + assert.ok(await storage.resolveExistingImagePath(scene.scene_image_path)); + assert.equal((await pool.query("SELECT scene_image_path FROM public.camera_input_passages WHERE id=$1", [scene.id])).rows[0].scene_image_path, scene.scene_image_path); + assert.equal((await pool.query("SELECT COUNT(*)::int AS count FROM public.plate_reads WHERE camera_name=$1", [removable.camera_name])).rows[0].count, 2); + assert.equal(await repository.get(removable.id), null); + assert.equal((await repository.list()).some((row) => row.camera_name === removable.camera_name), false, "History does not rediscover a deleted input as Blue Iris"); + assert.equal((await repository.mqttInputs()).some((row) => row.id === removable.id), false); + await assert.rejects(() => repository.receive(removable, body(removable, { carID: "late" }), "http"), (error) => error.status === 403); + await assert.rejects(() => repository.save({ direction_in: "Changed" }, removable.id), (error) => error.status === 404); + for (const id of [buffered.eventId, queued.eventId]) { + const abandoned = (await pool.query("SELECT * FROM public.camera_input_events WHERE id=$1", [id])).rows[0]; + assert.equal(await processor.process(abandoned, { finalize: true }), false); + assert.equal(abandoned.payload.image, undefined); + assert.notEqual(abandoned.status, "pending"); + } + const deletedRow = (await pool.query("SELECT * FROM public.camera_inputs WHERE id=$1", [removable.id])).rows[0]; + assert.equal(deletedRow.credential_hash, null); + assert.equal(deletedRow.broker_id, null); + assert.ok(deletedRow.deleted_at); + assert.equal((await repository.remove({ id: removable.id })).already_deleted, true); + const replacement = await repository.save({ camera_name: removable.camera_name, source: "axis", device_id: removable.device_id }); + assert.notEqual(replacement.input.id, removable.id); + assert.ok(replacement.credential); + await repository.remove({ id: removable.id }); + assert.ok(await repository.get(replacement.input.id), "A stale deletion cannot delete the replacement"); + assert.equal((await pool.query("SELECT COUNT(*)::int AS count FROM public.mqttbrokers WHERE id=$1", [input.broker_id])).rows[0].count, 1); + assert.ok(await repository.get(input.id), "Other camera inputs are preserved"); + + assert.equal((await processPlateRead({ camera: "Legacy Delete", plate_number: "LEGACY1" })).status, 201); + assert.equal((await repository.list()).find((row) => row.camera_name === "Legacy Delete").legacy, true); + await repository.remove({ camera_name: "Legacy Delete" }); + assert.equal((await repository.list()).some((row) => row.camera_name === "Legacy Delete"), false); + assert.equal((await processPlateRead({ camera: "Legacy Delete", plate_number: "BLOCKED" })).status, 200); + assert.equal((await pool.query("SELECT COUNT(*)::int AS count FROM public.plate_reads WHERE camera_name='Legacy Delete'")).rows[0].count, 1); + const biReplacement = await repository.save({ camera_name: "Legacy Delete", source: "blue_iris" }); + await assert.rejects(() => repository.remove({ camera_name: "Legacy Delete" }), (error) => error.status === 409, "A stale implicit-camera action cannot delete a newly configured input"); + assert.equal((await processPlateRead({ camera: "Legacy Delete", plate_number: "RESTORE" })).status, 201); + assert.ok(await repository.get(biReplacement.input.id)); + assert.equal((await pool.query("SELECT connection_status FROM public.camera_inputs WHERE camera_name='Legacy Delete' AND deleted_at IS NOT NULL")).rows[0].connection_status, "deleted"); + await pool.query(migrations); + assert.equal(await repository.get(removable.id), null, "Repeated migrations preserve deletion"); console.log( - "PASS: real PostgreSQL schema/upgrade, existing Blue Iris ingestion, Axis HTTP/MQTT deduplication, corrections, immutable observations, image storage, finalization, carID reuse, manual review preservation, transaction rollback and retry.", + "PASS: real PostgreSQL schema/upgrade, Blue Iris compatibility, Axis HTTP/MQTT deduplication, corrections, images, finalization, rollback/retry, camera input deletion, in-flight synchronization, history preservation and safe replacement.", ); } catch (error) { console.error( diff --git a/test/camera-inputs.test.mjs b/test/camera-inputs.test.mjs index 6e4ba23..42e9ece 100644 --- a/test/camera-inputs.test.mjs +++ b/test/camera-inputs.test.mjs @@ -438,6 +438,7 @@ test("real MQTT QoS 1 acknowledges poison input and persists valid input before const sockets = new Set(); let socket; const acked = new Set(); + let unsubscribed = false; let persist; let received; const receivedGate = new Promise((resolve) => { @@ -473,6 +474,10 @@ test("real MQTT QoS 1 acknowledges poison input and persists valid input before resolve(); } if (packet.cmd === "puback") acked.add(packet.messageId); + if (packet.cmd === "unsubscribe") { + unsubscribed = packet.unsubscriptions.includes("axis/test/event"); + connection.write(mqttPacket.generate({ cmd: "unsuback", messageId: packet.messageId })); + } }); }); server.listen(0, "127.0.0.1"); @@ -536,6 +541,10 @@ test("real MQTT QoS 1 acknowledges poison input and persists valid input before while (!acked.has(7) && Date.now() < until) await new Promise((resolve) => setTimeout(resolve, 10)); assert.equal(acked.has(7), true); + runtime.repository.mqttInputs = async () => []; + await runtime.sync(); + assert.equal(unsubscribed, true, "Removing an input cancels its live broker subscription"); + assert.equal(runtime.clients.size, 0); } finally { persist(); await runtime.stop(); diff --git a/test/help-manual.test.mjs b/test/help-manual.test.mjs index c675fff..782b592 100644 --- a/test/help-manual.test.mjs +++ b/test/help-manual.test.mjs @@ -18,7 +18,7 @@ async function source(path) { } test("the user guide is structured, searchable, and role-aware", () => { - assert.equal(HELP_MANUAL.manualVersion, "3.29"); + assert.equal(HELP_MANUAL.manualVersion, "3.30"); assert.ok(HELP_MANUAL.sections.length >= 24); const ids = HELP_MANUAL.sections.map((section) => section.id); diff --git a/test/release-info.test.mjs b/test/release-info.test.mjs index 72203d6..6011fdb 100644 --- a/test/release-info.test.mjs +++ b/test/release-info.test.mjs @@ -24,8 +24,8 @@ test("release information resolves a commit-pinned deployment image", () => { }); assert.equal(release.version, "0.1.61"); - assert.equal(release.manualVersion, "3.29"); - assert.equal(release.manualUpdatedAt, "November 2, 2026"); + assert.equal(release.manualVersion, "3.30"); + assert.equal(release.manualUpdatedAt, "November 3, 2026"); assert.equal(release.gitSha, "8cd2fa8"); assert.equal(release.channel, "staging"); assert.equal(release.source, "commit-pinned image"); From 4fbdd2c71dab8e1db38455bef5e515f220fa461a Mon Sep 17 00:00:00 2001 From: prsmith777 Date: Wed, 4 Nov 2026 00:03:07 -0700 Subject: [PATCH 2/2] Prepare Community 0.1.62 camera input deletion release --- .github/ISSUE_TEMPLATE/bug_report.yml | 2 +- CHANGELOG.md | 7 +++++++ docs/COMMUNITY_PRODUCT_ROADMAP.md | 7 ++++++- docs/INSTALL.md | 2 +- docs/UPDATES.md | 19 ++++++++++++++++--- lib/help-manual.mjs | 2 +- lib/release-info.mjs | 10 +++++----- package.json | 2 +- test/release-info.test.mjs | 24 ++++++++++++------------ 9 files changed, 50 insertions(+), 25 deletions(-) diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml index 2bf3ea9..2f8727b 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.yml +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -16,7 +16,7 @@ body: attributes: label: ALPR Community version description: Find this under Settings → Release. Include the source revision there when reporting an installation or update problem. - placeholder: v0.1.61 + placeholder: v0.1.62 validations: required: true diff --git a/CHANGELOG.md b/CHANGELOG.md index eed633c..2a288a0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## 0.1.62 — 2026-11-04 + +- Add **Delete input** to Axis and Blue Iris camera input settings, including automatically discovered Blue Iris cameras, with a named confirmation dialog. +- Stop imports, revoke the deleted input's HTTP credential, retire its live MQTT subscription, and cancel queued detections and unfinished passages. Preserve saved plate reads, direction observations, images, shared brokers, and other camera inputs. +- Keep deleted inputs out of the settings list after refresh. Re-adding the same camera creates a fresh input identity and credential; stale deletion requests cannot remove its replacement. +- Add a tracked database migration and real PostgreSQL, MQTT and browser coverage for deletion, in-flight processing and history preservation. Update User Guide 3.30 and current install/update guidance; existing installations use the normal updater without manual SQL. + ## 0.1.61 — 2026-11-02 - Return HTTP 404 for Home Assistant display image IDs outside the supported PostgreSQL integer range. Reject these IDs before querying images, avoiding the previous HTTP 503 response. diff --git a/docs/COMMUNITY_PRODUCT_ROADMAP.md b/docs/COMMUNITY_PRODUCT_ROADMAP.md index 9848ab3..87ffd7f 100644 --- a/docs/COMMUNITY_PRODUCT_ROADMAP.md +++ b/docs/COMMUNITY_PRODUCT_ROADMAP.md @@ -1,6 +1,6 @@ # Community product roadmap -Last reviewed: November 2, 2026 +Last reviewed: November 4, 2026 ## Reliable upgrades and integration setup @@ -24,6 +24,11 @@ while preserving original observations and human review. Recognition remains independent of recording. Real Axis camera/firmware validation remains outstanding; see [Camera inputs](CAMERA_INPUTS.md) for supported formats and setup. +Community v0.1.62 adds camera input deletion for Axis and Blue Iris, including +automatically discovered Blue Iris cameras. Deletion stops imports and cancels +unfinished work while preserving saved plate history and images. Deleted inputs +stay hidden; explicitly adding the camera again creates a fresh input identity. + ## Adjustable table columns Community v0.1.58 adds draggable header dividers to Recognition Feed and Plate diff --git a/docs/INSTALL.md b/docs/INSTALL.md index 0732eea..962838b 100644 --- a/docs/INSTALL.md +++ b/docs/INSTALL.md @@ -64,7 +64,7 @@ Clone the canonical repository and detach at the exact stable release tag: ```bash git clone https://github.com/prsmith777/ALPR-Database-Community.git cd ALPR-Database-Community -git checkout --detach v0.1.61 +git checkout --detach v0.1.62 ./alpr-community install ``` diff --git a/docs/UPDATES.md b/docs/UPDATES.md index f25af49..e2c7bc2 100644 --- a/docs/UPDATES.md +++ b/docs/UPDATES.md @@ -47,7 +47,7 @@ shown on the GitHub Releases page, rather than deploying moving `main`: ```bash git clone https://github.com/prsmith777/ALPR-Database-Community.git cd ALPR-Database-Community -git checkout --detach v0.1.61 +git checkout --detach v0.1.62 ./alpr-community install ``` @@ -88,7 +88,7 @@ alpr_native_update() ( set -Eeuo pipefail download_dir="$(mktemp -d /tmp/alpr-maintenance-download.XXXXXX)" trap 'rm -rf -- "$download_dir"' EXIT - asset_base="https://github.com/prsmith777/ALPR-Database-Community/releases/download/v0.1.61" + asset_base="https://github.com/prsmith777/ALPR-Database-Community/releases/download/v0.1.62" curl -fLsS --retry 3 "$asset_base/community-maintenance.sh" -o "$download_dir/community-maintenance.sh" curl -fLsS --retry 3 "$asset_base/community-maintenance.sh.sha256" -o "$download_dir/community-maintenance.sh.sha256" (cd "$download_dir" && sha256sum --check --strict community-maintenance.sh.sha256) @@ -99,7 +99,7 @@ unset -f alpr_native_update ``` The launcher verifies the canonical repository and exact released tag, loads the -fixed tools outside your checkout, and asks for **INSTALL v0.1.61**. It uses the +fixed tools outside your checkout, and asks for **INSTALL v0.1.62**. It uses the same guarded backup/install workflow and does not reset or reinstall your system. It temporarily stops only this installation's matching per-user systemd update agent, then restarts it with the installed code. Keep the terminal open and do @@ -372,6 +372,19 @@ ALPR_UPDATE_CLEANUP=ALPR_UPDATE_CLEANUP These acknowledgements prevent an unattended typo from installing, accepting, rolling back, or deleting rollback assets. They are not passwords. +## v0.1.62: camera input deletion + +Use the normal Windows or Linux update workflow. The updater applies the new +tracked migration without manual SQL. Existing camera inputs remain enabled +and keep their saved configuration unless you explicitly delete them. + +Open **Settings > Integrations > Camera Inputs**, select **Delete input**, and +confirm the named camera. Imports stop, queued detections and unfinished passages +are cancelled, and saved plate history and images are kept. Deleted Blue Iris +camera names are ignored until explicitly added again. To reconnect any deleted +camera, use **Add camera input** and configure its new HTTP endpoint/credential +or MQTT subscription as appropriate. See [Camera inputs](CAMERA_INPUTS.md). + ## v0.1.61: Home Assistant image validation Use the normal update workflow. Oversized display image IDs now return HTTP 404 diff --git a/lib/help-manual.mjs b/lib/help-manual.mjs index 6e70d78..c811488 100644 --- a/lib/help-manual.mjs +++ b/lib/help-manual.mjs @@ -13,7 +13,7 @@ export const HELP_MANUAL = Object.freeze({ shortTitle: "User Guide", description: "A practical guide to using, configuring, and safely administering the portable Community application.", manualVersion: "3.30", - updatedAt: "November 3, 2026", + updatedAt: "November 4, 2026", coverageBaseline: "Published clean-history Community release with portable configuration and no private deployment controls.", filename: "ALPR-Database-Community-User-Guide.pdf", sections: [ diff --git a/lib/release-info.mjs b/lib/release-info.mjs index 05cada7..ddaa296 100644 --- a/lib/release-info.mjs +++ b/lib/release-info.mjs @@ -4,12 +4,12 @@ import builtReleaseMetadata from "./built-release-metadata.mjs"; import { HELP_MANUAL } from "./help-manual.mjs"; export const CURRENT_RELEASE_NOTES = Object.freeze({ - title: "Home Assistant display image validation", - publishedAt: "2026-11-02", + title: "Camera input deletion", + publishedAt: "2026-11-04", items: Object.freeze([ - "Return HTTP 404 for oversized Home Assistant display image IDs before querying images, replacing the previous HTTP 503 response.", - "Preserve read-only display access, camera scope, expiration, revocation and exact parent-origin restrictions.", - "Add integer-boundary unit, PostgreSQL and production-browser regression coverage; update User Guide 3.29. This patch adds no database migrations and uses the normal update workflow.", + "Delete Axis and Blue Iris camera inputs from Settings > Integrations > Camera Inputs, with confirmation and saved plate history and images preserved.", + "Stop imports, revoke the HTTP credential, retire the live MQTT subscription and cancel queued detections and unfinished passages. Deleted inputs stay hidden after refresh; re-adding a camera creates a fresh input identity and credential.", + "Add a tracked database migration and PostgreSQL, MQTT and browser regression coverage; update User Guide 3.30. Existing installations use the normal update workflow without manual SQL.", ]), }); diff --git a/package.json b/package.json index fd75292..db98819 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "blueiris-alpr-database", - "version": "0.1.61", + "version": "0.1.62", "private": true, "engines": { "node": ">=24.0.0 <25" diff --git a/test/release-info.test.mjs b/test/release-info.test.mjs index 6011fdb..c1ddabf 100644 --- a/test/release-info.test.mjs +++ b/test/release-info.test.mjs @@ -23,28 +23,28 @@ test("release information resolves a commit-pinned deployment image", () => { ALPR_RELEASE_CHANNEL: "staging", }); - assert.equal(release.version, "0.1.61"); + assert.equal(release.version, "0.1.62"); assert.equal(release.manualVersion, "3.30"); - assert.equal(release.manualUpdatedAt, "November 3, 2026"); + assert.equal(release.manualUpdatedAt, "November 4, 2026"); assert.equal(release.gitSha, "8cd2fa8"); assert.equal(release.channel, "staging"); assert.equal(release.source, "commit-pinned image"); assert.equal(release.readOnly, true); assert.equal( release.notes.title, - "Home Assistant display image validation" + "Camera input deletion" ); - assert.equal(release.notes.publishedAt, "2026-11-02"); + assert.equal(release.notes.publishedAt, "2026-11-04"); assert.ok(release.notes.items.length >= 3); const notes = release.notes.items.join(" "); - assert.match(notes, /HTTP 404/); - assert.match(notes, /oversized Home Assistant display image IDs/); - assert.match(notes, /before querying images/); - assert.match(notes, /read-only display access/); - assert.match(notes, /camera scope, expiration, revocation/); - assert.match(notes, /parent-origin restrictions/); - assert.match(notes, /no database migrations/); - assert.match(notes, /User Guide 3\.29/); + assert.match(notes, /Delete Axis and Blue Iris camera inputs/); + assert.match(notes, /saved plate history and images preserved/); + assert.match(notes, /revoke the HTTP credential/); + assert.match(notes, /MQTT subscription/); + assert.match(notes, /fresh input identity and credential/); + assert.match(notes, /tracked database migration/); + assert.match(notes, /without manual SQL/); + assert.match(notes, /User Guide 3\.30/); });