signal-bot/signal_bot/pack_add.py
Krzysztof kuhy Rudnicki aefffb2fd9
Some checks are pending
CI / check (push) Waiting to run
feat: add a photo to the album from the chat, tagged, stripped and verified
Send a photo captioned "!add_photo alfa wakacje" in one of the album's own
groups and it lands in the pack tagged with both, retrievable through !alfa
and the new !losowe immediately -- no restart, and no tagger session on the PC.
A label matching nobody becomes a custom tag, and !losowe is the only door to
one, which is what keeps a live swap a *data* swap: it can never register a
trigger or widen a command's groups.

No typed label travels. Labels become pseudonym keys in a new registry
arg_resolver, at the dispatcher, before the line that logs the command name --
so no handler, journal entry, command_uses row or reply body ever holds a word
somebody typed. The reply is counts and pseudonyms: "dodano · p1: 4 · t1: 1".

Stripping is exiftool with a *positive* check on the output, never an exit
code. ffmpeg was tried first and fails silently on photos: given a JPEG with a
real APP1 Exif segment it returned a byte-identical file, GPS intact, exit 0.
The surviving-tag allowlist is per tag *name* rather than per group, because
measurement showed a group-level "must be empty" rule rejects every format
except JPEG -- a valid PNG always reports its IHDR, an MP4 some fifty QuickTime
tags that are the container itself. Codec configuration (CompressorName,
VendorID, the HEVC parameter set) is on the list by decision: CompressorName
lives in the avc1 sample description and exiftool cannot write it at all, so
the alternative was refusing every video and every iPhone HEIC. Location and
identity tags are still refused, and the e2e run re-reads the stored files to
prove a QuickTime geotag did not survive.

.webm and .svg stay on the format allowlist and are stored *unstripped*:
exiftool 13.55 can write neither, and its SVG reader does not even surface
<metadata>. That is a deliberate, documented hole, not an oversight.

Two things this had to defuse along the way:
- personal_data_sources now reads custom.json, so "!add_photo kot <photo>"
  would have outlawed the word "kot" and refused every future commit, fixable
  only by hand-editing an album the committer cannot see. Minting now refuses
  a word that is already a command, and the gate subtracts the repo's own
  alias vocabulary from custom labels only -- curated people.json names are
  never excused.
- signal_bot/external.py is now the single subprocess site in the repository,
  so ruff's S603 needs exactly one scoped per-file-ignore instead of one per
  module that shells out. A test asserts nothing else imports subprocess.

A failed add changes nothing: media and the three manifests are written, the
album is reloaded, and only a load that succeeds is published; a load that
fails rolls all four back and keeps serving the pack that was already working,
without raising -- Restart=always would turn a ConfigError into a loop.

977 tests, 100% branch coverage, no omits and no suppressions. scripts/e2e.sh
gains 8 scenarios driven against the real exiftool on media generated at run
time, and asserts the invariants a reply cannot: that a refused upload is not
stored, that a message with no attachment leaves custom.json byte-identical,
and that signal-cli's own copy of every ingested attachment is gone.

Closes TODO-add-photo.md.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JqqE22jp94B1ypwxppdr1o
2026-08-31 11:20:00 +02:00

175 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.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, CommandContext, 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__