Files
webmail/lib/push-preferences.ts
T

35 lines
1.3 KiB
TypeScript

/**
* Settings the service worker needs when a push arrives. The worker shows
* push notifications without the page (and so without the settings store),
* so the page mirrors them into the worker's own Cache API store, where
* public/sw.js reads them before calling showNotification (#1289).
*/
const BASE_PATH = (process.env.NEXT_PUBLIC_BASE_PATH ?? '').replace(/\/+$/, '');
/** Same store as sw.js's PUSH_STATE_CACHE. */
export const PUSH_STATE_CACHE = 'bulwark-push-state-v1';
export interface PushPreferences {
/** False: show push notifications for new mail without a sound. */
sound: boolean;
}
/** The cache key sw.js reads the preferences from. */
export function pushPreferencesKey(origin: string): string {
return `${origin}${BASE_PATH}/__push-state/prefs`;
}
export async function writePushPreferences(prefs: PushPreferences): Promise<void> {
if (typeof window === 'undefined' || typeof caches === 'undefined') return;
try {
const cache = await caches.open(PUSH_STATE_CACHE);
await cache.put(
pushPreferencesKey(window.location.origin),
new Response(JSON.stringify(prefs), { headers: { 'Content-Type': 'application/json' } }),
);
} catch {
// Without the store the worker keeps its default: a sound for every alert.
}
}