|
| 1 | +import { LoginConfig } from '../types'; |
| 2 | +import AsyncStore from './AsyncStore'; |
| 3 | +import { |
| 4 | + FirebaseMessagingTypes, |
| 5 | + setBackgroundMessageHandler, |
| 6 | +} from '@react-native-firebase/messaging'; |
| 7 | +import { DeliveredMessageConfirmation, StreamChat } from 'stream-chat'; |
| 8 | +import notifee from '@notifee/react-native'; |
| 9 | +import { getMessaging } from '@react-native-firebase/messaging'; |
| 10 | + |
| 11 | +const messaging = getMessaging(); |
| 12 | + |
| 13 | +const displayNotification = async ( |
| 14 | + remoteMessage: FirebaseMessagingTypes.RemoteMessage, |
| 15 | + channelId: string, |
| 16 | +) => { |
| 17 | + const { stream, ...rest } = remoteMessage.data ?? {}; |
| 18 | + const data = { |
| 19 | + ...rest, |
| 20 | + ...((stream as unknown as Record<string, string> | undefined) ?? {}), // extract and merge stream object if present |
| 21 | + }; |
| 22 | + if (data.body && data.title) { |
| 23 | + await notifee.displayNotification({ |
| 24 | + android: { |
| 25 | + channelId, |
| 26 | + pressAction: { |
| 27 | + id: 'default', |
| 28 | + }, |
| 29 | + }, |
| 30 | + body: data.body as string, |
| 31 | + title: data.title as string, |
| 32 | + data, |
| 33 | + }); |
| 34 | + } |
| 35 | +}; |
| 36 | + |
| 37 | +setBackgroundMessageHandler(messaging, async (remoteMessage) => { |
| 38 | + try { |
| 39 | + const loginConfig = await AsyncStore.getItem<LoginConfig>( |
| 40 | + '@stream-rn-sampleapp-login-config', |
| 41 | + null, |
| 42 | + ); |
| 43 | + if (!loginConfig) { |
| 44 | + return; |
| 45 | + } |
| 46 | + const chatClient = StreamChat.getInstance(loginConfig.apiKey); |
| 47 | + await chatClient._setToken({ id: loginConfig.userId }, loginConfig.userToken); |
| 48 | + |
| 49 | + const notification = remoteMessage.data; |
| 50 | + |
| 51 | + const deliverMessageConfirmation = [ |
| 52 | + { |
| 53 | + cid: notification?.cid, |
| 54 | + id: notification?.id, |
| 55 | + }, |
| 56 | + ]; |
| 57 | + |
| 58 | + await chatClient?.markChannelsDelivered({ |
| 59 | + latest_delivered_messages: deliverMessageConfirmation as DeliveredMessageConfirmation[], |
| 60 | + }); |
| 61 | + // create the android channel to send the notification to |
| 62 | + const channelId = await notifee.createChannel({ |
| 63 | + id: 'chat-messages', |
| 64 | + name: 'Chat Messages', |
| 65 | + }); |
| 66 | + // display the notification |
| 67 | + await displayNotification(remoteMessage, channelId); |
| 68 | + } catch (error) { |
| 69 | + console.error(error); |
| 70 | + } |
| 71 | +}); |
0 commit comments