Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 | 1x 1x 1x 1x 1x 1x 5x 5x 1x 9x 9x 9x 9x 9x 9x 9x 9x 9x 6x 9x 6x 9x 6x 9x 8x 9x 4x 4x 4x 4x 4x 4x 9x 7x 2x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 3x 5x 5x 5x 5x 5x 5x 1x 5x 5x 15x 9x 9x 9x 9x 9x 1x 1x 8x 2x 2x 2x 2x | import { useEffect, useRef } from 'react';
import { Alert, PermissionsAndroid, Platform } from 'react-native';
import {
AuthorizationStatus,
getInitialNotification,
getMessaging,
getToken,
onMessage,
onNotificationOpenedApp,
onTokenRefresh,
registerDeviceForRemoteMessages,
requestPermission,
} from '@react-native-firebase/messaging';
import { getDeviceInstallationID } from '@/services/deviceInstallation';
import {
registerPushDevice,
unregisterPushDevice,
} from '@/services/pushDeviceService';
import {
normalizePushNotificationPayload,
NormalizedPushNotificationPayload,
} from '@/firebase/pushNotificationPayload';
async function ensureAndroidPostNotificationsPermission(): Promise<boolean> {
if (Platform.OS !== 'android' || Platform.Version < 33) {
return true;
}
const result = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.POST_NOTIFICATIONS,
);
return result === PermissionsAndroid.RESULTS.GRANTED;
}
export type PushMessagingOptions = {
authToken?: string | null;
pushNotificationsEnabled?: boolean;
/** Called whenever an FCM token is acquired or rotated (send this to your server). */
onFcmToken?: (token: string) => void;
onNotificationReceived?: (payload: NormalizedPushNotificationPayload) => void;
onNotificationOpened?: (payload: NormalizedPushNotificationPayload) => void;
};
/** Registers foreground listeners and requests permission + token. Not used on web. */
export function usePushMessaging(options?: PushMessagingOptions) {
const pushNotificationsEnabled = options?.pushNotificationsEnabled ?? true;
const onFcmTokenRef = useRef(options?.onFcmToken);
const onNotificationReceivedRef = useRef(options?.onNotificationReceived);
const onNotificationOpenedRef = useRef(options?.onNotificationOpened);
const authTokenRef = useRef(options?.authToken ?? null);
const previousEffectiveAuthTokenRef = useRef<string | null>(
pushNotificationsEnabled ? options?.authToken ?? null : null,
);
const currentFcmTokenRef = useRef<string | null>(null);
const lastSyncedKeyRef = useRef<string | null>(null);
useEffect(() => {
onFcmTokenRef.current = options?.onFcmToken;
}, [options?.onFcmToken]);
useEffect(() => {
onNotificationReceivedRef.current = options?.onNotificationReceived;
}, [options?.onNotificationReceived]);
useEffect(() => {
onNotificationOpenedRef.current = options?.onNotificationOpened;
}, [options?.onNotificationOpened]);
useEffect(() => {
authTokenRef.current = options?.authToken ?? null;
}, [options?.authToken]);
const syncTokenToBackend = async (fcmToken: string, authToken: string) => {
const installationID = await getDeviceInstallationID();
const platform = Platform.OS === 'ios' ? 'IOS' : 'ANDROID';
const syncKey = `${authToken}:${installationID}:${fcmToken}`;
Iif (lastSyncedKeyRef.current === syncKey) {
return;
}
await registerPushDevice(
installationID,
{
fcm_token: fcmToken,
platform,
device_info: `${Platform.OS} ${Platform.Version}`,
},
authToken,
);
lastSyncedKeyRef.current = syncKey;
};
useEffect(() => {
if (
!pushNotificationsEnabled ||
(Platform.OS !== 'ios' && Platform.OS !== 'android')
) {
return undefined;
}
const unsubscribers: Array<() => void> = [];
let active = true;
(async () => {
const messaging = getMessaging();
const notificationsOk = await ensureAndroidPostNotificationsPermission();
Iif (!active || !notificationsOk) {
return;
}
const status = await requestPermission(messaging);
const notificationsAllowed =
status === AuthorizationStatus.AUTHORIZED ||
status === AuthorizationStatus.PROVISIONAL ||
status === AuthorizationStatus.EPHEMERAL;
Iif (!active || !notificationsAllowed) {
return;
}
if (Platform.OS === 'ios') {
await registerDeviceForRemoteMessages(messaging);
}
const pushTokenToServer = async () => {
const token = await getToken(messaging);
Iif (!active) return;
currentFcmTokenRef.current = token;
onFcmTokenRef.current?.(token);
const authToken = authTokenRef.current;
if (authToken) {
await syncTokenToBackend(token, authToken).catch(() => {});
}
};
await pushTokenToServer();
unsubscribers.push(
onTokenRefresh(messaging, () => {
void pushTokenToServer();
}),
);
unsubscribers.push(
onMessage(messaging, (remoteMessage) => {
const payload = normalizePushNotificationPayload(remoteMessage);
onNotificationReceivedRef.current?.(payload);
Iif (payload.body) {
Alert.alert(payload.title, payload.body, [
{ text: 'Dismiss', style: 'cancel' },
{
text: 'View',
onPress: () => onNotificationOpenedRef.current?.(payload),
},
]);
}
}),
);
unsubscribers.push(
onNotificationOpenedApp(messaging, (remoteMessage) => {
onNotificationOpenedRef.current?.(
normalizePushNotificationPayload(remoteMessage),
);
}),
);
const initialNotification = await getInitialNotification(messaging);
if (active && initialNotification) {
onNotificationOpenedRef.current?.(
normalizePushNotificationPayload(initialNotification),
);
}
})().catch(() => {});
return () => {
active = false;
unsubscribers.forEach((u) => u());
};
}, [pushNotificationsEnabled]);
useEffect(() => {
const effectiveAuthToken = pushNotificationsEnabled
? options?.authToken ?? null
: null;
const previousEffectiveAuthToken = previousEffectiveAuthTokenRef.current;
previousEffectiveAuthTokenRef.current = effectiveAuthToken;
if (effectiveAuthToken && currentFcmTokenRef.current) {
void syncTokenToBackend(
currentFcmTokenRef.current,
effectiveAuthToken,
).catch(() => {});
return;
}
if (!effectiveAuthToken && previousEffectiveAuthToken) {
lastSyncedKeyRef.current = null;
void (async () => {
const installationID = await getDeviceInstallationID();
await unregisterPushDevice(installationID, previousEffectiveAuthToken);
})().catch(() => {});
}
}, [options?.authToken, pushNotificationsEnabled]);
}
|