signal-bot/signal_bot/portraits.py
Krzysztof kuhy Rudnicki 558dd297a4 release: 0.0.7 «Telesfor» — !papież, and the bot can test itself
Adds !papież / !papiez / !pope: a random pope as a photo, captioned with his
Latin name, reign and pl.wikipedia link. popes.json already carried a Commons
portrait filename for all 267 and nothing had ever consumed it.

The Latin name comes from the Latin column of Poczet papieży, not from the
la.wikipedia sitelink. The sitelink resolved for all 267 and was still wrong:
la.wikipedia numbers several popes differently, so #154 came out as
"Stefan IX — Stephanus X" in a single caption, which reads as an off-by-one.
The table's own column says "Stephanus Nonus" and cannot disagree with the
name beside it. LATIN_OVERRIDES ships empty; it is a tripwire, not a backlog.

Portraits are cached on disk under CacheDirectory=signal-bot, named from the
ordinal so no upstream string ever reaches a path, and bounded at 267 entries
so nothing needs evicting. Verified that CacheDirectory wins against
ProtectHome=read-only before relying on it.

Also adds POST /_selftest and scripts/selftest.sh. Signal never delivers an
account its own sends, so no command has ever been exercised end-to-end
without asking a human to type it. This injects a real frame into the live
dispatcher; it is loopback-only and refuses any group not in SELFTEST_GROUPS,
which is empty by default.

Verified against the real endpoints, not just the fake: 267/267 portraits
resolve on Commons, regeneration is byte-identical on every previously
shipped field, and !papież was driven 7 times through the live dispatcher in
testbot, returning distinct popes.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015d48t4qsQLBJnDwDeo2Nom
2026-08-30 17:06:25 +02:00

131 lines
4.6 KiB
Python

# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
"""On-disk cache of papal portraits, keyed by ordinal.
The set is closed: 267 popes, one portrait each, so this cache is bounded by
construction and never evicts. That is what makes writing images to disk safe
here when http_client refuses to -- the filename comes from the ordinal, so
nothing upstream controls a path, and the directory belongs to systemd.
"""
from __future__ import annotations
import base64
import os
from pathlib import Path
from typing import TYPE_CHECKING, Final
from signal_bot.endpoints import PORTRAIT_WIDTH
from signal_bot.http_client import ImageFetchError
if TYPE_CHECKING:
from signal_bot.http_client import ImageFetcher
from signal_bot.versioning import Pope
# Where imageinfo puts the thumbnail URL in its reply.
_THUMB_PATH: Final = ("query", "pages", 0, "imageinfo", 0, "thumburl")
# Commons hosts these four for the 267 portraits: 245 jpg, 15 png, 6 gif,
# 1 jpeg. An unknown suffix is refused rather than guessed, because the
# extension is what tells Signal how to render the attachment.
_SUFFIXES: Final = frozenset({".jpg", ".jpeg", ".png", ".gif"})
def default_cache_dir() -> Path:
"""Return the portrait directory, preferring the one systemd hands us.
Under the unit CACHE_DIRECTORY is set and writable even though
ProtectHome=read-only makes the rest of $HOME immutable; outside it -- a
test run, a shell -- XDG applies. Mirrors scripts/signal_api_watchdog.sh.
"""
explicit = os.environ.get("PORTRAIT_CACHE_DIR", "").strip()
if explicit:
return Path(explicit)
cache = os.environ.get("CACHE_DIRECTORY", "").strip()
if cache:
return Path(cache) / "portraits"
home = os.environ.get("XDG_CACHE_HOME", "").strip() or str(Path.home() / ".cache")
return Path(home) / "signal-bot" / "portraits"
class PortraitCache:
"""Fetches a pope's portrait once, then serves it from disk forever."""
def __init__(
self,
fetcher: ImageFetcher,
api_url: str,
cache_dir: Path | None = None,
) -> None:
"""Store the fetcher, the Commons endpoint and where files land."""
self._fetcher = fetcher
self._api_url = api_url
self._dir = default_cache_dir() if cache_dir is None else cache_dir
def path_for(self, pope: Pope) -> Path:
"""Return the cache path for one pope.
Named from the ordinal, never from the Commons filename: those carry
spaces, parentheses, commas and non-ASCII, and are attacker-adjacent
data in a way an integer is not.
"""
suffix = Path(pope.portrait).suffix.lower()
if suffix not in _SUFFIXES:
msg = f"portrait for #{pope.ordinal} has an unusable suffix: {pope.portrait!r}"
raise ImageFetchError(msg)
return self._dir / f"{pope.ordinal:03d}{suffix}"
async def get_base64(self, pope: Pope) -> str:
"""Return the portrait base64-encoded, as the transport wants it."""
return base64.b64encode(await self.get_bytes(pope)).decode("ascii")
async def get_bytes(self, pope: Pope) -> bytes:
"""Return the portrait bytes, downloading them only on a miss."""
path = self.path_for(pope)
cached = _read(path)
if cached is not None:
return cached
image = await self._fetcher.fetch_bytes(
self._api_url,
_THUMB_PATH,
params={
"action": "query",
"format": "json",
"formatversion": "2",
"prop": "imageinfo",
"iiprop": "url",
"iiurlwidth": str(PORTRAIT_WIDTH),
"titles": f"File:{pope.portrait}",
},
)
_write(path, image)
return image
def _read(path: Path) -> bytes | None:
"""Return cached bytes, or None when there is nothing usable there.
An empty file is a miss, not a hit: that is what a crash between create
and write leaves behind, and serving it would post a broken attachment
into the group forever.
"""
try:
data = path.read_bytes()
except OSError:
return None
return data or None
def _write(path: Path, image: bytes) -> None:
"""Write the portrait atomically, ignoring a cache that will not take it.
A read-only or missing cache directory must not cost the group its photo
-- the bytes are already in hand. The next call simply misses again.
"""
try:
path.parent.mkdir(parents=True, exist_ok=True)
temporary = path.with_suffix(path.suffix + ".tmp")
temporary.write_bytes(image)
temporary.replace(path)
except OSError:
return