mirror of
https://github.com/kuhyx/signal-bot.git
synced 2026-11-21 18:42:20 +01:00
A custom alias is data the command table is built from, so it cannot be a live switch like the ones already on the tab. Instead the management page writes aliases_custom.json in the bot's state directory and then asks the bot to reload, in one step: whenever the answer is anything but `reloaded` -- a word another command has, a name no command has, a bot still connecting -- the file is restored byte for byte and the bot's own reason is shown next to the field. What is on disk is therefore always what the bot serves, and a typo cannot sit in the file poisoning every later reload. The registry appends the operator's words to the shipped list at registration, which keeps `!pomoc` on the shipped spelling and routes the new words through the same clash check as aliases.json. An alias for a name no command has fails the whole build (ConfigError -> `kept`), because a silently ignored entry is how a file drifts. The tagger treats custom aliases as reserved words too, so a person cannot be given one. registry.py crossed the 250-line cap and now re-exports the record and the error types from command.py; the bot's state directory lookup, previously duplicated in pack.py and the suggestions export, is state_dir.py. Proven end to end: !e2ekot is unknown, the file is written and reload.sh runs, !e2ekot posts a cat, a file naming a command that does not exist is refused with 409 and the previous table still answers. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
193 lines
7.1 KiB
Python
193 lines
7.1 KiB
Python
# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
|
|
"""Adding somebody to the roster of an album that already has one.
|
|
|
|
The tagger could only ever write ``people.json`` from empty: the setup form
|
|
appeared when there were no people, ``Album.setup`` overwrote the file whole,
|
|
and the keys were handed out by position -- ``p{len + 1}``. Together those
|
|
mean the obvious thing (edit the list to insert somebody) renumbers everyone
|
|
after them, and every ``tags.json`` entry then points at the wrong person,
|
|
silently, with no error at any layer. So in practice a roster was written once
|
|
and never touched, and a new face meant hand-editing JSON.
|
|
|
|
This module is the append-only path instead. Keys come from the highest number
|
|
in use, never the count -- the same rule ``pack_custom.next_key`` follows, and
|
|
for the same reason: deleting ``p3`` by hand must not let a later add reuse the
|
|
key and inherit its photos.
|
|
|
|
Two checks before anything is written, and they are different in kind:
|
|
|
|
* **Against the album**, by writing the file and then calling ``pack_load.load``
|
|
on it. That is the whole of pack_load's validation -- trigger shape, no
|
|
digits, uniqueness after folding, across people and combos and custom labels
|
|
-- rather than a second copy of it here that could drift. A failure rolls the
|
|
file back to the bytes it had.
|
|
* **Against the bot's own commands**, from ``aliases.json``. ``load`` cannot see
|
|
those: a person triggered by ``!losuj`` is a perfectly valid pack that
|
|
quietly shadows ``!random`` at run time. This is the same collision
|
|
``pack_add`` refuses a custom label for.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
from pathlib import Path
|
|
from typing import TYPE_CHECKING, Any, Final
|
|
|
|
from signal_bot.custom_aliases import default_path as custom_path
|
|
from signal_bot.custom_aliases import load as load_custom
|
|
from signal_bot.folding import fold
|
|
from signal_bot.groups import ConfigError
|
|
from signal_bot.pack import PEOPLE_FILE
|
|
from signal_bot.pack_load import load
|
|
from signal_bot.pack_store import write_json
|
|
|
|
if TYPE_CHECKING:
|
|
from collections.abc import Sequence
|
|
|
|
ALIAS_FILE: Final = Path(__file__).with_name("aliases.json")
|
|
|
|
# The person-key shape, mirroring pack_custom.KEY_PATTERN for custom tags.
|
|
KEY_PREFIX: Final = "p"
|
|
|
|
|
|
def reserved() -> frozenset[str]:
|
|
"""Every folded word that is already one of the bot's own commands.
|
|
|
|
The shipped aliases and the operator's own, because both become
|
|
triggers at the same table -- and the registry would refuse the clash
|
|
at the next reload, which is later and less clear than refusing here.
|
|
"""
|
|
document = json.loads(ALIAS_FILE.read_text(encoding="utf-8"))
|
|
shipped = (
|
|
trigger
|
|
for name, triggers in document.items()
|
|
if not name.startswith("_")
|
|
for trigger in triggers
|
|
)
|
|
custom = (trigger for words in load_custom(custom_path()).values() for trigger in words)
|
|
return frozenset(fold(trigger) for trigger in (*shipped, *custom))
|
|
|
|
|
|
def next_key(people: Sequence[dict[str, Any]]) -> str:
|
|
"""The key a new person would take, without taking it.
|
|
|
|
One past the highest number in use rather than the count, so a roster
|
|
somebody has edited by hand cannot make an add reuse a retired key.
|
|
"""
|
|
used = [
|
|
int(key.removeprefix(KEY_PREFIX))
|
|
for person in people
|
|
if isinstance(key := person.get("key"), str)
|
|
and key.startswith(KEY_PREFIX)
|
|
and key.removeprefix(KEY_PREFIX).isdigit()
|
|
]
|
|
return f"{KEY_PREFIX}{max(used, default=0) + 1}"
|
|
|
|
|
|
def normalise(triggers: Sequence[str]) -> list[str]:
|
|
"""Trigger spellings as they are stored: "!"-prefixed, blanks dropped.
|
|
|
|
People type "alfa" as often as "!alfa" and the difference is not one
|
|
worth an error message.
|
|
"""
|
|
cleaned = []
|
|
for raw in triggers:
|
|
word = raw.strip()
|
|
if word:
|
|
cleaned.append(word if word.startswith("!") else f"!{word}")
|
|
return cleaned
|
|
|
|
|
|
def add_person(directory: Path, triggers: Sequence[str]) -> str:
|
|
"""Append one person to the roster and prove the album still loads.
|
|
|
|
Args:
|
|
directory: The album directory.
|
|
triggers: What somebody types to get this person's photos.
|
|
|
|
Returns:
|
|
The key the new person was given.
|
|
|
|
Raises:
|
|
ConfigError: The triggers are empty, collide with one of the bot's
|
|
own commands, or leave the album in a state that does not load.
|
|
The manifest is unchanged in every one of those cases.
|
|
"""
|
|
wanted = normalise(triggers)
|
|
if not wanted:
|
|
msg = "a person needs at least one trigger"
|
|
raise ConfigError(msg)
|
|
taken = reserved() & {fold(trigger) for trigger in wanted}
|
|
if taken:
|
|
msg = f"already a command: {sorted(taken)}"
|
|
raise ConfigError(msg)
|
|
path = directory / PEOPLE_FILE
|
|
document = _document(path)
|
|
people = list(document.get("people", []))
|
|
key = next_key(people)
|
|
document["people"] = [*people, {"key": key, "triggers": wanted}]
|
|
return _commit(directory, path, document, key)
|
|
|
|
|
|
def merge(document: dict[str, Any], people: Sequence[dict[str, Any]]) -> list[dict[str, Any]]:
|
|
"""The roster with ``people`` folded in, existing keys left where they are.
|
|
|
|
Used by the setup form, which used to replace the file wholesale. Anyone
|
|
already present keeps their key and gains any new triggers; anyone new is
|
|
appended with a fresh key.
|
|
"""
|
|
merged = [dict(person) for person in document.get("people", [])]
|
|
by_key = {person.get("key"): person for person in merged}
|
|
for person in people:
|
|
existing = by_key.get(person.get("key"))
|
|
if existing is None:
|
|
fresh = dict(person)
|
|
fresh["key"] = next_key(merged)
|
|
merged.append(fresh)
|
|
by_key[fresh["key"]] = fresh
|
|
continue
|
|
seen = set(existing.get("triggers", []))
|
|
existing["triggers"] = [
|
|
*existing.get("triggers", []),
|
|
*(t for t in person.get("triggers", []) if t not in seen),
|
|
]
|
|
return merged
|
|
|
|
|
|
def _commit(directory: Path, path: Path, document: dict[str, Any], key: str) -> str:
|
|
"""Write the roster, or put back exactly what was there and re-raise."""
|
|
previous = path.read_bytes() if path.exists() else None
|
|
write_json(path, document)
|
|
try:
|
|
load(directory)
|
|
except ConfigError:
|
|
if previous is None:
|
|
path.unlink(missing_ok=True)
|
|
else:
|
|
path.write_bytes(previous)
|
|
raise
|
|
return key
|
|
|
|
|
|
def _document(path: Path) -> dict[str, Any]:
|
|
"""The roster as it stands.
|
|
|
|
Strict, unlike the ledger's reader: this file *is* the album's manifest,
|
|
and appending to a document that failed to parse would write a roster
|
|
that silently dropped everyone already in it.
|
|
|
|
Raises:
|
|
ConfigError: The file is not a JSON object.
|
|
"""
|
|
if not path.exists():
|
|
return {}
|
|
try:
|
|
document = json.loads(path.read_text(encoding="utf-8"))
|
|
except json.JSONDecodeError as error:
|
|
msg = f"{path.name} is not valid JSON: {error}"
|
|
raise ConfigError(msg) from error
|
|
if not isinstance(document, dict):
|
|
msg = f"{path.name} is not an object"
|
|
raise ConfigError(msg)
|
|
return document
|