# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence. """The photo tagger, absorbed. These are ``tool/tagger.py``'s seven routes, moved here so they are inside the coverage gate rather than beside it -- which is the reason an unconditional ImportError once sat in that file through two releases. The behaviour is unchanged, deliberately: ``Album`` already deals in ``KeyError`` and ``ConfigError`` so routes can translate them, and the media route is still indexed by integer. That last one is not a style choice. A filename supplied by a client is a path, and this directory holds private photographs. """ from __future__ import annotations from typing import TYPE_CHECKING, Any from fastapi import APIRouter, HTTPException, status from fastapi.responses import FileResponse from signal_bot.groups import ConfigError from signal_bot.manage.routes_status import live_groups from signal_bot.pack import MEDIA_DIR if TYPE_CHECKING: from signal_bot.manage.deps import ManageDeps def roster(api: APIRouter, deps: ManageDeps) -> None: """The two endpoints that write people.json. Split from :func:`router` along the seam that matters: everything here can refuse, and a refusal has to reach the page rather than the next restart. Args: api: The router to register on. deps: The running app's album. """ @api.post("/setup") async def setup(payload: dict[str, Any]) -> dict[str, str]: """Write the roster, then prove the bot could load it.""" try: deps.album.setup( list(payload.get("groups", [])), list(payload.get("people", [])), list(payload.get("combos", [])), ) except ConfigError as error: # Straight into the page: a manifest the bot would refuse should # be fixed here, in the form, not found at the next restart. raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail=str(error) ) from error return {"status": "ok"} @api.post("/person") async def person(payload: dict[str, Any]) -> dict[str, str]: """Add one person mid-session, and return the key they were given.""" # Mid-session, not only at setup: the reason to add somebody is # usually a photo of them already on the screen. try: key = deps.album.add_person([str(t) for t in payload.get("triggers", [])]) except ConfigError as error: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail=str(error) ) from error return {"status": "ok", "key": key} def router(deps: ManageDeps) -> APIRouter: """Every album endpoint the page needs. Args: deps: The running app's album and HTTP client. Returns: A router to include in the management app. """ api = APIRouter(prefix="/api/album") roster(api, deps) @api.get("/state") async def state() -> dict[str, Any]: """Everything the tagging view draws itself from.""" return {**deps.album.state(), "known_groups": await live_groups(deps)} @api.post("/tag") async def tag(payload: dict[str, Any]) -> dict[str, str]: """Record who is in one file.""" try: deps.album.tag(str(payload["file"]), [str(key) for key in payload.get("keys", [])]) except KeyError as error: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(error)) from error return {"status": "ok"} @api.get("/summary") async def summary() -> dict[str, list[str]]: """What each command would answer with, and what is still untagged.""" return {"lines": deps.album.summary()} @api.get("/media/{index}") async def media(index: int) -> FileResponse: """One item, by position in the album.""" # By index, never by a name the page sends back: a filename from a # client is a path, and portraits.path_for exists for the same reason. files = deps.album.files if not 0 <= index < len(files): raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="no such item") return FileResponse(deps.album.directory / MEDIA_DIR / files[index]) return api