aboutsummaryrefslogtreecommitdiff
path: root/src/services/FCMService.ts
blob: f76e94b65330a3c5d71a7d89bf416354661ea364 (plain)
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
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 {StreamChat} from 'stream-chat';
import {FCM_ENDPOINT} from '../constants';
import * as RootNavigation from '../RootNavigation';

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 (chatClient: StreamChat) => {
    const registration_id: string | null = await AsyncStorage.getItem(
      '@fcmToken',
    );
    if (registration_id !== null) {
      chatClient.addDevice(registration_id, 'firebase');
    }
    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!');
      }
    }
  };

  deactivateFcmService = async () => {
    // TODO: Make PATCH call to deactivate device
    console.log('Deactivating FCM device');
  };

  createNotificationListeners = () => {
    // Called when app is opened from backrground state
    messaging().onNotificationOpenedApp((remoteMessage) => {
      if (remoteMessage) {
        if (remoteMessage.category === 'CHAT') {
          RootNavigation.navigate('ChatList');
        } else {
          RootNavigation.navigate('Notifications');
        }
      }
    });

    messaging().onMessage((remoteMessage) => {
      console.log(
        'Received a remote notification!!',
        remoteMessage.notification?.body,
      );
    });

    messaging().onTokenRefresh((fcmToken) => {
      AsyncStorage.setItem('@fcmToken', fcmToken).catch((err) => {
        console.log('Failed to store new token!');
        console.log(err);
      });
    });
  };
}

export const fcmService = new FCMService();