mirror of
https://github.com/kuhyx/signal-bot.git
synced 2026-11-11 13:57:32 +01:00
Some checks are pending
CI / check (push) Waiting to run
You asked for !add_photo in testbot without the real album being reachable there. One album cannot do that: its people.json "groups" list *is* the privacy guarantee, so making the commands exist in a second group necessarily makes the real photos postable there. So the bot now loads several albums. PHOTO_PACK_DIR takes a comma-separated list, the spelling GROUP_IDS and TRUSTED_INVITERS already use. Each album carries its own group scope, its own people, its own tags and its own custom labels; they share nothing but the process they run in. That makes trigger collisions between albums legal for the first time, and the registry had to learn it. Two albums are two different sets of people and both may reasonably call somebody "!alfa" -- no message can ever mean both, because a command a group is not scoped to is not a command there at all. So a trigger may be claimed more than once, and DuplicateTriggerError now fires only where the group sets *overlap*. Overlapping albums are refused at startup rather than resolved by registration order: a coin toss about which private album receives a photo is the outcome this whole design exists to prevent. Two consequences worth naming: - registry.resolve() takes an optional group. Without one it still answers "does anything claim this word", which is what pack_add's mint check wants; with one it answers "what runs here", which is what the dispatcher wants. resolve_with_args no longer resolves-then-checks, because with two claimants the first one found may be the wrong group's. - CommandContext moved to signal_bot/context.py to keep registry.py under the 250-line cap. A filing change: that file is "which word runs what", this one is "what the thing that runs may do". DOCS-add-photo.md is likewise a split, not new prose -- DOCS-photo-pack.md had grown past the cap and the ingest path is its own subject now. Verified live: the unit serves both albums, the real group resolves its 13 album commands and testbot its 7, and !losowe / !alfa / !dodaj all fire in testbot through the live dispatcher. 997 tests, 100% branch coverage, 28 e2e scenarios. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01JqqE22jp94B1ypwxppdr1o
176 lines
6.8 KiB
Python
176 lines
6.8 KiB
Python
# 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__
|