Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 | 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 4x 4x 4x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 8x 3x 3x 2x 2x 2x 2x 2x 2x 6x 6x 6x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 1x 2x 2x 2x 2x 1x 1x 1x 1x 1x 4x 2x 2x 2x 4x 2x 2x 2x 2x 2x 1x 3x 3x 3x 3x 3x 3x 3x 3x 2x 2x 3x 3x 3x 1x 2x 1x 2x 1x 3x 3x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 110x 109x 109x 5x 5x 2x 1x 1x 1x 4x 4x 5x 3x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 2x 13x 4x 4x 9x 1x 1x 1x 1x 2x 1x 2x 2x 1x 1x 1x 1x 5x | import { AppState, AppStateStatus, Linking } from 'react-native';
import { getApp } from '@react-native-firebase/app';
import {
getInitialNotification,
getMessaging,
onMessage,
onTokenRefresh,
} from '@react-native-firebase/messaging';
import notifee, { EventType } from '@notifee/react-native';
import { getPlatform } from '@repo/utils/platform';
import { sentryService } from '@/services/sentryService';
import { NOTIFICATION_LOG } from './constants';
import {
createNotificationData,
ensureNotificationChannel,
extractNotificationData,
extractNotificationFromMessage,
} from './helpers';
import { NotificationMessages } from './messages';
import * as Permissions from './permissions';
import * as Sync from './sync';
import * as Token from './token';
import type { NotificationPayload, PermissionStatus, RemoteMessage } from './types';
class NotificationService {
private fcmToken: string | null = null;
private tokenListeners: Array<(token: string) => void> = [];
private onNotificationTapCallback?: (data?: Record<string, unknown>) => void;
private messageListeners: Array<(data?: Record<string, unknown>) => void> = [];
private isInitialized = false;
private tokenRefreshListenerSet = false;
private foregroundMessageListenerSet = false;
private readonly messaging = getMessaging(getApp());
private pendingNotificationData: Record<string, unknown> | null = null;
private readonly processedNotificationIds = new Set<string>(); // Prevent duplicate processing of the same message ID
private refreshVersion = 0;
private versionListeners: Array<(version: number) => void> = [];
private disabledFeatures: Record<string, boolean> = {};
async initialize(): Promise<void> {
if (this.isInitialized) return;
try {
this.log(NotificationMessages.INITIALIZING);
await ensureNotificationChannel();
this.setupTokenRefreshListener();
this.setupForegroundMessageHandler();
this.setupNotificationEventHandlers();
const permissionStatus = await this.checkPermissionStatus();
Eif (permissionStatus.authorized) {
await this.getFCMToken();
}
this.isInitialized = true;
await this.markAllDisplayedAsProcessed();
this.refreshVersion = 0;
this.setupAppStateListener();
this.log(
NotificationMessages.INITIALIZED,
'info',
undefined,
NOTIFICATION_LOG.ACTIONS.INITIALIZE,
);
} catch (error) {
this.log(
NotificationMessages.INIT_ERROR(error),
'error',
error,
NOTIFICATION_LOG.ACTIONS.INITIALIZE,
);
}
}
async checkPermissionStatus(): Promise<PermissionStatus> {
return Permissions.checkPermissionStatus(this.messaging);
}
async requestPermissions(): Promise<boolean> {
const currentStatus = await this.checkPermissionStatus();
if (currentStatus.authorized) return true;
this.log(
NotificationMessages.REQUESTING_PERMISSION,
'info',
undefined,
NOTIFICATION_LOG.ACTIONS.REQUEST_PERMISSION,
);
const granted =
getPlatform() === 'ios'
? await Permissions.requestIOSPermission(this.messaging)
: await Permissions.requestAndroidPermission();
Eif (granted) {
await new Promise(resolve => setTimeout(resolve, 500));
await this.getFCMToken();
}
return granted;
}
async getFCMToken(): Promise<string | null> {
const token = await Token.fetchFCMToken(this.messaging, t => {
this.fcmToken = t;
this.notifyTokenListeners(t);
});
Iif (!token) {
this.log(
NotificationMessages.TOKEN_GET_ERROR('Empty token'),
'warn',
undefined,
NOTIFICATION_LOG.ACTIONS.GET_TOKEN,
);
}
return token;
}
async setupAfterLogin(): Promise<string | null> {
try {
const permissionStatus = await this.checkPermissionStatus();
Eif (!permissionStatus.authorized) {
const granted = await this.requestPermissions();
Iif (!granted) return null;
}
await ensureNotificationChannel();
return await this.getFCMToken();
} catch (error) {
this.log(
NotificationMessages.SETUP_AFTER_LOGIN_ERROR(error),
'error',
error,
NOTIFICATION_LOG.ACTIONS.SETUP_AFTER_LOGIN,
);
return null;
}
}
setDisabledFeatures(features: Record<string, boolean>): void {
const hasChanged = JSON.stringify(this.disabledFeatures) !== JSON.stringify(features);
this.disabledFeatures = features;
Eif (hasChanged) {
this.incrementRefreshVersion();
}
}
getToken(): string | null {
return this.fcmToken;
}
clearTokenCache(): void {
this.fcmToken = null;
}
onTokenUpdate(callback: (token: string) => void): () => void {
this.tokenListeners.push(callback);
Iif (this.fcmToken) callback(this.fcmToken);
return () => {
this.tokenListeners = this.tokenListeners.filter(listener => listener !== callback);
};
}
setOnNotificationTap(callback: (data?: Record<string, unknown>) => void): void {
this.onNotificationTapCallback = callback;
// Only process and clear if we have a valid callback
Eif (this.pendingNotificationData && typeof callback === 'function' && callback.name !== '') {
const data = this.pendingNotificationData;
this.pendingNotificationData = null;
callback(data);
}
}
getPendingNotificationData(): Record<string, unknown> | null {
return this.pendingNotificationData;
}
clearPendingNotificationData(): void {
this.pendingNotificationData = null;
}
addMessageListener(callback: (data?: Record<string, unknown>) => void): () => void {
this.messageListeners.push(callback);
return () => {
this.messageListeners = this.messageListeners.filter(listener => listener !== callback);
};
}
async displayNotification(notification: NotificationPayload | null, id?: string): Promise<void> {
if (!notification || (!notification.title && !notification.body)) return;
try {
await ensureNotificationChannel();
const notificationData = createNotificationData(notification);
if (id) notificationData.id = id;
await notifee.displayNotification(notificationData);
} catch (error) {
this.log(
NotificationMessages.NOTIFICATION_DISPLAY_ERROR(error),
'error',
error,
NOTIFICATION_LOG.ACTIONS.DISPLAY,
);
}
}
async handleRemoteMessage(remoteMessage: RemoteMessage): Promise<void> {
const isForeground = AppState.currentState === 'active';
const isAndroidPlatform = getPlatform() === 'android';
const hasNotificationPayload = !!remoteMessage.notification;
// On Android, if the message has a notification payload and the app is in the background/quit state,
// the OS automatically displays the notification. We should skip manual display to avoid duplicates.
const shouldSkipDisplay = isAndroidPlatform && !isForeground && hasNotificationPayload;
const notification = extractNotificationFromMessage(remoteMessage);
const msgId = remoteMessage.messageId;
Eif (notification) {
if (notification.data) {
notification.data._messageId = msgId;
// Mark as already refreshed to avoid double refresh in UI when app is in foreground
notification.data._alreadyRefreshed = true;
}
Eif (msgId) this.markNotificationAsProcessed(msgId);
const notificationData = extractNotificationData(notification.data);
if (
notificationData?.category &&
this.disabledFeatures[notificationData.category as string]
) {
return;
}
if (!shouldSkipDisplay) {
await this.displayNotification(notification, msgId);
}
if (notification.data) {
this.incrementRefreshVersion();
}
}
}
async getInitialNotification(): Promise<RemoteMessage | null> {
try {
// 1. Check Firebase initial notification
const remoteMessage = await getInitialNotification(this.messaging);
if (remoteMessage?.data) {
this.pendingNotificationData = remoteMessage.data as Record<string, unknown>;
return remoteMessage;
}
// 2. Check Notifee initial notification (for manually displayed ones or background taps)
const notifeeNotification = await notifee.getInitialNotification();
Eif (notifeeNotification?.notification?.data) {
this.pendingNotificationData = notifeeNotification.notification.data as Record<
string,
unknown
>;
// Return a shape compatible with RemoteMessage if possible, or just null as we set pendingData
}
return remoteMessage;
} catch (error) {
this.log(
NotificationMessages.INITIAL_NOTIFICATION_ERROR(error),
'error',
error,
NOTIFICATION_LOG.ACTIONS.CHECK_INITIAL,
);
return null;
}
}
async handleNotificationPress(
detail: Parameters<Parameters<typeof notifee.onForegroundEvent>[0]>[0]['detail'],
): Promise<void> {
const notificationData = detail.notification?.data as Record<string, unknown> | undefined;
const msgId = detail.notification?.id || (notificationData?._messageId as string);
Iif (msgId) this.markNotificationAsProcessed(msgId);
Eif (notificationData) this.pendingNotificationData = notificationData;
Iif (this.onNotificationTapCallback) {
this.onNotificationTapCallback(notificationData);
this.pendingNotificationData = null;
}
}
async syncWithDisplayedNotifications(): Promise<{ hasNew: boolean; ticketIds: string[] }> {
const result = await Sync.syncTrayNotifications(
id => this.isNotificationProcessed(id),
id => this.markNotificationAsProcessed(id),
);
Eif (result.hasNew) this.incrementRefreshVersion();
return result;
}
async markAllDisplayedAsProcessed(): Promise<void> {
await Sync.markTrayAsProcessed(id => this.markNotificationAsProcessed(id));
}
markNotificationAsProcessed(id: string): void {
if (!id) return;
this.processedNotificationIds.add(id);
if (this.processedNotificationIds.size > 100) {
const firstItem = this.processedNotificationIds.values().next().value;
Eif (firstItem) this.processedNotificationIds.delete(firstItem);
}
}
isNotificationProcessed(id: string): boolean {
return this.processedNotificationIds.has(id);
}
getRefreshVersion(): number {
return this.refreshVersion;
}
addVersionListener(callback: (version: number) => void): () => void {
this.versionListeners.push(callback);
return () => {
this.versionListeners = this.versionListeners.filter(l => l !== callback);
};
}
private incrementRefreshVersion(): void {
this.refreshVersion++;
this.versionListeners.forEach(l => l(this.refreshVersion));
}
private lastSyncTime = 0;
private setupAppStateListener(): void {
AppState.addEventListener('change', async (nextAppState: AppStateStatus) => {
Eif (nextAppState === 'active') {
const now = Date.now();
Iif (now - this.lastSyncTime < 1000) return;
this.lastSyncTime = now;
await this.syncWithDisplayedNotifications();
}
});
}
private setupTokenRefreshListener(): void {
Iif (this.tokenRefreshListenerSet) return;
onTokenRefresh(this.messaging, token => {
this.fcmToken = token;
this.notifyTokenListeners(token);
});
this.tokenRefreshListenerSet = true;
}
private setupForegroundMessageHandler(): void {
Iif (this.foregroundMessageListenerSet) return;
onMessage(this.messaging, async remoteMessage => {
const notification = extractNotificationFromMessage(remoteMessage);
const msgId = remoteMessage.messageId;
Eif (msgId) this.markNotificationAsProcessed(msgId);
Eif (notification?.data) {
const notificationData = extractNotificationData(notification.data);
const category = notificationData?.category as string;
Eif (!category || !this.disabledFeatures[category]) {
const dataWithId = { ...notification.data, _messageId: msgId };
this.messageListeners.forEach(listener => listener(dataWithId));
}
}
await this.handleRemoteMessage(remoteMessage);
});
this.foregroundMessageListenerSet = true;
}
private setupNotificationEventHandlers(): void {
notifee.onForegroundEvent(async ({ type, detail }) => {
if (type === EventType.PRESS) await this.handleNotificationPress(detail);
});
}
private notifyTokenListeners(token: string): void {
this.tokenListeners.forEach(callback => callback(token));
}
private log(
message: string,
level: 'info' | 'warn' | 'error' = 'info',
data?: unknown,
action?: string,
): void {
if (level === 'error') {
const error = data instanceof Error ? data : new Error(message);
sentryService.captureException(error, {
tags: {
component: NOTIFICATION_LOG.COMPONENT,
platform: getPlatform(),
action: action || 'unknown',
},
extra: { message, data },
});
} else Iif (level === 'warn' && data) {
sentryService.addBreadcrumb({
message,
level: 'warning',
category: NOTIFICATION_LOG.COMPONENT,
data: { ...(data as Record<string, unknown>), action },
});
}
}
async subscribeToTopic(topic: string): Promise<void> {
try {
await this.messaging.subscribeToTopic(topic);
} catch (error) {
this.log(
NotificationMessages.TOPIC_SUBSCRIBE_ERROR(topic, error),
'error',
error,
NOTIFICATION_LOG.ACTIONS.SUBSCRIBE,
);
}
}
async unsubscribeFromTopic(topic: string): Promise<void> {
try {
await this.messaging.unsubscribeFromTopic(topic);
} catch (error) {
this.log(
NotificationMessages.TOPIC_UNSUBSCRIBE_ERROR(topic, error),
'error',
error,
NOTIFICATION_LOG.ACTIONS.UNSUBSCRIBE,
);
}
}
async cancelAllNotifications(): Promise<void> {
await notifee.cancelAllNotifications();
}
async cancelNotification(id: string): Promise<void> {
await notifee.cancelNotification(id);
}
async getBadgeCount(): Promise<number> {
return Permissions.isIOS() ? await notifee.getBadgeCount() : 0;
}
async setBadgeCount(count: number): Promise<void> {
Eif (Permissions.isIOS()) await notifee.setBadgeCount(count);
}
async openNotificationSettings(): Promise<void> {
try {
if (Permissions.isIOS()) {
await Linking.openSettings();
return;
}
try {
await notifee.openNotificationSettings();
} catch {
// Fallback for Android devices where notification settings deep-link is unavailable.
await Linking.openSettings();
}
} catch (error) {
this.log(
NotificationMessages.SETTINGS_OPEN_ERROR(error),
'error',
error,
NOTIFICATION_LOG.ACTIONS.OPEN_SETTINGS,
);
}
}
}
export const notificationService = new NotificationService();
export default notificationService;
|