-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathKnockExpoPushNotificationProvider.tsx
More file actions
337 lines (303 loc) · 9.71 KB
/
KnockExpoPushNotificationProvider.tsx
File metadata and controls
337 lines (303 loc) · 9.71 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
import { Message, MessageEngagementStatus } from "@knocklabs/client";
import { useKnockClient } from "@knocklabs/react-core";
import {
type KnockPushNotificationContextType,
KnockPushNotificationProvider,
usePushNotifications,
} from "@knocklabs/react-native";
import Constants from "expo-constants";
import * as Device from "expo-device";
import * as Network from "expo-network";
import * as Notifications from "expo-notifications";
import React, {
createContext,
useCallback,
useContext,
useEffect,
useState,
} from "react";
export interface KnockExpoPushNotificationContextType
extends KnockPushNotificationContextType {
expoPushToken: string | null;
registerForPushNotifications: () => Promise<void>;
onNotificationReceived: (
handler: (notification: Notifications.Notification) => void,
) => void;
onNotificationTapped: (
handler: (response: Notifications.NotificationResponse) => void,
) => void;
}
Notifications.setNotificationHandler({
handleNotification: async () => {
return {
shouldShowAlert: true,
shouldPlaySound: true,
shouldSetBadge: true,
shouldShowBanner: true,
shouldShowList: true,
};
},
});
const defaultNotificationHandler = async (
_notification: Notifications.Notification,
): Promise<Notifications.NotificationBehavior> => {
return {
shouldShowAlert: true,
shouldPlaySound: true,
shouldSetBadge: true,
shouldShowBanner: true,
shouldShowList: true,
};
};
const KnockExpoPushNotificationContext = createContext<
KnockExpoPushNotificationContextType | undefined
>(undefined);
export interface KnockExpoPushNotificationProviderProps {
knockExpoChannelId: string;
customNotificationHandler?: (
notification: Notifications.Notification,
) => Promise<Notifications.NotificationBehavior>;
children?: React.ReactElement;
autoRegister?: boolean;
}
async function requestPushPermissionIfNeeded(): Promise<string> {
const { status: existingStatus } = await Notifications.getPermissionsAsync();
if (existingStatus !== "granted") {
const { status } = await Notifications.requestPermissionsAsync();
return status;
}
return existingStatus;
}
async function getExpoPushToken(): Promise<Notifications.ExpoPushToken | null> {
try {
if (
!Constants.expoConfig ||
!Constants.expoConfig.extra ||
!Constants.expoConfig.extra.eas
) {
console.error(
"[Knock] Expo Project ID is not defined in the app configuration.",
);
return null;
}
const token = await Notifications.getExpoPushTokenAsync({
projectId: Constants.expoConfig.extra.eas.projectId,
});
return token;
} catch (error) {
console.error("[Knock] Error getting Expo push token:", error);
return null;
}
}
async function requestPermissionAndGetPushToken(): Promise<Notifications.ExpoPushToken | null> {
// Check for device support
if (!Device.isDevice) {
console.warn("[Knock] Must use physical device for Push Notifications");
return null;
}
const permissionStatus = await requestPushPermissionIfNeeded();
if (permissionStatus !== "granted") {
console.warn("[Knock] Push notification permission not granted");
return null;
}
return getExpoPushToken();
}
const InternalKnockExpoPushNotificationProvider: React.FC<
KnockExpoPushNotificationProviderProps
> = ({
knockExpoChannelId,
customNotificationHandler,
children,
autoRegister = true,
}) => {
const { registerPushTokenToChannel, unregisterPushTokenFromChannel } =
usePushNotifications();
const [expoPushToken, setExpoPushToken] = useState<string | null>(null);
const knockClient = useKnockClient();
const { isInternetReachable } = Network.useNetworkState();
const [notificationReceivedHandler, setNotificationReceivedHandler] =
useState<(notification: Notifications.Notification) => void>(
() => () => {},
);
const [notificationTappedHandler, setNotificationTappedHandler] = useState<
(response: Notifications.NotificationResponse) => void
>(() => () => {});
const handleNotificationReceived = useCallback(
(handler: (notification: Notifications.Notification) => void) => {
setNotificationReceivedHandler(() => handler);
},
[],
);
const handleNotificationTapped = useCallback(
(handler: (response: Notifications.NotificationResponse) => void) => {
setNotificationTappedHandler(() => handler);
},
[],
);
const registerForPushNotifications = useCallback(async (): Promise<void> => {
try {
knockClient.log(`[Knock] Registering for push notifications`);
const token = await requestPermissionAndGetPushToken();
knockClient.log(`[Knock] Token received: ${token?.data}`);
if (token?.data) {
knockClient.log(`[Knock] Setting push token: ${token.data}`);
setExpoPushToken(token.data);
}
} catch (error) {
console.error(`[Knock] Error registering for push notifications:`, error);
}
}, [knockClient]);
const updateKnockMessageStatusFromNotification = useCallback(
async (
notification: Notifications.Notification,
status: MessageEngagementStatus,
): Promise<Message | void> => {
const messageId = notification.request.content.data?.[
"knock_message_id"
] as string | undefined;
// Skip status update if this isn't a Knock notification
// Fixes issue: https://github.com/knocklabs/javascript/issues/589
if (!messageId) {
knockClient.log(
"[Knock] Skipping status update for non-Knock notification",
);
return;
}
return knockClient.messages.updateStatus(messageId, status);
},
[knockClient],
);
useEffect(() => {
if (expoPushToken) {
return;
}
const fetchExpoTokenIfNeeded = async () => {
const { status: existingStatus } =
await Notifications.getPermissionsAsync();
if (
existingStatus === "granted" &&
Device.isDevice &&
isInternetReachable
) {
try {
const token = await getExpoPushToken();
setExpoPushToken(token ? token.data : null);
} catch (error) {
console.error(`[Knock] Error getting expo push token:`, error);
}
}
};
fetchExpoTokenIfNeeded();
}, [isInternetReachable, expoPushToken]);
useEffect(() => {
Notifications.setNotificationHandler({
handleNotification:
customNotificationHandler ?? defaultNotificationHandler,
});
const response = Notifications.getLastNotificationResponse();
if (response?.notification) {
knockClient.log(
"[Knock] Expo Push Notification was interacted with (initial)",
);
updateKnockMessageStatusFromNotification(
response.notification,
"interacted",
);
notificationTappedHandler(response);
}
}, [
customNotificationHandler,
knockClient,
notificationTappedHandler,
updateKnockMessageStatusFromNotification,
]);
useEffect(() => {
if (autoRegister) {
registerForPushNotifications()
.then(() => {
if (expoPushToken) {
registerPushTokenToChannel(expoPushToken, knockExpoChannelId)
.then((_result) => {
knockClient.log("[Knock] setChannelData success");
})
.catch((_error) => {
console.error(
"[Knock] Error in setting push token or channel data",
_error,
);
});
}
})
.catch((_error) => {
console.error(
"[Knock] Error in setting push token or channel data",
_error,
);
});
}
const notificationReceivedSubscription =
Notifications.addNotificationReceivedListener((notification) => {
knockClient.log(
"[Knock] Expo Push Notification received in foreground:",
);
updateKnockMessageStatusFromNotification(notification, "interacted");
notificationReceivedHandler(notification);
});
const notificationResponseSubscription =
Notifications.addNotificationResponseReceivedListener((response) => {
knockClient.log("[Knock] Expo Push Notification was interacted with");
updateKnockMessageStatusFromNotification(
response.notification,
"interacted",
);
notificationTappedHandler(response);
});
return () => {
notificationReceivedSubscription.remove();
notificationResponseSubscription.remove();
};
}, [
registerForPushNotifications,
notificationReceivedHandler,
notificationTappedHandler,
autoRegister,
expoPushToken,
knockExpoChannelId,
knockClient,
registerPushTokenToChannel,
updateKnockMessageStatusFromNotification,
]);
return (
<KnockExpoPushNotificationContext.Provider
value={{
expoPushToken,
registerForPushNotifications,
registerPushTokenToChannel,
unregisterPushTokenFromChannel,
onNotificationReceived: handleNotificationReceived,
onNotificationTapped: handleNotificationTapped,
}}
>
{children}
</KnockExpoPushNotificationContext.Provider>
);
};
export const KnockExpoPushNotificationProvider: React.FC<
KnockExpoPushNotificationProviderProps
> = (props) => {
return (
<KnockPushNotificationProvider>
<InternalKnockExpoPushNotificationProvider {...props} />
</KnockPushNotificationProvider>
);
};
export const useExpoPushNotifications =
(): KnockExpoPushNotificationContextType => {
const context = useContext(KnockExpoPushNotificationContext);
if (context === undefined) {
throw new Error(
"[Knock] useExpoPushNotifications must be used within a KnockExpoPushNotificationProvider",
);
}
return context;
};