react-native-notify-sphere 1.0.0 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1080 -15
- package/android/src/main/AndroidManifest.xml +8 -1
- package/android/src/main/java/com/notifysphere/NotifySphereModule.kt +0 -6
- package/ios/NotifySphere.mm +0 -6
- package/lib/module/NativeNotifySphere.js +11 -0
- package/lib/module/NativeNotifySphere.js.map +1 -1
- package/lib/module/index.js +463 -105
- package/lib/module/index.js.map +1 -1
- package/lib/typescript/src/NativeNotifySphere.d.ts +11 -1
- package/lib/typescript/src/NativeNotifySphere.d.ts.map +1 -1
- package/lib/typescript/src/index.d.ts +213 -25
- package/lib/typescript/src/index.d.ts.map +1 -1
- package/package.json +9 -11
- package/src/NativeNotifySphere.ts +12 -3
- package/src/index.tsx +670 -154
package/lib/module/index.js
CHANGED
|
@@ -1,42 +1,125 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
|
|
3
3
|
import messaging from '@react-native-firebase/messaging';
|
|
4
|
-
import notifee, { AndroidImportance, AndroidStyle, EventType
|
|
5
|
-
} from '@notifee/react-native';
|
|
4
|
+
import notifee, { AndroidImportance, AndroidStyle, EventType } from '@notifee/react-native';
|
|
6
5
|
import axios from 'axios';
|
|
6
|
+
import AsyncStorage from '@react-native-async-storage/async-storage';
|
|
7
7
|
import { PermissionsAndroid, Platform } from 'react-native';
|
|
8
|
-
|
|
9
|
-
|
|
8
|
+
const STORAGE_KEY_TOKEN = '@notifysphere_fcm_token';
|
|
9
|
+
const STORAGE_KEY_SUB_ID = '@notifysphere_subscription_id';
|
|
10
|
+
const STORAGE_KEY_USER_HASH = '@notifysphere_user_hash';
|
|
11
|
+
|
|
12
|
+
// ─── Type definitions ──────────────────────────────────────────────────────────
|
|
13
|
+
|
|
14
|
+
/** Shape of a Firebase Cloud Messaging remote message */
|
|
15
|
+
|
|
16
|
+
/** Shape of a Notifee notification object (returned from press events) */
|
|
17
|
+
|
|
18
|
+
/** Normalised notification data delivered to the consumer callback */
|
|
19
|
+
|
|
20
|
+
// ─── Internal logger ──────────────────────────────────────────────────────────
|
|
21
|
+
|
|
22
|
+
let _debug = false;
|
|
23
|
+
const log = (...args) => {
|
|
24
|
+
if (_debug) console.log('[NotifySphere]', ...args);
|
|
25
|
+
};
|
|
26
|
+
const warn = (...args) => {
|
|
27
|
+
if (_debug) console.warn('[NotifySphere]', ...args);
|
|
28
|
+
};
|
|
29
|
+
// Errors are always surfaced regardless of the debug flag
|
|
30
|
+
const logError = (...args) => console.error('[NotifySphere]', ...args);
|
|
31
|
+
|
|
32
|
+
// ─── Default endpoints ────────────────────────────────────────────────────────
|
|
33
|
+
|
|
34
|
+
const DEFAULT_BASE_URL = 'https://api.notifysphere.in';
|
|
35
|
+
// const DEFAULT_BASE_URL = 'https://apinotify.dothejob.in';
|
|
36
|
+
const DEFAULT_TRACKING_URL = DEFAULT_BASE_URL + '/onpress/handle';
|
|
37
|
+
const DEFAULT_DELIVERY_URL = DEFAULT_BASE_URL + '/delivery/confirm';
|
|
38
|
+
;
|
|
39
|
+
|
|
40
|
+
// ─── NotifySphere class ───────────────────────────────────────────────────────
|
|
41
|
+
|
|
10
42
|
class NotifySphere {
|
|
11
43
|
static callback = null;
|
|
44
|
+
static fcmToken = null;
|
|
45
|
+
static appId = null;
|
|
46
|
+
static subscriptionId = null;
|
|
47
|
+
static baseUrl = DEFAULT_BASE_URL;
|
|
48
|
+
static trackingUrl = DEFAULT_TRACKING_URL;
|
|
49
|
+
static deliveryUrl = DEFAULT_DELIVERY_URL;
|
|
50
|
+
static apiKey = null;
|
|
51
|
+
static unsubscribers = [];
|
|
52
|
+
static initialized = false;
|
|
53
|
+
static createdChannels = new Set();
|
|
12
54
|
|
|
13
|
-
//
|
|
55
|
+
// ─── Press tracking ──────────────────────────────────────────────────────
|
|
14
56
|
|
|
15
|
-
|
|
16
|
-
|
|
57
|
+
/**
|
|
58
|
+
* Tracks a notification press event and fires the consumer callback.
|
|
59
|
+
* Accepts both Firebase remote messages and Notifee notification objects.
|
|
60
|
+
*/
|
|
61
|
+
static async callbackOnpress(notification, status) {
|
|
17
62
|
try {
|
|
18
|
-
const
|
|
19
|
-
|
|
20
|
-
|
|
63
|
+
const notificationId = notification.data?.notification_id ?? notification.data?.notification_id;
|
|
64
|
+
const headers = {
|
|
65
|
+
'Content-Type': 'application/json'
|
|
66
|
+
};
|
|
67
|
+
if (NotifySphere.apiKey) {
|
|
68
|
+
headers['Authorization'] = `Bearer ${NotifySphere.apiKey}`;
|
|
69
|
+
}
|
|
70
|
+
const response = await axios.post(NotifySphere.trackingUrl, {
|
|
71
|
+
notification_id: notificationId,
|
|
72
|
+
subscription_id: NotifySphere.subscriptionId,
|
|
21
73
|
onPressStatus: 1
|
|
74
|
+
}, {
|
|
75
|
+
headers,
|
|
76
|
+
maxBodyLength: Infinity
|
|
22
77
|
});
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
78
|
+
log('onPress tracking response:', response.data);
|
|
79
|
+
NotifySphere.sendCallback(notification, status);
|
|
80
|
+
} catch (err) {
|
|
81
|
+
logError('Error in callbackOnpress:', err);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// ─── Delivery confirmation ───────────────────────────────────────────────
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Sends a delivery receipt to the server as soon as a notification arrives.
|
|
89
|
+
*
|
|
90
|
+
* This fires in three scenarios:
|
|
91
|
+
* - Foreground : app is open when the message arrives
|
|
92
|
+
* - Background : app is alive in the background (data-only FCM message)
|
|
93
|
+
* - Terminated : app is completely killed (data-only FCM message only —
|
|
94
|
+
* notification messages are shown by the OS without waking
|
|
95
|
+
* the app, so this cannot fire in that case)
|
|
96
|
+
*/
|
|
97
|
+
static async callbackOnDelivery(remoteMessage) {
|
|
98
|
+
try {
|
|
99
|
+
const notificationId = remoteMessage.data?.notification_id;
|
|
100
|
+
const headers = {
|
|
101
|
+
'Content-Type': 'application/json'
|
|
32
102
|
};
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
103
|
+
if (NotifySphere.apiKey) {
|
|
104
|
+
headers['Authorization'] = `Bearer ${NotifySphere.apiKey}`;
|
|
105
|
+
}
|
|
106
|
+
console.log("NotifySphere.deliveryUrl", NotifySphere.deliveryUrl);
|
|
107
|
+
const response = await axios.post(NotifySphere.deliveryUrl, {
|
|
108
|
+
notification_id: notificationId,
|
|
109
|
+
subscription_id: NotifySphere.subscriptionId,
|
|
110
|
+
onDeliveredStatus: 1
|
|
111
|
+
}, {
|
|
112
|
+
headers,
|
|
113
|
+
maxBodyLength: Infinity
|
|
114
|
+
});
|
|
115
|
+
log('Delivery confirmation response:', response.data);
|
|
116
|
+
} catch (err) {
|
|
117
|
+
logError('Error sending delivery confirmation:', err);
|
|
38
118
|
}
|
|
39
119
|
}
|
|
120
|
+
|
|
121
|
+
// ─── Permissions ─────────────────────────────────────────────────────────
|
|
122
|
+
|
|
40
123
|
static async checkApplicationPermission() {
|
|
41
124
|
try {
|
|
42
125
|
if (Platform.OS === 'android' && Platform.Version >= 33) {
|
|
@@ -47,36 +130,112 @@ class NotifySphere {
|
|
|
47
130
|
return authStatus === messaging.AuthorizationStatus.AUTHORIZED || authStatus === messaging.AuthorizationStatus.PROVISIONAL;
|
|
48
131
|
}
|
|
49
132
|
return true;
|
|
50
|
-
} catch (
|
|
51
|
-
|
|
133
|
+
} catch (err) {
|
|
134
|
+
logError('Error requesting notification permission:', err);
|
|
52
135
|
return false;
|
|
53
136
|
}
|
|
54
137
|
}
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
138
|
+
|
|
139
|
+
// ─── User details fingerprint ─────────────────────────────────────────────
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* Builds a stable string fingerprint of all user-profile fields.
|
|
143
|
+
* Used to detect whether any detail has changed since the last registration,
|
|
144
|
+
* so the API is only called when something actually differs.
|
|
145
|
+
*/
|
|
146
|
+
static buildUserHash(config) {
|
|
147
|
+
const fields = {
|
|
148
|
+
applicationUserId: config.applicationUserId,
|
|
149
|
+
type: config.type,
|
|
150
|
+
name: config.name ?? '',
|
|
151
|
+
lat: config.lat ?? '',
|
|
152
|
+
long: config.long ?? '',
|
|
153
|
+
city: config.city ?? '',
|
|
154
|
+
state: config.state ?? '',
|
|
155
|
+
email: config.email ?? '',
|
|
156
|
+
phone: config.phone ?? '',
|
|
157
|
+
// Stringify tags with sorted keys so order doesn't affect the hash
|
|
158
|
+
tags: config.tags ? JSON.stringify(Object.keys(config.tags).sort().reduce((acc, k) => {
|
|
159
|
+
acc[k] = config.tags[k];
|
|
160
|
+
return acc;
|
|
161
|
+
}, {})) : ''
|
|
70
162
|
};
|
|
163
|
+
return JSON.stringify(fields);
|
|
71
164
|
}
|
|
165
|
+
|
|
166
|
+
// ─── Initialize ──────────────────────────────────────────────────────────
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* Initialises the SDK and sets up notification listeners.
|
|
170
|
+
*
|
|
171
|
+
* Safe to call every time the app opens — it only hits the registration API
|
|
172
|
+
* when the FCM token OR any user detail (email, phone, location, tags, etc.)
|
|
173
|
+
* has changed since the last successful registration.
|
|
174
|
+
* Listeners are registered only once per process lifetime.
|
|
175
|
+
*
|
|
176
|
+
* Token changes are also handled automatically via `onTokenRefresh`.
|
|
177
|
+
*/
|
|
72
178
|
static async initialize(config) {
|
|
179
|
+
_debug = config.debug ?? false;
|
|
180
|
+
NotifySphere.appId = config.appId;
|
|
181
|
+
NotifySphere.baseUrl = config.baseUrl ?? DEFAULT_BASE_URL;
|
|
182
|
+
NotifySphere.trackingUrl = config.trackingUrl ?? DEFAULT_TRACKING_URL;
|
|
183
|
+
NotifySphere.deliveryUrl = config.deliveryUrl ?? DEFAULT_DELIVERY_URL;
|
|
184
|
+
NotifySphere.apiKey = config.apiKey ?? null;
|
|
73
185
|
const hasPermission = await NotifySphere.checkApplicationPermission();
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
186
|
+
if (!hasPermission) {
|
|
187
|
+
warn('Notification permission not granted — aborting initialization');
|
|
188
|
+
return undefined;
|
|
189
|
+
}
|
|
190
|
+
try {
|
|
191
|
+
const fcmToken = await messaging().getToken();
|
|
192
|
+
NotifySphere.fcmToken = fcmToken;
|
|
193
|
+
|
|
194
|
+
// ── Restore cached subscription_id immediately so tracking calls
|
|
195
|
+
// have it available even before the registration API responds.
|
|
196
|
+
const cachedSubId = await AsyncStorage.getItem(STORAGE_KEY_SUB_ID);
|
|
197
|
+
if (cachedSubId) {
|
|
198
|
+
NotifySphere.subscriptionId = cachedSubId;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
// ── Only call the registration API when the FCM token OR any user
|
|
202
|
+
// detail has changed. This avoids a redundant network call on every
|
|
203
|
+
// app open while still syncing updates (email, phone, location, etc.)
|
|
204
|
+
const [cachedToken, cachedUserHash] = await Promise.all([AsyncStorage.getItem(STORAGE_KEY_TOKEN), AsyncStorage.getItem(STORAGE_KEY_USER_HASH)]);
|
|
205
|
+
const currentUserHash = NotifySphere.buildUserHash(config);
|
|
206
|
+
let subscriptionId = cachedSubId ?? undefined;
|
|
207
|
+
const tokenChanged = fcmToken !== cachedToken;
|
|
208
|
+
const userChanged = currentUserHash !== cachedUserHash;
|
|
209
|
+
if (tokenChanged || userChanged) {
|
|
210
|
+
if (tokenChanged) log('FCM token changed — re-registering device');
|
|
211
|
+
if (userChanged) log('User details changed — re-registering device');
|
|
212
|
+
subscriptionId = await NotifySphere.registerDevice(config, fcmToken, currentUserHash);
|
|
213
|
+
} else {
|
|
214
|
+
log('Token and user details unchanged — skipping registration API call');
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
// ── Channel and listeners are always set up (idempotent)
|
|
218
|
+
await NotifySphere.ensureChannel('channel_default', 'Default Channel', 'default');
|
|
219
|
+
if (!NotifySphere.initialized) {
|
|
220
|
+
NotifySphere.setupListeners();
|
|
221
|
+
// Watch for token refreshes (Firebase can rotate the token silently)
|
|
222
|
+
NotifySphere.watchTokenRefresh(config);
|
|
223
|
+
NotifySphere.initialized = true;
|
|
224
|
+
}
|
|
225
|
+
return subscriptionId;
|
|
226
|
+
} catch (err) {
|
|
227
|
+
logError('Error during initialization:', err);
|
|
228
|
+
return undefined;
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/**
|
|
233
|
+
* Calls the registration API and persists the token, subscription_id, and
|
|
234
|
+
* user hash so future launches can detect what has changed.
|
|
235
|
+
* Extracted so it can also be called from the token-refresh watcher.
|
|
236
|
+
*/
|
|
237
|
+
static async registerDevice(config, fcmToken, userHash) {
|
|
238
|
+
const res = await axios.post(`${NotifySphere.baseUrl}/apps/${config.appId}/users`, {
|
|
80
239
|
applicationUserId: config.applicationUserId,
|
|
81
240
|
token: fcmToken,
|
|
82
241
|
type: config.type,
|
|
@@ -88,85 +247,247 @@ class NotifySphere {
|
|
|
88
247
|
state: config.state,
|
|
89
248
|
email: config.email,
|
|
90
249
|
phone: config.phone,
|
|
91
|
-
tags: config.tags
|
|
92
|
-
sdk: devInfo.sdk,
|
|
93
|
-
device_model: devInfo.device_model,
|
|
94
|
-
device_os: devInfo.device_os,
|
|
95
|
-
device_version: devInfo.device_version,
|
|
96
|
-
carrier: devInfo.carrier,
|
|
97
|
-
app_version: devInfo.app_version,
|
|
98
|
-
timezone_id: devInfo.timezone_id
|
|
250
|
+
tags: config.tags
|
|
99
251
|
}
|
|
100
252
|
}, {
|
|
101
253
|
headers: {
|
|
102
254
|
'Content-Type': 'application/json'
|
|
103
255
|
},
|
|
104
256
|
maxBodyLength: Infinity
|
|
105
|
-
}).then(async res => {
|
|
106
|
-
console.log('res313132', res);
|
|
107
|
-
return res.data.subscription_id;
|
|
108
|
-
}).catch(err => {
|
|
109
|
-
console.log('err31232', err);
|
|
110
257
|
});
|
|
111
|
-
|
|
112
|
-
|
|
258
|
+
log('Device registration response:', res.data);
|
|
259
|
+
const subscriptionId = res.data?.subscription_id;
|
|
260
|
+
NotifySphere.subscriptionId = subscriptionId ?? null;
|
|
261
|
+
|
|
262
|
+
// Persist token, subscription_id, and user hash for future launch comparisons
|
|
263
|
+
const hash = userHash ?? NotifySphere.buildUserHash(config);
|
|
264
|
+
await Promise.all([AsyncStorage.setItem(STORAGE_KEY_TOKEN, fcmToken), AsyncStorage.setItem(STORAGE_KEY_USER_HASH, hash), subscriptionId ? AsyncStorage.setItem(STORAGE_KEY_SUB_ID, subscriptionId) : Promise.resolve()]);
|
|
265
|
+
return subscriptionId;
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/**
|
|
269
|
+
* Listens for Firebase token refreshes and automatically re-registers
|
|
270
|
+
* the device when the token rotates, without requiring the consumer to
|
|
271
|
+
* call initialize() again.
|
|
272
|
+
*/
|
|
273
|
+
static watchTokenRefresh(config) {
|
|
274
|
+
const unsubRefresh = messaging().onTokenRefresh(async newToken => {
|
|
275
|
+
log('FCM token refreshed — re-registering device');
|
|
276
|
+
NotifySphere.fcmToken = newToken;
|
|
277
|
+
try {
|
|
278
|
+
// User details haven't changed here, reuse the existing hash
|
|
279
|
+
const existingHash = (await AsyncStorage.getItem(STORAGE_KEY_USER_HASH)) ?? NotifySphere.buildUserHash(config);
|
|
280
|
+
await NotifySphere.registerDevice(config, newToken, existingHash);
|
|
281
|
+
} catch (err) {
|
|
282
|
+
logError('Error re-registering after token refresh:', err);
|
|
283
|
+
}
|
|
284
|
+
});
|
|
285
|
+
NotifySphere.unsubscribers.push(unsubRefresh);
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
// ─── Update tags ─────────────────────────────────────────────────────────
|
|
289
|
+
|
|
290
|
+
/**
|
|
291
|
+
* Updates user tags without re-registering the device.
|
|
292
|
+
* `appId` is optional here — it falls back to the value passed in `initialize`.
|
|
293
|
+
*/
|
|
294
|
+
static async updateTags(params) {
|
|
295
|
+
const appId = params.appId ?? NotifySphere.appId;
|
|
296
|
+
if (!NotifySphere.fcmToken) {
|
|
297
|
+
warn('FCM token missing — cannot update tags');
|
|
298
|
+
return null;
|
|
299
|
+
}
|
|
300
|
+
if (!appId) {
|
|
301
|
+
warn('appId missing — cannot update tags');
|
|
302
|
+
return null;
|
|
303
|
+
}
|
|
304
|
+
try {
|
|
305
|
+
const res = await axios.post(`${NotifySphere.baseUrl}/apps/${appId}/users`, {
|
|
306
|
+
applicationUserId: params.applicationUserId,
|
|
307
|
+
token: NotifySphere.fcmToken,
|
|
308
|
+
type: params.type,
|
|
309
|
+
user: {
|
|
310
|
+
tags: params.tags
|
|
311
|
+
}
|
|
312
|
+
}, {
|
|
313
|
+
headers: {
|
|
314
|
+
'Content-Type': 'application/json'
|
|
315
|
+
},
|
|
316
|
+
maxBodyLength: Infinity
|
|
317
|
+
});
|
|
318
|
+
log('Tags update response:', res.data);
|
|
319
|
+
return res.data;
|
|
320
|
+
} catch (err) {
|
|
321
|
+
logError('Error updating tags:', err);
|
|
322
|
+
return null;
|
|
323
|
+
}
|
|
113
324
|
}
|
|
325
|
+
|
|
326
|
+
// ─── Public callback setter ───────────────────────────────────────────────
|
|
327
|
+
|
|
328
|
+
/** Register a callback to receive notification events (received / opened / initial). */
|
|
114
329
|
static onNotification(callback) {
|
|
115
330
|
NotifySphere.callback = callback;
|
|
116
331
|
}
|
|
332
|
+
|
|
333
|
+
// ─── Background handler ───────────────────────────────────────────────────
|
|
334
|
+
|
|
335
|
+
/**
|
|
336
|
+
* Registers Firebase and Notifee background handlers.
|
|
337
|
+
*
|
|
338
|
+
* **IMPORTANT:** Call this in your root `index.js` file, before
|
|
339
|
+
* `AppRegistry.registerComponent()`, so it is available when the app wakes
|
|
340
|
+
* in the background — or starts from a terminated state — to handle a
|
|
341
|
+
* notification.
|
|
342
|
+
*
|
|
343
|
+
* When the app is **terminated**, React Native only runs `index.js` (a
|
|
344
|
+
* headless JS task). Your app components and `initialize()` never execute,
|
|
345
|
+
* so any custom `deliveryUrl` / `apiKey` you passed to `initialize()` are
|
|
346
|
+
* not available. Pass them here instead so they are set before the handler
|
|
347
|
+
* fires.
|
|
348
|
+
*
|
|
349
|
+
* @example
|
|
350
|
+
* // index.js
|
|
351
|
+
* import { AppRegistry } from 'react-native';
|
|
352
|
+
* import NotifySphere from 'react-native-notify-sphere';
|
|
353
|
+
* import App from './App';
|
|
354
|
+
*
|
|
355
|
+
* NotifySphere.setBackgroundHandler({
|
|
356
|
+
* deliveryUrl: 'https://your-server.com/ondelivery/handle', // optional
|
|
357
|
+
* apiKey: 'your-api-key', // optional
|
|
358
|
+
* });
|
|
359
|
+
* AppRegistry.registerComponent('MyApp', () => App);
|
|
360
|
+
*/
|
|
361
|
+
static setBackgroundHandler(config) {
|
|
362
|
+
// Apply any config overrides immediately — before the handler fires —
|
|
363
|
+
// so they are in place even when the app starts from a terminated state.
|
|
364
|
+
if (config?.deliveryUrl) {
|
|
365
|
+
NotifySphere.deliveryUrl = config.deliveryUrl;
|
|
366
|
+
}
|
|
367
|
+
if (config?.apiKey) {
|
|
368
|
+
NotifySphere.apiKey = config.apiKey;
|
|
369
|
+
}
|
|
370
|
+
if (config?.subscriptionId) {
|
|
371
|
+
NotifySphere.subscriptionId = config.subscriptionId;
|
|
372
|
+
}
|
|
373
|
+
messaging().setBackgroundMessageHandler(async remoteMessage => {
|
|
374
|
+
const msg = remoteMessage;
|
|
375
|
+
// Run both in parallel — display and delivery receipt
|
|
376
|
+
await Promise.all([NotifySphere.displayLocalNotification(msg), NotifySphere.callbackOnDelivery(msg)]);
|
|
377
|
+
});
|
|
378
|
+
notifee.onBackgroundEvent(async ({
|
|
379
|
+
type,
|
|
380
|
+
detail
|
|
381
|
+
}) => {
|
|
382
|
+
log('Background notifee event, type:', type);
|
|
383
|
+
if (type === EventType.PRESS && detail.notification) {
|
|
384
|
+
await NotifySphere.callbackOnpress(detail.notification, 'press');
|
|
385
|
+
}
|
|
386
|
+
});
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
// ─── Cleanup ──────────────────────────────────────────────────────────────
|
|
390
|
+
|
|
391
|
+
/**
|
|
392
|
+
* Unsubscribes all active listeners and resets internal state.
|
|
393
|
+
* Call this when you want to stop receiving notifications (e.g. on logout).
|
|
394
|
+
*/
|
|
395
|
+
static destroy() {
|
|
396
|
+
for (const unsub of NotifySphere.unsubscribers) {
|
|
397
|
+
unsub();
|
|
398
|
+
}
|
|
399
|
+
NotifySphere.unsubscribers = [];
|
|
400
|
+
NotifySphere.initialized = false;
|
|
401
|
+
log('NotifySphere destroyed — all listeners removed');
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
// ─── Private: listeners ───────────────────────────────────────────────────
|
|
405
|
+
|
|
117
406
|
static setupListeners() {
|
|
118
|
-
|
|
119
|
-
|
|
407
|
+
// Foreground messages — display, send delivery receipt, and fire callback
|
|
408
|
+
const unsubMessage = messaging().onMessage(async remoteMessage => {
|
|
409
|
+
const msg = remoteMessage;
|
|
410
|
+
log('Foreground message received:', msg);
|
|
411
|
+
// Display and delivery receipt run in parallel for speed
|
|
412
|
+
|
|
413
|
+
await Promise.all([NotifySphere.displayLocalNotification(msg), NotifySphere.callbackOnDelivery(msg)]);
|
|
414
|
+
NotifySphere.sendCallback(msg, 'received');
|
|
120
415
|
});
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
416
|
+
|
|
417
|
+
// App brought from background via notification tap
|
|
418
|
+
const unsubOpened = messaging().onNotificationOpenedApp(async remoteMessage => {
|
|
419
|
+
log('App opened from background via notification:', remoteMessage.messageId);
|
|
420
|
+
await NotifySphere.callbackOnpress(remoteMessage, 'opened');
|
|
124
421
|
});
|
|
422
|
+
|
|
423
|
+
// App launched from a quit state via notification tap
|
|
125
424
|
messaging().getInitialNotification().then(remoteMessage => {
|
|
126
425
|
if (remoteMessage) {
|
|
127
426
|
NotifySphere.callbackOnpress(remoteMessage, 'initial');
|
|
128
427
|
}
|
|
129
|
-
});
|
|
130
|
-
|
|
428
|
+
}).catch(err => logError('getInitialNotification error:', err));
|
|
429
|
+
|
|
430
|
+
// Notifee foreground press events (covers in-app notification taps)
|
|
431
|
+
const unsubForeground = notifee.onForegroundEvent(({
|
|
131
432
|
type,
|
|
132
433
|
detail
|
|
133
434
|
}) => {
|
|
134
|
-
if (type === EventType.PRESS) {
|
|
135
|
-
console.log('detail323213', detail);
|
|
435
|
+
if (type === EventType.PRESS && detail.notification) {
|
|
136
436
|
NotifySphere.callbackOnpress(detail.notification, 'opened');
|
|
137
437
|
}
|
|
138
438
|
});
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
439
|
+
NotifySphere.unsubscribers.push(unsubMessage, unsubOpened, unsubForeground);
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
// ─── Private: channel management ─────────────────────────────────────────
|
|
443
|
+
|
|
444
|
+
/**
|
|
445
|
+
* Creates a notification channel if it hasn't been created yet this session.
|
|
446
|
+
* Notifee handles idempotency across app restarts; this in-memory guard
|
|
447
|
+
* prevents redundant async calls within the same session.
|
|
448
|
+
*/
|
|
449
|
+
static async ensureChannel(id, name, sound) {
|
|
450
|
+
if (NotifySphere.createdChannels.has(id)) return;
|
|
451
|
+
const soundName = sound.replace(/\..+$/, '');
|
|
452
|
+
const channelDef = {
|
|
453
|
+
id,
|
|
454
|
+
name,
|
|
455
|
+
importance: AndroidImportance.HIGH,
|
|
456
|
+
sound: soundName !== 'default' ? soundName : undefined,
|
|
457
|
+
lights: true,
|
|
458
|
+
lightColor: '#0000FF',
|
|
459
|
+
vibration: true
|
|
460
|
+
};
|
|
461
|
+
await notifee.createChannel(channelDef);
|
|
462
|
+
NotifySphere.createdChannels.add(id);
|
|
463
|
+
log('Android channel created/verified:', id);
|
|
149
464
|
}
|
|
465
|
+
|
|
466
|
+
// ─── Private: display notification ───────────────────────────────────────
|
|
467
|
+
|
|
150
468
|
static async displayLocalNotification(remoteMessage) {
|
|
469
|
+
// Use || so empty strings fall back just like null/undefined
|
|
151
470
|
const soundRaw = remoteMessage.data?.sound || 'default';
|
|
152
|
-
const
|
|
153
|
-
const
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
const
|
|
471
|
+
const soundName = soundRaw.replace(/\..+$/, '');
|
|
472
|
+
const channelId = `channel_${soundName}`;
|
|
473
|
+
await NotifySphere.ensureChannel(channelId, `Channel ${soundName}`, soundRaw);
|
|
474
|
+
|
|
475
|
+
// Resolve image — empty string treated same as missing
|
|
476
|
+
const image = remoteMessage.data?.imageUrl || remoteMessage.notification?.android?.imageUrl || remoteMessage.notification?.imageUrl || remoteMessage.notification?.ios?.attachments?.[0]?.url || undefined;
|
|
477
|
+
|
|
478
|
+
// Resolve title/body — empty string treated as missing
|
|
479
|
+
const title = remoteMessage.data?.title || remoteMessage.notification?.title || undefined;
|
|
480
|
+
const body = remoteMessage.data?.body || remoteMessage.notification?.body || undefined;
|
|
481
|
+
|
|
482
|
+
// smallIcon falls back to 'ic_stat_onesignal_default' if empty/missing
|
|
483
|
+
// largeIcon is removed entirely
|
|
484
|
+
const smallIcon = NotifySphere.resolveIcon(remoteMessage.data?.smallIcon) ?? 'ic_stat_onesignal_default';
|
|
162
485
|
await notifee.displayNotification({
|
|
163
|
-
title
|
|
164
|
-
body
|
|
486
|
+
title,
|
|
487
|
+
body,
|
|
165
488
|
android: {
|
|
166
|
-
channelId
|
|
167
|
-
|
|
168
|
-
sound: androidSoundName !== 'default' ? androidSoundName : undefined,
|
|
169
|
-
largeIcon: image,
|
|
489
|
+
channelId,
|
|
490
|
+
smallIcon,
|
|
170
491
|
style: image ? {
|
|
171
492
|
type: AndroidStyle.BIGPICTURE,
|
|
172
493
|
picture: image
|
|
@@ -174,11 +495,9 @@ class NotifySphere {
|
|
|
174
495
|
},
|
|
175
496
|
ios: {
|
|
176
497
|
sound: soundRaw,
|
|
177
|
-
// must be a bundled sound file or "default"
|
|
178
498
|
attachments: image ? [{
|
|
179
499
|
url: image
|
|
180
500
|
}] : undefined,
|
|
181
|
-
// ✅ this is correct
|
|
182
501
|
foregroundPresentationOptions: {
|
|
183
502
|
alert: true,
|
|
184
503
|
badge: true,
|
|
@@ -188,15 +507,54 @@ class NotifySphere {
|
|
|
188
507
|
data: remoteMessage.data
|
|
189
508
|
});
|
|
190
509
|
}
|
|
191
|
-
|
|
510
|
+
|
|
511
|
+
/**
|
|
512
|
+
* Returns the icon string if it is a real, usable value.
|
|
513
|
+
* Treats empty string (""), "ic_stat_onesignal_default", and
|
|
514
|
+
* any other placeholder-like value as absent (returns undefined).
|
|
515
|
+
*/
|
|
516
|
+
static resolveIcon(value) {
|
|
517
|
+
if (!value) return undefined; // catches "" / null / undefined
|
|
518
|
+
return value;
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
// ─── Private: fire consumer callback ─────────────────────────────────────
|
|
522
|
+
|
|
523
|
+
/**
|
|
524
|
+
* Normalises both Firebase remote messages and Notifee notification objects
|
|
525
|
+
* into the common NotificationData shape and fires the consumer callback.
|
|
526
|
+
*/
|
|
527
|
+
static sendCallback(notification, type) {
|
|
192
528
|
if (!NotifySphere.callback) return;
|
|
193
|
-
|
|
529
|
+
|
|
530
|
+
// Detect shape: Firebase messages have a `notification` or `messageId` field
|
|
531
|
+
const isFirebase = 'notification' in notification || 'messageId' in notification;
|
|
532
|
+
let title;
|
|
533
|
+
let body;
|
|
534
|
+
let data;
|
|
535
|
+
let image;
|
|
536
|
+
let sound;
|
|
537
|
+
if (isFirebase) {
|
|
538
|
+
const msg = notification;
|
|
539
|
+
title = msg.notification?.title ?? msg.data?.title;
|
|
540
|
+
body = msg.notification?.body ?? msg.data?.body;
|
|
541
|
+
data = msg.data;
|
|
542
|
+
image = msg.notification?.android?.imageUrl || msg.notification?.imageUrl || msg.notification?.ios?.attachments?.[0]?.url || msg.data?.imageUrl;
|
|
543
|
+
sound = msg.data?.sound;
|
|
544
|
+
} else {
|
|
545
|
+
const notif = notification;
|
|
546
|
+
title = notif.title;
|
|
547
|
+
body = notif.body;
|
|
548
|
+
data = notif.data;
|
|
549
|
+
image = notif.data?.imageUrl;
|
|
550
|
+
sound = notif.data?.sound;
|
|
551
|
+
}
|
|
194
552
|
NotifySphere.callback({
|
|
195
|
-
title
|
|
196
|
-
body
|
|
197
|
-
data
|
|
553
|
+
title,
|
|
554
|
+
body,
|
|
555
|
+
data,
|
|
198
556
|
image,
|
|
199
|
-
sound
|
|
557
|
+
sound
|
|
200
558
|
}, type);
|
|
201
559
|
}
|
|
202
560
|
}
|