forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseNotifications.ts
More file actions
421 lines (360 loc) · 11.8 KB
/
Copy pathuseNotifications.ts
File metadata and controls
421 lines (360 loc) · 11.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
'use client';
import { useState, useEffect, useCallback, useRef } from 'react';
import { useRouter } from '@tschk/moonshine-next/navigation';
import type {
OmiNotification,
NotificationType,
NotificationPermissionStatus,
} from '@/types/notification';
import {
requestNotificationPermission,
getCurrentFCMToken,
onForegroundMessage,
getNotificationPermission,
} from '@/lib/firebase';
import { registerFCMToken, unregisterFCMToken } from '@/lib/api';
import type { MessagePayload } from 'firebase/messaging';
// Constants
const STORAGE_KEY = 'omi-notifications';
const MAX_NOTIFICATIONS = 100;
const FCM_TOKEN_KEY = 'omi-fcm-token';
/**
* Load notifications from localStorage
*/
function loadNotifications(): OmiNotification[] {
if (typeof window === 'undefined') return [];
try {
const stored = localStorage.getItem(STORAGE_KEY);
if (!stored) return [];
return JSON.parse(stored);
} catch {
return [];
}
}
/**
* Save notifications to localStorage
*/
function saveNotifications(notifications: OmiNotification[]): void {
if (typeof window === 'undefined') return;
try {
// Limit to max notifications
const trimmed = notifications.slice(0, MAX_NOTIFICATIONS);
localStorage.setItem(STORAGE_KEY, JSON.stringify(trimmed));
} catch (error) {
console.error('Failed to save notifications:', error);
}
}
/**
* Get stored FCM token
*/
function getStoredFCMToken(): string | null {
if (typeof window === 'undefined') return null;
return localStorage.getItem(FCM_TOKEN_KEY);
}
/**
* Store FCM token
*/
function storeFCMToken(token: string | null): void {
if (typeof window === 'undefined') return;
if (token) {
localStorage.setItem(FCM_TOKEN_KEY, token);
} else {
localStorage.removeItem(FCM_TOKEN_KEY);
}
}
/**
* Convert FCM payload to OmiNotification
*/
function payloadToNotification(payload: MessagePayload): OmiNotification {
const data = payload.data || {};
const notification = payload.notification || {};
return {
id: data.notification_id || `notif-${Date.now()}`,
type: (data.notification_type as NotificationType) || 'announcement',
title: notification.title || data.title || 'Omi',
body: notification.body || data.body || '',
timestamp: new Date().toISOString(),
read: false,
navigate_to: data.navigate_to,
data,
};
}
/**
* Get the route for a notification based on its type and navigate_to value
*/
function getNotificationRoute(notification: OmiNotification): string {
const navigateTo = notification.navigate_to;
if (!navigateTo) return '/';
// Handle different notification types and their routes
if (navigateTo.startsWith('/tasks')) {
const taskId = navigateTo.split('/').pop();
return taskId ? `/tasks?highlight=${taskId}` : '/tasks';
}
// Recaps merged into Timeline: a recap is a tile in the day it summarises.
if (navigateTo.startsWith('/daily-summary')) {
const recapId = navigateTo.split('/').pop();
return recapId ? `/conversations?recap=${recapId}` : '/conversations';
}
if (navigateTo.startsWith('/recaps')) {
const recapId = navigateTo.split('/').pop();
return recapId ? `/conversations?recap=${recapId}` : '/conversations';
}
if (navigateTo.startsWith('/conversations')) {
return navigateTo.replace('/conversations', '/conversations');
}
if (navigateTo.startsWith('/apps')) {
const appId = navigateTo.split('/').pop();
return appId ? `/apps?id=${appId}` : '/apps';
}
// Handle /chat/{app_id} routes - use query param for capability-aware routing
// MainLayout's ChatAppRouter will check if app has chat capability:
// - If yes: open chat panel with that app
// - If no: open notification center (notification-only apps like Bitcoin)
if (navigateTo.startsWith('/chat/')) {
const appId = navigateTo.split('/').pop();
return appId ? `/home?chatApp=${appId}` : '/home';
}
return navigateTo;
}
export interface UseNotificationsReturn {
// State
notifications: OmiNotification[];
unreadCount: number;
permission: NotificationPermissionStatus;
isSupported: boolean;
isLoading: boolean;
fcmToken: string | null;
// Actions
requestPermission: () => Promise<boolean>;
markAsRead: (notificationId: string) => void;
markAllAsRead: () => void;
clearNotification: (notificationId: string) => void;
clearAllNotifications: () => void;
// Navigation
navigateToNotification: (notification: OmiNotification) => void;
// Cleanup
unregisterToken: () => Promise<void>;
// Debug - send a test notification to verify UI works
sendTestNotification: () => void;
}
/**
* Hook for managing notifications
*/
export function useNotifications(): UseNotificationsReturn {
const router = useRouter();
const [notifications, setNotifications] = useState<OmiNotification[]>([]);
const [permission, setPermission] = useState<NotificationPermissionStatus>('default');
const [isSupported, setIsSupported] = useState(false);
const [isLoading, setIsLoading] = useState(true);
const [fcmToken, setFcmToken] = useState<string | null>(null);
const unsubscribeRef = useRef<(() => void) | null>(null);
// Calculate unread count
const unreadCount = notifications.filter((n) => !n.read).length;
// Handle foreground message (defined before useEffect that uses it)
const handleForegroundMessage = useCallback(
(payload: MessagePayload) => {
const notification = payloadToNotification(payload);
setNotifications((prev) => {
const updated = [notification, ...prev].slice(0, MAX_NOTIFICATIONS);
saveNotifications(updated);
return updated;
});
// Show browser notification for foreground messages
if (Notification.permission === 'granted') {
const browserNotif = new Notification(notification.title, {
body: notification.body,
icon: '/logo.png',
tag: notification.id,
});
browserNotif.onclick = () => {
window.focus();
const route = getNotificationRoute(notification);
router.push(route);
browserNotif.close();
};
}
},
[router],
);
// Initialize on mount
useEffect(() => {
async function init() {
setIsLoading(true);
// Load stored notifications
const stored = loadNotifications();
setNotifications(stored);
// Check basic browser support (without triggering Firebase initialization)
const hasNotificationSupport =
typeof window !== 'undefined' &&
'Notification' in window &&
'serviceWorker' in navigator;
setIsSupported(hasNotificationSupport);
// Get current permission status
const perm = getNotificationPermission();
setPermission(perm);
// Only try to get token if permission already granted
// This will initialize the service worker and messaging
if (perm === 'granted' && hasNotificationSupport) {
try {
// Get stored token BEFORE getting new one to compare
const storedToken = getStoredFCMToken();
const token = await getCurrentFCMToken();
if (token) {
setFcmToken(token);
// Register with backend if token changed or first time
if (token !== storedToken) {
try {
await registerFCMToken(token);
storeFCMToken(token);
} catch (error) {
console.error('Failed to register FCM token:', error);
}
}
// Subscribe to foreground messages
const unsubscribe = await onForegroundMessage(handleForegroundMessage);
if (unsubscribe) {
unsubscribeRef.current = unsubscribe;
}
}
} catch (error) {
console.error('Failed to initialize FCM:', error);
}
}
setIsLoading(false);
}
init();
return () => {
if (unsubscribeRef.current) {
unsubscribeRef.current();
}
};
}, [handleForegroundMessage]);
// Request notification permission
const requestPermissionHandler = useCallback(async (): Promise<boolean> => {
if (!isSupported) return false;
setIsLoading(true);
try {
const token = await requestNotificationPermission();
if (token) {
setFcmToken(token);
storeFCMToken(token);
setPermission('granted');
// Register token with backend
await registerFCMToken(token);
// Subscribe to foreground messages
const unsubscribe = await onForegroundMessage(handleForegroundMessage);
if (unsubscribe) {
unsubscribeRef.current = unsubscribe;
}
setIsLoading(false);
return true;
} else {
// Permission was denied
setPermission(getNotificationPermission());
setIsLoading(false);
return false;
}
} catch (error) {
console.error('Failed to request notification permission:', error);
setIsLoading(false);
return false;
}
}, [isSupported, handleForegroundMessage]);
// Mark notification as read
const markAsRead = useCallback((notificationId: string) => {
setNotifications((prev) => {
const updated = prev.map((n) =>
n.id === notificationId ? { ...n, read: true } : n,
);
saveNotifications(updated);
return updated;
});
}, []);
// Mark all as read
const markAllAsRead = useCallback(() => {
setNotifications((prev) => {
const updated = prev.map((n) => ({ ...n, read: true }));
saveNotifications(updated);
return updated;
});
}, []);
// Clear a notification
const clearNotification = useCallback((notificationId: string) => {
setNotifications((prev) => {
const updated = prev.filter((n) => n.id !== notificationId);
saveNotifications(updated);
return updated;
});
}, []);
// Clear all notifications
const clearAllNotifications = useCallback(() => {
setNotifications([]);
saveNotifications([]);
}, []);
// Navigate to notification
const navigateToNotification = useCallback(
(notification: OmiNotification) => {
markAsRead(notification.id);
const route = getNotificationRoute(notification);
router.push(route);
},
[router, markAsRead],
);
// Unregister token (for logout)
const unregisterToken = useCallback(async () => {
const token = fcmToken || getStoredFCMToken();
if (token) {
await unregisterFCMToken(token);
storeFCMToken(null);
setFcmToken(null);
}
if (unsubscribeRef.current) {
unsubscribeRef.current();
unsubscribeRef.current = null;
}
}, [fcmToken]);
// Send a test notification (for debugging)
const sendTestNotification = useCallback(() => {
const testNotification: OmiNotification = {
id: `test-${Date.now()}`,
type: 'announcement',
title: 'Test Notification',
body: 'This is a test notification to verify the UI is working correctly.',
timestamp: new Date().toISOString(),
read: false,
};
setNotifications((prev) => {
const updated = [testNotification, ...prev].slice(0, MAX_NOTIFICATIONS);
saveNotifications(updated);
return updated;
});
// Also show a browser notification
if (Notification.permission === 'granted') {
const browserNotif = new Notification(testNotification.title, {
body: testNotification.body,
icon: '/logo.png',
tag: testNotification.id,
});
browserNotif.onclick = () => {
window.focus();
browserNotif.close();
};
}
}, []);
return {
notifications,
unreadCount,
permission,
isSupported,
isLoading,
fcmToken,
requestPermission: requestPermissionHandler,
markAsRead,
markAllAsRead,
clearNotification,
clearAllNotifications,
navigateToNotification,
unregisterToken,
sendTestNotification,
};
}