atagen

malice

public
Star0
Watch0
20fe182f3204e4d4923607816147c3fa0ae4cccc
2
ssh://brewery@pls.lobotomise.me:33/atagen/malice.git
web/src/lib/notifications.tsTypescript193 lines6.9 KB
1
import { get, writable } from 'svelte/store';
2
import { mediaUrl } from './api';
3
import {
4
  arrivalIn,
5
  type Arrival,
6
  badgeTotal,
7
  isRoomWatched,
8
  notifyingCount,
9
  planNotification,
10
  roomTag,
11
  sourceFromSummary,
12
  sourceFromTimeline,
13
  type NotificationPlan
14
} from './notification-model';
15
import { effectiveRooms } from './mute';
16
import { selectedRoomId, sessionUser, timelines } from './store';
17
import type { RoomSummary } from './types';
18
19
const SETTLE_MS = 300;
20
21
export const OPEN_ROOM_MESSAGE = 'malice-open-room';
22
23
export type NotificationPermissionState = NotificationPermission | 'unsupported';
24
25
const supported = typeof Notification !== 'undefined';
26
const preferenceKey = (account: string) => `malice.notifications.${account}`;
27
28
export const notificationsEnabled = writable(false);
29
export const notificationPermission = writable<NotificationPermissionState>(supported ? Notification.permission : 'unsupported');
30
31
function readPreference(account: string | null | undefined): boolean {
32
  if (!account) return false;
33
  try {
34
    return localStorage.getItem(preferenceKey(account)) === '1';
35
  } catch {
36
    return false;
37
  }
38
}
39
40
function writePreference(account: string, enabled: boolean): void {
41
  try {
42
    localStorage.setItem(preferenceKey(account), enabled ? '1' : '0');
43
  } catch {}
44
}
45
46
/** Must run inside a user gesture, since browsers refuse the permission prompt otherwise. */
47
export async function enableNotifications(): Promise<void> {
48
  const account = get(sessionUser);
49
  if (!supported || !account) return;
50
  const result = Notification.permission === 'default' ? await Notification.requestPermission() : Notification.permission;
51
  notificationPermission.set(result);
52
  const on = result === 'granted';
53
  writePreference(account, on);
54
  notificationsEnabled.set(on);
55
}
56
57
export function disableNotifications(): void {
58
  const account = get(sessionUser);
59
  if (account) writePreference(account, false);
60
  notificationsEnabled.set(false);
61
}
62
63
function active(): boolean {
64
  return supported && get(notificationsEnabled) && Notification.permission === 'granted';
65
}
66
67
async function registration(): Promise<ServiceWorkerRegistration | null> {
68
  if (!('serviceWorker' in navigator) || !navigator.serviceWorker.controller) return null;
69
  try {
70
    return await navigator.serviceWorker.ready;
71
  } catch {
72
    return null;
73
  }
74
}
75
76
async function show(plan: NotificationPlan, openRoom: (roomId: string) => void): Promise<void> {
77
  const icon = mediaUrl(plan.iconMxc, 128) ?? undefined;
78
  const options: NotificationOptions & { renotify?: boolean } = {
79
    body: plan.body,
80
    tag: plan.tag,
81
    icon,
82
    renotify: plan.renotify,
83
    data: { roomId: plan.roomId }
84
  };
85
  const reg = await registration();
86
  if (reg) {
87
    await reg.showNotification(plan.title, options);
88
    return;
89
  }
90
  const note = new Notification(plan.title, options);
91
  note.onclick = () => {
92
    window.focus();
93
    openRoom(plan.roomId);
94
    note.close();
95
  };
96
}
97
98
async function closeRoom(roomId: string): Promise<void> {
99
  const reg = await registration();
100
  if (!reg) return;
101
  for (const note of await reg.getNotifications({ tag: roomTag(roomId) })) note.close();
102
}
103
104
function setBadge(total: number): void {
105
  const nav = navigator as Navigator & { setAppBadge?: (n: number) => Promise<void>; clearAppBadge?: () => Promise<void> };
106
  if (total > 0) void nav.setAppBadge?.(total).catch(() => undefined);
107
  else void nav.clearAppBadge?.().catch(() => undefined);
108
}
109
110
/** Watches room summaries for notifying unread increases, shows and clears notifications, and keeps the app badge current. */
111
export function startNotifications(openRoom: (roomId: string) => void): () => void {
112
  let previous = new Map<string, RoomSummary>();
113
  let notified = new Set<string>();
114
  let badge = -1;
115
116
  const unsubscribeSession = sessionUser.subscribe((account) => notificationsEnabled.set(readPreference(account)));
117
118
  void registration().then(async (reg) => {
119
    for (const note of (await reg?.getNotifications()) ?? []) {
120
      const roomId = (note.data as { roomId?: unknown } | null)?.roomId;
121
      if (typeof roomId === 'string') notified.add(roomId);
122
    }
123
  });
124
125
  const watched = (roomId: string) =>
126
    isRoomWatched(roomId, get(selectedRoomId), document.visibilityState === 'visible', document.hasFocus());
127
128
  const clearRead = (list: RoomSummary[]) => {
129
    for (const room of list) {
130
      if (notified.has(room.room_id) && (notifyingCount(room) === 0 || watched(room.room_id))) {
131
        notified.delete(room.room_id);
132
        void closeRoom(room.room_id);
133
      }
134
    }
135
  };
136
137
  const waiting = new Map<string, Arrival & { timer: ReturnType<typeof setTimeout> }>();
138
139
  const queue = (roomId: string, mention: boolean) => {
140
    clearTimeout(waiting.get(roomId)?.timer);
141
    const timer = setTimeout(() => {
142
      waiting.delete(roomId);
143
      const room = get(effectiveRooms).find((r) => r.room_id === roomId);
144
      if (!room || !active() || watched(roomId) || notifyingCount(room) === 0) return;
145
      const source = sourceFromTimeline(get(timelines)[roomId]) ?? sourceFromSummary(room);
146
      notified.add(roomId);
147
      void show(planNotification(room, source, { mention }), openRoom);
148
    }, SETTLE_MS);
149
    waiting.set(roomId, { mention, timer });
150
  };
151
152
  const onRooms = (list: RoomSummary[]) => {
153
    const next = new Map(list.map((room) => [room.room_id, room]));
154
    const prior = previous;
155
    previous = next;
156
    if (!active()) {
157
      if (badge !== 0) setBadge((badge = 0));
158
      return;
159
    }
160
    const total = badgeTotal(list);
161
    if (total !== badge) setBadge((badge = total));
162
    const now = Date.now();
163
    for (const room of list) {
164
      const arrival = arrivalIn(prior.get(room.room_id), room, now);
165
      if (!arrival || watched(room.room_id)) continue;
166
      queue(room.room_id, arrival.mention || (waiting.get(room.room_id)?.mention ?? false));
167
    }
168
    clearRead(list);
169
  };
170
171
  const unsubscribeRooms = effectiveRooms.subscribe(onRooms);
172
  const unsubscribeEnabled = notificationsEnabled.subscribe(() => onRooms(get(effectiveRooms)));
173
  const onAttention = () => clearRead(get(effectiveRooms));
174
  const onMessage = (ev: MessageEvent) => {
175
    const data = ev.data as { type?: unknown; roomId?: unknown } | null;
176
    if (data?.type === OPEN_ROOM_MESSAGE && typeof data.roomId === 'string') openRoom(data.roomId);
177
  };
178
  window.addEventListener('focus', onAttention);
179
  document.addEventListener('visibilitychange', onAttention);
180
  const unsubscribeSelected = selectedRoomId.subscribe(onAttention);
181
  if ('serviceWorker' in navigator) navigator.serviceWorker.addEventListener('message', onMessage);
182
183
  return () => {
184
    unsubscribeSession();
185
    unsubscribeRooms();
186
    unsubscribeEnabled();
187
    unsubscribeSelected();
188
    for (const { timer } of waiting.values()) clearTimeout(timer);
189
    window.removeEventListener('focus', onAttention);
190
    document.removeEventListener('visibilitychange', onAttention);
191
    if ('serviceWorker' in navigator) navigator.serviceWorker.removeEventListener('message', onMessage);
192
  };
193
}