package host.exp.exponent.notifications import android.content.Context import expo.modules.notifications.notifications.model.Notification import expo.modules.notifications.notifications.model.NotificationRequest import expo.modules.notifications.notifications.model.NotificationResponse import expo.modules.notifications.service.delegates.ExpoPresentationDelegate import host.exp.exponent.experience.ExperienceActivity import host.exp.exponent.kernel.ExperienceKey import host.exp.exponent.notifications.model.ScopedNotificationRequest class ScopedNotificationsUtils(context: Context) { private val exponentNotificationManager: ExponentNotificationManager = ExponentNotificationManager(context) fun shouldHandleNotification(notification: Notification, experienceKey: ExperienceKey): Boolean { return shouldHandleNotification(notification.notificationRequest, experienceKey) } fun shouldHandleNotification( notificationRequest: NotificationRequest, experienceKey: ExperienceKey ): Boolean { // expo-notifications notification if (notificationRequest is ScopedNotificationRequest) { return notificationRequest.checkIfBelongsToExperience(experienceKey) } // legacy or foreign notification val foreignNotification = ExpoPresentationDelegate.parseNotificationIdentifier(notificationRequest.identifier) if (foreignNotification != null) { val foreignNotificationExperienceScopeKey = foreignNotification.first val foreignNotificationExperienceKey = foreignNotificationExperienceScopeKey?.let { ExperienceKey(it) } val notificationBelongsToSomeExperience = foreignNotificationExperienceKey != null && exponentNotificationManager.getAllNotificationsIds(foreignNotificationExperienceKey).contains(foreignNotification.second) val notificationExperienceIsCurrentExperience = foreignNotificationExperienceKey != null && experienceKey.scopeKey == foreignNotificationExperienceKey.scopeKey val notificationIsPersistentExponentNotification = foreignNotificationExperienceScopeKey == null && foreignNotification.second == ExperienceActivity.PERSISTENT_EXPONENT_NOTIFICATION_ID // If notification doesn't belong to any experience it's a foreign notification // and we want to deliver it to all the experiences. If it does belong to some experience, // we want to handle it only if it belongs to "current" experience. If it is the persistent // Exponent notification do not pass it to any experience. return !notificationIsPersistentExponentNotification && (!notificationBelongsToSomeExperience || notificationExperienceIsCurrentExperience) } // fallback return true } companion object { fun getExperienceScopeKey(notificationResponse: NotificationResponse?): String? { if (notificationResponse == null || notificationResponse.notification == null) { return null } val notificationRequest = notificationResponse.notification.notificationRequest if (notificationRequest is ScopedNotificationRequest) { return notificationRequest.experienceScopeKeyString } return null } } }