feat: add REST API endpoints for events, known objects, and settings

Routes package with CRUD endpoints: event listing/filtering/tagging/dismissal,
known object management with thumbnails, settings CRUD, and stats.
64 tests passing.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-03-07 17:09:21 -06:00
parent 031b9eaaec
commit b7c729d331
7 changed files with 1124 additions and 7 deletions
View File
+226
View File
@@ -0,0 +1,226 @@
"""Event API endpoints for frigate-notify v2."""
import base64
import logging
from typing import Optional
from fastapi import APIRouter, HTTPException, Query
from fastapi.responses import Response
from database import get_connection
from models import EventResponse, TagEventRequest
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/api/events", tags=["events"])
@router.get("", response_model=list[EventResponse])
async def list_events(
camera: Optional[str] = Query(default=None),
label: Optional[str] = Query(default=None),
status: Optional[str] = Query(default=None),
limit: int = Query(default=50, ge=1, le=500),
offset: int = Query(default=0, ge=0),
):
"""List events with optional filters and pagination.
Returns events without snapshot/embedding BLOBs but with has_snapshot bool.
Joins to known_objects for matched_object_name.
"""
conn = get_connection()
query = """
SELECT
e.id, e.frigate_event_id, e.camera, e.label, e.score,
CASE WHEN e.snapshot IS NOT NULL THEN 1 ELSE 0 END AS has_snapshot,
e.match_status, e.matched_object_id,
ko.name AS matched_object_name,
e.match_confidence, e.ai_description, e.notified, e.created_at
FROM events e
LEFT JOIN known_objects ko ON e.matched_object_id = ko.id
"""
conditions = []
params: list = []
if camera:
conditions.append("e.camera = ?")
params.append(camera)
if label:
conditions.append("e.label = ?")
params.append(label)
if status:
conditions.append("e.match_status = ?")
params.append(status)
if conditions:
query += " WHERE " + " AND ".join(conditions)
query += " ORDER BY e.created_at DESC LIMIT ? OFFSET ?"
params.extend([limit, offset])
cursor = conn.execute(query, params)
rows = cursor.fetchall()
return [
EventResponse(
id=row["id"],
frigate_event_id=row["frigate_event_id"],
camera=row["camera"],
label=row["label"],
score=row["score"],
has_snapshot=bool(row["has_snapshot"]),
match_status=row["match_status"],
matched_object_id=row["matched_object_id"],
matched_object_name=row["matched_object_name"],
match_confidence=row["match_confidence"],
ai_description=row["ai_description"],
notified=bool(row["notified"]),
created_at=row["created_at"],
)
for row in rows
]
@router.get("/{event_id}", response_model=EventResponse)
async def get_event(event_id: int):
"""Get a single event detail. Includes base64-encoded snapshot if exists."""
conn = get_connection()
cursor = conn.execute(
"""
SELECT
e.id, e.frigate_event_id, e.camera, e.label, e.score,
e.snapshot,
CASE WHEN e.snapshot IS NOT NULL THEN 1 ELSE 0 END AS has_snapshot,
e.match_status, e.matched_object_id,
ko.name AS matched_object_name,
e.match_confidence, e.ai_description, e.notified, e.created_at
FROM events e
LEFT JOIN known_objects ko ON e.matched_object_id = ko.id
WHERE e.id = ?
""",
(event_id,),
)
row = cursor.fetchone()
if not row:
raise HTTPException(status_code=404, detail="Event not found")
snapshot_b64 = None
if row["snapshot"] is not None:
snapshot_b64 = base64.b64encode(row["snapshot"]).decode("ascii")
return EventResponse(
id=row["id"],
frigate_event_id=row["frigate_event_id"],
camera=row["camera"],
label=row["label"],
score=row["score"],
has_snapshot=bool(row["has_snapshot"]),
snapshot_base64=snapshot_b64,
match_status=row["match_status"],
matched_object_id=row["matched_object_id"],
matched_object_name=row["matched_object_name"],
match_confidence=row["match_confidence"],
ai_description=row["ai_description"],
notified=bool(row["notified"]),
created_at=row["created_at"],
)
@router.get("/{event_id}/snapshot")
async def get_event_snapshot(event_id: int):
"""Return raw JPEG snapshot for an event. 404 if no snapshot."""
conn = get_connection()
cursor = conn.execute(
"SELECT snapshot FROM events WHERE id = ?",
(event_id,),
)
row = cursor.fetchone()
if not row:
raise HTTPException(status_code=404, detail="Event not found")
if row["snapshot"] is None:
raise HTTPException(status_code=404, detail="No snapshot available")
return Response(content=row["snapshot"], media_type="image/jpeg")
@router.post("/{event_id}/tag")
async def tag_event(event_id: int, body: TagEventRequest):
"""Tag an event as a known object.
Either provide known_object_id to link to an existing object,
or provide name + type to create a new known object.
If the event has an embedding, store it in the embeddings table.
"""
conn = get_connection()
# Verify event exists
cursor = conn.execute(
"SELECT id, embedding FROM events WHERE id = ?",
(event_id,),
)
event_row = cursor.fetchone()
if not event_row:
raise HTTPException(status_code=404, detail="Event not found")
known_object_id = body.known_object_id
if known_object_id is not None:
# Verify the known object exists
cursor = conn.execute(
"SELECT id FROM known_objects WHERE id = ?",
(known_object_id,),
)
if not cursor.fetchone():
raise HTTPException(status_code=404, detail="Known object not found")
elif body.name and body.type:
# Create a new known object
cursor = conn.execute(
"INSERT INTO known_objects (name, type) VALUES (?, ?)",
(body.name, body.type),
)
known_object_id = cursor.lastrowid
conn.commit()
else:
raise HTTPException(
status_code=400,
detail="Must provide either known_object_id or both name and type",
)
# If event has an embedding, store it in the embeddings table
if event_row["embedding"] is not None:
conn.execute(
"INSERT INTO embeddings (known_object_id, embedding) VALUES (?, ?)",
(known_object_id, event_row["embedding"]),
)
# Update event
conn.execute(
"""UPDATE events
SET match_status = 'known',
matched_object_id = ?,
match_confidence = 1.0
WHERE id = ?""",
(known_object_id, event_id),
)
conn.commit()
return {"status": "ok", "matched_object_id": known_object_id}
@router.post("/{event_id}/dismiss")
async def dismiss_event(event_id: int):
"""Set event match_status to 'unknown'."""
conn = get_connection()
cursor = conn.execute("SELECT id FROM events WHERE id = ?", (event_id,))
if not cursor.fetchone():
raise HTTPException(status_code=404, detail="Event not found")
conn.execute(
"UPDATE events SET match_status = 'unknown' WHERE id = ?",
(event_id,),
)
conn.commit()
return {"status": "ok"}
+177
View File
@@ -0,0 +1,177 @@
"""Known objects API endpoints for frigate-notify v2."""
import logging
from typing import Optional
from fastapi import APIRouter, HTTPException, Query
from fastapi.responses import Response
from database import get_connection
from models import KnownObjectResponse, KnownObjectUpdate
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/api/known-objects", tags=["known-objects"])
@router.get("")
async def list_known_objects(
type: Optional[str] = Query(default=None, pattern="^(person|vehicle|pet)$"),
):
"""List all known objects with embedding_count. Optional type filter."""
conn = get_connection()
query = """
SELECT
ko.id, ko.name, ko.type, ko.action,
ko.created_at, ko.updated_at,
COUNT(e.id) AS embedding_count
FROM known_objects ko
LEFT JOIN embeddings e ON ko.id = e.known_object_id
"""
params: list = []
if type:
query += " WHERE ko.type = ?"
params.append(type)
query += " GROUP BY ko.id ORDER BY ko.name"
cursor = conn.execute(query, params)
rows = cursor.fetchall()
return [
{
"id": row["id"],
"name": row["name"],
"type": row["type"],
"action": row["action"],
"created_at": row["created_at"],
"updated_at": row["updated_at"],
"embedding_count": row["embedding_count"],
}
for row in rows
]
@router.get("/{object_id}")
async def get_known_object(object_id: int):
"""Get a single known object with list of its embeddings (id, created_at only)."""
conn = get_connection()
cursor = conn.execute(
"SELECT id, name, type, action, created_at, updated_at FROM known_objects WHERE id = ?",
(object_id,),
)
row = cursor.fetchone()
if not row:
raise HTTPException(status_code=404, detail="Known object not found")
# Get embeddings list
emb_cursor = conn.execute(
"SELECT id, created_at FROM embeddings WHERE known_object_id = ? ORDER BY created_at",
(object_id,),
)
embeddings = [
{"id": e["id"], "created_at": e["created_at"]} for e in emb_cursor.fetchall()
]
return {
"id": row["id"],
"name": row["name"],
"type": row["type"],
"action": row["action"],
"created_at": row["created_at"],
"updated_at": row["updated_at"],
"embeddings": embeddings,
}
@router.get("/{object_id}/thumbnails/{embedding_id}")
async def get_embedding_thumbnail(object_id: int, embedding_id: int):
"""Return raw JPEG thumbnail from embeddings table."""
conn = get_connection()
cursor = conn.execute(
"SELECT thumbnail FROM embeddings WHERE id = ? AND known_object_id = ?",
(embedding_id, object_id),
)
row = cursor.fetchone()
if not row:
raise HTTPException(status_code=404, detail="Embedding not found")
if row["thumbnail"] is None:
raise HTTPException(status_code=404, detail="No thumbnail available")
return Response(content=row["thumbnail"], media_type="image/jpeg")
@router.put("/{object_id}")
async def update_known_object(object_id: int, body: KnownObjectUpdate):
"""Update name/type/action for a known object. Sets updated_at."""
conn = get_connection()
cursor = conn.execute(
"SELECT id FROM known_objects WHERE id = ?",
(object_id,),
)
if not cursor.fetchone():
raise HTTPException(status_code=404, detail="Known object not found")
updates = []
params: list = []
if body.name is not None:
updates.append("name = ?")
params.append(body.name)
if body.type is not None:
updates.append("type = ?")
params.append(body.type)
if body.action is not None:
updates.append("action = ?")
params.append(body.action)
if not updates:
raise HTTPException(status_code=400, detail="No fields to update")
updates.append("updated_at = CURRENT_TIMESTAMP")
params.append(object_id)
conn.execute(
f"UPDATE known_objects SET {', '.join(updates)} WHERE id = ?",
params,
)
conn.commit()
# Return the updated object
cursor = conn.execute(
"SELECT id, name, type, action, created_at, updated_at FROM known_objects WHERE id = ?",
(object_id,),
)
row = cursor.fetchone()
return KnownObjectResponse(
id=row["id"],
name=row["name"],
type=row["type"],
action=row["action"],
created_at=row["created_at"],
updated_at=row["updated_at"],
)
@router.delete("/{object_id}")
async def delete_known_object(object_id: int):
"""Delete a known object. Embeddings cascade delete automatically."""
conn = get_connection()
cursor = conn.execute(
"SELECT id FROM known_objects WHERE id = ?",
(object_id,),
)
if not cursor.fetchone():
raise HTTPException(status_code=404, detail="Known object not found")
conn.execute("DELETE FROM known_objects WHERE id = ?", (object_id,))
conn.commit()
return {"status": "ok"}
+78
View File
@@ -0,0 +1,78 @@
"""Settings and stats API endpoints for frigate-notify v2."""
import logging
from datetime import date
from fastapi import APIRouter
from config import config
from database import get_connection
from models import StatsResponse
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/api", tags=["settings"])
@router.get("/settings")
async def get_settings():
"""Return all settings from DB plus runtime config values."""
conn = get_connection()
cursor = conn.execute("SELECT key, value FROM settings")
db_settings = {row["key"]: row["value"] for row in cursor.fetchall()}
# Merge with runtime config values
return {
**db_settings,
"recognition_threshold_high": config.RECOGNITION_THRESHOLD_HIGH,
"recognition_threshold_low": config.RECOGNITION_THRESHOLD_LOW,
"rate_limit_seconds": config.RATE_LIMIT_SECONDS,
"allowed_labels": list(config.ALLOWED_LABELS),
"min_score": config.MIN_SCORE,
}
@router.put("/settings")
async def update_settings(body: dict):
"""Accept dict body, upsert each key/value into settings table."""
conn = get_connection()
for key, value in body.items():
conn.execute(
"INSERT INTO settings (key, value) VALUES (?, ?) "
"ON CONFLICT(key) DO UPDATE SET value = excluded.value",
(key, str(value)),
)
conn.commit()
return {"status": "ok"}
@router.get("/stats", response_model=StatsResponse)
async def get_stats():
"""Return event and object counts."""
conn = get_connection()
total = conn.execute("SELECT COUNT(*) FROM events").fetchone()[0]
known = conn.execute(
"SELECT COUNT(*) FROM events WHERE match_status = 'known'"
).fetchone()[0]
unknown = conn.execute(
"SELECT COUNT(*) FROM events WHERE match_status = 'unknown'"
).fetchone()[0]
unreviewed = conn.execute(
"SELECT COUNT(*) FROM events WHERE match_status = 'unreviewed'"
).fetchone()[0]
objects_count = conn.execute("SELECT COUNT(*) FROM known_objects").fetchone()[0]
today = date.today().isoformat()
events_today = conn.execute(
"SELECT COUNT(*) FROM events WHERE DATE(created_at) = ?",
(today,),
).fetchone()[0]
return StatsResponse(
total_events=total,
known_matches=known,
unknown_events=unknown,
unreviewed=unreviewed,
known_objects_count=objects_count,
events_today=events_today,
)