Files
poorBird/server/src/poorbird/api/routes/captures.py
T
Thomas KarnerandClaude Opus 5 735cbcc5a0 Add the captures API and auth-checked image serving (SPEC 3.3)
The server half of the gallery. Listing and delivery land together because
neither is useful alone: a listing with no way to fetch bytes renders empty
tiles, and image serving with nothing to enumerate has no entry point.

Delivery follows the design deploy/Caddyfile already committed to. The app
authorises, then answers empty with X-Accel-Redirect and Caddy reads the file,
so a 3 MB JPEG never occupies a Python worker thread. There is no Caddy in
development, though, and that header reaching a browser is an empty 200 - every
image in the gallery blank, with nothing to explain it. So
POORBIRD_SERVE_IMAGES_DIRECTLY makes the app send the bytes instead.

The important part is what that flag does NOT do: the authorisation is the same
code either way, and the flag only changes how an already-authorised response
is finished. A separate unauthenticated file route "only reachable in dev" is
exactly the kind of thing that survives into production because it works, and
this deliberately is not one.

Both delivery paths refuse a path that escapes its root. captures.path is
written by our own ingest code so it should never happen, but "should never" is
not a security control and the cost of being wrong is serving an arbitrary file
off the server. The handoff path needs it just as much as the direct one - a
traversal in the header makes *Caddy* read the file, where the app never opens
it at all.

Keyset paging, not OFFSET. At 5000 captures a day OFFSET gets slower the
further back you scroll, which is the direction a gallery scrolls. The cursor
carries (received_at, id), and the id is in there for a specific reason: a
burst arrives inside the same fraction of a second, so ties are normal rather
than exotic, and a timestamp-only cursor would either repeat rows or skip them.
A gallery that loses a frame while you scroll is one you cannot trust.

Page size is fetched as limit + 1 rather than counted. It answers "is there
another page" without a COUNT over the whole filtered set, and the test for a
full final page covers the off-by-one that trick invites.

Filters cover the columns that have data: device, received-date range, kept,
reviewed, pre_trigger, trigger. Taxon and tag filters are in TODO Phase 3 and
deliberately absent - both need a join, and neither has anything to join to
until the observation editor and a seeded taxa table exist. A filter that can
only ever return nothing is worse than an absent one, because the UI offers it.

Dates filter on received_at and never captured_at_device, which is NULL
whenever the camera's clock was unsynced (API.md, X-Captured-At: 0). Filtering
on it would silently drop exactly those frames.

A missing thumbnail is 404 rather than a fallback to the full JPEG. The grid
needs to tell "queued" from "never decoded" and show a placeholder; a silent
fallback would make 200 tiles fetch a hundred times the bytes and still look
like it worked.

`poorbird check` now verifies the layout the handoff depends on: Caddy serves
the PARENT of both roots, so they have to be siblings named images/ and
thumbs/. Getting it wrong produces 404s from Caddy with nothing in the app's
log, which is the kind of thing worth failing a preflight check over rather
than discovering in a browser.

One test-quality fix worth naming: two delivery tests were inheriting their
mode from whatever server/.env happened to say, and broke the moment
SERVE_IMAGES_DIRECTLY=true was added there for the dev server's benefit. Both
modes are now named explicitly by a fixture, and conftest pins the production
default - a test that changes its answer because of an untracked file is not
testing the code.

Verified against the real server and the six real captures already in the dev
database: 401 before signing in, two pages of three with no overlap and correct
termination, device_name garden-feeder on the detail, a 1572-byte WebP with
RIFF magic and a 3469-byte JPEG with FFD8FF magic, and 401 on the image again
immediately after logout.

Mutation-tested the two claims that matter: removing the traversal guard and
reducing the cursor to a timestamp each failed exactly the tests written for
them. The traversal test escapes to a canary file that really exists just
outside the root rather than to /etc/passwd, which does not exist on this
machine and would have let the test pass for the wrong reason.

Tests: 257 -> 293.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-21 19:06:59 +02:00

288 lines
9.8 KiB
Python

