- add verbatim GPLv3 text as LICENSE - declare license and license-files in pyproject - add SPDX headers to Python sources - document licensing in README
392 lines
12 KiB
Python
392 lines
12 KiB
Python
# SPDX-License-Identifier: GPL-3.0-or-later
|
|
# Copyright (C) 2026 kawaiipunk
|
|
|
|
from __future__ import annotations
|
|
|
|
from datetime import datetime, time, timedelta, timezone
|
|
from pathlib import Path
|
|
from zoneinfo import ZoneInfo
|
|
|
|
import httpx
|
|
|
|
from signal_cal_bot.config import (
|
|
AnnounceConfig,
|
|
CalendarConfig,
|
|
Config,
|
|
FormatConfig,
|
|
ImagesConfig,
|
|
PostingConfig,
|
|
RemindersConfig,
|
|
SignalConfig,
|
|
WatchdogConfig,
|
|
)
|
|
from signal_cal_bot.expand import Event
|
|
from signal_cal_bot.feed import Feed, FeedResponse, normalize_feed_url
|
|
from signal_cal_bot.scheduler import (
|
|
Bot,
|
|
clamp_send_at,
|
|
in_window,
|
|
next_window_start,
|
|
reminder_time,
|
|
)
|
|
from signal_cal_bot.store import PageInfo, Store
|
|
from signal_cal_bot.watchdog import Watchdog
|
|
|
|
LONDON = ZoneInfo("Europe/London")
|
|
UTC = timezone.utc
|
|
WINDOWS = ((time(8, 0), time(10, 0)), (time(18, 0), time(21, 0)))
|
|
GUARD = timedelta(hours=1)
|
|
|
|
|
|
def local(*args) -> datetime:
|
|
return datetime(*args, tzinfo=LONDON)
|
|
|
|
|
|
def make_event(
|
|
*,
|
|
uid: str = "1",
|
|
series_id: str = "tec:1",
|
|
summary: str = "Folk Night",
|
|
start: datetime,
|
|
end: datetime | None = None,
|
|
all_day: bool = False,
|
|
image_url: str = "",
|
|
) -> Event:
|
|
return Event(
|
|
key=f"{uid}|{start.astimezone(UTC).isoformat()}",
|
|
uid=uid,
|
|
series_id=series_id,
|
|
summary=summary,
|
|
start=start.astimezone(UTC),
|
|
end=(end or start + timedelta(hours=2)).astimezone(UTC),
|
|
all_day=all_day,
|
|
location="Old Print Works\nB12 9AH",
|
|
url="https://commonscalendar.uk/event/folk-night/",
|
|
image_url=image_url,
|
|
tz="Europe/London",
|
|
)
|
|
|
|
|
|
def make_config(tmp_path, **overrides) -> Config:
|
|
defaults = dict(
|
|
signal=SignalConfig(
|
|
api_url="http://signal-api:8080", number="+447700900000", group_id="group.test"
|
|
),
|
|
calendar=CalendarConfig(url="https://example.test/feed.ics", timezone="Europe/London"),
|
|
posting=PostingConfig(),
|
|
announce=AnnounceConfig(),
|
|
reminders=RemindersConfig(),
|
|
images=ImagesConfig(),
|
|
format=FormatConfig(),
|
|
watchdog=WatchdogConfig(enabled=False),
|
|
db_path=tmp_path / "db.sqlite3",
|
|
cache_dir=tmp_path / "cache",
|
|
)
|
|
defaults.update(overrides)
|
|
return Config(**defaults)
|
|
|
|
|
|
# -- window helpers ---------------------------------------------------------
|
|
|
|
|
|
def test_webcal_is_fetched_over_https():
|
|
assert normalize_feed_url("webcal://example.test/x.ics") == "https://example.test/x.ics"
|
|
assert normalize_feed_url("https://example.test/x.ics") == "https://example.test/x.ics"
|
|
|
|
|
|
def test_in_window():
|
|
assert in_window(local(2026, 11, 18, 9, 0), WINDOWS)
|
|
assert not in_window(local(2026, 11, 18, 15, 0), WINDOWS)
|
|
assert not in_window(local(2026, 11, 18, 21, 0), WINDOWS)
|
|
|
|
|
|
def test_next_window_start():
|
|
assert next_window_start(local(2026, 11, 18, 7, 0), WINDOWS) == local(2026, 11, 18, 8, 0)
|
|
assert next_window_start(local(2026, 11, 18, 10, 30), WINDOWS) == local(2026, 11, 18, 18, 0)
|
|
assert next_window_start(local(2026, 11, 18, 21, 30), WINDOWS) == local(2026, 11, 19, 8, 0)
|
|
|
|
|
|
def test_clamp_defers_to_evening():
|
|
due = local(2026, 11, 18, 14, 0)
|
|
assert clamp_send_at(due, due, local(2026, 11, 25, 18, 0), WINDOWS, GUARD) == local(
|
|
2026, 11, 18, 18, 0
|
|
)
|
|
|
|
|
|
def test_clamp_respects_urgent_guard():
|
|
due = local(2026, 11, 18, 18, 30)
|
|
start = local(2026, 11, 18, 19, 0)
|
|
# Next window is tomorrow 08:00, which is after the event: send now.
|
|
assert clamp_send_at(due, due, start, WINDOWS, GUARD) == due
|
|
|
|
|
|
# -- reminder planning ------------------------------------------------------
|
|
|
|
|
|
def test_reminder_three_days_before_lands_in_window():
|
|
event = make_event(start=local(2026, 11, 21, 14, 0))
|
|
config = make_config(Path("/tmp"), posting=PostingConfig())
|
|
due = reminder_time(event, "3d", local(2026, 11, 10, 12, 0), config, LONDON)
|
|
assert due == local(2026, 11, 18, 18, 0)
|
|
|
|
|
|
def test_reminder_falls_back_to_day_of():
|
|
event = make_event(start=local(2026, 11, 20, 14, 0))
|
|
config = make_config(Path("/tmp"))
|
|
due = reminder_time(event, "3d", local(2026, 11, 19, 12, 0), config, LONDON)
|
|
assert due == local(2026, 11, 20, 9, 0)
|
|
|
|
|
|
def test_reminder_day_of_moves_before_early_event():
|
|
event = make_event(start=local(2026, 11, 20, 8, 30))
|
|
config = make_config(Path("/tmp"))
|
|
due = reminder_time(event, "3d", local(2026, 11, 19, 12, 0), config, LONDON)
|
|
assert due == local(2026, 11, 20, 7, 30)
|
|
|
|
|
|
def test_reminder_disabled_fallback_returns_none():
|
|
event = make_event(start=local(2026, 11, 20, 14, 0))
|
|
config = make_config(
|
|
Path("/tmp"), reminders=RemindersConfig(fallback_to_day_of=False)
|
|
)
|
|
assert reminder_time(event, "3d", local(2026, 11, 19, 12, 0), config, LONDON) is None
|
|
|
|
|
|
# -- end to end -------------------------------------------------------------
|
|
|
|
|
|
class FakeSender:
|
|
def __init__(self):
|
|
self.sent: list[dict] = []
|
|
|
|
def send(self, message, recipients, attachments=None, text_mode="normal"):
|
|
self.sent.append(
|
|
{"message": message, "recipients": recipients, "attachments": attachments}
|
|
)
|
|
|
|
|
|
class FakeImages:
|
|
def data_uri(self, url):
|
|
return None
|
|
|
|
|
|
class FakeScraper:
|
|
def details(self, url):
|
|
return PageInfo(image_url="", venue="", postcode="")
|
|
|
|
|
|
class BoomScraper:
|
|
def details(self, url):
|
|
raise RuntimeError("page down")
|
|
|
|
|
|
class BoomImages:
|
|
def data_uri(self, url):
|
|
raise RuntimeError("image down")
|
|
|
|
|
|
class FailingSender:
|
|
def __init__(self, exc):
|
|
self.exc = exc
|
|
self.attempts = 0
|
|
|
|
def send(self, message, recipients, attachments=None, text_mode="normal"):
|
|
self.attempts += 1
|
|
raise self.exc
|
|
|
|
|
|
class FakeFeed:
|
|
def __init__(self, content: bytes):
|
|
self.content = content
|
|
self.committed = False
|
|
|
|
def due(self, now):
|
|
return True
|
|
|
|
def fetch(self, now):
|
|
return FeedResponse(content=self.content)
|
|
|
|
def commit(self, response):
|
|
self.committed = True
|
|
|
|
|
|
def build_bot(tmp_path, sender, **overrides):
|
|
config = overrides.pop("config", None) or make_config(tmp_path)
|
|
store = Store(config.db_path)
|
|
http = httpx.Client()
|
|
bot = Bot(
|
|
config=config,
|
|
store=store,
|
|
feed=overrides.pop(
|
|
"feed", Feed(config.calendar.url, store, 15, http)
|
|
),
|
|
sender=sender,
|
|
images=overrides.pop("images", FakeImages()),
|
|
scraper=overrides.pop("scraper", FakeScraper()),
|
|
watchdog=overrides.pop(
|
|
"watchdog", Watchdog(config.watchdog, sender, "+447700900000")
|
|
),
|
|
http=http,
|
|
)
|
|
return bot, store
|
|
|
|
|
|
def test_first_run_seeds_silently_then_announces_new_series(tmp_path):
|
|
sender = FakeSender()
|
|
bot, store = build_bot(tmp_path, sender)
|
|
|
|
existing = make_event(uid="1", series_id="tec:1", start=local(2026, 11, 20, 9, 0))
|
|
bot._sync([existing], local(2026, 11, 18, 12, 0))
|
|
assert store.due_outbox(local(2026, 11, 18, 18, 0)) == []
|
|
|
|
newcomer = make_event(
|
|
uid="2", series_id="tec:2", summary="Film Night", start=local(2026, 11, 25, 19, 0)
|
|
)
|
|
bot._sync([existing, newcomer], local(2026, 11, 18, 12, 1))
|
|
pending = store.due_outbox(local(2026, 11, 18, 18, 0))
|
|
assert [item.kind for item in pending] == ["announce"]
|
|
|
|
bot._dispatch(local(2026, 11, 18, 18, 0))
|
|
assert len(sender.sent) == 1
|
|
assert sender.sent[0]["recipients"] == ["group.test"]
|
|
assert sender.sent[0]["message"].startswith("Film Night")
|
|
assert "#November #November25" in sender.sent[0]["message"]
|
|
|
|
# A later occurrence of the same series must not be announced again.
|
|
third = make_event(
|
|
uid="3", series_id="tec:2", summary="Film Night", start=local(2026, 12, 2, 19, 0)
|
|
)
|
|
bot._sync([existing, newcomer, third], local(2026, 11, 18, 18, 5))
|
|
assert store.due_outbox(local(2026, 11, 18, 18, 10)) == []
|
|
|
|
|
|
def test_reminder_is_sent_at_its_window(tmp_path):
|
|
sender = FakeSender()
|
|
bot, store = build_bot(tmp_path, sender)
|
|
|
|
event = make_event(uid="9", series_id="tec:9", start=local(2026, 11, 25, 14, 0))
|
|
bot._sync([event], local(2026, 11, 18, 12, 0)) # seeds; still plans reminders
|
|
bot._dispatch(local(2026, 11, 18, 18, 0))
|
|
assert sender.sent == []
|
|
|
|
# Three days before is 22 Nov 14:00, deferred to the 18:00 window.
|
|
bot._dispatch(local(2026, 11, 22, 18, 5))
|
|
assert len(sender.sent) == 1
|
|
assert sender.sent[0]["message"].startswith("Folk Night")
|
|
|
|
# Idempotent: dispatching again must not resend.
|
|
bot._dispatch(local(2026, 11, 22, 18, 10))
|
|
assert len(sender.sent) == 1
|
|
|
|
|
|
def test_stale_reminder_is_dropped_not_sent(tmp_path):
|
|
sender = FakeSender()
|
|
bot, store = build_bot(tmp_path, sender)
|
|
|
|
event = make_event(uid="10", series_id="tec:10", start=local(2026, 11, 18, 15, 0))
|
|
bot._sync([event], local(2026, 11, 18, 12, 0))
|
|
bot._dispatch(local(2026, 11, 18, 18, 0)) # event already started
|
|
assert sender.sent == []
|
|
assert store.due_outbox(local(2026, 11, 18, 18, 5)) == []
|
|
|
|
|
|
# -- failure handling -------------------------------------------------------
|
|
|
|
|
|
def test_signal_connection_error_does_not_wedge_the_outbox(tmp_path):
|
|
sender = FailingSender(httpx.ConnectError("connection refused"))
|
|
config = make_config(
|
|
tmp_path, watchdog=WatchdogConfig(enabled=True, send_failures=1)
|
|
)
|
|
watchdog = Watchdog(config.watchdog, sender, "+447700900000")
|
|
bot, store = build_bot(tmp_path, sender, config=config, watchdog=watchdog)
|
|
|
|
event = make_event(uid="20", series_id="tec:20", start=local(2026, 11, 25, 19, 0))
|
|
bot._sync([event], local(2026, 11, 18, 12, 0))
|
|
bot._sync(
|
|
[event, make_event(uid="21", series_id="tec:21", start=local(2026, 11, 26, 19, 0))],
|
|
local(2026, 11, 18, 12, 1),
|
|
)
|
|
|
|
now = local(2026, 11, 18, 18, 0)
|
|
bot._dispatch(now) # must not raise
|
|
|
|
pending = store.due_outbox(now)
|
|
assert pending, "the failed post should stay queued"
|
|
assert pending[0].attempts == 1
|
|
# The announcement stays queued, so it is not marked as delivered.
|
|
assert store.due_outbox(now)[0].kind == "announce"
|
|
|
|
|
|
def test_scraper_and_image_failures_still_send_text(tmp_path):
|
|
sender = FakeSender()
|
|
bot, store = build_bot(
|
|
tmp_path,
|
|
sender,
|
|
images=BoomImages(),
|
|
scraper=BoomScraper(),
|
|
)
|
|
|
|
event = make_event(
|
|
uid="22",
|
|
series_id="tec:22",
|
|
start=local(2026, 11, 25, 19, 0),
|
|
image_url="https://example.test/poster.png",
|
|
)
|
|
bot._sync([event], local(2026, 11, 18, 12, 0))
|
|
bot._sync(
|
|
[event, make_event(uid="23", series_id="tec:23", start=local(2026, 11, 26, 19, 0))],
|
|
local(2026, 11, 18, 12, 1),
|
|
)
|
|
bot._dispatch(local(2026, 11, 18, 18, 0))
|
|
|
|
assert len(sender.sent) == 1
|
|
assert sender.sent[0]["attachments"] == []
|
|
assert sender.sent[0]["message"].startswith("Folk Night")
|
|
|
|
|
|
# -- gone events ------------------------------------------------------------
|
|
|
|
|
|
def test_reminder_for_gone_event_is_dropped(tmp_path):
|
|
sender = FakeSender()
|
|
bot, store = build_bot(tmp_path, sender)
|
|
|
|
event = make_event(uid="30", series_id="tec:30", start=local(2026, 11, 25, 14, 0))
|
|
bot._sync([event], local(2026, 11, 18, 12, 0))
|
|
store.mark_gone([], local(2026, 11, 18, 13, 0), up_to=event.end + timedelta(days=2))
|
|
|
|
bot._dispatch(local(2026, 11, 22, 18, 5))
|
|
assert sender.sent == []
|
|
assert store.due_outbox(local(2026, 11, 22, 18, 10)) == []
|
|
|
|
|
|
def test_events_beyond_feed_coverage_are_not_marked_gone(tmp_path):
|
|
sender = FakeSender()
|
|
bot, store = build_bot(tmp_path, sender)
|
|
|
|
event = make_event(uid="31", series_id="tec:31", start=local(2026, 12, 20, 14, 0))
|
|
bot._sync([event], local(2026, 11, 18, 12, 0))
|
|
store.mark_gone([], local(2026, 11, 18, 13, 0), up_to=local(2026, 11, 30, 0, 0))
|
|
|
|
stored = store.get_event(event.key)
|
|
assert stored is not None and stored.gone is False
|
|
|
|
|
|
# -- feed seeding -----------------------------------------------------------
|
|
|
|
|
|
def test_empty_first_feed_does_not_seed(tmp_path):
|
|
sender = FakeSender()
|
|
empty = (
|
|
b"BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//test//EN\r\n"
|
|
b"END:VCALENDAR\r\n"
|
|
)
|
|
feed = FakeFeed(empty)
|
|
bot, store = build_bot(tmp_path, sender, feed=feed)
|
|
|
|
bot._refresh_feed(local(2026, 11, 18, 12, 0))
|
|
|
|
assert store.get_meta("seeded") is None
|
|
assert feed.committed is False
|