Skip to content

The open-source AI receptionist for businesses. Answers every call, books the appointment and hands over to a person when needed. You own the code and the data.

6.7 KB
Raw Blame
// Notifications for finished calls from the open page (Notification API, no push service), when the
// device switch in User settings › Preferences is on: this browser subscribed for push (the page's
// notification and the push share a tag, so one shows), or, where push cannot work, the member's
// `browser` setting. Only when the tab is in the background, only for calls that finished after the app
// opened, never for test calls or spam; an urgent call already while it runs, when the assistant flags it (like the
// push of kind `urgent`; the same tag, so its end replaces it). Clicking one opens the call. In the desktop app
// (native/desktop/bridge.ts) the app shows them, also with its window closed.
import type { NotificationSettingsData } from '@linedesk/actions'
import type { Call } from '@linedesk/db/types'
import { useEffect, useRef } from 'react'
import { setQueryData, useQuery } from '../cachedQuery.ts'
import { onPushOpensCall, pushSupport, refreshPushHere, thisDeviceId } from '../push.ts'
import { tabWorkspace } from '../tabWorkspace.ts'
import { readAction } from '../settings/settings-api.ts'
import { useRows } from '../store.tsx'
import { callHash } from './useRoute.ts'
import { i18n } from '../i18n/index.tsx'
import { desktopApp } from '../native/desktop/bridge.ts'

// The member's settings, shared by this hook and Account settings, Notifications (which updates them on
// change): the last known at once (also across page loads), checked again in the background.
const NOTIFICATIONS = 'notifications'
const loadNotificationSettings = () => readAction<NotificationSettingsData>('notifications.get')
export const useNotificationQuery = () => useQuery(NOTIFICATIONS, loadNotificationSettings, { persist: true })
export const useNotificationSettings = () => useNotificationQuery().data ?? null
/** Applies a change at once, here and on the settings page; the server gets it through the outbox. */
export const setNotificationSettings = (next: NotificationSettingsData) =>
  setQueryData(NOTIFICATIONS, next, { persist: true })

export const browserNotificationsSupported = () => typeof window !== 'undefined' && 'Notification' in window

/** What a call was when last seen: news is a change of these. */
export type Seen = Pick<Call, 'status' | 'urgency'>

const isNoise = (c: Call) => !!c.deleted_at || c.source === 'test' || c.outcome === 'spam'

/**
 * Calls that just finished: completed now, not completed (or not there) before, and ended after
 * `sinceMs` (the first sync of a fresh browser brings old calls too: they are history, not news).
 */
export function newlyFinished(calls: readonly Call[], before: ReadonlyMap<string, Seen>, sinceMs: number): Call[] {
  return calls.filter(
    c =>
      c.status === 'completed' &&
      before.get(c.id)?.status !== 'completed' &&
      Date.parse(c.ended_at ?? '') >= sinceMs &&
      !isNoise(c),
  )
}

/**
 * Calls still running that just became urgent (the assistant flagged them): urgent now, not before, started after
 * `sinceMs`. They notify at once; a finished one is newlyFinished's.
 */
export function newlyUrgent(calls: readonly Call[], before: ReadonlyMap<string, Seen>, sinceMs: number): Call[] {
  return calls.filter(
    c =>
      c.status !== 'completed' &&
      c.urgency === 'urgent' &&
      before.get(c.id)?.urgency !== 'urgent' &&
      Date.parse(c.started_at ?? '') >= sinceMs &&
      !isNoise(c),
  )
}

/** Clock differences between server and browser. */
const SLACK_MS = 60_000

/** "New call", or the call's title; "Urgent: …" for an urgent call. */
function notificationTitle(call: Call): string {
  const { t } = i18n()
  const title = call.title || t('shell.notification.newCall')
  return call.urgency === 'urgent' ? t('shell.notification.urgent', { title }) : title
}

function show(call: Call, callerName: (call: Call) => string) {
  const title = notificationTitle(call)
  const body = [callerName(call), call.summary].filter(Boolean).join(' · ')
  // The desktop app shows it itself: urgent ones stay, a click brings its window back (native/desktop/bridge.ts).
  const desktop = desktopApp()
  if (desktop) return desktop.notify({ id: call.id, title, body, urgent: call.urgency === 'urgent' })
  const notification = new Notification(title, {
    body,
    tag: `call-${call.id}`, // one notification per call, even with several tabs open
  })
  notification.onclick = () => {
    window.focus()
    window.location.hash = callHash(call.id)
    notification.close()
  }
}

/** Whether the device switch is on here (see the file comment); permission is checked by the caller. */
export async function notifiesHere(prefs: NotificationSettingsData): Promise<boolean> {
  if (pushSupport() !== 'supported' || !prefs.push.publicKey) return prefs.effective.browser
  const id = await thisDeviceId().catch(() => null)
  return id !== null && prefs.push.devices.includes(id)
}

/** The workspaces whose push device was registered again since this page loaded (once each). */
const refreshed = new Set<string>()

/** Once per start and workspace: this device's push registration again, with the current session (refreshPushHere). */
function refreshPushOnce() {
  const workspace = tabWorkspace()
  if (!workspace || refreshed.has(workspace)) return
  refreshed.add(workspace)
  void loadNotificationSettings()
    .then(settings => refreshPushHere(settings, i18n().t('account.notify.callsChannel')))
    .catch(() => {})
}

export function useCallNotifications(callerName: (call: Call) => string) {
  const calls = useRows('calls')
  const prefs = useNotificationSettings()
  const seen = useRef<Map<string, Seen>>(new Map())
  const since = useRef(Date.now() - SLACK_MS)
  const name = useRef(callerName)
  name.current = callerName

  // This device's push registration belongs to the session it is signed in with now.
  useEffect(refreshPushOnce)

  // A click on a push notification (service worker) opens its call here.
  useEffect(
    () =>
      onPushOpensCall(id => {
        window.location.hash = callHash(id)
      }),
    [],
  )

  useEffect(() => {
    const before = seen.current
    seen.current = new Map(calls.map(c => [c.id, { status: c.status, urgency: c.urgency }]))
    if (!prefs || !browserNotificationsSupported() || Notification.permission !== 'granted') return
    // The desktop app decides itself whether its window is in front (a hidden window may still report focus).
    if (!desktopApp() && document.visibilityState === 'visible' && document.hasFocus()) return
    const fresh = [...newlyUrgent(calls, before, since.current), ...newlyFinished(calls, before, since.current)]
    if (fresh.length === 0) return
    void notifiesHere(prefs).then(on => {
      if (on) for (const call of fresh) show(call, name.current)
    })
  }, [calls, prefs])
}