mirror of
https://github.com/kuhyx/signal-bot.git
synced 2026-11-10 20:27:17 +01:00
The tally was one integer per person, deleted after each post. Nothing dated survived it, so weeks, months, records, streaks and weekday averages were all unanswerable. This replaces it with an append-only per-message log holding metadata only -- never a message body -- and rebuilds the nightly report on top. What changes for the group: a photo posted without a caption now counts (it was worth zero), stickers count, the bot's own messages no longer do, people who said nothing appear with a 0, and the report covers the previous full calendar day in Europe/Warsaw instead of "since the last post" -- which used to merge two days whenever a group went quiet. Notable decisions, each with the trap it avoids: - Events and people are PERMANENT_TABLES: neither forget_group nor a future SCHEMA_VERSION bump may drop them. Both paths used to cost a day's counter and would now cost the entire history, and forget_group fires on a listing that merely omits members. - is_own comes from which envelope branch carried the payload, not from comparing identities. The account is spelled as a uuid on some frames and a +E.164 number on others, so any comparison misses one of them. - The roster is stashed in refresh(), not _adopt(), which returns early once the watched set stops changing -- i.e. always, in the steady state. - The roster matches on uuid OR number because /v1/groups spells kuhy as +48123456789 while his messages carry an ACI uuid. Joining on uuid alone would have listed him twice every night, once with 0. - Members whose display name we have never seen are counted, not named: their only spellings are a uuid or a phone number. - (group, uuid, sent_at_ms) is the primary key, so a websocket redelivery after a reconnect cannot inflate the counts. - Days come from a stored Warsaw date string, never a timestamp range: 2026-03-29 is 23 hours long and 2026-10-25 is 25. - Polish number agreement is a real rule with a 12-14 exception, so "44 znaki" and "45 znaków" are both spelled correctly. config.py and startup.py were two lines under the 250-line cap and both had to grow, so config_env and startup_retry come out of them first, as pure moves. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_015d48t4qsQLBJnDwDeo2Nom
194 lines
6.4 KiB
Python
194 lines
6.4 KiB
Python
# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
|
|
"""Shared fixtures and envelope builders."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import datetime as dt
|
|
import json
|
|
from typing import TYPE_CHECKING, Any
|
|
|
|
import httpx
|
|
import pytest
|
|
|
|
from signal_bot.config import Config
|
|
from signal_bot.discovery import GroupDirectory
|
|
from signal_bot.store import Store
|
|
from signal_bot.transport_fake import FakeTransport
|
|
from signal_bot.trust import InviteTrust
|
|
|
|
if TYPE_CHECKING:
|
|
from collections.abc import Callable
|
|
from pathlib import Path
|
|
|
|
# Canonical ``group.<base64>`` ids, the spelling /v1/groups reports and the
|
|
# only one /v2/send accepts. The *_INTERNAL forms are what an envelope
|
|
# carries: exactly what the canonical form decodes to.
|
|
WATCHED_GROUP = "group.ZDJGMFkyaGxaQzFuY205MWNDMXBaQzB6TWkxaWVYUmxjeUVoSVNFaElRPT0="
|
|
WATCHED_INTERNAL = "d2F0Y2hlZC1ncm91cC1pZC0zMi1ieXRlcyEhISEhIQ=="
|
|
SECOND_GROUP = "group.YzJWamIyNWtMV2R5YjNWd0xXbGtMVE15TFdKNWRHVnpJU0VoSVNFaA=="
|
|
SECOND_INTERNAL = "c2Vjb25kLWdyb3VwLWlkLTMyLWJ5dGVzISEhISEh"
|
|
OTHER_GROUP = "group.YjNSb1pYSXRaM0p2ZFhBdGFXUXRNekl0WW5sMFpYTWhJU0VoSVNFPQ=="
|
|
|
|
# The operator, and somebody who is not.
|
|
TRUSTED_NUMBER = "+48123456789"
|
|
STRANGER_NUMBER = "+15555550123"
|
|
|
|
|
|
@pytest.fixture
|
|
def config() -> Config:
|
|
"""The production shape: no allowlist, groups discovered from the account."""
|
|
return Config(
|
|
phone_number="+15550000000",
|
|
api_base_url="http://localhost:9922",
|
|
database_path=":memory:",
|
|
cooldown_seconds=10,
|
|
)
|
|
|
|
|
|
def group_entry(group_id: str, *, member: bool = True, name: str = "e2e") -> dict[str, Any]:
|
|
"""One /v1/groups row, in both spellings the real API uses."""
|
|
return {"id": group_id, "internal_id": group_id, "name": name, "member": member}
|
|
|
|
|
|
def listing_client(entries: list[dict[str, Any]]) -> httpx.AsyncClient:
|
|
"""A client whose /v1/groups always answers with these rows."""
|
|
return mock_client(lambda request: httpx.Response(200, json=entries))
|
|
|
|
|
|
# Captured before any monkeypatching, so a test that patches
|
|
# httpx.AsyncClient cannot make this helper recurse into itself.
|
|
_REAL_ASYNC_CLIENT = httpx.AsyncClient
|
|
|
|
|
|
def mock_client(handler: Callable[[httpx.Request], httpx.Response]) -> httpx.AsyncClient:
|
|
"""A client whose every request is answered by this handler."""
|
|
return _REAL_ASYNC_CLIENT(transport=httpx.MockTransport(handler))
|
|
|
|
|
|
def signal_client(
|
|
*group_ids: str, mode: str = "json-rpc", member: bool = True
|
|
) -> httpx.AsyncClient:
|
|
"""Answer both startup probes: the container mode, then the group listing."""
|
|
|
|
def handler(request: httpx.Request) -> httpx.Response:
|
|
if "/v1/groups" in request.url.path:
|
|
return httpx.Response(200, json=[group_entry(gid, member=member) for gid in group_ids])
|
|
return httpx.Response(200, json={"mode": mode})
|
|
|
|
return mock_client(handler)
|
|
|
|
|
|
@pytest.fixture
|
|
async def directory(config: Config, store: Store) -> GroupDirectory:
|
|
"""A directory that has already discovered both test groups."""
|
|
client = listing_client([group_entry(WATCHED_GROUP), group_entry(SECOND_GROUP)])
|
|
found = GroupDirectory(config, client, store, InviteTrust(()))
|
|
await found.refresh()
|
|
return found
|
|
|
|
|
|
@pytest.fixture(autouse=True)
|
|
def _portraits_stay_out_of_the_real_cache(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
|
"""Point the portrait cache at a temp dir for every test in the suite.
|
|
|
|
Without this, any test that runs the !papież handler writes into the
|
|
caller's real ~/.cache/signal-bot/portraits -- silently, and while still
|
|
passing. Autouse because the write happens several layers below the test
|
|
that triggers it, so opting in per test is a rule nobody would remember.
|
|
"""
|
|
monkeypatch.setenv("PORTRAIT_CACHE_DIR", str(tmp_path / "portraits"))
|
|
|
|
|
|
@pytest.fixture
|
|
def store() -> Store:
|
|
with Store(":memory:") as opened:
|
|
yield opened
|
|
|
|
|
|
@pytest.fixture
|
|
def transport() -> FakeTransport:
|
|
return FakeTransport()
|
|
|
|
|
|
@pytest.fixture
|
|
def clock() -> dt.datetime:
|
|
return dt.datetime(2026, 8, 29, 12, 0, tzinfo=dt.UTC)
|
|
|
|
|
|
# The exotic payload shapes, one per key, so the builder below stays inside
|
|
# the argument limit instead of growing a boolean per frame variant.
|
|
EXTRAS: dict[str, dict[str, Any]] = {
|
|
"sticker": {"sticker": {"packId": "abc", "stickerId": 6}},
|
|
"reaction": {"reaction": {"emoji": "👍", "targetAuthor": "x"}},
|
|
"quote": {"quote": {"id": 1719177917000, "author": "x", "text": "..."}},
|
|
}
|
|
|
|
|
|
def envelope(
|
|
*,
|
|
text: str | None = "hello",
|
|
group_id: str | None = WATCHED_GROUP,
|
|
sender: tuple[str, str] = ("uuid-alice", "Alice"),
|
|
sync: bool = False,
|
|
attachments: tuple[str, ...] = (),
|
|
extra: str = "",
|
|
timestamp: int = 1719177917717,
|
|
) -> str:
|
|
"""Build one raw websocket frame in either envelope shape."""
|
|
uuid, name = sender
|
|
payload: dict[str, Any] = {"timestamp": timestamp}
|
|
if text is not None:
|
|
payload["message"] = text
|
|
if group_id is not None:
|
|
payload["groupInfo"] = {"groupId": group_id, "type": "DELIVER"}
|
|
if extra:
|
|
payload.update(EXTRAS[extra])
|
|
if attachments:
|
|
payload["attachments"] = [
|
|
{"contentType": c, "id": str(i)} for i, c in enumerate(attachments)
|
|
]
|
|
|
|
body: dict[str, Any] = {
|
|
"source": name,
|
|
"sourceNumber": STRANGER_NUMBER,
|
|
"sourceUuid": uuid,
|
|
"sourceName": name,
|
|
"sourceDevice": 69,
|
|
"timestamp": timestamp,
|
|
}
|
|
if sync:
|
|
body["syncMessage"] = {"sentMessage": payload}
|
|
else:
|
|
body["dataMessage"] = payload
|
|
return json.dumps({"envelope": body, "account": "+15550000000"})
|
|
|
|
|
|
def update_envelope(
|
|
*,
|
|
group_id: str = WATCHED_GROUP,
|
|
number: str = TRUSTED_NUMBER,
|
|
uuid: str = "uuid-operator",
|
|
) -> str:
|
|
"""Build a group-membership-change frame: no text, groupInfo type UPDATE.
|
|
|
|
This is the shape signal-cli emits when somebody adds the bot to a
|
|
group, and the only frame that names who did it.
|
|
"""
|
|
return json.dumps(
|
|
{
|
|
"envelope": {
|
|
"source": number,
|
|
"sourceNumber": number,
|
|
"sourceUuid": uuid,
|
|
"sourceName": "kuhy",
|
|
"timestamp": 1719177917717,
|
|
"dataMessage": {
|
|
"timestamp": 1719177917717,
|
|
"message": None,
|
|
"groupInfo": {"groupId": group_id, "type": "UPDATE"},
|
|
},
|
|
},
|
|
"account": "+15550000000",
|
|
}
|
|
)
|