garage44.eu/jeroen/midas

logclone: git clone https://garage44.eu/jeroen/midas.git

.. /web/src/lib/notify.ts

raw

import {api} from '@/lib/api'
import {local} from '@/lib/reactive'

/**
 * This browser's notifications (push.rs, sw.js): whether it can be notified,
 * whether it is, and turning it on or off. On an iPhone a page can be notified
 * only once it is added to the Home Screen; elsewhere any current browser can.
 */
export const notify = local({
    supported: typeof navigator !== 'undefined' && 'serviceWorker' in navigator && typeof window !== 'undefined' && 'PushManager' in window,
    on: false,
    busy: false,
    error: '',
})

/** The hub's public key as a browser takes it: the bytes of base64url. */
function bytes(b64url: string): Uint8Array<ArrayBuffer> {
    const b64 = b64url.replace(/-/g, '+').replace(/_/g, '/') + '='.repeat((4 - (b64url.length % 4)) % 4)
    return Uint8Array.from(atob(b64), (c) => c.charCodeAt(0))
}

/** Whether this browser is subscribed already: asked once when the page opens. */
export async function checkNotify() {
    if (!notify.supported) return
    const reg = await navigator.serviceWorker.getRegistration('/')
    notify.on = !!(await reg?.pushManager.getSubscription())
}

export async function setNotify(on: boolean) {
    if (!notify.supported || notify.busy) return
    notify.busy = true
    notify.error = ''
    try {
        if (on) {
            if ((await Notification.requestPermission()) !== 'granted') throw new Error('notifications are not allowed for this page in the browser’s settings')
            const reg = await navigator.serviceWorker.register('/sw.js', {scope: '/'})
            await navigator.serviceWorker.ready
            const {key} = await api.pushKey()
            const sub = (await reg.pushManager.getSubscription()) ?? (await reg.pushManager.subscribe({userVisibleOnly: true, applicationServerKey: bytes(key)}))
            // Firefox resolves `subscribe` with null rather than rejecting when
            // it cannot reach its push service: turned off in about:config
            // (dom.push.*), blocked by the network, or absent from the build.
            if (!sub) throw new Error('this browser could not reach its push service, so it cannot deliver notifications')
            await api.pushSubscribe(sub.endpoint)
            notify.on = true
        } else {
            const reg = await navigator.serviceWorker.getRegistration('/')
            const sub = await reg?.pushManager.getSubscription()
            if (sub) {
                await api.pushUnsubscribe(sub.endpoint).catch(() => undefined)
                await sub.unsubscribe()
            }
            notify.on = false
        }
    } catch (e) {
        notify.error = (e as Error).message
    } finally {
        notify.busy = false
    }
}

/**
 * The account's ntfy topic (push.rs): for a phone the browser cannot be
 * notified on, the ntfy app is told instead. `saved` is the hub's, `draft` the field's.
 */
export const ntfy = local({saved: '', draft: '', loaded: false})

export async function checkNtfy() {
    const {topic} = await api.pushNtfy()
    ntfy.saved = ntfy.draft = topic ?? ''
    ntfy.loaded = true
}

export async function saveNtfy(topic: string) {
    // The hub turns a bare name into its ntfy.sh address: show what it keeps.
    const kept = await api.setPushNtfy(topic.trim())
    ntfy.saved = ntfy.draft = kept.topic ?? ''
}