diff options
| author | Shravya Ramesh <37447613+shravyaramesh@users.noreply.github.com> | 2020-12-29 11:41:57 -0800 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2020-12-29 14:41:57 -0500 |
| commit | 05cd91206a6ce3361097d9eb408a447eae3d120e (patch) | |
| tree | 1b8c5ba82358c3f9b393ea42d03b6c9c7219ce7f /src/services/FCMService.ts | |
| parent | efaa41884b5aa4b4704380eb3615d3801958a775 (diff) | |
[TMA-288] notifications frontend infra (#154)
* Configured settings to enable remote notifications
* Added FCM services
* Added background message handler + api calls
* minor fixes
* minor changes requested from pr
Diffstat (limited to 'src/services/FCMService.ts')
| -rw-r--r-- | src/services/FCMService.ts | 177 |
1 files changed, 177 insertions, 0 deletions
diff --git a/src/services/FCMService.ts b/src/services/FCMService.ts new file mode 100644 index 00000000..11cb7510 --- /dev/null +++ b/src/services/FCMService.ts @@ -0,0 +1,177 @@ +import AsyncStorage from '@react-native-community/async-storage'; +import messaging from '@react-native-firebase/messaging'; +import {Platform} from 'react-native'; +import {getDeviceId, getDeviceName} from 'react-native-device-info'; +import {FCM_ENDPOINT} from '../constants'; + +class FCMService { + setUpPushNotifications = () => { + // Requesting user to permit notifications + this.checkPermission(); + + // Registering with FCM to receive unique device/app token + this.registerAppWithFCM(); + + //Store registration_id/device token to AsyncStorage + this.getToken(); + + // Receive a notification + this.createNotificationListeners(); + + // // Schedule a local notification + // PushNotification.localNotificationSchedule({ + // //... You can use all the options from localNotifications + // message: 'My Notification Message', // (required) + // date: new Date(Date.now() + 60 * 1000), // in 60 secs + // allowWhileIdle: false, // (optional) set notification to work while on doze, default: false + // }); + + // // Send local notification when app in foreground since remote notifications + // // aren't displayed when app is in the foreground + // PushNotification.localNotification({ + // //... You can use all the options from localNotifications + // message: 'My Notification Message', // (required) + // date: new Date(Date.now() + 60 * 1000), // in 60 secs + // allowWhileIdle: false, // (optional) set notification to work while on doze, default: false + //}); + }; + + registerAppWithFCM = async () => { + if (Platform.OS === 'ios') { + if (!messaging().isDeviceRegisteredForRemoteMessages) { + await messaging().registerDeviceForRemoteMessages(); + } + await messaging().setAutoInitEnabled(true); + } + }; + + checkPermission = async () => { + try { + const permission = await messaging().hasPermission(); + // Permission might be 0 (not allowed), 1 (allowed), -1(unknown) + if (permission !== 1) { + await messaging().requestPermission({ + sound: true, + announcement: true, + badge: true, + alert: true, + }); + } + } catch (error) { + console.log('[FCMService] Permission Rejected ', error); + } + }; + + // Receiving fcm unique device token to receive remote messages through fcm + getToken = async () => { + messaging() + .getToken() + .then(async (fcmToken) => { + if (fcmToken) { + await AsyncStorage.setItem('@fcmToken', fcmToken); + return fcmToken; + } + }) + .catch((error) => { + console.log('[FCMService] getToken rejected', error); + }); + return ''; + }; + + sendFcmTokenToServer = async () => { + const registration_id: string | null = await AsyncStorage.getItem( + '@fcmToken', + ); + const device_id = getDeviceId(); + const type = Platform.OS; + let active: boolean = false; + let name: string = ''; + await getDeviceName().then((deviceName) => { + name = deviceName; + }); + + await messaging() + .hasPermission() + .then((hasPermission) => { + active = hasPermission === 1; + }); + const token = await AsyncStorage.getItem('token'); + + if (registration_id && type) { + let response = await fetch(FCM_ENDPOINT, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + Authorization: 'Token ' + token, + }, + body: JSON.stringify({ + registration_id, + type, + device_id, + name, + active, + }), + }); + + if (response.status === 201) { + console.log('Successfully stored device token!'); + } else { + console.log('Failed to store device token!'); + console.log(response); + } + } + }; + + deactivateFcmService = async () => { + //Make PATCH call to deactivate device + console.log('Deactivating FCM device'); + }; + + createNotificationListeners = () => { + // messaging().onNotificationOpenedApp((remoteMessage) => { + // console.log( + // '[FCMService] onNotificationOpenedApp Notification caused app to open', + // ); + // if (remoteMessage) { + // const notification = remoteMessage.notification; + // onOpenNotification(notification); + // } + // }); + + // messaging() + // .getInitialNotification() + // .then((remoteMessage) => { + // console.log( + // '[FCMService] getInitialNotification Notification caused app to open', + // ); + + // if (remoteMessage) { + // const notification = remoteMessage.notification; + // onOpenNotification(notification); + // } + // }); + + messaging().onMessage((remoteMessage) => { + console.log('Received a remote notification!!'); + if (remoteMessage) { + let notification = remoteMessage.notification; + let notificationId = remoteMessage.messageId; + console.log( + 'notificationsId: ', + notificationId, + ' notification: ', + notification, + ); + } + }); + + messaging().onTokenRefresh((fcmToken) => { + AsyncStorage.setItem('@fcmToken', fcmToken).catch((err) => { + console.log('Failed to store new token!'); + console.log(err); + }); + }); + }; +} + +export const fcmService = new FCMService(); |
