"""Turning an event into an email."""
from __future__ import annotations
import html
from dataclasses import dataclass
from typing import Any
from s365b.core.branding import Branding
from s365b.db.models import Event
[docs]
LINKS = {
"job_failed": "/jobs",
"job_warning": "/jobs",
"job_stopped": "/jobs",
"job_succeeded": "/jobs",
"restore_succeeded": "/jobs",
"restore_warning": "/jobs",
"restore_failed": "/jobs",
"restore_stopped": "/jobs",
"test": "/settings/notifications",
}
@dataclass(frozen=True, slots=True)
[docs]
class Message:
"""An email ready to send.
Attributes:
subject: Subject line.
text: Plain-text body.
html: HTML body.
"""
def _rows(body: dict[str, Any]) -> list[tuple[str, str]]:
rows: list[tuple[str, str]] = []
for key, value in body.items():
if key in ("items", "failures", "totals", "always") or value in (None, "", [], {}):
continue
rows.append((key.replace("_", " ").capitalize(), str(value)))
totals = body.get("totals")
if isinstance(totals, dict):
parts = [f"{v} {k}" for k, v in totals.items() if k != "bytes" and v]
rows.append(("Changes", ", ".join(parts) or "none"))
return rows
def _lines(body: dict[str, Any]) -> list[str]:
lines: list[str] = []
for f in body.get("failures") or []:
lines.append(f"{f.get('object') or f.get('module')}: {f.get('error') or f.get('warning')}")
for item in body.get("items") or []:
where = f" ({item['path']})" if item.get("path") else ""
lines.append(f"{item.get('change', '').capitalize()}: {item.get('name')}{where}")
return lines
[docs]
def render(event: Event, branding: Branding, base_url: str, prefix: str = "") -> Message:
"""Build the email for an event.
Args:
event: The event.
branding: Product name and email footer.
base_url: Public URL of the web UI, for the link.
prefix: Subject prefix; empty means ``[<product name>]``.
Returns:
The message.
"""
prefix = prefix or f"[{branding.product_name}]"
level = event.severity.upper()
subject = f"{prefix} [{level}] {event.subject}"
body: dict[str, Any] = dict(event.body or {})
path = LINKS.get(event.type, "/browse" if "." in event.type else "/")
link = f"{base_url.rstrip('/')}{path}"
rows, lines = _rows(body), _lines(body)
footer = branding.email_footer.strip()
text = [event.subject, ""]
text += [f"{k}: {v}" for k, v in rows]
if lines:
text += ["", *(f"- {line}" for line in lines[:100])]
if len(lines) > 100:
text.append(f"- … and {len(lines) - 100} more")
text += ["", f"Open {branding.product_name}: {link}"]
if footer:
text += ["", "--", footer]
e = html.escape
parts = [
'<div style="font-family:system-ui,-apple-system,Segoe UI,sans-serif;font-size:15px;'
'line-height:1.5;color:#1b1f27;max-width:40rem">',
f'<p style="margin:0 0 4px;font-size:12px;letter-spacing:.06em;color:#5b6270">'
f"{e(level)} · {e(branding.product_name)}</p>",
f'<h1 style="font-size:19px;margin:0 0 16px">{e(event.subject)}</h1>',
]
if rows:
parts.append('<table style="border-collapse:collapse;margin-bottom:16px">')
parts += [
f'<tr><th style="text-align:left;padding:2px 16px 2px 0;color:#5b6270;'
f'font-weight:normal">{e(k)}</th><td>{e(v)}</td></tr>'
for k, v in rows
]
parts.append("</table>")
if lines:
parts.append("<ul>" + "".join(f"<li>{e(line)}</li>" for line in lines[:100]) + "</ul>")
if len(lines) > 100:
parts.append(f"<p>… and {len(lines) - 100} more.</p>")
parts.append(f'<p><a href="{e(link)}">Open {e(branding.product_name)}</a></p>')
if footer:
parts.append(
f'<p style="margin-top:24px;font-size:13px;color:#5b6270;white-space:pre-line">'
f"{e(footer)}</p>"
)
parts.append("</div>")
return Message(subject=subject, text="\n".join(text), html="".join(parts))