signal-bot/signal_bot/manage/routes_aliases.py
Krzysztof kuhy Rudnicki da016e1b94
Some checks failed
CI / check (push) Has been cancelled
CI / web (push) Has been cancelled
!dodaj lands in a queue; the management page approves it into the album
A photo sent to the chat no longer enters the album by itself. pack_add
strips it, checks it against the album and the queue, and writes it to
pending/ with a sidecar naming the people and labels the sender proposed;
the reply is "czeka na zatwierdzenie". The management page lists the queue
above the tagger, with the proposal pre-ticked, and Approve moves the file
in, mints the labels, records approved_at and asks the bot to rebuild its
table through /_reload -- the same publish path every other data change
takes, so PackHolder.reload is gone. A reload the bot refuses is reported
on the page, not rolled back: the photo is in the album either way.

The personal-data gate now reads pending/*.json too, so a label that is
still waiting for approval is forbidden in the tree already. The e2e run
boots the management page beside the bot with the same environment,
proves the queue is stripped and never reaches media/, approves it through
the real routes, and has !losowe answer with the photo afterwards without
a restart; exiftool is found through media_strip.locate() there rather
than PATH, which lacks vendor_perl on Arch.

!gadaj is dropped from !odcisz: it was within a typo of !dodaj, and the
nearest-command suggestion must never be a coin toss.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-09-04 22:55:39 +02:00

87 lines
2.9 KiB
Python

# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
"""The operator's aliases: one file, written here, proven by the bot.
An alias is data the command table is built from, so unlike a switch it
goes through ``POST /_reload``. The write and the reload are one step on
purpose: the file is put back exactly as it was whenever the bot does not
come back ``reloaded``, so what is on disk is always what the bot serves.
Otherwise a typo'd name would sit in the file, refused at every later
reload of anything else, until somebody worked out which edit did it.
"""
from __future__ import annotations
from typing import TYPE_CHECKING, Any
from fastapi import APIRouter, HTTPException, status
from pydantic import BaseModel
from signal_bot.custom_aliases import load, normalise, store
from signal_bot.groups import ConfigError
from signal_bot.manage.bot_reload import reload_bot
if TYPE_CHECKING:
from pathlib import Path
from signal_bot.manage.deps import ManageDeps
class AliasRequest(BaseModel):
"""Every custom trigger one command should have; empty removes them all."""
triggers: list[str]
def _restore(path: Path, previous: bytes | None) -> None:
"""Put the file back as it was before the write, byte for byte."""
if previous is None:
path.unlink(missing_ok=True)
else:
path.write_bytes(previous)
def router(deps: ManageDeps) -> APIRouter:
"""The table and the per-command PUT.
Args:
deps: The running app's configuration and shared HTTP client.
Returns:
A router to include in the management app.
"""
api = APIRouter(prefix="/api")
def current() -> dict[str, tuple[str, ...]]:
"""The file as it stands, or the reason it cannot be read (409)."""
try:
return load(deps.aliases_path)
except ConfigError as error:
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(error)) from error
@api.get("/aliases")
async def list_aliases() -> dict[str, dict[str, list[str]]]:
"""Every custom alias, by command name."""
return {"aliases": {name: list(words) for name, words in current().items()}}
@api.put("/aliases/{name}")
async def put_aliases(name: str, request: AliasRequest) -> dict[str, Any]:
"""Set one command's custom triggers and make them live, or change nothing."""
try:
words = normalise(request.triggers)
except ConfigError as error:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST, detail=str(error)
) from error
aliases = current()
path = deps.aliases_path
previous = path.read_bytes() if path.exists() else None
store(path, {**aliases, name: words})
try:
answer = await reload_bot(deps)
except HTTPException:
_restore(path, previous)
raise
return {"name": name, "triggers": list(words), **answer}
return api