Add a notification history
Every notification is written down with how it went through each channel (or why it was not sent: held for quiet hours, a routing rule said nobody, no channel on). Records -> Notifications lists them with a filter, a search and Send again. Errors are cleaned of every secret in the settings; kept 30 days. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
5c6ccc0a4b
commit
9126200295
18 files changed
+9886
-34
No files matched your search
@@ -19,6 +19,7 @@ import { dependenciesRouter } from "./routes/dependencies.js";
|
||||
import { pushRouter } from "./routes/push.js";
|
||||
import { endpointsRouter } from "./routes/endpoints.js";
|
||||
import { changesRouter } from "./routes/changes.js";
|
||||
import { notificationLogRouter } from "./routes/notificationLog.js";
|
||||
import { backupsRouter } from "./routes/backups.js";
|
||||
import { metricsRouter, metricsTokensRouter } from "./routes/metrics.js";
|
||||
import { eventWebhooksRouter } from "./routes/eventWebhooks.js";
|
||||
@@ -175,6 +176,7 @@ export function createApp() {
|
||||
app.use("/api/push", pushRouter);
|
||||
app.use("/api/endpoints", endpointsRouter);
|
||||
app.use("/api/changes", changesRouter);
|
||||
app.use("/api/notification-log", notificationLogRouter);
|
||||
app.use("/api/backups", backupsRouter);
|
||||
app.use("/api/metrics-tokens", metricsTokensRouter);
|
||||
app.use("/api/event-webhooks", eventWebhooksRouter);
|
||||
|
||||
@@ -1662,6 +1662,22 @@ export const jellyfinReadings = sqliteTable(
|
||||
|
||||
// ─── Duplicati ──────────────────────────────────────────────────────────────
|
||||
|
||||
// What was sent: one row for each notification, with how it went through each channel, so "why did I not get it?" has an answer. Kept 30 days and at most 1000 rows (services/notificationLog.ts).
|
||||
export const notificationLog = sqliteTable(
|
||||
"notification_log",
|
||||
{
|
||||
id: integer("id").primaryKey({ autoIncrement: true }),
|
||||
at: text("at").notNull(), // ISO
|
||||
title: text("title").notNull(),
|
||||
message: text("message").notNull(), // cut at 4000 characters
|
||||
status: text("status").notNull(), // sent | partly | failed | none (no channel to send it to) | held (quiet hours or away) | muted (a routing rule says nobody)
|
||||
results: text("results").notNull().default("[]"), // JSON: [{ channel, ok, error }]
|
||||
note: text("note"), // why it was held or muted
|
||||
resentOf: integer("resent_of"), // the entry it is a resend of
|
||||
},
|
||||
(t) => [index("notification_log_at_idx").on(t.at)],
|
||||
);
|
||||
|
||||
// A Duplicati that reports to this app: one row per machine running it, with the secret token its reports carry in their address (only the hash is kept). Duplicati pushes a
|
||||
// report after every operation (its own "send-http-url" option); services/duplicati.ts reads them.
|
||||
export const duplicatiSources = sqliteTable("duplicati_sources", {
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
import { Router } from "express";
|
||||
import { requireAuth, requireRole } from "../auth/middleware.js";
|
||||
import { recordAudit } from "../services/audit.js";
|
||||
import { resendLogged } from "../services/notify.js";
|
||||
import { listLogged, STATUSES, type LogStatus } from "../services/notificationLog.js";
|
||||
import { asyncHandler } from "../utils/asyncHandler.js";
|
||||
|
||||
export const notificationLogRouter = Router();
|
||||
|
||||
// What was sent says what is going on in the lab, and why a channel is failing: operators and administrators, like the change log.
|
||||
notificationLogRouter.use(requireAuth, requireRole("operator"));
|
||||
|
||||
// ?status=failed &q=word &limit=200
|
||||
notificationLogRouter.get("/", asyncHandler(async (req, res) => {
|
||||
const status = STATUSES.find((s) => s === req.query.status) as LogStatus | undefined;
|
||||
const limit = Number(req.query.limit);
|
||||
const entries = await listLogged({ status, q: typeof req.query.q === "string" ? req.query.q.slice(0, 100) : undefined, limit: Number.isFinite(limit) ? limit : 200 });
|
||||
res.json({ entries, statuses: STATUSES });
|
||||
}));
|
||||
|
||||
// Sends one again, to every channel that is on (not to the audience it first had, and without the buttons an alert carried), and writes down how that went.
|
||||
notificationLogRouter.post("/:id/resend", asyncHandler(async (req, res) => {
|
||||
const id = /^\d+$/.test(req.params.id) ? Number(req.params.id) : NaN;
|
||||
if (!Number.isInteger(id)) return res.status(400).json({ error: "invalid_id" });
|
||||
const sent = await resendLogged(id);
|
||||
if (!sent) return res.status(404).json({ error: "not_found" });
|
||||
await recordAudit({ actor: req.currentUser!, category: "notification", action: "resend", targetType: "notification", targetId: id, detail: { newEntry: sent.id } });
|
||||
res.json({ ok: true, entry: sent.id });
|
||||
}));
|
||||
@@ -47,6 +47,7 @@ const KIND_OF_CATEGORY: Record<string, ChangeKind> = {
|
||||
todo: "other",
|
||||
note: "servers",
|
||||
webhook: "settings",
|
||||
notification: "settings",
|
||||
integration: "integrations",
|
||||
dns: "integrations",
|
||||
secret: "integrations",
|
||||
@@ -194,6 +195,8 @@ export function describeChange(category: string, action: string, detail: Record<
|
||||
return { title: `${typeof detail.changed === "number" ? detail.changed : "Several"} snoozed alert${detail.changed === 1 ? "" : "s"} woken at once`, tone: "neutral", detail: null };
|
||||
case "inventory/bulk_change":
|
||||
return { title: detail.change === "undo" ? "A change to several pieces of hardware was undone" : `${typeof detail.changed === "number" ? detail.changed : "Several"} piece${detail.changed === 1 ? "" : "s"} of hardware changed at once`, tone: "neutral", detail: genericSummary(detail, ["ids", "changed", "change"]) };
|
||||
case "notification/resend":
|
||||
return { title: "A notification was sent again", tone: "neutral", detail: null };
|
||||
case "webhook/retry":
|
||||
return { title: `A webhook message was sent again${name ? `: ${name}` : str(detail.label) ? `: ${str(detail.label)}` : ""}`, tone: detail.ok === false ? "bad" : "neutral", detail: str(detail.event) };
|
||||
case "duplicati/create_source":
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
/**
|
||||
* What was sent: every notification is written down with how it went through each channel, so "why did I not get it?" has an answer — it went through ntfy and Gotify said 401, it was held
|
||||
* for quiet hours, a routing rule said nobody should hear it, or no channel was switched on to send it to. Kept 30 days and at most 1000 entries. Nothing here can make sending fail: writing
|
||||
* it down is best-effort, like the channels themselves. An error's text is cleaned of every token, key and password in the settings before it is kept, since a channel may say them back.
|
||||
*/
|
||||
import { and, desc, eq, like, lt, notInArray, or } from "drizzle-orm";
|
||||
import { db } from "../db/client.js";
|
||||
import { notificationLog } from "../db/schema.js";
|
||||
import { getSettings } from "./settingsStore.js";
|
||||
|
||||
export const KEEP_DAYS = 30;
|
||||
export const KEEP_ROWS = 1000;
|
||||
export const MAX_MESSAGE = 4000;
|
||||
export const MAX_ERROR = 300;
|
||||
export const STATUSES = ["sent", "partly", "failed", "none", "held", "muted"] as const;
|
||||
export type LogStatus = (typeof STATUSES)[number];
|
||||
|
||||
export interface ChannelResult {
|
||||
/** gotify, ntfy, telegram, pushover, smtp, webhook, webPush, or email (an escalation to one address). */
|
||||
channel: string;
|
||||
ok: boolean;
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
export type LogRow = typeof notificationLog.$inferSelect;
|
||||
|
||||
const clip = (text: string, max: number) => (text.length <= max ? text : `${text.slice(0, max - 1)}…`);
|
||||
|
||||
/** Pure: how a notification went, from how each channel did. Nothing switched on to send it to is "none". */
|
||||
export function statusOf(results: ChannelResult[]): LogStatus {
|
||||
if (results.length === 0) return "none";
|
||||
const ok = results.filter((r) => r.ok).length;
|
||||
return ok === results.length ? "sent" : ok === 0 ? "failed" : "partly";
|
||||
}
|
||||
|
||||
/** Pure: text with each of these values (at least six characters, so a stray short word is not swallowed) replaced by dots. */
|
||||
export function scrub(text: string, secrets: (string | null | undefined)[]): string {
|
||||
let out = text;
|
||||
for (const s of [...new Set(secrets.filter((x): x is string => typeof x === "string" && x.length >= 6))].sort((a, b) => b.length - a.length)) {
|
||||
out = out.split(s).join("•••");
|
||||
// A token inside an address is also written percent-encoded.
|
||||
const encoded = encodeURIComponent(s);
|
||||
if (encoded !== s) out = out.split(encoded).join("•••");
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
async function secretsNow(): Promise<string[]> {
|
||||
const s = await getSettings();
|
||||
return [s.gotify.token, s.ntfy.token, s.telegram.token, s.pushover.appToken, s.pushover.userKey, s.smtp.password, s.webhook.secret, s.webhook.url, s.telegram.chatId].filter((x): x is string => typeof x === "string");
|
||||
}
|
||||
|
||||
let sinceTrim = 0;
|
||||
|
||||
/** Keeps the log to KEEP_DAYS and KEEP_ROWS: old entries first, and only now and then the count. */
|
||||
async function trim(now: Date): Promise<void> {
|
||||
await db.delete(notificationLog).where(lt(notificationLog.at, new Date(now.getTime() - KEEP_DAYS * 86_400_000).toISOString()));
|
||||
if (++sinceTrim < 50) return;
|
||||
sinceTrim = 0;
|
||||
const keep = await db.select({ id: notificationLog.id }).from(notificationLog).orderBy(desc(notificationLog.at), desc(notificationLog.id)).limit(KEEP_ROWS);
|
||||
if (keep.length === KEEP_ROWS) await db.delete(notificationLog).where(notInArray(notificationLog.id, keep.map((k) => k.id)));
|
||||
}
|
||||
|
||||
/** Writes down one notification: what it said, and how it went (or why it was held or muted). Returns its id, or null when it could not be written — never throws. */
|
||||
export async function recordNotification(entry: { title: string; message: string; results: ChannelResult[]; status?: LogStatus; note?: string | null; resentOf?: number | null }, now: Date = new Date()): Promise<number | null> {
|
||||
try {
|
||||
const secrets = await secretsNow();
|
||||
const results = entry.results.map((r) => ({ channel: r.channel, ok: r.ok, error: r.error === null ? null : clip(scrub(r.error.replace(/\s+/g, " ").trim(), secrets), MAX_ERROR) }));
|
||||
const [row] = await db
|
||||
.insert(notificationLog)
|
||||
.values({ at: now.toISOString(), title: clip(entry.title, 300), message: clip(entry.message, MAX_MESSAGE), status: entry.status ?? statusOf(results), results: JSON.stringify(results), note: entry.note ?? null, resentOf: entry.resentOf ?? null })
|
||||
.returning({ id: notificationLog.id });
|
||||
await trim(now);
|
||||
return row.id;
|
||||
} catch (err) {
|
||||
console.error("[notificationLog] couldn't write it down:", err instanceof Error ? err.message : err);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function resultsOf(row: Pick<LogRow, "results">): ChannelResult[] {
|
||||
try {
|
||||
const v = JSON.parse(row.results);
|
||||
return Array.isArray(v) ? (v as ChannelResult[]) : [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
export async function getLogged(id: number): Promise<LogRow | null> {
|
||||
return (await db.select().from(notificationLog).where(eq(notificationLog.id, id)).limit(1))[0] ?? null;
|
||||
}
|
||||
|
||||
/** The newest first, optionally of one status, or with a word in the title or message. */
|
||||
export async function listLogged(options: { status?: LogStatus; q?: string; limit?: number } = {}): Promise<(Omit<LogRow, "results"> & { results: ChannelResult[] })[]> {
|
||||
const q = options.q?.trim();
|
||||
const rows = await db
|
||||
.select()
|
||||
.from(notificationLog)
|
||||
.where(and(options.status ? eq(notificationLog.status, options.status) : undefined, q ? or(like(notificationLog.title, `%${q.replace(/[%_]/g, "")}%`), like(notificationLog.message, `%${q.replace(/[%_]/g, "")}%`)) : undefined))
|
||||
.orderBy(desc(notificationLog.at), desc(notificationLog.id))
|
||||
.limit(Math.min(500, Math.max(1, Math.round(options.limit ?? 200))));
|
||||
return rows.map((r) => ({ ...r, results: resultsOf(r) }));
|
||||
}
|
||||
@@ -12,12 +12,18 @@ import { dampRaised, dampRecovered } from "./flapGuard.js";
|
||||
import { withoutSnoozed } from "./alertSnoozes.js";
|
||||
import { actionsFor, footerText, ntfyActionsHeader, type NotifyActions } from "./alertActionLinks.js";
|
||||
import { firstMatchingRule, metaOfConditionKey, pushAccepts, type ChannelId, type NotifyMeta } from "./notifyRouting.js";
|
||||
import { getLogged, recordNotification, type ChannelResult } from "./notificationLog.js";
|
||||
|
||||
// ─── Channel senders (best-effort — failures are logged, never thrown) ──────
|
||||
|
||||
async function sendGotify(title: string, message: string, actions?: NotifyActions | null) {
|
||||
/** How one channel did: null when it is not switched on (or has nobody to send to), so there is nothing to say about it. */
|
||||
type SendOutcome = { ok: true } | { ok: false; error: string } | null;
|
||||
const OK: SendOutcome = { ok: true };
|
||||
const failure = (error: string): SendOutcome => ({ ok: false, error });
|
||||
|
||||
async function sendGotify(title: string, message: string, actions?: NotifyActions | null): Promise<SendOutcome> {
|
||||
const { gotify } = await getSettings();
|
||||
if (!gotify.enabled || !gotify.url || !gotify.token) return;
|
||||
if (!gotify.enabled || !gotify.url || !gotify.token) return null;
|
||||
const base = gotify.url.replace(/\/$/, "");
|
||||
try {
|
||||
const res = await fetch(`${base}/message?token=${encodeURIComponent(gotify.token)}`, {
|
||||
@@ -26,9 +32,15 @@ async function sendGotify(title: string, message: string, actions?: NotifyAction
|
||||
// Gotify has no buttons: a tap opens the page with them (and the address is in the text, for a client that does not tap).
|
||||
body: JSON.stringify({ title, message: actions ? message + footerText(actions) : message, priority: gotify.priority ?? 5, ...(actions ? { extras: { "client::notification": { click: { url: actions.pageUrl } } } } : {}) }),
|
||||
});
|
||||
if (!res.ok) console.error(`[notify] Gotify error ${res.status}: ${await res.text().catch(() => "")}`);
|
||||
if (!res.ok) {
|
||||
const error = `Gotify error ${res.status}: ${await res.text().catch(() => "")}`;
|
||||
console.error(`[notify] ${error}`);
|
||||
return failure(error);
|
||||
}
|
||||
return OK;
|
||||
} catch (err) {
|
||||
console.error("[notify] Gotify failed:", err instanceof Error ? err.message : err);
|
||||
return failure(`Gotify failed: ${err instanceof Error ? err.message : err}`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -41,9 +53,9 @@ export function headerSafe(text: string): string {
|
||||
return /^[ -~]*$/.test(text) ? text : `=?UTF-8?B?${Buffer.from(text, "utf8").toString("base64")}?=`;
|
||||
}
|
||||
|
||||
async function sendNtfy(title: string, message: string, actions?: NotifyActions | null) {
|
||||
async function sendNtfy(title: string, message: string, actions?: NotifyActions | null): Promise<SendOutcome> {
|
||||
const { ntfy } = await getSettings();
|
||||
if (!ntfy.enabled || !ntfy.url || !ntfy.topic) return;
|
||||
if (!ntfy.enabled || !ntfy.url || !ntfy.topic) return null;
|
||||
const base = ntfy.url.replace(/\/$/, "");
|
||||
const headers: Record<string, string> = {
|
||||
"Content-Type": "text/plain",
|
||||
@@ -57,9 +69,15 @@ async function sendNtfy(title: string, message: string, actions?: NotifyActions
|
||||
}
|
||||
try {
|
||||
const res = await fetch(`${base}/${encodeURIComponent(ntfy.topic)}`, { method: "POST", headers, body: message });
|
||||
if (!res.ok) console.error(`[notify] ntfy error ${res.status}: ${await res.text().catch(() => "")}`);
|
||||
if (!res.ok) {
|
||||
const error = `ntfy error ${res.status}: ${await res.text().catch(() => "")}`;
|
||||
console.error(`[notify] ${error}`);
|
||||
return failure(error);
|
||||
}
|
||||
return OK;
|
||||
} catch (err) {
|
||||
console.error("[notify] ntfy failed:", err instanceof Error ? err.message : err);
|
||||
return failure(`ntfy failed: ${err instanceof Error ? err.message : err}`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -122,29 +140,33 @@ export async function pushoverSend(cfg: { appToken: string; userKey: string; dev
|
||||
if (!res.ok || json?.status !== 1) throw new Error(`Pushover: ${json?.errors?.length ? json.errors.join(", ") : `HTTP ${res.status}`}`);
|
||||
}
|
||||
|
||||
async function sendTelegram(title: string, message: string, actions?: NotifyActions | null) {
|
||||
async function sendTelegram(title: string, message: string, actions?: NotifyActions | null): Promise<SendOutcome> {
|
||||
const { telegram } = await getSettings();
|
||||
if (!telegram.enabled || !telegram.token || !telegram.chatId) return;
|
||||
if (!telegram.enabled || !telegram.token || !telegram.chatId) return null;
|
||||
try {
|
||||
await telegramSend(telegram, `${title}\n\n${message}`, actions);
|
||||
return OK;
|
||||
} catch (err) {
|
||||
console.error("[notify]", err instanceof Error ? err.message : "Telegram failed");
|
||||
return failure(err instanceof Error ? err.message : "Telegram failed");
|
||||
}
|
||||
}
|
||||
|
||||
async function sendPushover(title: string, message: string, actions?: NotifyActions | null) {
|
||||
async function sendPushover(title: string, message: string, actions?: NotifyActions | null): Promise<SendOutcome> {
|
||||
const { pushover } = await getSettings();
|
||||
if (!pushover.enabled || !pushover.appToken || !pushover.userKey) return;
|
||||
if (!pushover.enabled || !pushover.appToken || !pushover.userKey) return null;
|
||||
try {
|
||||
await pushoverSend(pushover, title, message, actions);
|
||||
return OK;
|
||||
} catch (err) {
|
||||
console.error("[notify]", err instanceof Error ? err.message : "Pushover failed");
|
||||
return failure(err instanceof Error ? err.message : "Pushover failed");
|
||||
}
|
||||
}
|
||||
|
||||
async function sendSmtp(title: string, message: string, actions?: NotifyActions | null) {
|
||||
async function sendSmtp(title: string, message: string, actions?: NotifyActions | null): Promise<SendOutcome> {
|
||||
const { smtp } = await getSettings();
|
||||
if (!smtp.enabled || !smtp.host || !smtp.to || !smtp.from) return;
|
||||
if (!smtp.enabled || !smtp.host || !smtp.to || !smtp.from) return null;
|
||||
try {
|
||||
const transporter = nodemailer.createTransport({
|
||||
host: smtp.host,
|
||||
@@ -153,14 +175,16 @@ async function sendSmtp(title: string, message: string, actions?: NotifyActions
|
||||
auth: smtp.username ? { user: smtp.username, pass: smtp.password } : undefined,
|
||||
});
|
||||
await transporter.sendMail({ from: smtp.from, to: smtp.to, subject: title, text: actions ? message + footerText(actions) : message });
|
||||
return OK;
|
||||
} catch (err) {
|
||||
console.error("[notify] SMTP failed:", err instanceof Error ? err.message : err);
|
||||
return failure(`SMTP failed: ${err instanceof Error ? err.message : err}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function sendWebhook(title: string, message: string, actions?: NotifyActions | null) {
|
||||
async function sendWebhook(title: string, message: string, actions?: NotifyActions | null): Promise<SendOutcome> {
|
||||
const { webhook } = await getSettings();
|
||||
if (!webhook.enabled || !webhook.url) return;
|
||||
if (!webhook.enabled || !webhook.url) return null;
|
||||
const headers: Record<string, string> = { "Content-Type": "application/json" };
|
||||
if (webhook.secret) headers["X-Webhook-Secret"] = webhook.secret;
|
||||
try {
|
||||
@@ -169,32 +193,42 @@ async function sendWebhook(title: string, message: string, actions?: NotifyActio
|
||||
headers,
|
||||
body: JSON.stringify({ content: `**${title}**\n${message}${actions ? footerText(actions) : ""}` }),
|
||||
});
|
||||
if (!res.ok) console.error(`[notify] Webhook error ${res.status}: ${await res.text().catch(() => "")}`);
|
||||
if (!res.ok) {
|
||||
const error = `Webhook error ${res.status}: ${await res.text().catch(() => "")}`;
|
||||
console.error(`[notify] ${error}`);
|
||||
return failure(error);
|
||||
}
|
||||
return OK;
|
||||
} catch (err) {
|
||||
console.error("[notify] Webhook failed:", err instanceof Error ? err.message : err);
|
||||
return failure(`Webhook failed: ${err instanceof Error ? err.message : err}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function sendWebPush(title: string, message: string, only: number[] | null, actions?: NotifyActions | null) {
|
||||
async function sendWebPush(title: string, message: string, only: number[] | null, actions?: NotifyActions | null): Promise<SendOutcome> {
|
||||
const { webPush } = await getSettings();
|
||||
if (!webPush.enabled) return;
|
||||
if (!webPush.enabled) return null;
|
||||
// For one alert, buttons on the notification itself (browsers show two); for several, a tap opens the app.
|
||||
const buttons = actions?.direct.slice(0, 2).map((d) => ({ action: d.id, title: d.label, path: d.path }));
|
||||
const message_ = { title, body: message, ...(buttons?.length ? { actions: buttons } : {}) };
|
||||
try {
|
||||
if (only === null) await sendPush(message_);
|
||||
else if (only.length > 0) await sendPush(message_, await db.select().from(pushSubscriptions).where(inArray(pushSubscriptions.id, only)));
|
||||
// No browser wants it: nothing was asked of the channel.
|
||||
else return null;
|
||||
return OK;
|
||||
} catch (err) {
|
||||
console.error("[notify] Web push failed:", err instanceof Error ? err.message : err);
|
||||
return failure(`Web push failed: ${err instanceof Error ? err.message : err}`);
|
||||
}
|
||||
}
|
||||
|
||||
/** Email to one address, through the email channel's server, whatever the channel's own recipient is (an escalation to someone else). */
|
||||
async function sendExtraEmail(title: string, message: string, to: string) {
|
||||
async function sendExtraEmail(title: string, message: string, to: string): Promise<SendOutcome> {
|
||||
const { smtp } = await getSettings();
|
||||
if (!smtp.host || !smtp.from) {
|
||||
console.error("[notify] An escalation wants to email someone, but email isn't set up.");
|
||||
return;
|
||||
return failure("An escalation wants to email someone, but email isn't set up.");
|
||||
}
|
||||
try {
|
||||
const transporter = nodemailer.createTransport({
|
||||
@@ -204,8 +238,10 @@ async function sendExtraEmail(title: string, message: string, to: string) {
|
||||
auth: smtp.username ? { user: smtp.username, pass: smtp.password } : undefined,
|
||||
});
|
||||
await transporter.sendMail({ from: smtp.from, to, subject: title, text: message });
|
||||
return OK;
|
||||
} catch (err) {
|
||||
console.error("[notify] Extra email failed:", err instanceof Error ? err.message : err);
|
||||
return failure(`Email failed: ${err instanceof Error ? err.message : err}`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -249,18 +285,21 @@ export async function audienceFor(meta?: NotifyMeta): Promise<Audience> {
|
||||
return { channels, pushIds };
|
||||
}
|
||||
|
||||
async function sendToChannels(title: string, message: string, audience: Audience = EVERYONE, actions: NotifyActions | null = null): Promise<void> {
|
||||
/** Sends to the channels the audience names (and are switched on), and writes down how each went: the entry's id, or null if it could not be written. */
|
||||
async function sendToChannels(title: string, message: string, audience: Audience = EVERYONE, actions: NotifyActions | null = null, resentOf: number | null = null): Promise<number | null> {
|
||||
const to = (c: ChannelId) => audience.channels === null || audience.channels.includes(c);
|
||||
await Promise.all([
|
||||
to("gotify") ? sendGotify(title, message, actions) : undefined,
|
||||
to("ntfy") ? sendNtfy(title, message, actions) : undefined,
|
||||
to("telegram") ? sendTelegram(title, message, actions) : undefined,
|
||||
to("pushover") ? sendPushover(title, message, actions) : undefined,
|
||||
to("smtp") ? sendSmtp(title, message, actions) : undefined,
|
||||
to("webhook") ? sendWebhook(title, message, actions) : undefined,
|
||||
to("webPush") ? sendWebPush(title, message, audience.pushIds, actions) : undefined,
|
||||
audience.email ? sendExtraEmail(title, actions ? message + footerText(actions) : message, audience.email) : undefined,
|
||||
]);
|
||||
const jobs: [string, Promise<SendOutcome>][] = [];
|
||||
if (to("gotify")) jobs.push(["gotify", sendGotify(title, message, actions)]);
|
||||
if (to("ntfy")) jobs.push(["ntfy", sendNtfy(title, message, actions)]);
|
||||
if (to("telegram")) jobs.push(["telegram", sendTelegram(title, message, actions)]);
|
||||
if (to("pushover")) jobs.push(["pushover", sendPushover(title, message, actions)]);
|
||||
if (to("smtp")) jobs.push(["smtp", sendSmtp(title, message, actions)]);
|
||||
if (to("webhook")) jobs.push(["webhook", sendWebhook(title, message, actions)]);
|
||||
if (to("webPush")) jobs.push(["webPush", sendWebPush(title, message, audience.pushIds, actions)]);
|
||||
if (audience.email) jobs.push(["email", sendExtraEmail(title, actions ? message + footerText(actions) : message, audience.email)]);
|
||||
const outcomes = await Promise.all(jobs.map(async ([channel, run]) => [channel, await run] as const));
|
||||
const results: ChannelResult[] = outcomes.filter(([, o]) => o !== null).map(([channel, o]) => ({ channel, ok: o!.ok, error: o!.ok ? null : o!.error }));
|
||||
return recordNotification({ title, message, results, resentOf });
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -268,10 +307,15 @@ async function sendToChannels(title: string, message: string, audience: Audience
|
||||
* said nobody. Escalations use this with their own channels.
|
||||
*/
|
||||
export async function notifyAudience(title: string, message: string, audience: Audience, options: { quietHours?: boolean; actions?: NotifyActions | null; critical?: boolean } = {}): Promise<void> {
|
||||
if (isMuted(audience)) return;
|
||||
if (isMuted(audience)) {
|
||||
await recordNotification({ title, message, results: [], status: "muted", note: "A routing rule says nobody should be told." });
|
||||
return;
|
||||
}
|
||||
// Held when quiet hours or an away stretch say so — unless it is critical and they let critical through (services/availability.ts).
|
||||
if (options.quietHours !== false && (await holdReason(options.critical === true))) {
|
||||
const held = options.quietHours !== false ? await holdReason(options.critical === true) : null;
|
||||
if (held) {
|
||||
await enqueueNotification(title, message, audience.channels === null && audience.pushIds === null && !audience.email ? null : JSON.stringify(audience));
|
||||
await recordNotification({ title, message, results: [], status: "held", note: held === "away" ? "Held while you are away; it is sent in the digest when you are back." : "Held for quiet hours; it is sent in the digest when they end." });
|
||||
return;
|
||||
}
|
||||
await sendToChannels(title, message, audience, options.actions ?? null);
|
||||
@@ -300,6 +344,13 @@ export async function notifyNow(title: string, message: string): Promise<void> {
|
||||
await sendToChannels(title, message);
|
||||
}
|
||||
|
||||
/** Sends a notification that was logged once more, to every channel that is on, and writes down the new attempt: its entry, or null if there is no such notification. */
|
||||
export async function resendLogged(id: number): Promise<{ id: number | null } | null> {
|
||||
const original = await getLogged(id);
|
||||
if (!original) return null;
|
||||
return { id: await sendToChannels(original.title, original.message, EVERYONE, null, id) };
|
||||
}
|
||||
|
||||
/** How many channels are switched on and filled in enough to send, so a "send it now" can say when there is nowhere to send to. */
|
||||
export async function enabledChannelCount(): Promise<number> {
|
||||
const { gotify, ntfy, telegram, pushover, smtp, webhook, webPush } = await getSettings();
|
||||
|
||||
Reference in new issue
Block a user