import { reportError } from './monitor'; import webpush from 'web-push'; import { and, asc, eq, isNull, lte } from 'drizzle-orm'; import { db } from './db'; import { events, nativePushTokens, posts, pushMessages, pushSubscriptions, settings } from './db/schema'; import { sendNative } from './fcm'; import { getSettings } from './settings'; import { addDays, formatLong, TZ, today } from '$lib/dates'; import { PUSH_TOPICS, type PushTopic } from '$lib/push'; // ─── Schlüssel ──────────────────────────────────────────────────────────────── type Keys = { publicKey: string; privateKey: string }; let keys: Keys | null = null; /** VAPID-Schlüssel aus der .env oder – beim ersten Mal – erzeugt und gespeichert */ function vapid(): Keys { if (keys) return keys; if (process.env.VAPID_PUBLIC_KEY && process.env.VAPID_PRIVATE_KEY) { keys = { publicKey: process.env.VAPID_PUBLIC_KEY, privateKey: process.env.VAPID_PRIVATE_KEY }; } else { const row = db.select().from(settings).where(eq(settings.key, 'vapid')).get(); if (row) keys = row.value as Keys; else { keys = webpush.generateVAPIDKeys(); db.insert(settings).values({ key: 'vapid', value: keys }).run(); } } const s = getSettings(); const subject = s.contactEmail ? `mailto:${s.contactEmail}` : (process.env.ORIGIN ?? 'mailto:admin@example.org'); webpush.setVapidDetails(subject, keys.publicKey, keys.privateKey); return keys; } export const publicKey = () => vapid().publicKey; // ─── Abos ───────────────────────────────────────────────────────────────────── export type BrowserSubscription = { endpoint: string; keys: { p256dh: string; auth: string } }; const cleanTopics = (topics: unknown): PushTopic[] => Array.isArray(topics) ? [...new Set(topics.filter((t): t is PushTopic => typeof t === 'string' && t in PUSH_TOPICS))] : []; export function saveSubscription(sub: BrowserSubscription, topics: unknown) { const t = cleanTopics(topics); db.insert(pushSubscriptions) .values({ endpoint: sub.endpoint, p256dh: sub.keys.p256dh, auth: sub.keys.auth, topics: t }) .onConflictDoUpdate({ target: pushSubscriptions.endpoint, set: { p256dh: sub.keys.p256dh, auth: sub.keys.auth, topics: t } }) .run(); return t; } export function removeSubscription(endpoint: string) { db.delete(pushSubscriptions).where(eq(pushSubscriptions.endpoint, endpoint)).run(); } /** Empfänger je Thema – Browser (Web-Push) und App-Geräte zusammen */ export function subscriberCounts() { const web = db.select({ topics: pushSubscriptions.topics }).from(pushSubscriptions).all(); const app = db.select({ topics: nativePushTokens.topics }).from(nativePushTokens).all(); const counts = Object.fromEntries(Object.keys(PUSH_TOPICS).map((k) => [k, 0])) as Record; for (const r of [...web, ...app]) for (const t of r.topics) if (t in counts) counts[t as PushTopic]++; return { total: web.length + app.length, web: web.length, app: app.length, byTopic: counts }; } // ─── Versand ────────────────────────────────────────────────────────────────── type Payload = { title: string; body?: string; url?: string }; /** * Sendet an alle Abos eines Themas. Mit `dedupeKey` wird dieselbe Nachricht * garantiert nur einmal verschickt (z. B. nach einem Neustart). */ export async function sendToTopic( topic: PushTopic | 'all', payload: Payload, opts: { automatic?: boolean; dedupeKey?: string; sentBy?: number } = {} ) { vapid(); const subs = db .select() .from(pushSubscriptions) .all() .filter((s) => (topic === 'all' ? s.topics.length > 0 : s.topics.includes(topic))); const appDevices = db .select({ topics: nativePushTokens.topics }) .from(nativePushTokens) .all() .filter((d) => (topic === 'all' ? d.topics.length > 0 : d.topics.includes(topic))).length; // Automatische Nachrichten ohne Empfänger nicht als „gesendet“ vermerken – // sonst wäre z. B. eine Schließzeit-Erinnerung verbraucht, bevor jemand abonniert hat if (opts.automatic && subs.length === 0 && appDevices === 0) return null; let messageId: number; try { messageId = db .insert(pushMessages) .values({ topic, title: payload.title, body: payload.body ?? '', url: payload.url ?? '/', automatic: opts.automatic ?? false, dedupeKey: opts.dedupeKey ?? null, sentBy: opts.sentBy ?? null }) .returning({ id: pushMessages.id }) .get().id; } catch { return null; // schon gesendet (dedupeKey) } const body = JSON.stringify({ title: payload.title, body: payload.body ?? '', url: payload.url ?? '/' }); let ok = 0, failed = 0; // in kleinen Gruppen senden, damit der Server nicht überlastet for (let i = 0; i < subs.length; i += 10) { await Promise.all( subs.slice(i, i + 10).map(async (s) => { try { await webpush.sendNotification({ endpoint: s.endpoint, keys: { p256dh: s.p256dh, auth: s.auth } }, body, { TTL: 60 * 60 * 24, urgency: 'normal' }); ok++; } catch (e) { failed++; const status = (e as { statusCode?: number }).statusCode; // Abo existiert nicht mehr (App deinstalliert, Berechtigung entzogen) if (status === 404 || status === 410) removeSubscription(s.endpoint); } }) ); } // Native Apps (iOS/Android) über Firebase const native = await sendNative(topic, { title: payload.title, body: payload.body ?? '', url: payload.url ?? '/' }); ok += native.ok; failed += native.failed; db.update(pushMessages).set({ recipients: ok, failures: failed }).where(eq(pushMessages.id, messageId)).run(); return { recipients: ok, failures: failed }; } // ─── Automatische Benachrichtigungen ────────────────────────────────────────── /** * Meldungen mit „Benachrichtigung senden“, die jetzt sichtbar sind. Jede Meldung * wird genau einmal gemeldet – auch wenn sie als Entwurf mit älterem Datum * angelegt und erst später veröffentlicht wurde. */ export async function sendDuePosts() { const due = db .select() .from(posts) .where( and( eq(posts.notify, true), isNull(posts.notifiedAt), eq(posts.published, true), lte(posts.publishedAt, new Date()) ) ) .all(); for (const p of due) { db.update(posts).set({ notifiedAt: new Date() }).where(eq(posts.id, p.id)).run(); await sendToTopic('news', { title: p.title, body: p.teaser, url: `/meldungen/${p.slug}` }, { automatic: true, dedupeKey: `post-${p.id}` }); } } /** Erinnerung am Nachmittag vor einer Schließzeit */ export async function sendClosureReminders() { const hour = Number(new Intl.DateTimeFormat('de-DE', { hour: 'numeric', hour12: false, timeZone: TZ }).format(new Date())); if (hour < 14) return; const tomorrow = addDays(today(), 1); const closures = db .select() .from(events) .where(and(eq(events.kind, 'closure'), eq(events.published, true), eq(events.startDate, tomorrow))) .all(); for (const c of closures) { const until = c.endDate && c.endDate !== c.startDate ? ` bis ${formatLong(c.endDate)}` : ''; await sendToTopic( 'closures', { title: `Morgen geschlossen: ${c.title}`, body: `Die Werkstatt ist ab ${formatLong(c.startDate)}${until} geschlossen.`, url: '/termine?zeige=schliesszeiten' }, { automatic: true, dedupeKey: `closure-${c.id}-${c.startDate}` } ); } } export function startPushScheduler() { const run = () => Promise.all([sendDuePosts(), sendClosureReminders()]).catch((e) => reportError('Push-Zeitplan', e)); run(); setInterval(run, 5 * 60e3).unref(); } /** Geplante Benachrichtigungen (Meldungen mit Häkchen, noch nicht gesendet) */ export function pendingPostNotifications() { return db .select({ id: posts.id, title: posts.title, published: posts.published, publishedAt: posts.publishedAt }) .from(posts) .where(and(eq(posts.notify, true), isNull(posts.notifiedAt))) .orderBy(asc(posts.publishedAt)) .all() .map((p) => ({ ...p, publishedAt: p.publishedAt.toISOString() })); }