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
|
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();
|