This repository has been archived by the owner on Jan 27, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
notification.js
71 lines (60 loc) · 1.89 KB
/
notification.js
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
import messaging from '@react-native-firebase/messaging';
import Toast from 'react-native-toast-message';
import {saveNotificationToken} from './lib/notification';
const validNotificationTypes = new Map([
['device_state', 'Device State Event'],
['motion_event', 'Motion Event'],
]);
async function onTokenRefresh(state, token) {
const results = await Promise.all(
state.accountList.map(async ([id, {serverUuid, address, port}]) => {
const url = 'https://' + address + (port ? ':' + port : '');
try {
return await saveNotificationToken(url, id, serverUuid, token);
} catch (err) {
return {success: false, message: err.message};
}
}),
);
const failed = results.filter(({success}) => !success);
if (failed.length > 0) {
Toast.show({
type: 'error',
text1: 'Notification System',
text2: failed.length + ' account could not update notification token',
});
}
}
function showInAppNotification(message, onShowCamera) {
const {
data: {eventType, deviceId, deviceName},
} = message;
if (!isValidNotificationType(eventType)) {
Toast.show({
type: 'info',
text1: eventType,
});
return;
}
Toast.show({
type: 'info',
text1: validNotificationTypes.get(eventType),
text2: deviceName,
onPress: () => onShowCamera(deviceId),
});
}
export function isValidNotificationType(type) {
return validNotificationTypes.has(type);
}
export function handleNotification(state, onShowCamera) {
const messageHandlerCleanup = messaging().onMessage(async (message) => {
if (state.activeAccount && message.data.serverId === state.activeAccount.serverUuid) {
showInAppNotification(message, onShowCamera);
}
});
const tokenHandlerCleanup = messaging().onTokenRefresh(async (token) => onTokenRefresh(state, token));
return () => {
messageHandlerCleanup();
tokenHandlerCleanup();
};
}