atagen

malice

public
Star0
Watch0
0b88effaec6d8c5b10a7d8def9b9a3c999d2442f
2
ssh://brewery@pls.lobotomise.me:33/atagen/malice.git

Blame: web/src/lib/notifications.ts

db4e552594cbatagen2026-10-26 04:43 UTC1
import { get, writable } from 'svelte/store';
db4e552594cbatagen2026-10-26 04:43 UTC2
import { mediaUrl } from './api';
db4e552594cbatagen2026-10-26 04:43 UTC3
import {
db4e552594cbatagen2026-10-26 04:43 UTC4
  arrivalIn,
db4e552594cbatagen2026-10-26 04:43 UTC5
  type Arrival,
db4e552594cbatagen2026-10-26 04:43 UTC6
  badgeTotal,
db4e552594cbatagen2026-10-26 04:43 UTC7
  isRoomWatched,
db4e552594cbatagen2026-10-26 04:43 UTC8
  notifyingCount,
db4e552594cbatagen2026-10-26 04:43 UTC9
  planNotification,
db4e552594cbatagen2026-10-26 04:43 UTC10
  roomTag,
db4e552594cbatagen2026-10-26 04:43 UTC11
  sourceFromSummary,
db4e552594cbatagen2026-10-26 04:43 UTC12
  sourceFromTimeline,
db4e552594cbatagen2026-10-26 04:43 UTC13
  type NotificationPlan
db4e552594cbatagen2026-10-26 04:43 UTC14
} from './notification-model';
20fe182f3204atagen2026-10-26 05:50 UTC15
import { effectiveRooms } from './mute';
c8d898e6eb59atagen2026-10-27 03:55 UTC16
import { startMessageSound } from './message-sound';
235ce394f90datagen2026-10-26 06:54 UTC17
import { PUSH_CHANGED_MESSAGE } from './push-model';
235ce394f90datagen2026-10-26 06:54 UTC18
import { disablePush, enablePush, pushActive, syncPush } from './push';
20fe182f3204atagen2026-10-26 05:50 UTC19
import { selectedRoomId, sessionUser, timelines } from './store';
db4e552594cbatagen2026-10-26 04:43 UTC20
import type { RoomSummary } from './types';
db4e552594cbatagen2026-10-26 04:43 UTC21
db4e552594cbatagen2026-10-26 04:43 UTC22
const SETTLE_MS = 300;
db4e552594cbatagen2026-10-26 04:43 UTC23
db4e552594cbatagen2026-10-26 04:43 UTC24
export const OPEN_ROOM_MESSAGE = 'malice-open-room';
db4e552594cbatagen2026-10-26 04:43 UTC25
db4e552594cbatagen2026-10-26 04:43 UTC26
export type NotificationPermissionState = NotificationPermission | 'unsupported';
db4e552594cbatagen2026-10-26 04:43 UTC27
db4e552594cbatagen2026-10-26 04:43 UTC28
const supported = typeof Notification !== 'undefined';
db4e552594cbatagen2026-10-26 04:43 UTC29
const preferenceKey = (account: string) => `malice.notifications.${account}`;
db4e552594cbatagen2026-10-26 04:43 UTC30
db4e552594cbatagen2026-10-26 04:43 UTC31
export const notificationsEnabled = writable(false);
db4e552594cbatagen2026-10-26 04:43 UTC32
export const notificationPermission = writable<NotificationPermissionState>(supported ? Notification.permission : 'unsupported');
db4e552594cbatagen2026-10-26 04:43 UTC33
db4e552594cbatagen2026-10-26 04:43 UTC34
function readPreference(account: string | null | undefined): boolean {
db4e552594cbatagen2026-10-26 04:43 UTC35
  if (!account) return false;
db4e552594cbatagen2026-10-26 04:43 UTC36
  try {
db4e552594cbatagen2026-10-26 04:43 UTC37
    return localStorage.getItem(preferenceKey(account)) === '1';
db4e552594cbatagen2026-10-26 04:43 UTC38
  } catch {
db4e552594cbatagen2026-10-26 04:43 UTC39
    return false;
db4e552594cbatagen2026-10-26 04:43 UTC40
  }
db4e552594cbatagen2026-10-26 04:43 UTC41
}
db4e552594cbatagen2026-10-26 04:43 UTC42
db4e552594cbatagen2026-10-26 04:43 UTC43
function writePreference(account: string, enabled: boolean): void {
db4e552594cbatagen2026-10-26 04:43 UTC44
  try {
db4e552594cbatagen2026-10-26 04:43 UTC45
    localStorage.setItem(preferenceKey(account), enabled ? '1' : '0');
db4e552594cbatagen2026-10-26 04:43 UTC46
  } catch {}
db4e552594cbatagen2026-10-26 04:43 UTC47
}
db4e552594cbatagen2026-10-26 04:43 UTC48
db4e552594cbatagen2026-10-26 04:43 UTC49
/** Must run inside a user gesture, since browsers refuse the permission prompt otherwise. */
db4e552594cbatagen2026-10-26 04:43 UTC50
export async function enableNotifications(): Promise<void> {
db4e552594cbatagen2026-10-26 04:43 UTC51
  const account = get(sessionUser);
db4e552594cbatagen2026-10-26 04:43 UTC52
  if (!supported || !account) return;
db4e552594cbatagen2026-10-26 04:43 UTC53
  const result = Notification.permission === 'default' ? await Notification.requestPermission() : Notification.permission;
db4e552594cbatagen2026-10-26 04:43 UTC54
  notificationPermission.set(result);
db4e552594cbatagen2026-10-26 04:43 UTC55
  const on = result === 'granted';
db4e552594cbatagen2026-10-26 04:43 UTC56
  writePreference(account, on);
db4e552594cbatagen2026-10-26 04:43 UTC57
  notificationsEnabled.set(on);
235ce394f90datagen2026-10-26 06:54 UTC58
  if (on) await enablePush(account);
db4e552594cbatagen2026-10-26 04:43 UTC59
}
db4e552594cbatagen2026-10-26 04:43 UTC60
db4e552594cbatagen2026-10-26 04:43 UTC61
export function disableNotifications(): void {
db4e552594cbatagen2026-10-26 04:43 UTC62
  const account = get(sessionUser);
235ce394f90datagen2026-10-26 06:54 UTC63
  if (account) {
235ce394f90datagen2026-10-26 06:54 UTC64
    writePreference(account, false);
235ce394f90datagen2026-10-26 06:54 UTC65
    void disablePush(account);
235ce394f90datagen2026-10-26 06:54 UTC66
  }
db4e552594cbatagen2026-10-26 04:43 UTC67
  notificationsEnabled.set(false);
db4e552594cbatagen2026-10-26 04:43 UTC68
}
db4e552594cbatagen2026-10-26 04:43 UTC69
db4e552594cbatagen2026-10-26 04:43 UTC70
function active(): boolean {
db4e552594cbatagen2026-10-26 04:43 UTC71
  return supported && get(notificationsEnabled) && Notification.permission === 'granted';
db4e552594cbatagen2026-10-26 04:43 UTC72
}
db4e552594cbatagen2026-10-26 04:43 UTC73
db4e552594cbatagen2026-10-26 04:43 UTC74
async function registration(): Promise<ServiceWorkerRegistration | null> {
db4e552594cbatagen2026-10-26 04:43 UTC75
  if (!('serviceWorker' in navigator) || !navigator.serviceWorker.controller) return null;
db4e552594cbatagen2026-10-26 04:43 UTC76
  try {
db4e552594cbatagen2026-10-26 04:43 UTC77
    return await navigator.serviceWorker.ready;
db4e552594cbatagen2026-10-26 04:43 UTC78
  } catch {
db4e552594cbatagen2026-10-26 04:43 UTC79
    return null;
db4e552594cbatagen2026-10-26 04:43 UTC80
  }
db4e552594cbatagen2026-10-26 04:43 UTC81
}
db4e552594cbatagen2026-10-26 04:43 UTC82
db4e552594cbatagen2026-10-26 04:43 UTC83
async function show(plan: NotificationPlan, openRoom: (roomId: string) => void): Promise<void> {
db4e552594cbatagen2026-10-26 04:43 UTC84
  const icon = mediaUrl(plan.iconMxc, 128) ?? undefined;
db4e552594cbatagen2026-10-26 04:43 UTC85
  const options: NotificationOptions & { renotify?: boolean } = {
db4e552594cbatagen2026-10-26 04:43 UTC86
    body: plan.body,
db4e552594cbatagen2026-10-26 04:43 UTC87
    tag: plan.tag,
db4e552594cbatagen2026-10-26 04:43 UTC88
    icon,
db4e552594cbatagen2026-10-26 04:43 UTC89
    renotify: plan.renotify,
db4e552594cbatagen2026-10-26 04:43 UTC90
    data: { roomId: plan.roomId }
db4e552594cbatagen2026-10-26 04:43 UTC91
  };
db4e552594cbatagen2026-10-26 04:43 UTC92
  const reg = await registration();
db4e552594cbatagen2026-10-26 04:43 UTC93
  if (reg) {
db4e552594cbatagen2026-10-26 04:43 UTC94
    await reg.showNotification(plan.title, options);
db4e552594cbatagen2026-10-26 04:43 UTC95
    return;
db4e552594cbatagen2026-10-26 04:43 UTC96
  }
db4e552594cbatagen2026-10-26 04:43 UTC97
  const note = new Notification(plan.title, options);
db4e552594cbatagen2026-10-26 04:43 UTC98
  note.onclick = () => {
db4e552594cbatagen2026-10-26 04:43 UTC99
    window.focus();
db4e552594cbatagen2026-10-26 04:43 UTC100
    openRoom(plan.roomId);
db4e552594cbatagen2026-10-26 04:43 UTC101
    note.close();
db4e552594cbatagen2026-10-26 04:43 UTC102
  };
db4e552594cbatagen2026-10-26 04:43 UTC103
}
db4e552594cbatagen2026-10-26 04:43 UTC104
db4e552594cbatagen2026-10-26 04:43 UTC105
async function closeRoom(roomId: string): Promise<void> {
db4e552594cbatagen2026-10-26 04:43 UTC106
  const reg = await registration();
db4e552594cbatagen2026-10-26 04:43 UTC107
  if (!reg) return;
db4e552594cbatagen2026-10-26 04:43 UTC108
  for (const note of await reg.getNotifications({ tag: roomTag(roomId) })) note.close();
db4e552594cbatagen2026-10-26 04:43 UTC109
}
db4e552594cbatagen2026-10-26 04:43 UTC110
db4e552594cbatagen2026-10-26 04:43 UTC111
function setBadge(total: number): void {
db4e552594cbatagen2026-10-26 04:43 UTC112
  const nav = navigator as Navigator & { setAppBadge?: (n: number) => Promise<void>; clearAppBadge?: () => Promise<void> };
db4e552594cbatagen2026-10-26 04:43 UTC113
  if (total > 0) void nav.setAppBadge?.(total).catch(() => undefined);
db4e552594cbatagen2026-10-26 04:43 UTC114
  else void nav.clearAppBadge?.().catch(() => undefined);
db4e552594cbatagen2026-10-26 04:43 UTC115
}
db4e552594cbatagen2026-10-26 04:43 UTC116
db4e552594cbatagen2026-10-26 04:43 UTC117
/** Watches room summaries for notifying unread increases, shows and clears notifications, and keeps the app badge current. */
db4e552594cbatagen2026-10-26 04:43 UTC118
export function startNotifications(openRoom: (roomId: string) => void): () => void {
db4e552594cbatagen2026-10-26 04:43 UTC119
  let previous = new Map<string, RoomSummary>();
db4e552594cbatagen2026-10-26 04:43 UTC120
  let notified = new Set<string>();
db4e552594cbatagen2026-10-26 04:43 UTC121
  let badge = -1;
db4e552594cbatagen2026-10-26 04:43 UTC122
235ce394f90datagen2026-10-26 06:54 UTC123
  const unsubscribeSession = sessionUser.subscribe((account) => {
235ce394f90datagen2026-10-26 06:54 UTC124
    const enabled = readPreference(account);
235ce394f90datagen2026-10-26 06:54 UTC125
    notificationsEnabled.set(enabled);
235ce394f90datagen2026-10-26 06:54 UTC126
    if (account) void syncPush(account, enabled);
235ce394f90datagen2026-10-26 06:54 UTC127
  });
db4e552594cbatagen2026-10-26 04:43 UTC128
db4e552594cbatagen2026-10-26 04:43 UTC129
  void registration().then(async (reg) => {
db4e552594cbatagen2026-10-26 04:43 UTC130
    for (const note of (await reg?.getNotifications()) ?? []) {
db4e552594cbatagen2026-10-26 04:43 UTC131
      const roomId = (note.data as { roomId?: unknown } | null)?.roomId;
db4e552594cbatagen2026-10-26 04:43 UTC132
      if (typeof roomId === 'string') notified.add(roomId);
db4e552594cbatagen2026-10-26 04:43 UTC133
    }
db4e552594cbatagen2026-10-26 04:43 UTC134
  });
db4e552594cbatagen2026-10-26 04:43 UTC135
db4e552594cbatagen2026-10-26 04:43 UTC136
  const watched = (roomId: string) =>
db4e552594cbatagen2026-10-26 04:43 UTC137
    isRoomWatched(roomId, get(selectedRoomId), document.visibilityState === 'visible', document.hasFocus());
db4e552594cbatagen2026-10-26 04:43 UTC138
db4e552594cbatagen2026-10-26 04:43 UTC139
  const clearRead = (list: RoomSummary[]) => {
db4e552594cbatagen2026-10-26 04:43 UTC140
    for (const room of list) {
db4e552594cbatagen2026-10-26 04:43 UTC141
      if (notified.has(room.room_id) && (notifyingCount(room) === 0 || watched(room.room_id))) {
db4e552594cbatagen2026-10-26 04:43 UTC142
        notified.delete(room.room_id);
db4e552594cbatagen2026-10-26 04:43 UTC143
        void closeRoom(room.room_id);
db4e552594cbatagen2026-10-26 04:43 UTC144
      }
db4e552594cbatagen2026-10-26 04:43 UTC145
    }
db4e552594cbatagen2026-10-26 04:43 UTC146
  };
db4e552594cbatagen2026-10-26 04:43 UTC147
db4e552594cbatagen2026-10-26 04:43 UTC148
  const waiting = new Map<string, Arrival & { timer: ReturnType<typeof setTimeout> }>();
db4e552594cbatagen2026-10-26 04:43 UTC149
db4e552594cbatagen2026-10-26 04:43 UTC150
  const queue = (roomId: string, mention: boolean) => {
db4e552594cbatagen2026-10-26 04:43 UTC151
    clearTimeout(waiting.get(roomId)?.timer);
db4e552594cbatagen2026-10-26 04:43 UTC152
    const timer = setTimeout(() => {
db4e552594cbatagen2026-10-26 04:43 UTC153
      waiting.delete(roomId);
20fe182f3204atagen2026-10-26 05:50 UTC154
      const room = get(effectiveRooms).find((r) => r.room_id === roomId);
db4e552594cbatagen2026-10-26 04:43 UTC155
      if (!room || !active() || watched(roomId) || notifyingCount(room) === 0) return;
235ce394f90datagen2026-10-26 06:54 UTC156
      if (get(pushActive)) return;
db4e552594cbatagen2026-10-26 04:43 UTC157
      const source = sourceFromTimeline(get(timelines)[roomId]) ?? sourceFromSummary(room);
db4e552594cbatagen2026-10-26 04:43 UTC158
      notified.add(roomId);
db4e552594cbatagen2026-10-26 04:43 UTC159
      void show(planNotification(room, source, { mention }), openRoom);
db4e552594cbatagen2026-10-26 04:43 UTC160
    }, SETTLE_MS);
db4e552594cbatagen2026-10-26 04:43 UTC161
    waiting.set(roomId, { mention, timer });
db4e552594cbatagen2026-10-26 04:43 UTC162
  };
db4e552594cbatagen2026-10-26 04:43 UTC163
db4e552594cbatagen2026-10-26 04:43 UTC164
  const onRooms = (list: RoomSummary[]) => {
db4e552594cbatagen2026-10-26 04:43 UTC165
    const next = new Map(list.map((room) => [room.room_id, room]));
db4e552594cbatagen2026-10-26 04:43 UTC166
    const prior = previous;
db4e552594cbatagen2026-10-26 04:43 UTC167
    previous = next;
db4e552594cbatagen2026-10-26 04:43 UTC168
    if (!active()) {
db4e552594cbatagen2026-10-26 04:43 UTC169
      if (badge !== 0) setBadge((badge = 0));
db4e552594cbatagen2026-10-26 04:43 UTC170
      return;
db4e552594cbatagen2026-10-26 04:43 UTC171
    }
db4e552594cbatagen2026-10-26 04:43 UTC172
    const total = badgeTotal(list);
db4e552594cbatagen2026-10-26 04:43 UTC173
    if (total !== badge) setBadge((badge = total));
db4e552594cbatagen2026-10-26 04:43 UTC174
    const now = Date.now();
db4e552594cbatagen2026-10-26 04:43 UTC175
    for (const room of list) {
db4e552594cbatagen2026-10-26 04:43 UTC176
      const arrival = arrivalIn(prior.get(room.room_id), room, now);
db4e552594cbatagen2026-10-26 04:43 UTC177
      if (!arrival || watched(room.room_id)) continue;
db4e552594cbatagen2026-10-26 04:43 UTC178
      queue(room.room_id, arrival.mention || (waiting.get(room.room_id)?.mention ?? false));
db4e552594cbatagen2026-10-26 04:43 UTC179
    }
db4e552594cbatagen2026-10-26 04:43 UTC180
    clearRead(list);
db4e552594cbatagen2026-10-26 04:43 UTC181
  };
db4e552594cbatagen2026-10-26 04:43 UTC182
c8d898e6eb59atagen2026-10-27 03:55 UTC183
  const unsubscribeSound = startMessageSound();
20fe182f3204atagen2026-10-26 05:50 UTC184
  const unsubscribeRooms = effectiveRooms.subscribe(onRooms);
20fe182f3204atagen2026-10-26 05:50 UTC185
  const unsubscribeEnabled = notificationsEnabled.subscribe(() => onRooms(get(effectiveRooms)));
235ce394f90datagen2026-10-26 06:54 UTC186
  const onAttention = () => {
235ce394f90datagen2026-10-26 06:54 UTC187
    notificationPermission.set(supported ? Notification.permission : 'unsupported');
235ce394f90datagen2026-10-26 06:54 UTC188
    if (supported && Notification.permission !== 'granted') pushActive.set(false);
235ce394f90datagen2026-10-26 06:54 UTC189
    clearRead(get(effectiveRooms));
235ce394f90datagen2026-10-26 06:54 UTC190
    const open = get(selectedRoomId);
235ce394f90datagen2026-10-26 06:54 UTC191
    if (open && get(pushActive) && watched(open)) void closeRoom(open);
235ce394f90datagen2026-10-26 06:54 UTC192
  };
db4e552594cbatagen2026-10-26 04:43 UTC193
  const onMessage = (ev: MessageEvent) => {
db4e552594cbatagen2026-10-26 04:43 UTC194
    const data = ev.data as { type?: unknown; roomId?: unknown } | null;
235ce394f90datagen2026-10-26 06:54 UTC195
    const account = get(sessionUser);
235ce394f90datagen2026-10-26 06:54 UTC196
    if (data?.type === PUSH_CHANGED_MESSAGE && account) void syncPush(account, get(notificationsEnabled));
db4e552594cbatagen2026-10-26 04:43 UTC197
    if (data?.type === OPEN_ROOM_MESSAGE && typeof data.roomId === 'string') openRoom(data.roomId);
db4e552594cbatagen2026-10-26 04:43 UTC198
  };
db4e552594cbatagen2026-10-26 04:43 UTC199
  window.addEventListener('focus', onAttention);
db4e552594cbatagen2026-10-26 04:43 UTC200
  document.addEventListener('visibilitychange', onAttention);
db4e552594cbatagen2026-10-26 04:43 UTC201
  const unsubscribeSelected = selectedRoomId.subscribe(onAttention);
db4e552594cbatagen2026-10-26 04:43 UTC202
  if ('serviceWorker' in navigator) navigator.serviceWorker.addEventListener('message', onMessage);
db4e552594cbatagen2026-10-26 04:43 UTC203
db4e552594cbatagen2026-10-26 04:43 UTC204
  return () => {
db4e552594cbatagen2026-10-26 04:43 UTC205
    unsubscribeSession();
db4e552594cbatagen2026-10-26 04:43 UTC206
    unsubscribeRooms();
c8d898e6eb59atagen2026-10-27 03:55 UTC207
    unsubscribeSound();
db4e552594cbatagen2026-10-26 04:43 UTC208
    unsubscribeEnabled();
db4e552594cbatagen2026-10-26 04:43 UTC209
    unsubscribeSelected();
db4e552594cbatagen2026-10-26 04:43 UTC210
    for (const { timer } of waiting.values()) clearTimeout(timer);
db4e552594cbatagen2026-10-26 04:43 UTC211
    window.removeEventListener('focus', onAttention);
db4e552594cbatagen2026-10-26 04:43 UTC212
    document.removeEventListener('visibilitychange', onAttention);
db4e552594cbatagen2026-10-26 04:43 UTC213
    if ('serviceWorker' in navigator) navigator.serviceWorker.removeEventListener('message', onMessage);
db4e552594cbatagen2026-10-26 04:43 UTC214
  };
db4e552594cbatagen2026-10-26 04:43 UTC215
}