import { useEffect, useRef, useState, type KeyboardEvent, type ReactNode } from "react"; import { useSearchParams } from "react-router-dom"; import { api, type AppSettings, type GotifySettings, type NtfySettings, type SmtpSettings, type WebhookSettings, type WebPushSettings, type RoutingSettings, type EscalationSettings, type NotificationEvents, type DigestSettings, type QuietHoursSettings, type HealthCheckSettings, } from "../../api/client"; import { readableError } from "../../utils/errors"; import { ErrorNotice } from "../../components/Notice"; import { PageSkeleton } from "../../components/Skeleton"; import PushDevices from "../../components/PushDevices"; import RoutingEditor from "../../components/RoutingEditor"; const TIMEZONES = [ "UTC", "Europe/Stockholm", "Europe/London", "Europe/Berlin", "Europe/Paris", "Europe/Oslo", "Europe/Helsinki", "Europe/Amsterdam", "Europe/Copenhagen", "America/New_York", "America/Chicago", "America/Denver", "America/Los_Angeles", "America/Toronto", "America/Sao_Paulo", "Asia/Tokyo", "Asia/Shanghai", "Asia/Singapore", "Asia/Dubai", "Australia/Sydney", ]; const DEFAULT_GOTIFY: GotifySettings = { enabled: false, url: "", token: "", priority: 5 }; const DEFAULT_NTFY: NtfySettings = { enabled: false, url: "https://ntfy.sh", topic: "", token: "", priority: 3 }; const DEFAULT_SMTP: SmtpSettings = { enabled: false, host: "", port: 587, secure: false, username: "", password: "", from: "", to: "" }; const DEFAULT_WEBHOOK: WebhookSettings = { enabled: false, url: "", secret: "" }; const DEFAULT_WEBPUSH: WebPushSettings = { enabled: false, contact: "" }; const DEFAULT_ROUTING: RoutingSettings = { rules: [] }; const DEFAULT_ESCALATION: EscalationSettings = { enabled: false, steps: [] }; const DEFAULT_NOTIFICATIONS: NotificationEvents = { dnsAdd: true, dnsUpdate: true, dnsDelete: true, secretCheck: true, tailscaleKeyCheck: true, dockerUpdateCheck: true, proxmoxBackupCheck: true, pbsVerificationCheck: true, healthAlerts: true, automationAlerts: true, updateRunResults: true, domainExpiryCheck: true, secretCheckTime: "08:00", timezone: "UTC", integrationFailureAlerts: true, integrationFailureThreshold: 3, }; const DEFAULT_QUIET_HOURS: QuietHoursSettings = { enabled: false, start: "22:00", end: "07:00" }; const DEFAULT_DIGEST: DigestSettings = { enabled: false, day: 1, time: "08:00" }; // Monday first, as a week reads; the numbers are what the server keeps (0 = Sunday). const DIGEST_DAYS: { value: number; label: string }[] = [ { value: 1, label: "Monday" }, { value: 2, label: "Tuesday" }, { value: 3, label: "Wednesday" }, { value: 4, label: "Thursday" }, { value: 5, label: "Friday" }, { value: 6, label: "Saturday" }, { value: 0, label: "Sunday" }, ]; const DEFAULT_HEALTH_CHECKS: HealthCheckSettings = { serverOfflineMinutes: 60, diskUsagePercent: 90, domainWarnDays: 30, diskForecastDays: 14, backupStaleHours: 48 }; type TestResult = { ok: boolean; message: string } | null; type EventKey = { [K in keyof NotificationEvents]: NotificationEvents[K] extends boolean ? K : never }[keyof NotificationEvents]; const TABS = [ { id: "channels", label: "Channels" }, { id: "events", label: "What to send" }, { id: "routing", label: "Who hears what" }, { id: "when", label: "When" }, ] as const; type TabId = (typeof TABS)[number]["id"]; function TestBadge({ result }: { result: TestResult }) { if (!result) return null; return (
{result.ok ? "✓" : "✕"} {result.message}
); } /** The host of an address, for a channel's one-line summary — never the whole address, which can carry a token. */ function hostOf(address: string): string { try { return new URL(address).host; } catch { return address; } } /** One channel in the list: its name, whether it is on and filled in, and (opened) its settings. */ function ChannelRow({ name, description, enabled, onToggle, summary, complete, open, onOpen, children, }: { name: string; description: ReactNode; enabled: boolean; onToggle: (on: boolean) => void; /** What it is set to send to, once filled in ("elsa.lab", "my-topic"). */ summary: string; complete: boolean; open: boolean; onOpen: () => void; children: ReactNode; }) { const panelId = `channel-${name.replace(/\W+/g, "-").toLowerCase()}`; return (
{name}{" "} {enabled && complete && On} {enabled && !complete && On, but not filled in} {!enabled && complete && Off} {!enabled && !complete && Not set up}
{complete && summary ? summary : description}
{open && (
{complete && summary &&

{description}

} {children}
)}
); } function EventToggle({ label, checked, onChange }: { label: string; checked: boolean; onChange: (on: boolean) => void }) { return ( ); } function NumberField({ label, value, min, max, unit, hint, disabled, onChange, }: { label: string; value: number; min: number; max: number; unit: string; hint?: ReactNode; disabled?: boolean; onChange: (value: number) => void; }) { return (
onChange(Number(e.target.value))} /> {unit}
{hint &&
{hint}
}
); } export default function NotificationSettings() { const [params, setParams] = useSearchParams(); const tabParam = params.get("tab"); const tab: TabId = TABS.some((t) => t.id === tabParam) ? (tabParam as TabId) : "channels"; const tabRefs = useRef>({}); const [openChannel, setOpenChannel] = useState(null); const [loading, setLoading] = useState(true); const [loadError, setLoadError] = useState(null); const [saving, setSaving] = useState(false); const [saved, setSaved] = useState(false); const [saveError, setSaveError] = useState(null); /** The settings as last loaded or saved, so what has been changed since can be told. */ const [baseline, setBaseline] = useState(null); const [gotify, setGotify] = useState(DEFAULT_GOTIFY); const [ntfy, setNtfy] = useState(DEFAULT_NTFY); const [smtp, setSmtp] = useState(DEFAULT_SMTP); const [webhook, setWebhook] = useState(DEFAULT_WEBHOOK); const [webPush, setWebPush] = useState(DEFAULT_WEBPUSH); // Whether push is on as saved: people can only add their browsers once the server knows it is on. const [webPushSaved, setWebPushSaved] = useState(false); const [routing, setRouting] = useState(DEFAULT_ROUTING); const [escalation, setEscalation] = useState(DEFAULT_ESCALATION); const [notifications, setNotifications] = useState(DEFAULT_NOTIFICATIONS); const [quietHours, setQuietHours] = useState(DEFAULT_QUIET_HOURS); const [healthChecks, setHealthChecks] = useState(DEFAULT_HEALTH_CHECKS); const [digest, setDigest] = useState(DEFAULT_DIGEST); const [digestPreview, setDigestPreview] = useState<{ title: string; message: string } | null>(null); const [digestBusy, setDigestBusy] = useState<"preview" | "send" | null>(null); const [digestResult, setDigestResult] = useState(null); const [queuedCount, setQueuedCount] = useState(null); const [flushing, setFlushing] = useState(false); const [flushResult, setFlushResult] = useState(null); const [testingGotify, setTestingGotify] = useState(false); const [testGotifyResult, setTestGotifyResult] = useState(null); const [testingNtfy, setTestingNtfy] = useState(false); const [testNtfyResult, setTestNtfyResult] = useState(null); const [testingSmtp, setTestingSmtp] = useState(false); const [testSmtpResult, setTestSmtpResult] = useState(null); const [testingWebhook, setTestingWebhook] = useState(false); const [testWebhookResult, setTestWebhookResult] = useState(null); const snapshot = JSON.stringify({ gotify, ntfy, smtp, webhook, webPush, routing, escalation, notifications, quietHours, healthChecks, digest }); const dirty = baseline !== null && snapshot !== baseline; useEffect(() => { api.settings .get() .then((res: { settings: AppSettings }) => { const s = res.settings; setGotify(s.gotify); setNtfy(s.ntfy); setSmtp(s.smtp); setWebhook(s.webhook); const wp = s.webPush ?? DEFAULT_WEBPUSH; setWebPush(wp); setWebPushSaved(wp.enabled); const rt = s.routing ?? DEFAULT_ROUTING; const es = s.escalation ?? DEFAULT_ESCALATION; setRouting(rt); setEscalation(es); setNotifications(s.notifications); setQuietHours(s.quietHours); setHealthChecks(s.healthChecks); const d = s.digest ?? DEFAULT_DIGEST; setDigest(d); setBaseline(JSON.stringify({ gotify: s.gotify, ntfy: s.ntfy, smtp: s.smtp, webhook: s.webhook, webPush: wp, routing: rt, escalation: es, notifications: s.notifications, quietHours: s.quietHours, healthChecks: s.healthChecks, digest: d })); }) .catch((err) => setLoadError(err instanceof Error ? err.message : String(err))) .finally(() => setLoading(false)); api.settings .quietHoursQueue() .then((res) => setQueuedCount(res.count)) .catch(() => {}); }, []); // The browser asks before the tab is closed or reloaded with changes that haven't been saved. useEffect(() => { if (!dirty) return; const warn = (e: BeforeUnloadEvent) => { e.preventDefault(); e.returnValue = ""; }; window.addEventListener("beforeunload", warn); return () => window.removeEventListener("beforeunload", warn); }, [dirty]); function selectTab(id: TabId) { setParams( (prev) => { const next = new URLSearchParams(prev); if (id === "channels") next.delete("tab"); else next.set("tab", id); return next; }, { replace: true }, ); } function onTabKey(e: KeyboardEvent) { const at = TABS.findIndex((t) => t.id === tab); const to = e.key === "ArrowRight" ? (at + 1) % TABS.length : e.key === "ArrowLeft" ? (at + TABS.length - 1) % TABS.length : e.key === "Home" ? 0 : e.key === "End" ? TABS.length - 1 : -1; if (to === -1) return; e.preventDefault(); selectTab(TABS[to].id); tabRefs.current[TABS[to].id]?.focus(); } async function handleSave() { setSaving(true); setSaveError(null); setSaved(false); try { await api.settings.update({ gotify, ntfy, smtp, webhook, webPush, routing, escalation, notifications, quietHours, healthChecks, digest }); setBaseline(snapshot); setWebPushSaved(webPush.enabled); setSaved(true); setTimeout(() => setSaved(false), 3000); } catch (err) { setSaveError(err instanceof Error ? err.message : String(err)); } finally { setSaving(false); } } async function handleDigestPreview() { setDigestBusy("preview"); setDigestResult(null); try { const res = await api.settings.digestPreview(); setDigestPreview({ title: res.title, message: res.message }); } catch (err) { setDigestResult({ ok: false, message: err instanceof Error ? err.message : String(err) }); } finally { setDigestBusy(null); } } async function handleDigestSend() { setDigestBusy("send"); setDigestResult(null); try { const res = await api.settings.digestSend(); setDigestResult({ ok: true, message: `Sent through ${res.channels} channel${res.channels === 1 ? "" : "s"}.` }); } catch (err) { setDigestResult({ ok: false, message: readableError(err) }); } finally { setDigestBusy(null); } } async function handleFlushNow() { setFlushing(true); setFlushResult(null); try { const res = await api.settings.flushQuietHours(); setFlushResult(res.flushed > 0 ? `Sent a digest of ${res.flushed} queued notification${res.flushed !== 1 ? "s" : ""}.` : "Nothing was queued."); setQueuedCount(0); } catch (err) { setFlushResult(err instanceof Error ? err.message : String(err)); } finally { setFlushing(false); } } async function handleTestGotify() { setTestingGotify(true); setTestGotifyResult(null); try { await api.settings.testGotify(gotify); setTestGotifyResult({ ok: true, message: "Notification sent successfully." }); } catch (err) { setTestGotifyResult({ ok: false, message: err instanceof Error ? err.message : String(err) }); } finally { setTestingGotify(false); } } async function handleTestNtfy() { setTestingNtfy(true); setTestNtfyResult(null); try { await api.settings.testNtfy(ntfy); setTestNtfyResult({ ok: true, message: "Notification sent successfully." }); } catch (err) { setTestNtfyResult({ ok: false, message: err instanceof Error ? err.message : String(err) }); } finally { setTestingNtfy(false); } } async function handleTestSmtp() { setTestingSmtp(true); setTestSmtpResult(null); try { await api.settings.testSmtp(smtp); setTestSmtpResult({ ok: true, message: "Test email sent successfully." }); } catch (err) { setTestSmtpResult({ ok: false, message: err instanceof Error ? err.message : String(err) }); } finally { setTestingSmtp(false); } } async function handleTestWebhook() { setTestingWebhook(true); setTestWebhookResult(null); try { await api.settings.testWebhook(webhook); setTestWebhookResult({ ok: true, message: "Webhook delivered successfully." }); } catch (err) { setTestWebhookResult({ ok: false, message: err instanceof Error ? err.message : String(err) }); } finally { setTestingWebhook(false); } } if (loading) return ; const gotifyComplete = !!(gotify.url && gotify.token); const ntfyComplete = !!(ntfy.url && ntfy.topic); const smtpComplete = !!(smtp.host && smtp.from && smtp.to); const webhookComplete = !!webhook.url; const channelsOn = [gotify.enabled && gotifyComplete, ntfy.enabled && ntfyComplete, smtp.enabled && smtpComplete, webhook.enabled && webhookComplete, webPush.enabled].filter(Boolean).length; const toggle = (key: EventKey, label: string) => setNotifications((n) => ({ ...n, [key]: on }))} />; const dailyChecksEnabled = notifications.secretCheck || notifications.tailscaleKeyCheck || notifications.dockerUpdateCheck || notifications.proxmoxBackupCheck || notifications.pbsVerificationCheck || notifications.domainExpiryCheck; return ( <>

Notifications

{saveError && {saveError}} {saved && ✓ Settings saved} {dirty && !saved && Unsaved changes}
    {TABS.map((t) => (
  • ))}
{/* ── Channels ── */} {/* ── What to send ── */} {/* ── Who hears what ── */} {/* ── When ── */} ); }