Calendar reminders as push notifications

A job every minute finds the event reminders that fell due — repeating events
and moved occurrences expanded as the calendar view does — and pushes each
once to every device with notifications on (sdk.push, new: plugins can notify
through the new-mail push delivery). A reminder missed while the worker was down
is still sent within 10 minutes; cancelled events and declined invitations stay
quiet. Title, then "In 15 minutes, 14:00 · Room 2" in the user's zone and clock
format; it stays until dismissed and shows even with the app open; clicking it
opens that day (/p/calendar?date=…, new deep link).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-09 21:49:04 +02:00
co-authored by Claude Opus 5.5
parent 9611aedfcd
commit fa552392c8
6 changed files with 385 additions and 10 deletions
+39
View File
@@ -179,6 +179,12 @@ class PluginSdk:
CalDAV/CardDAV/ICS. Returns status + headers + body."""
return PluginHttp()
# --- notifications ------------------------------------------------------
@property
def push(self) -> PluginPush:
"""Notifications on the user's devices (Web Push) — calendar reminders."""
return PluginPush(self.name)
# --- secret vault -------------------------------------------------------
@property
def vault(self) -> PluginVault:
@@ -187,6 +193,39 @@ class PluginSdk:
return PluginVault()
class PluginPush:
"""``sdk.push``: show a notification on every device where the user turned
notifications on (Settings → Accounts → Notifications)."""
def __init__(self, plugin: str) -> None:
self._plugin = plugin
async def notify(
self,
user_id: uuid.UUID,
*,
title: str,
body: str = "",
url: str = "/mail",
tag: str | None = None,
sticky: bool = False,
) -> int:
"""Send one notification; returns how many devices it went to. ``tag``
replaces an earlier notification with the same tag (it is prefixed with
the plugin's name); ``sticky`` keeps it on screen until dismissed."""
from app.push.service import deliver
payload: dict[str, object] = {
"type": f"plugin.{self._plugin}",
"title": title[:200],
"body": body[:500],
"url": url if url.startswith("/") else "/mail",
"tag": f"{self._plugin}-{tag}" if tag else self._plugin,
"sticky": sticky,
}
return await deliver(user_id, [payload])
def sdk(name: str) -> PluginSdk:
"""Return the SDK facade bound to plugin ``name`` (SPEC §11)."""
return PluginSdk(name)
+20 -4
View File
@@ -200,6 +200,26 @@ async def notify(user_id: uuid.UUID, message_ids: list[uuid.UUID]) -> int:
pushes were delivered to push services."""
from app.db import session_scope
async with session_scope() as db:
if not await db.scalar(
select(PushSubscription.id).where(PushSubscription.user_id == user_id).limit(1)
):
return 0
messages = await _news(db, user_id, message_ids)
if not messages:
return 0
payloads = _payloads(messages, await _unread(db, user_id))
return await deliver(user_id, payloads)
async def deliver(user_id: uuid.UUID, payloads: list[dict[str, object]]) -> int:
"""Push ``payloads`` to every device of the user that is still signed in
(for new mail, and for plugins: calendar reminders); returns how many were
handed to push services. Devices that are gone are forgotten."""
from app.db import session_scope
if not payloads:
return 0
async with session_scope() as db:
# Plain values: the rows expire when the key pair is first saved below.
subs = [
@@ -210,10 +230,6 @@ async def notify(user_id: uuid.UUID, message_ids: list[uuid.UUID]) -> int:
]
if not subs:
return 0
messages = await _news(db, user_id, message_ids)
if not messages:
return 0
payloads = _payloads(messages, await _unread(db, user_id))
key = await vapid(db)
subject = _subject(await db.get(AppSettings, 1))
@@ -0,0 +1,130 @@
"""Event reminders as notifications (calendar plugin, sdk.push): due reminders
are sent once, repeating events remind on each occurrence, cancelled and
declined ones stay quiet."""
from __future__ import annotations
import uuid
from collections.abc import AsyncIterator
from datetime import UTC, datetime, timedelta
from typing import Any
import httpx
import pytest
import pytest_asyncio
from httpx import ASGITransport
from sqlalchemy import delete, text
from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
from sqlalchemy.pool import NullPool
from webmail_plugin_calendar import reminders # type: ignore[import-not-found]
from app.config import get_settings
from app.identity.passwords import hash_password
from app.identity.sessions import create_session
from app.main import create_app
from app.models import User
from app.plugins.sdk import PluginPush
CAL = "/api/plugins/calendar"
# Far from any real event in the dev database.
MON_9 = datetime(2031, 6, 2, 9, 0, tzinfo=UTC) # a Monday
@pytest_asyncio.fixture
async def ctx(
monkeypatch: pytest.MonkeyPatch,
) -> AsyncIterator[tuple[httpx.AsyncClient, uuid.UUID, list[dict[str, Any]], Any]]:
sent: list[dict[str, Any]] = []
async def fake_notify(self: PluginPush, user_id: uuid.UUID, **kw: Any) -> int:
sent.append({"user_id": user_id, **kw})
return 1
monkeypatch.setattr(PluginPush, "notify", fake_notify)
engine = create_async_engine(get_settings().database_url, poolclass=NullPool)
sm = async_sessionmaker(engine, expire_on_commit=False)
async with sm() as s:
user = User(
handle=f"rem{uuid.uuid4().hex[:8]}@test.local", password_hash=hash_password("pw")
)
s.add(user)
await s.commit()
token = await create_session(user.id, "pytest")
client = httpx.AsyncClient(
transport=ASGITransport(app=create_app()),
base_url="http://testserver",
cookies={"session": token, "csrf": "c"},
headers={"X-CSRF": "c"},
)
try:
yield client, user.id, sent, sm
finally:
await client.aclose()
async with sm() as s:
await s.execute(
text("DELETE FROM plg_calendar_calendars WHERE user_id = :u"), {"u": str(user.id)}
)
await s.execute(text("DELETE FROM plugin_kv WHERE user_id = :u"), {"u": str(user.id)})
await s.execute(delete(User).where(User.id == user.id))
await s.commit()
await engine.dispose()
async def _event(client: httpx.AsyncClient, **fields: Any) -> str:
cal = (await client.get(f"{CAL}/calendars")).json()[0]["id"]
r = await client.post(f"{CAL}/events", json={"calendar_id": cal, **fields})
assert r.status_code == 200, r.text
return str(r.json()["id"])
async def test_due_reminders_are_sent_once(ctx) -> None: # type: ignore[no-untyped-def]
client, user_id, sent, sm = ctx
await _event(
client,
summary="Dentist",
location="Main St 4",
dtstart=MON_9.isoformat(),
dtend=(MON_9 + timedelta(hours=1)).isoformat(),
reminders=[10, 60],
)
called_off = await _event(
client, summary="Called off", dtstart=MON_9.isoformat(), reminders=[10]
)
async with sm() as db: # cancelled by its organizer: never reminds
await db.execute(
text("UPDATE plg_calendar_events SET status = 'cancelled' WHERE id = :id"),
{"id": called_off},
)
await db.commit()
async def run(at: datetime) -> int:
return await reminders.reminder_job({}, now=at, only_user=user_id)
assert await run(MON_9 - timedelta(minutes=61)) == 0 # nothing due yet
assert await run(MON_9 - timedelta(minutes=60)) == 1 # the 1-hour reminder
assert sent[-1]["title"] == "Dentist"
assert sent[-1]["body"] == "In 1 hour, 09:00 · Main St 4"
assert sent[-1]["url"] == "/p/calendar?date=2031-06-02" and sent[-1]["sticky"] is True
assert await run(MON_9 - timedelta(minutes=59)) == 0 # not again
# The worker was down when the 10-minute reminder came due: sent late, once.
assert await run(MON_9 - timedelta(minutes=4)) == 1
assert sent[-1]["body"] == "In 10 minutes, 09:00 · Main St 4"
assert await run(MON_9 - timedelta(minutes=3)) == 0
assert len(sent) == 2
async def test_repeating_events_remind_on_each_occurrence(ctx) -> None: # type: ignore[no-untyped-def]
client, user_id, sent, _ = ctx
await _event(
client,
summary="Weekly sync",
dtstart=MON_9.isoformat(),
dtend=(MON_9 + timedelta(minutes=30)).isoformat(),
rrule="FREQ=WEEKLY;BYDAY=MO",
reminders=[15],
)
for week in range(3):
at = MON_9 + timedelta(weeks=week) - timedelta(minutes=15)
assert await reminders.reminder_job({}, now=at, only_user=user_id) == 1
tags = {s["tag"] for s in sent}
assert len(sent) == 3 and len(tags) == 3 # one notification per occurrence