mirror of
https://github.com/kuhyx/signal-bot.git
synced 2026-11-10 18:17:02 +01:00
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>
235 lines
8.9 KiB
Python
235 lines
8.9 KiB
Python
# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
|
|
"""``!add_photo``: propose an attachment for the album, tagged, from the chat.
|
|
|
|
Send a photo captioned ``!add_photo alfa beta`` and it lands in the album's
|
|
approval queue under both labels. It reaches the album -- and its commands
|
|
-- once somebody approves it on the management page; until then the group
|
|
is told it is waiting, and nothing else.
|
|
|
|
Three properties hold and none of them is incidental:
|
|
|
|
* **No name travels.** Labels become keys in the resolver, at the dispatcher,
|
|
before the line that logs the command name. A label nobody has becomes a
|
|
provisional token (``new1``) that means nothing outside this process; the
|
|
word itself goes into the queue's sidecar, inside the album's 0700, and is
|
|
minted as a custom tag only when the photo is approved.
|
|
* **Nothing unproven is stored.** Sniffed by magic bytes, stripped, and then
|
|
*verified* by reading the output back -- an exit code is what lied last time.
|
|
The two formats exiftool cannot write are the documented exception.
|
|
* **Nothing reaches the album without a human.** The queue is a directory the
|
|
bot only ever writes; every path from it into ``media/`` goes through
|
|
``pack_pending.approve``, which the bot's own process never calls.
|
|
|
|
The attachment is deleted from signal-cli's own store either way. That copy
|
|
lives outside the album's 0700 and is pre-existing for every photo the group
|
|
sends, but this is the first path that ingests one deliberately.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import logging
|
|
from typing import TYPE_CHECKING, Final
|
|
|
|
from signal_bot.folding import fold
|
|
from signal_bot.pack import MAX_NAMES, options_for
|
|
from signal_bot.pack_command import NAME_PREFIX, UNKNOWN
|
|
from signal_bot.pack_ingest import ingest
|
|
from signal_bot.pack_pending import Pending, queue
|
|
from signal_bot.pack_replies import (
|
|
ALREADY_QUEUED,
|
|
ALREADY_THERE,
|
|
AMBIGUOUS,
|
|
DUPLICATE_ONLY,
|
|
NEED_LABEL,
|
|
NEED_PHOTO,
|
|
QUEUED,
|
|
QUEUED_ONLY,
|
|
REJECTED,
|
|
TOO_MANY,
|
|
)
|
|
|
|
if TYPE_CHECKING:
|
|
from signal_bot.context import CommandContext
|
|
from signal_bot.media_strip import Stripper
|
|
from signal_bot.pack import Pack
|
|
from signal_bot.pack_holder import PackHolder
|
|
from signal_bot.pack_ingest import Ingested
|
|
from signal_bot.registry import ArgResolver, CommandRegistry, Handler
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
COMMAND_NAME: Final = f"{NAME_PREFIX}add"
|
|
DESCRIPTION: Final = "zgłasza załączone zdjęcie do albumu z etykietami; trafia tam po zatwierdzeniu"
|
|
|
|
# A label nobody has yet travels from the resolver to the handler as one of
|
|
# these, never as itself. Custom keys are ``t<n>`` and people ``p<n>``, so a
|
|
# token cannot be mistaken for either.
|
|
NEW_PREFIX: Final = "new"
|
|
# How many unclaimed tokens are kept. A token goes unclaimed when the
|
|
# dispatcher resolves the message and then does not run the handler -- a
|
|
# muted sender, mostly -- and without a cap those would accrue for ever.
|
|
PENDING_LIMIT: Final = 64
|
|
|
|
|
|
class AddResolver:
|
|
"""Turns typed labels into keys, standing in a token for a label nobody has.
|
|
|
|
``Bot.listen`` runs every frame in its own task, so two messages can be
|
|
between resolve and handle at once. Each new label therefore gets a
|
|
token of its own from a counter that never repeats, and the handler
|
|
claims exactly its own message's tokens; nothing here is per "current
|
|
message".
|
|
"""
|
|
|
|
def __init__(self, holder: PackHolder, registry: CommandRegistry) -> None:
|
|
"""Read labels through the holder, so a fresh tag resolves at once.
|
|
|
|
The registry is held so a new label can refuse a word that is already
|
|
a command. Without that, "!add_photo kot" proposes the label "kot",
|
|
and scripts/personal_data_sources feeds proposed labels to the
|
|
personal-data gate -- which would then find "kot" in aliases.json and
|
|
refuse every commit, for ever, until somebody hand-edited an album
|
|
nobody can see. Anyone in the group could do that by accident.
|
|
"""
|
|
self._holder = holder
|
|
self._registry = registry
|
|
self._labels: dict[str, str] = {}
|
|
self._minted = 0
|
|
|
|
def __call__(self, words: tuple[str, ...]) -> tuple[str, ...]:
|
|
"""Resolve every label to a key or a token."""
|
|
pack = self._holder.pack
|
|
tokens: dict[str, str] = {}
|
|
keys: list[str] = []
|
|
for word in words:
|
|
keys.extend(self._resolve(pack, tokens, word))
|
|
return tuple(keys)
|
|
|
|
def _resolve(self, pack: Pack, tokens: dict[str, str], word: str) -> list[str]:
|
|
"""One label: a person, a combination, a known tag, or a new one."""
|
|
options = options_for(pack, word)
|
|
if options is not None:
|
|
# An "any_of" combination means two different answers and there
|
|
# is nothing to pick between when tagging, so it is refused
|
|
# rather than guessed at.
|
|
return [UNKNOWN] if len(options) > 1 else sorted(options[0])
|
|
existing = pack.custom.resolve(word)
|
|
if existing is not None:
|
|
return [existing]
|
|
if self._registry.resolve(f"!{word}") is not None:
|
|
# Already a command word, so it is public, and minting it would
|
|
# make the word mean two things at once.
|
|
return [UNKNOWN]
|
|
folded = fold(word)
|
|
if folded not in tokens:
|
|
tokens[folded] = self._token(word)
|
|
return [tokens[folded]]
|
|
|
|
def _token(self, word: str) -> str:
|
|
"""A fresh token for ``word``, dropping the oldest unclaimed one at the cap."""
|
|
self._minted += 1
|
|
token = f"{NEW_PREFIX}{self._minted}"
|
|
self._labels[token] = word
|
|
while len(self._labels) > PENDING_LIMIT:
|
|
del self._labels[next(iter(self._labels))]
|
|
return token
|
|
|
|
def take(self, keys: tuple[str, ...]) -> tuple[tuple[str, ...], tuple[str, ...]]:
|
|
"""Split a message's keys into album keys and the labels behind its tokens."""
|
|
known: list[str] = []
|
|
labels: list[str] = []
|
|
for key in keys:
|
|
label = self._labels.pop(key, None)
|
|
if label is None:
|
|
known.append(key)
|
|
else:
|
|
labels.append(label)
|
|
return tuple(known), tuple(labels)
|
|
|
|
|
|
def add_handler(holder: PackHolder, resolver: AddResolver, stripper: Stripper) -> Handler:
|
|
"""Build the handler that answers ``!add_photo``."""
|
|
|
|
async def handler(ctx: CommandContext) -> None:
|
|
keys = tuple(dict.fromkeys(ctx.args))
|
|
# Claimed before any refusal, so a refused message leaves no token behind.
|
|
known, labels = resolver.take(keys)
|
|
refusal = _refusal(keys, ctx.message.attachment_ids)
|
|
if refusal is not None:
|
|
await ctx.reply(refusal)
|
|
return
|
|
result = await ingest(ctx, holder, stripper)
|
|
if not result.fresh:
|
|
await ctx.reply(_nothing_new(result))
|
|
return
|
|
for name, body in result.fresh.items():
|
|
entry = Pending(
|
|
name=name,
|
|
keys=known,
|
|
labels=labels,
|
|
by=ctx.message.source_uuid,
|
|
at=int(ctx.now),
|
|
group=ctx.group_id,
|
|
)
|
|
queue(holder.pack.directory, body, entry)
|
|
await ctx.reply(_receipt(result))
|
|
|
|
return handler
|
|
|
|
|
|
def _refusal(keys: tuple[str, ...], attachments: tuple[str, ...]) -> str | None:
|
|
"""The line that ends this command before anything is read, or None."""
|
|
if UNKNOWN in keys:
|
|
return AMBIGUOUS
|
|
if not keys:
|
|
return NEED_LABEL
|
|
if len(keys) > MAX_NAMES:
|
|
return TOO_MANY
|
|
return NEED_PHOTO if not attachments else None
|
|
|
|
|
|
def _nothing_new(result: Ingested) -> str:
|
|
"""Why none of the attachments went into the queue."""
|
|
if result.duplicates:
|
|
return DUPLICATE_ONLY
|
|
return QUEUED_ONLY if result.queued else REJECTED
|
|
|
|
|
|
def _receipt(result: Ingested) -> str:
|
|
"""Counts only -- never a label, never a filename."""
|
|
parts = [QUEUED.format(count=len(result.fresh))]
|
|
if result.duplicates:
|
|
parts.append(ALREADY_THERE.format(count=result.duplicates))
|
|
if result.queued:
|
|
parts.append(ALREADY_QUEUED.format(count=result.queued))
|
|
return " · ".join(parts)
|
|
|
|
|
|
def register_add_command(
|
|
registry: CommandRegistry,
|
|
holder: PackHolder,
|
|
stripper: Stripper,
|
|
triggers: tuple[str, ...],
|
|
) -> AddResolver:
|
|
"""Register ``!add_photo``, scoped to the album's own groups.
|
|
|
|
No decorator: per kuhy's "NO CAP, NO LIMITS" there is no cooldown, no
|
|
size cap and no daily limit on proposing photos for the album.
|
|
"""
|
|
resolver = AddResolver(holder, registry)
|
|
registry.register(
|
|
COMMAND_NAME,
|
|
triggers,
|
|
add_handler(holder, resolver, stripper),
|
|
DESCRIPTION,
|
|
groups=holder.pack.groups,
|
|
takes_args=True,
|
|
arg_resolver=_as_resolver(resolver),
|
|
)
|
|
return resolver
|
|
|
|
|
|
def _as_resolver(resolver: AddResolver) -> ArgResolver:
|
|
"""Narrow the callable class to the registry's function type."""
|
|
return resolver.__call__
|