# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence. """``!add_photo``: put an attachment into the album, tagged, from the chat. Send a photo captioned ``!add_photo alfa beta`` and it lands in the album tagged with both, retrievable through each of their existing commands immediately -- no restart, and no tagger session on the PC. 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. The reply carries counts and pseudonyms; ``dodano · p1: 4`` says a photo landed and nothing about whom. * **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. * **A failed add changes nothing.** Media and manifests are written, the album is reloaded, and only a load that succeeds is published. A load that fails rolls the files back and keeps serving the pack that was already working. 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.pack import MAX_NAMES, options_for from signal_bot.pack_command import NAME_PREFIX, UNKNOWN from signal_bot.pack_ingest import commit, ingest from signal_bot.pack_replies import ( AMBIGUOUS, DUPLICATE_ONLY, NEED_LABEL, NEED_PHOTO, 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_custom import CustomTags from signal_bot.pack_holder import PackHolder from signal_bot.registry import ArgResolver, CommandRegistry, Handler logger = logging.getLogger(__name__) COMMAND_NAME: Final = f"{NAME_PREFIX}add" DESCRIPTION: Final = "dodaje załączone zdjęcie do albumu z podanymi etykietami" class AddResolver: """Turns typed labels into keys, minting one for a label nobody has. The pending mint is held here and only here until the upload succeeds, so ``!add_photo dog`` with no attachment leaves ``custom.json`` untouched -- as does a rejected file, and as does a photo the album already has. ``pending`` is cleared at the top of every resolve. That is safe because ``Bot.listen`` awaits one ``dispatcher.handle`` before reading the next frame, so exactly one message's mints are ever outstanding; the test ``test_pack_add`` pins that by resolving twice in a row. """ 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 mint can refuse a word that is already a command. Without that, "!add_photo kot" mints the label "kot", and scripts/personal_data_sources feeds custom 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.pending: dict[str, str] = {} def __call__(self, words: tuple[str, ...]) -> tuple[str, ...]: """Resolve every label to a key, recording any mint it implies.""" self.pending = {} pack = self._holder.pack minted = pack.custom keys: list[str] = [] for word in words: resolved, minted = self._resolve(pack, minted, word) keys.extend(resolved) return tuple(keys) def _resolve(self, pack: Pack, minted: CustomTags, word: str) -> tuple[list[str], CustomTags]: """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])), minted existing = minted.resolve(word) if existing is not None: return [existing], minted 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], minted key = minted.next_key() self.pending[key] = word return [key], minted.with_label(key, word) def committed(self, base: CustomTags) -> CustomTags: """``base`` plus every pending mint, for writing to disk.""" for key, label in self.pending.items(): base = base.with_label(key, label) return base 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)) refusal = _refusal(keys, ctx.message.attachment_ids) if refusal is not None: await ctx.reply(refusal) return fresh, duplicates = await ingest(ctx, holder, stripper) if not fresh: await ctx.reply(DUPLICATE_ONLY if duplicates else REJECTED) return await commit(ctx, holder, resolver, keys, fresh, duplicates) 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 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 adding to 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__