"""The gallery: listing captures, and serving their bytes (SPEC 3.3).
Four routes, all behind a session. Any signed-in role may read the gallery --
that is what a ``viewer`` is for (SPEC 3.1) -- while a *device* never can: a
device token is scoped to the ingest endpoints and cannot resolve to a user at
all (api/deps.py vs api/userauth.py).
The image routes authorise and then hand off; see api/delivery.py for why the
bytes are Caddy's job in production and the app's in development.
"""
from __future__ import annotations
import base64
import binascii
import logging
import uuid
from datetime import UTC, datetime
from typing import Annotated
from fastapi import APIRouter, HTTPException, Query, Response, status
from sqlalchemy import Select, select, tuple_
from sqlalchemy.orm import selectinload
from ...models import Capture, Device
from ..delivery import IMAGE_URL_PREFIX, THUMB_URL_PREFIX, deliver
from ..deps import DbDep, SettingsDep
from ..ui_schemas import CaptureDetail, CapturePage, CaptureSummary
from ..userauth import CurrentUser
log = logging.getLogger(__name__)
router = APIRouter(prefix="/captures", tags=["gallery"])
# A virtualised grid asks for a screenful at a time. 200 is about four
# screens on a large monitor; beyond that the response is bigger than the
# scroll it serves.
DEFAULT_LIMIT = 50
MAX_LIMIT = 200
def _encode_cursor(capture: Capture) -> str:
"""Opaque-ish cursor: the sort key of the last row on this page.
Base64 so it does not look like something to hand-edit, not because it is
a secret -- it is a timestamp and a UUID the caller was just given.
"""
raw = f"{capture.received_at.astimezone(UTC).isoformat()}|{capture.id}"
return base64.urlsafe_b64encode(raw.encode()).decode()
def _decode_cursor(cursor: str) -> tuple[datetime, uuid.UUID]:
"""Parse a cursor, or 422.
Everything here is caller-supplied, so every failure mode is a bad request
rather than a 500: bad base64, bad UTF-8, a missing separator, an
unparseable timestamp, a malformed UUID.
"""
try:
raw = base64.urlsafe_b64decode(cursor.encode()).decode("utf-8")
stamp, _, ident = raw.partition("|")
if not ident:
raise ValueError("cursor has no id")
return datetime.fromisoformat(stamp), uuid.UUID(ident)
except (ValueError, binascii.Error, UnicodeDecodeError) as exc:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_CONTENT,
detail="invalid cursor",
) from exc
def _apply_filters(
stmt: Select,
*,
device_id: int | None,
received_from: datetime | None,
received_to: datetime | None,
kept: bool | None,
reviewed: bool | None,
pre_trigger: bool | None,
trigger: str | None,
) -> Select:
"""Filters over columns that exist today.
Taxon and tag filters are in TODO Phase 3 and are deliberately not here
yet: both need a join, and neither has any data to join to until the
observation editor and a seeded ``taxa`` table exist. A filter that can
only ever return nothing is worse than an absent one, because the UI would
offer it.
Dates filter on ``received_at``, never ``captured_at_device``, which is
NULL whenever the camera's clock was unsynced. Filtering on it would
silently drop exactly those frames.
"""
if device_id is not None:
stmt = stmt.where(Capture.device_id == device_id)
if received_from is not None:
stmt = stmt.where(Capture.received_at >= received_from)
if received_to is not None:
stmt = stmt.where(Capture.received_at <= received_to)
if kept is not None:
stmt = stmt.where(Capture.kept == kept)
if reviewed is not None:
stmt = stmt.where(Capture.reviewed == reviewed)
if pre_trigger is not None:
stmt = stmt.where(Capture.pre_trigger == pre_trigger)
if trigger is not None:
stmt = stmt.where(Capture.trigger == trigger)
return stmt
def _summary(capture: Capture) -> CaptureSummary:
return CaptureSummary(
id=capture.id,
device_id=capture.device_id,
received_at=capture.received_at,
captured_at_device=capture.captured_at_device,
width=capture.width,
height=capture.height,
bytes=capture.bytes,
trigger=capture.trigger,
pre_trigger=capture.pre_trigger,
burst_id=capture.burst_id,
burst_index=capture.burst_index,
burst_count=capture.burst_count,
reviewed=capture.reviewed,
kept=capture.kept,
has_thumb=capture.thumb_path is not None,
)
@router.get(
"",
response_model=CapturePage,
summary="List captures, newest first",
)
def list_captures(
db: DbDep,
_user: CurrentUser,
limit: Annotated[int, Query(ge=1, le=MAX_LIMIT)] = DEFAULT_LIMIT,
cursor: Annotated[str | None, Query()] = None,
device_id: Annotated[int | None, Query()] = None,
received_from: Annotated[datetime | None, Query()] = None,
received_to: Annotated[datetime | None, Query()] = None,
kept: Annotated[bool | None, Query()] = None,
reviewed: Annotated[bool | None, Query()] = None,
pre_trigger: Annotated[bool | None, Query()] = None,
trigger: Annotated[str | None, Query()] = None,
) -> CapturePage:
"""Newest first, keyset-paginated.
The sort is ``(received_at DESC, id DESC)``. The id is in the key not for
ordering's sake but because a burst arrives within the same fraction of a
second: on ties, a cursor that only carried the timestamp would either
repeat rows or skip them, and a gallery that loses a frame while scrolling
is a gallery you cannot trust.
"""
stmt = select(Capture)
stmt = _apply_filters(
stmt,
device_id=device_id,
received_from=received_from,
received_to=received_to,
kept=kept,
reviewed=reviewed,
pre_trigger=pre_trigger,
trigger=trigger,
)
if cursor is not None:
last_received, last_id = _decode_cursor(cursor)
# Row-value comparison, which maps onto the (device_id, received_at)
# index the same way a plain inequality would and needs no OR.
stmt = stmt.where(tuple_(Capture.received_at, Capture.id) < (last_received, last_id))
# One more than asked for, purely to learn whether another page exists
# without also running a COUNT over the whole filtered set.
rows = list(
db.scalars(
stmt.order_by(Capture.received_at.desc(), Capture.id.desc()).limit(limit + 1)
).all()
)
has_more = len(rows) > limit
page = rows[:limit]
return CapturePage(
items=[_summary(c) for c in page],
next_cursor=_encode_cursor(page[-1]) if has_more and page else None,
)
def _get_capture(db: DbDep, capture_id: uuid.UUID) -> Capture:
capture = db.get(Capture, capture_id)
if capture is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="no such capture")
return capture
@router.get(
"/{capture_id}",
response_model=CaptureDetail,
summary="One capture, with its observations and tags",
)
def get_capture(capture_id: uuid.UUID, db: DbDep, _user: CurrentUser) -> CaptureDetail:
capture = db.scalar(
select(Capture)
.where(Capture.id == capture_id)
# Eager, or rendering one capture with three observations is four
# queries and the pattern repeats per row the moment this is reused.
.options(
selectinload(Capture.observations),
selectinload(Capture.tags),
)
)
if capture is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="no such capture")
device = db.get(Device, capture.device_id)
return CaptureDetail(
**_summary(capture).model_dump(),
# The device row is ON DELETE CASCADE from captures, so this is only
# None in a torn state. Naming it rather than crashing.
device_name=device.name if device is not None else "unknown",
sha256=capture.sha256,
radar_state=capture.radar_state,
radar_distance_cm=capture.radar_distance_cm,
radar_energy=capture.radar_energy,
battery_mv=capture.battery_mv,
rssi=capture.rssi,
temp_c=capture.temp_c,
frame_seq=capture.frame_seq,
observations=list(capture.observations),
tags=list(capture.tags),
)
@router.get(
"/{capture_id}/image",
summary="The full JPEG, after an authorisation check",
response_class=Response,
)
def get_capture_image(
capture_id: uuid.UUID,
db: DbDep,
settings: SettingsDep,
_user: CurrentUser,
) -> Response:
capture = _get_capture(db, capture_id)
return deliver(
settings=settings,
root=settings.image_root,
url_prefix=IMAGE_URL_PREFIX,
relative=capture.path,
media_type="image/jpeg",
filename=f"{capture.id}.jpg",
)
@router.get(
"/{capture_id}/thumb",
summary="The 400px WebP thumbnail, after an authorisation check",
response_class=Response,
)
def get_capture_thumb(
capture_id: uuid.UUID,
db: DbDep,
settings: SettingsDep,
_user: CurrentUser,
) -> Response:
capture = _get_capture(db, capture_id)
if capture.thumb_path is None:
# Either the job has not run yet or the frame could not be decoded.
# 404 rather than falling back to the full image: a grid that quietly
# served 200 full-size JPEGs would look like it worked and would be a
# hundred times the bytes.
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="no thumbnail for this capture yet",
)
return deliver(
settings=settings,
root=settings.thumb_root,
url_prefix=THUMB_URL_PREFIX,
relative=capture.thumb_path,
media_type="image/webp",
filename=f"{capture.id}_400.webp",
)