atagen

malice

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