Files
surveybox/surveybox/mail/notify.py
T
marco.morath 42dd1f2d4a
CI / audit (push) Skipped
CI / checks (push) Failing after 37s
CI / image (push) Skipped
Initial Commit: Status Testing
2026-11-25 18:46:04 +01:00

636 lines
22 KiB
Python

# SPDX-License-Identifier: AGPL-3.0-or-later
"""Benachrichtigungen per E-Mail.
Jede Benachrichtigung gehört zu einem Ereignis. Empfänger schalten Ereignisse
im Konto ab, bestellen sie für ein einzelnes Formular ab oder nutzen den
Abmeldelink in der Mail (auch per Klick im Mailprogramm, RFC 8058).
Mails enthalten Links statt Antwortinhalten. Bei anonymen Formularen gibt es
keine Mails an Teilnehmende: Schon die Mail würde Person und Teilnahme
verbinden.
"""
from __future__ import annotations
import base64
import binascii
import logging
import uuid
from collections.abc import Callable, Iterable, Sequence
from dataclasses import dataclass
from datetime import UTC, datetime
from typing import Any
from sqlalchemy import select
from sqlalchemy.orm import Session
from surveybox.i18n import N_
from surveybox.mail import config as mail_config
from surveybox.mail import custom, outbox, render
from surveybox.models import (
Booking,
Comment,
Form,
FormMember,
FormMute,
GuestContact,
Question,
Response,
UserAccount,
)
from surveybox.security.tokens import constant_time_equal, derive_key, keyed_hash
from surveybox.settings import Settings
APP_NAME = "Surveybox"
log = logging.getLogger(__name__)
def app_name(settings: Settings) -> str:
"""Name der Instanz aus Einstellungen > Gestaltung (Standard: Surveybox)."""
from surveybox import appearance
return appearance.current(settings.data_dir).name
def safely(db: Session, func: Callable[..., Any], *args: Any) -> Any:
"""Benachrichtigung in einem Savepoint: Ein Fehler beim Erzeugen einer Mail
darf die eigentliche Aktion (z. B. eine Teilnahme) nie verhindern."""
try:
with db.begin_nested():
return func(db, *args)
except Exception:
log.exception("Benachrichtigung %s fehlgeschlagen", getattr(func, "__name__", func))
return None
@dataclass(frozen=True)
class Event:
label: str
audience: str # "participant" oder "manager"
default: bool = True
EVENTS: dict[str, Event] = {
"participation": Event(N_("Confirmation when I take part in a form"), "participant"),
"promoted": Event(N_("I have moved up from a waiting list"), "participant"),
"confirmed": Event(N_("A date has been confirmed in a poll I took part in"), "participant"),
"comment_published": Event(N_("My comment has been published"), "participant"),
"followup": Event(N_("Follow-up emails with documents from forms I took part in"),
"participant"),
"changed": Event(N_("An entry or date I chose has been removed from a form"),
"participant"),
"reminder": Event(N_("Reminder before the end date of a form I was invited to"),
"participant"),
"comment_new": Event(N_("New comments on forms I manage"), "manager"),
"slot_full": Event(N_("An entry in a form I own is booked up"), "manager"),
"deadline": Event(N_("A form I own has reached its end date"), "manager"),
"digest": Event(N_("Daily summary of new and changed answers to forms I manage"),
"manager"),
}
# --------------------------------------------------------------------------
# Einstellungen der Empfänger
# --------------------------------------------------------------------------
def wants(user: UserAccount, event: str) -> bool:
if not user.is_active or event not in EVENTS:
return False
prefs = user.notify_prefs or {}
value = prefs.get(event)
return EVENTS[event].default if value is None else bool(value)
def set_prefs(user: UserAccount, enabled: Iterable[str]) -> None:
chosen = set(enabled)
user.notify_prefs = {event: event in chosen for event in EVENTS}
def turn_off(user: UserAccount, event: str) -> None:
if event in EVENTS:
user.notify_prefs = {**(user.notify_prefs or {}), event: False}
def is_muted(db: Session, user_id: int, form_id: int) -> bool:
return db.get(FormMute, (user_id, form_id)) is not None
def mute(db: Session, user_id: int, form_id: int) -> None:
if not is_muted(db, user_id, form_id):
db.add(FormMute(user_id=user_id, form_id=form_id))
def unmute(db: Session, user_id: int, form_id: int) -> None:
row = db.get(FormMute, (user_id, form_id))
if row is not None:
db.delete(row)
def muted_forms(db: Session, user_id: int) -> list[Form]:
return list(
db.scalars(
select(Form)
.join(FormMute, FormMute.form_id == Form.id)
.where(FormMute.user_id == user_id)
.order_by(Form.title)
)
)
def language_of(user: UserAccount, settings: Settings) -> str:
return user.language or settings.default_language
@dataclass(frozen=True)
class Recipient:
"""Empfänger einer Mail: Benutzer oder Gast (bestätigte Adresse)."""
email: str
name: str
language: str
user: UserAccount | None = None
guest: GuestContact | None = None
@property
def ident(self) -> str:
if self.user is not None:
return f"u:{self.user.public_id}"
if self.guest is not None:
return f"g:{self.guest.public_id}"
return ""
def for_user(user: UserAccount, settings: Settings) -> Recipient:
return Recipient(user.email, user.display_name, language_of(user, settings), user=user)
def for_guest(contact: GuestContact, settings: Settings) -> Recipient:
return Recipient(contact.email, "", contact.language or settings.default_language,
guest=contact)
def allowed(db: Session, recipient: Recipient, event: str, form: Form | None) -> bool:
"""Will der Empfänger diese Benachrichtigung?"""
if recipient.user is not None:
user = recipient.user
return wants(user, event) and not (form is not None and is_muted(db, user.id, form.id))
guest = recipient.guest
return (
guest is not None
and guest.confirmed_at is not None # Double-Opt-in
and guest.notify
and EVENTS.get(event, Event("", "")).audience == "participant"
)
# --------------------------------------------------------------------------
# Abmeldelinks
# --------------------------------------------------------------------------
def _b64(data: bytes) -> str:
return base64.urlsafe_b64encode(data).decode("ascii").rstrip("=")
def _unb64(text: str) -> bytes:
return base64.urlsafe_b64decode(text + "=" * (-len(text) % 4))
def unsubscribe_token(
secret_key: str, who: UserAccount | Recipient, event: str, form: Form | None = None
) -> str:
ident = who.ident if isinstance(who, Recipient) else str(who.public_id)
payload = f"{ident}|{event}|{form.public_id if form is not None else ''}"
mac = keyed_hash(derive_key(secret_key, "unsubscribe"), payload)[:16]
return f"{_b64(payload.encode())}.{_b64(mac)}"
@dataclass(frozen=True)
class Unsubscribe:
public_id: uuid.UUID
event: str
form_public_id: uuid.UUID | None
kind: str = "user" # oder "guest"
@property
def user_public_id(self) -> uuid.UUID:
return self.public_id
def parse_unsubscribe(secret_key: str, token: str) -> Unsubscribe | None:
if len(token) > 400 or "." not in token:
return None
raw, _, mac = token.partition(".")
try:
payload = _unb64(raw).decode("utf-8")
given = _unb64(mac)
except (binascii.Error, UnicodeDecodeError, ValueError):
return None
expected = keyed_hash(derive_key(secret_key, "unsubscribe"), payload)[:16]
if not constant_time_equal(expected, given):
return None
parts = payload.split("|")
if len(parts) != 3 or parts[1] not in EVENTS:
return None
kind, ident = "user", parts[0]
if ident.startswith(("u:", "g:")):
kind = "guest" if ident[0] == "g" else "user"
ident = ident[2:]
try:
public_id = uuid.UUID(ident)
form_id = uuid.UUID(parts[2]) if parts[2] else None
except ValueError:
return None
return Unsubscribe(public_id, parts[1], form_id, kind)
# --------------------------------------------------------------------------
# Versand
# --------------------------------------------------------------------------
def _reply_to(db: Session, form: Form | None) -> str | None:
if form is not None and form.reply_to:
return form.reply_to
return mail_config.load(db).reply_to or None
def send(
db: Session,
settings: Settings,
to: UserAccount | Recipient,
*,
kind: str,
context: dict[str, Any],
event: str | None = None,
form: Form | None = None,
dedupe_key: str | None = None,
) -> bool:
"""Mail eintragen. Mit `event`: nur, wenn gewünscht, bestätigt und nicht abbestellt."""
recipient = to if isinstance(to, Recipient) else for_user(to, settings)
if event is not None and not allowed(db, recipient, event, form):
return False
secret = settings.secret_key.get_secret_value()
origin = settings.public_origin
headers: dict[str, str] = {}
unsubscribe_url = None
if event is not None:
token = unsubscribe_token(secret, recipient, event, form)
unsubscribe_url = f"{origin}/mail/unsubscribe/{token}"
headers["List-Unsubscribe"] = f"<{unsubscribe_url}>"
headers["List-Unsubscribe-Post"] = "List-Unsubscribe=One-Click"
ctx = {
"app_name": app_name(settings),
"origin": origin,
"name": recipient.name,
"form": form,
"guest": recipient.guest is not None,
"links_url": f"{origin}/links",
"unsubscribe_url": unsubscribe_url,
"settings_url": f"{origin}/account/notifications",
**context,
}
rendered = render.render(kind, recipient.language, ctx,
custom.for_kind(db, kind, recipient.language))
return outbox.enqueue(
db,
secret,
kind=kind,
recipient=recipient.email,
content=outbox.Content(
subject=rendered.subject,
text=rendered.text,
html=rendered.html,
reply_to=_reply_to(db, form),
headers=headers,
),
user_id=recipient.user.id if recipient.user is not None else None,
form_id=form.id if form is not None else None,
dedupe_key=dedupe_key,
)
def form_link(settings: Settings, form: Form) -> str:
return f"{settings.public_origin}/f/{form.share_token}"
def manage_link(settings: Settings, form: Form, page: str = "") -> str:
return f"{settings.public_origin}/forms/{form.public_id}{page}"
# --------------------------------------------------------------------------
# Ereignisse für Teilnehmende
# --------------------------------------------------------------------------
def _participant(
db: Session, settings: Settings, form: Form, response: Response
) -> Recipient | None:
"""Benutzer oder Gast hinter einer Antwort (bei anonymen Formularen niemand)."""
if form.anonymous:
return None
if response.user_id is not None:
user = db.get(UserAccount, response.user_id)
return for_user(user, settings) if user is not None else None
if response.guest_contact_id is not None:
contact = db.get(GuestContact, response.guest_contact_id)
return for_guest(contact, settings) if contact is not None else None
return None
participant = _participant
def participation_received(
db: Session, settings: Settings, form: Form, response: Response
) -> bool:
"""Bestätigung für Benutzer; Gäste bekommen stattdessen guest_receipt."""
if form.anonymous or response.user_id is None:
return False
user = db.get(UserAccount, response.user_id)
if user is None:
return False
return send(
db, settings, user, kind="participation", event="participation", form=form,
context={"link": form_link(settings, form)},
dedupe_key=f"participation:{response.id}",
)
def promoted(db: Session, settings: Settings, question: Question, moved: Sequence[Booking]) -> int:
"""Nachgerückt von der Warteliste: je Buchung höchstens eine Mail."""
count = 0
form = db.get(Form, question.form_id)
if form is None:
return 0
from surveybox.forms import types
for booking in moved:
response = db.get(Response, booking.response_id)
recipient = _participant(db, settings, form, response) if response is not None else None
if recipient is None:
continue
entry = (
question.label
if question.config.get("single")
else types.option_label(question, booking.option_id) or question.label
)
stamp = (booking.promoted_at or datetime.now(UTC)).isoformat()
if send(
db, settings, recipient, kind="promoted", event="promoted", form=form,
context={"entry": entry, "link": form_link(settings, form)},
dedupe_key=f"promoted:{booking.id}:{stamp}",
):
count += 1
return count
def dates_confirmed(
db: Session, settings: Settings, form: Form, question: Question, new_ids: Sequence[str]
) -> int:
"""Neu bestätigte Termine einer Abstimmung an alle Teilnehmenden mit Konto."""
if form.anonymous or not new_ids:
return 0
from surveybox.forms import types
by_id = {o["id"]: o for o in types.options_of(question)}
options = [by_id[i] for i in new_ids if i in by_id]
if not options:
return 0
responses = db.scalars(
select(Response).where(
Response.form_id == form.id,
(Response.user_id.is_not(None)) | (Response.guest_contact_id.is_not(None)),
)
).all()
recipients: dict[str, Recipient] = {}
for response in responses:
found = _participant(db, settings, form, response)
if found is not None:
recipients.setdefault(found.ident, found)
calendar = (
f"{settings.public_origin}/f/{form.share_token}/calendar.ics"
if form.calendar_mode != "off"
else None
)
count = 0
key = ",".join(sorted(o["id"] for o in options))
for ident in sorted(recipients):
if send(
db, settings, recipients[ident], kind="confirmed", event="confirmed", form=form,
context={"options": options, "link": form_link(settings, form),
"calendar": calendar},
dedupe_key=f"confirmed:{question.id}:{key}:{ident}",
):
count += 1
return count
def booking_events(db: Session, settings: Settings, form: Form, events: Any) -> None:
"""Nachgerückte Personen und ausgebuchte Einträge aus forms.booking.Events."""
by_question: dict[int, tuple[Question, list[Booking]]] = {}
for question, booking in events.promoted:
by_question.setdefault(question.id, (question, []))[1].append(booking)
for question, moved in by_question.values():
promoted(db, settings, question, moved)
for question, option_id in events.filled:
slot_full(db, settings, form, question, option_id)
def comment_published(db: Session, settings: Settings, form: Form, comment: Comment) -> bool:
if comment.user_id is None:
return False
user = db.get(UserAccount, comment.user_id)
if user is None:
return False
return send(
db, settings, user, kind="comment_published", event="comment_published", form=form,
context={"link": form_link(settings, form)},
dedupe_key=f"comment_published:{comment.id}",
)
# --------------------------------------------------------------------------
# Ereignisse für Verwalter
# --------------------------------------------------------------------------
def managers(db: Session, form: Form) -> list[UserAccount]:
"""Eigentümer und Mitbearbeitende (direkt oder über Gruppen samt Untergruppen)."""
from surveybox.accounts import scope
ids: set[int] = set()
if form.owner_id is not None:
ids.add(form.owner_id)
rows = db.execute(
select(FormMember.user_id, FormMember.group_id).where(
FormMember.form_id == form.id, FormMember.role == "editor"
)
).all()
ids.update(uid for uid, _ in rows if uid is not None)
groups = [gid for _, gid in rows if gid is not None]
if groups:
tree = scope.load_tree(db)
ids.update(u.id for u in scope.users_in_groups(db, scope.descendants(tree, groups)))
if not ids:
return []
return list(
db.scalars(
select(UserAccount)
.where(UserAccount.id.in_(ids), UserAccount.is_active.is_(True))
.order_by(UserAccount.id)
)
)
def comment_created(
db: Session, settings: Settings, form: Form, comment: Comment, author_is_manager: bool
) -> int:
if not form.comments_notify or author_is_manager:
return 0
count = 0
for user in managers(db, form):
if user.id == comment.user_id:
continue
if send(
db, settings, user, kind="comment_new", event="comment_new", form=form,
context={"pending": comment.status == "pending",
"link": manage_link(settings, form, "/comments")},
dedupe_key=f"comment_new:{comment.id}:{user.id}",
):
count += 1
return count
def _owner(db: Session, form: Form) -> UserAccount | None:
return db.get(UserAccount, form.owner_id) if form.owner_id is not None else None
def slot_full(
db: Session, settings: Settings, form: Form, question: Question, option_id: str
) -> bool:
owner = _owner(db, form)
if owner is None:
return False
from surveybox.forms import types
entry = (
question.label
if question.config.get("single")
else types.option_label(question, option_id) or question.label
)
day = datetime.now(UTC).date().isoformat()
return send(
db, settings, owner, kind="slot_full", event="slot_full", form=form,
context={"entry": entry, "link": manage_link(settings, form, "/responses")},
dedupe_key=f"slot_full:{question.id}:{option_id}:{day}",
)
def deadline_reached(db: Session, settings: Settings, form: Form, responses: int) -> bool:
owner = _owner(db, form)
if owner is None or form.closes_at is None:
return False
return send(
db, settings, owner, kind="deadline", event="deadline", form=form,
context={"responses": responses, "link": manage_link(settings, form, "/responses")},
dedupe_key=f"deadline:{form.id}:{form.closes_at.isoformat()}",
)
# --------------------------------------------------------------------------
# Mails ohne Ereignis (immer, nicht abbestellbar)
# --------------------------------------------------------------------------
def retention_notice(
db: Session, settings: Settings, form: Form, mode: str, when: datetime, responses: int
) -> bool:
"""Eigentümer: Die Löschfrist läuft bald ab (nicht abbestellbar, betrifft Pflichten)."""
from babel.dates import format_date
owner = _owner(db, form)
if owner is None:
return False
language = language_of(owner, settings)
return send(
db, settings, owner, kind="retention_notice", form=form,
context={
"mode": mode,
"date": format_date(when.astimezone(settings.tz).date(), format="long",
locale=language),
"responses": responses,
"link": manage_link(settings, form, "/responses"),
"settings_link": manage_link(settings, form, "/settings"),
},
dedupe_key=f"retention:{form.id}:{when.date().isoformat()}",
)
def guest_receipt(
db: Session,
settings: Settings,
form: Form,
contact: GuestContact,
link: str,
confirm: str | None,
edited: bool = False,
) -> bool:
"""Gast: Eingangsbestätigung mit persönlichem Link (und ggf. Bestätigungslink).
Sind Folge-Mails eingerichtet, sagt die Mail ausdrücklich, dass sie nur nach der
Bestätigung der Adresse ankommen.
"""
from surveybox.forms import followups # followups importiert dieses Modul
return send(
db, settings, for_guest(contact, settings), kind="guest_receipt", form=form,
context={"link": link, "confirm": confirm, "edited": edited,
"can_edit": form.allow_edit == "until_close",
"followups_planned": bool(confirm) and followups.planned(db, form)},
)
def guest_export(db: Session, settings: Settings, contact: GuestContact, link: str) -> bool:
"""Gast: Link zum Herunterladen aller Daten an dieser Adresse."""
return send(db, settings, for_guest(contact, settings), kind="guest_export",
context={"link": link})
def guest_erase(db: Session, settings: Settings, contact: GuestContact, link: str) -> bool:
"""Gast: Link zum Löschen aller Daten an dieser Adresse."""
return send(db, settings, for_guest(contact, settings), kind="guest_erase",
context={"link": link})
def guest_links(
db: Session, settings: Settings, contact: GuestContact, links: list[tuple[Form, str]]
) -> bool:
return send(
db, settings, for_guest(contact, settings), kind="guest_links",
context={"links": links},
)
def registration(
db: Session, settings: Settings, email: str, name: str, language: str, link: str | None
) -> bool:
"""Link zum Anlegen eines Kontos; ohne Link: Hinweis, dass es schon ein Konto gibt."""
recipient = Recipient(email, name, language)
origin = settings.public_origin
return send(
db, settings, recipient, kind="register" if link else "register_exists",
context={"link": link, "login_url": f"{origin}/login", "forgot_url": f"{origin}/forgot"},
)
def account_link(
db: Session, settings: Settings, user: UserAccount, link: str, *, invite: bool
) -> bool:
"""Einladung oder Link zum Zurücksetzen des Passworts."""
return send(
db, settings, user, kind="invite" if invite else "password_reset",
context={"link": link},
)