import { http } from '@/lib/http'; /** * Web-Push im Browser: Service Worker registrieren, Push je Gerät an- und abmelden. * Funktioniert nur über HTTPS (oder localhost); auf iPhone/iPad erst, wenn das Portal * als App zum Home-Bildschirm hinzugefügt wurde. */ export const pushSupported = () => typeof window !== 'undefined' && window.isSecureContext && 'serviceWorker' in navigator && 'PushManager' in window && 'Notification' in window; let registration = null; export function registerServiceWorker() { if (typeof window === 'undefined' || !window.isSecureContext || !('serviceWorker' in navigator)) return Promise.resolve(null); registration ??= navigator.serviceWorker.register('/sw.js', { scope: '/' }).catch(() => null); return registration; } function keyToBytes(base64url) { const base64 = (base64url + '='.repeat((4 - (base64url.length % 4)) % 4)).replace(/-/g, '+').replace(/_/g, '/'); return Uint8Array.from(atob(base64), (c) => c.charCodeAt(0)); } export async function currentSubscription() { if (!pushSupported()) return null; const reg = await registerServiceWorker(); return reg ? reg.pushManager.getSubscription() : null; } export async function enablePush(publicKey) { if (!pushSupported()) throw new Error('Dieser Browser unterstützt keine Push-Benachrichtigungen.'); const permission = await Notification.requestPermission(); if (permission !== 'granted') { throw new Error('Benachrichtigungen sind für dieses Portal im Browser blockiert. Bitte in den Website-Einstellungen erlauben.'); } const reg = await registerServiceWorker(); await navigator.serviceWorker.ready; let subscription = await reg.pushManager.getSubscription(); // Anderer Serverschlüssel (z. B. nach Umzug) → neu abonnieren if (subscription && subscription.options?.applicationServerKey) { const current = new Uint8Array(subscription.options.applicationServerKey); const expected = keyToBytes(publicKey); if (current.length !== expected.length || current.some((byte, i) => byte !== expected[i])) { await subscription.unsubscribe(); subscription = null; } } subscription ??= await reg.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: keyToBytes(publicKey) }); await http.post('/push/abo', subscription.toJSON()); return subscription; } export async function disablePush() { const subscription = await currentSubscription(); if (!subscription) return; await http.delete('/push/abo', { endpoint: subscription.endpoint }).catch(() => {}); await subscription.unsubscribe(); }