mirror of
https://github.com/Novaloop-AG/element-x-ios.git
synced 2026-11-03 06:55:59 +00:00
Notify every signed-in account and turn notifications on and off per account (#6337)
* Store the notifications switch per account Adds AccountSettings.enableNotifications and moves the app-wide value into the signed in accounts before they're restored: the first account takes it out of the app settings and the others get the same switch, so someone who turned notifications off keeps them off. * Add a notification service to every user session Each account's NotificationService sets its pusher when its notifications are on and deletes it when they're off (appending with multiple accounts), keeps the account's unread count and decides which of its delivered notifications to clear. It asks the NotificationManager, the only owner of the notification center, through actions: remove the notifications matching a rule, request authorization and the unread count. The UserSessionManager connects every live session's service to the manager, and flows and screens use the session's service instead of the manager, which leaves the flow parameters. * Route notifications by account Taps only open rooms of the active account for now, a tap made while restoring only opens once its account is the active one, replies are sent from the account they were made for, and signing out only clears that account's notifications unless it was the last one. The notification extension hides pushes for an account that signed out while other accounts are still signed in. * Turn notifications on and off for each account The notification settings switch is now saved per account, and each account's NotificationService sets or deletes its pusher when it changes, asking for permission when it's turned on. * Apply review suggestions to multi-account notifications Migration - Move the notifications switch with a single per-account migration, like 26.10.1 and 26.10.2, and drop its dedicated test. Notification manager and service - Follow each account's badge count publisher directly, removing the badge count action and the stored counts. - Only reset the badge and unregister from APNs when the last account signs out, as each account already clears its own notifications. - Set up the service's subscriptions in a single setupSubscriptions(). - Rename switchChanged(to:) to enableNotificationsChanged(to:) and pusherConfiguration(identifiers:) to pusherConfiguration(for:). - Build the service without hopping to the main actor, it already runs there. Notification service extension - Check the account's switch in NotificationHandler using the session's settings, and log an error when a push arrives for an account that's turned off. - Always show pushes that match no signed-in account and log an error, so a broken setup stays visible. Other - Store a pending inline reply in a PendingInlineReplyDetails struct. - Assign the chats tab badge with weakAssign. - Make PusherConfiguration Equatable so the pusher test checks it in one expectation. - Clarify the comment about notifications without a receiver. * Print instead of logging before the app hooks run in the NSE A push that matches no signed-in account goes back to printing, as MXLog shouldn't be used before the app hooks have run. The push is still shown so a broken setup stays visible.
This commit is contained in:
@@ -64,7 +64,10 @@ class AppCoordinator: AppCoordinatorProtocol, AuthenticationFlowCoordinatorDeleg
|
||||
private let appRouteURLParser: AppRouteURLParser
|
||||
|
||||
private var storedAppRoute: AppRoute?
|
||||
@Consumable private var storedInlineReply: (roomID: String, message: String)?
|
||||
/// The account of a notification tapped while restoring, its route only opens once that account is the active one.
|
||||
@Consumable private var storedAppRouteReceiverID: String?
|
||||
/// A reply made from a notification before its account was live.
|
||||
private var storedInlineReply: PendingInlineReplyDetails?
|
||||
@Consumable private var storedRoomsToAwait: Set<String>?
|
||||
|
||||
init(appDelegate: AppDelegate) {
|
||||
@@ -125,7 +128,8 @@ class AppCoordinator: AppCoordinatorProtocol, AuthenticationFlowCoordinatorDeleg
|
||||
analyticsService: analyticsService,
|
||||
appHooks: appHooks,
|
||||
networkMonitor: networkMonitor)
|
||||
userSessionManager = UserSessionManager(userSessionStore: userSessionStore, appSettings: appSettings)
|
||||
notificationManager = NotificationManager(notificationCenter: UNUserNotificationCenter.current(), appSettings: appSettings)
|
||||
userSessionManager = UserSessionManager(userSessionStore: userSessionStore, appSettings: appSettings, notificationManager: notificationManager)
|
||||
|
||||
let appLockService = AppLockService(keychainController: keychainController, appSettings: appSettings)
|
||||
let appLockNavigationCoordinator = NavigationRootCoordinator()
|
||||
@@ -133,9 +137,6 @@ class AppCoordinator: AppCoordinatorProtocol, AuthenticationFlowCoordinatorDeleg
|
||||
navigationCoordinator: appLockNavigationCoordinator,
|
||||
appSettings: appSettings)
|
||||
|
||||
notificationManager = NotificationManager(notificationCenter: UNUserNotificationCenter.current(),
|
||||
appSettings: appSettings)
|
||||
|
||||
bugReportService = BugReportService(rageshakeURLPublisher: appSettings.bugReportRageshakeURL.publisher,
|
||||
applicationID: appSettings.bugReportApplicationID,
|
||||
sdkGitSHA: sdkGitSha(),
|
||||
@@ -147,8 +148,7 @@ class AppCoordinator: AppCoordinatorProtocol, AuthenticationFlowCoordinatorDeleg
|
||||
|
||||
windowManager.delegate = self
|
||||
|
||||
notificationManager.delegate = self
|
||||
notificationManager.start()
|
||||
configureNotificationManager()
|
||||
|
||||
guard let currentVersion = Version(InfoPlistReader(bundle: .main).bundleShortVersionString) else {
|
||||
fatalError("The app's version number **must** use semver for migration purposes.")
|
||||
@@ -407,6 +407,10 @@ class AppCoordinator: AppCoordinatorProtocol, AuthenticationFlowCoordinatorDeleg
|
||||
// there is not a user session yet
|
||||
return false
|
||||
}
|
||||
// Only the active account's rooms can be on screen.
|
||||
if let receiverID = content.receiverID, receiverID != userSession?.clientProxy.userID {
|
||||
return true
|
||||
}
|
||||
return !userSessionFlowCoordinator.isDisplayingRoomScreen(withRoomID: roomID)
|
||||
}
|
||||
|
||||
@@ -414,10 +418,20 @@ class AppCoordinator: AppCoordinatorProtocol, AuthenticationFlowCoordinatorDeleg
|
||||
MXLog.info("Tapped Notification")
|
||||
|
||||
guard let roomID = content.roomID,
|
||||
content.receiverID != nil else {
|
||||
let receiverID = content.receiverID else {
|
||||
return
|
||||
}
|
||||
|
||||
if let userSession {
|
||||
guard receiverID == userSession.clientProxy.userID else {
|
||||
// TODO: Switch to the receiver's account and open the room (element-hq/element-meta#3328).
|
||||
MXLog.info("Ignoring a notification tap for \(receiverID), it isn't the active account.")
|
||||
return
|
||||
}
|
||||
} else {
|
||||
storedAppRouteReceiverID = receiverID
|
||||
}
|
||||
|
||||
let eventID = appSettings.focusEventOnNotificationTap ? content.eventID : nil
|
||||
if content.categoryIdentifier == NotificationConstants.Category.invite {
|
||||
if let userSession {
|
||||
@@ -440,17 +454,18 @@ class AppCoordinator: AppCoordinatorProtocol, AuthenticationFlowCoordinatorDeleg
|
||||
func handleInlineReply(_ service: NotificationManagerProtocol, content: UNNotificationContent, replyText: String) async {
|
||||
MXLog.info("Handle notification reply")
|
||||
|
||||
guard let roomID = content.roomID else {
|
||||
guard let roomID = content.roomID,
|
||||
let receiverID = content.receiverID else {
|
||||
return
|
||||
}
|
||||
|
||||
if userSession == nil {
|
||||
// Store the data so it can be used after the session is established
|
||||
storedInlineReply = (roomID, replyText)
|
||||
guard let userSession = userSessionManager.session(for: receiverID) else {
|
||||
// Store the data so it can be sent once the receiver's session is live.
|
||||
storedInlineReply = PendingInlineReplyDetails(userID: receiverID, roomID: roomID, message: replyText)
|
||||
return
|
||||
}
|
||||
|
||||
await processInlineReply(roomID: roomID, replyText: replyText)
|
||||
await processInlineReply(replyText, roomID: roomID, userSession: userSession)
|
||||
}
|
||||
|
||||
// MARK: - Private
|
||||
@@ -559,6 +574,11 @@ class AppCoordinator: AppCoordinatorProtocol, AuthenticationFlowCoordinatorDeleg
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if oldVersion < Version(26, 10, 3) {
|
||||
MXLog.info("Migrating to version 26.10.3, moving the notifications switch into the account.")
|
||||
userSession.userSettings.account.migrateAppSettingsValue(\.enableNotificationsKey)
|
||||
}
|
||||
}
|
||||
|
||||
/// This could be removed once the adoption of 25.06.x is widespread.
|
||||
@@ -715,8 +735,9 @@ class AppCoordinator: AppCoordinatorProtocol, AuthenticationFlowCoordinatorDeleg
|
||||
|
||||
await userSessionManager.restoreSessions { [weak self] userSession in
|
||||
await self?.performUserSessionMigrations(userSession)
|
||||
} didAdd: { [weak self] _ in
|
||||
} didAdd: { [weak self] userSession in
|
||||
self?.showActiveSessionIfRestoring()
|
||||
self?.sendStoredInlineReply(from: userSession)
|
||||
}
|
||||
|
||||
guard !Task.isCancelled else { return }
|
||||
@@ -738,6 +759,16 @@ class AppCoordinator: AppCoordinatorProtocol, AuthenticationFlowCoordinatorDeleg
|
||||
stateMachine.processEvent(.createdUserSession)
|
||||
}
|
||||
|
||||
/// Sends a reply made from a notification before its account was live.
|
||||
private func sendStoredInlineReply(from userSession: UserSessionProtocol) {
|
||||
guard let storedInlineReply, storedInlineReply.userID == userSession.clientProxy.userID else { return }
|
||||
self.storedInlineReply = nil
|
||||
|
||||
Task {
|
||||
await processInlineReply(storedInlineReply.message, roomID: storedInlineReply.roomID, userSession: userSession)
|
||||
}
|
||||
}
|
||||
|
||||
private func startAuthentication() {
|
||||
let encryptionKeyProvider = EncryptionKeyProvider()
|
||||
let classicAppManager = ClassicAppManager()
|
||||
@@ -771,6 +802,13 @@ class AppCoordinator: AppCoordinatorProtocol, AuthenticationFlowCoordinatorDeleg
|
||||
fatalError("User session not setup")
|
||||
}
|
||||
|
||||
if let storedAppRouteReceiverID, storedAppRouteReceiverID != userSession.clientProxy.userID {
|
||||
// TODO: Switch to the receiver's account and open the room (element-hq/element-meta#3328).
|
||||
MXLog.info("Dropping a notification tap for \(storedAppRouteReceiverID), it isn't the active account.")
|
||||
storedAppRoute = nil
|
||||
storedRoomsToAwait = nil
|
||||
}
|
||||
|
||||
if let storedRoomsToAwait {
|
||||
userSession.clientProxy.roomsToAwait = storedRoomsToAwait
|
||||
}
|
||||
@@ -779,10 +817,6 @@ class AppCoordinator: AppCoordinatorProtocol, AuthenticationFlowCoordinatorDeleg
|
||||
let storedAppRoute = storedAppRoute.take() {
|
||||
userSessionFlowCoordinator.handleAppRoute(storedAppRoute, animated: false)
|
||||
}
|
||||
|
||||
if let storedInlineReply {
|
||||
await processInlineReply(roomID: storedInlineReply.roomID, replyText: storedInlineReply.message)
|
||||
}
|
||||
}
|
||||
|
||||
private func startAuthenticationSoftLogout() {
|
||||
@@ -858,7 +892,6 @@ class AppCoordinator: AppCoordinatorProtocol, AuthenticationFlowCoordinatorDeleg
|
||||
appHooks: appHooks,
|
||||
analytics: analyticsService,
|
||||
userIndicatorController: userIndicatorController,
|
||||
notificationManager: notificationManager,
|
||||
stateMachineFactory: StateMachineFactory())
|
||||
|
||||
let userSessionFlowCoordinator = UserSessionFlowCoordinator(isNewLogin: isNewLogin,
|
||||
@@ -913,14 +946,10 @@ class AppCoordinator: AppCoordinatorProtocol, AuthenticationFlowCoordinatorDeleg
|
||||
return
|
||||
}
|
||||
|
||||
// The user will log out, clear any existing notifications and unregister from receving new ones
|
||||
UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
|
||||
UNUserNotificationCenter.current().removeAllDeliveredNotifications()
|
||||
UNUserNotificationCenter.current().setBadgeCount(0)
|
||||
|
||||
unregisterForRemoteNotifications()
|
||||
|
||||
Task {
|
||||
// Delete the pusher while the session can still reach the server.
|
||||
await userSession.notificationService.tearDown()
|
||||
|
||||
// First log out from the server
|
||||
await userSession.clientProxy.logout()
|
||||
|
||||
@@ -928,6 +957,11 @@ class AppCoordinator: AppCoordinatorProtocol, AuthenticationFlowCoordinatorDeleg
|
||||
userSessionManager.remove(userID: userSession.clientProxy.userID)
|
||||
tearDownUserSession()
|
||||
|
||||
// Signed in accounts that aren't live yet still count.
|
||||
if userSessionManager.userIDs.isEmpty {
|
||||
notificationManager.reset()
|
||||
}
|
||||
|
||||
userSession.userSettings.account.reset()
|
||||
appHooks.remoteSettingsHook.reset(appSettings)
|
||||
|
||||
@@ -945,8 +979,6 @@ class AppCoordinator: AppCoordinatorProtocol, AuthenticationFlowCoordinatorDeleg
|
||||
userIndicatorController.retractAllIndicators()
|
||||
|
||||
userSessionFlowCoordinator = nil
|
||||
|
||||
notificationManager.setUserSession(nil)
|
||||
}
|
||||
|
||||
private func presentSplashScreen(isSoftLogout: Bool = false, disableAppLock: Bool = false) {
|
||||
@@ -976,15 +1008,14 @@ class AppCoordinator: AppCoordinatorProtocol, AuthenticationFlowCoordinatorDeleg
|
||||
|
||||
// TODO: Calls only follow the active account, ElementCallService must change to hold every account's session.
|
||||
elementCallService.setUserSession(userSession)
|
||||
// TODO: Notifications only follow the active account, the NotificationManager must change to handle every account.
|
||||
configureNotificationManager(for: userSession)
|
||||
Task {
|
||||
await resumeClientServices()
|
||||
}
|
||||
}
|
||||
|
||||
private func configureNotificationManager(for userSession: UserSessionProtocol) {
|
||||
notificationManager.setUserSession(userSession)
|
||||
private func configureNotificationManager() {
|
||||
notificationManager.delegate = self
|
||||
notificationManager.start()
|
||||
|
||||
appDelegateObserver = appDelegate.callbacks
|
||||
.receive(on: DispatchQueue.main)
|
||||
@@ -1142,11 +1173,7 @@ class AppCoordinator: AppCoordinatorProtocol, AuthenticationFlowCoordinatorDeleg
|
||||
MXLog.info("Sentry configured (enabled: \(options.enabled))")
|
||||
}
|
||||
|
||||
private func processInlineReply(roomID: String, replyText: String) async {
|
||||
guard let userSession else {
|
||||
fatalError("User session not setup")
|
||||
}
|
||||
|
||||
private func processInlineReply(_ replyText: String, roomID: String, userSession: UserSessionProtocol) async {
|
||||
guard case let .joined(roomProxy) = await userSession.clientProxy.roomForIdentifier(roomID) else {
|
||||
MXLog.error("Tried to reply in an unjoined room: \(roomID)")
|
||||
return
|
||||
@@ -1486,3 +1513,9 @@ private extension AppCoordinator {
|
||||
task.setTaskCompleted(success: true)
|
||||
}
|
||||
}
|
||||
|
||||
private struct PendingInlineReplyDetails {
|
||||
let userID: String
|
||||
let roomID: String
|
||||
let message: String
|
||||
}
|
||||
|
||||
@@ -37,7 +37,6 @@ struct CommonFlowParameters {
|
||||
let appHooks: AppHooks
|
||||
let analytics: AnalyticsServiceProtocol
|
||||
let userIndicatorController: UserIndicatorControllerProtocol
|
||||
let notificationManager: NotificationManagerProtocol
|
||||
let stateMachineFactory: StateMachineFactoryProtocol
|
||||
|
||||
var windowManager: WindowManagerProtocol {
|
||||
|
||||
@@ -32,6 +32,10 @@ final nonisolated class AccountSettings: @unchecked Sendable {
|
||||
@UserPreference(defaultValue: true)
|
||||
var showAllRoomListActivity: Bool
|
||||
|
||||
/// Whether this account's notifications are on. When off, its pusher is deleted from the homeserver.
|
||||
@UserPreference(defaultValue: true)
|
||||
var enableNotifications: Bool
|
||||
|
||||
/// The tone played when the user hasn't selected one, which the homeserver can configure remotely.
|
||||
let defaultNotificationTone: RemotePreference<NotificationTone> = .init(.default)
|
||||
|
||||
|
||||
@@ -232,9 +232,6 @@ final nonisolated class AppSettings: @unchecked Sendable {
|
||||
pushGatewayBaseURL.appending(path: "_matrix/push/v1/notify")
|
||||
}
|
||||
|
||||
@UserPreference(defaultValue: true)
|
||||
var enableNotifications: Bool
|
||||
|
||||
@UserPreference(defaultValue: false)
|
||||
var hideQuietNotificationAlerts: Bool
|
||||
|
||||
|
||||
@@ -379,7 +379,6 @@ class ChatsTabFlowCoordinator: FlowCoordinatorProtocol {
|
||||
bugReportService: flowParameters.bugReportService,
|
||||
selectedRoomPublisher: selectedRoomSubject.asCurrentValuePublisher(),
|
||||
analyticsService: flowParameters.analytics,
|
||||
notificationManager: flowParameters.notificationManager,
|
||||
userIndicatorController: flowParameters.userIndicatorController)
|
||||
let coordinator = HomeScreenCoordinator(parameters: parameters)
|
||||
|
||||
@@ -565,7 +564,7 @@ class ChatsTabFlowCoordinator: FlowCoordinatorProtocol {
|
||||
Task {
|
||||
let _ = await userSession.clientProxy.trackRecentlyVisitedRoom(roomID)
|
||||
|
||||
await flowParameters.notificationManager.removeDeliveredMessageNotifications(for: roomID)
|
||||
userSession.notificationService.removeDeliveredMessageNotifications(for: roomID)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -23,7 +23,6 @@ class OnboardingFlowCoordinator: FlowCoordinatorProtocol {
|
||||
private let appMediator: AppMediatorProtocol
|
||||
private let userSettings: UserSettings
|
||||
private let appHooks: AppHooks
|
||||
private let notificationManager: NotificationManagerProtocol
|
||||
private let userIndicatorController: UserIndicatorControllerProtocol
|
||||
private let windowManager: WindowManagerProtocol
|
||||
private var isNewLogin: Bool
|
||||
@@ -71,7 +70,6 @@ class OnboardingFlowCoordinator: FlowCoordinatorProtocol {
|
||||
appMediator = flowParameters.appMediator
|
||||
userSettings = flowParameters.userSession.userSettings
|
||||
appHooks = flowParameters.appHooks
|
||||
notificationManager = flowParameters.notificationManager
|
||||
userIndicatorController = flowParameters.userIndicatorController
|
||||
windowManager = flowParameters.windowManager
|
||||
|
||||
@@ -399,7 +397,7 @@ class OnboardingFlowCoordinator: FlowCoordinatorProtocol {
|
||||
}
|
||||
|
||||
private func presentNotificationPermissionsScreen() {
|
||||
let coordinator = NotificationPermissionsScreenCoordinator(parameters: .init(notificationManager: notificationManager))
|
||||
let coordinator = NotificationPermissionsScreenCoordinator(parameters: .init(notificationService: userSession.notificationService))
|
||||
|
||||
coordinator.actions
|
||||
.sink { [weak self] action in
|
||||
|
||||
@@ -529,21 +529,9 @@ class UserSessionFlowCoordinator: FlowCoordinatorProtocol {
|
||||
}
|
||||
|
||||
private func setupUnreadNotificationsObserver() {
|
||||
let roomListPublisher = userSession.clientProxy.staticRoomSummaryProvider.roomListPublisher
|
||||
|
||||
Task { [weak self] in
|
||||
for await roomSummaries in roomListPublisher.values {
|
||||
guard let self else { return }
|
||||
|
||||
let badgeCount = Int(userSession.clientProxy.totalUnreadNotifications)
|
||||
|
||||
chatsTabDetails.badgeCount = badgeCount
|
||||
|
||||
await flowParameters.notificationManager.removeDeliveredNotificationsForFullyReadRooms(roomSummaries)
|
||||
await flowParameters.notificationManager.updateAppBadgeCount(badgeCount)
|
||||
}
|
||||
}
|
||||
.store(in: &cancellables)
|
||||
userSession.notificationService.badgeCountPublisher
|
||||
.weakAssign(to: \.badgeCount, on: chatsTabDetails)
|
||||
.store(in: &cancellables)
|
||||
}
|
||||
|
||||
// MARK: - Native calls
|
||||
|
||||
@@ -3760,6 +3760,41 @@ nonisolated class ClientProxyMock: ClientProxyProtocol, @unchecked Sendable {
|
||||
setPusherWithReceivedInvocationsLock.withLock { setPusherWithUnderlyingReceivedInvocations.append(configuration) }
|
||||
try await setPusherWithClosure?(configuration)
|
||||
}
|
||||
//MARK: - deletePusher
|
||||
|
||||
nonisolated(unsafe) var deletePusherWithThrowableError: Error?
|
||||
private let deletePusherWithCallsCountLock = NSLock()
|
||||
private nonisolated(unsafe) var deletePusherWithUnderlyingCallsCount = 0
|
||||
var deletePusherWithCallsCount: Int {
|
||||
get { deletePusherWithCallsCountLock.withLock { deletePusherWithUnderlyingCallsCount } }
|
||||
set { deletePusherWithCallsCountLock.withLock { deletePusherWithUnderlyingCallsCount = newValue } }
|
||||
}
|
||||
var deletePusherWithCalled: Bool {
|
||||
return deletePusherWithCallsCount > 0
|
||||
}
|
||||
private let deletePusherWithReceivedIdentifiersLock = NSLock()
|
||||
private nonisolated(unsafe) var deletePusherWithUnderlyingReceivedIdentifiers: PusherIdentifiers?
|
||||
var deletePusherWithReceivedIdentifiers: PusherIdentifiers? {
|
||||
get { deletePusherWithReceivedIdentifiersLock.withLock { deletePusherWithUnderlyingReceivedIdentifiers } }
|
||||
set { deletePusherWithReceivedIdentifiersLock.withLock { deletePusherWithUnderlyingReceivedIdentifiers = newValue } }
|
||||
}
|
||||
private let deletePusherWithReceivedInvocationsLock = NSLock()
|
||||
private nonisolated(unsafe) var deletePusherWithUnderlyingReceivedInvocations: [PusherIdentifiers] = []
|
||||
var deletePusherWithReceivedInvocations: [PusherIdentifiers] {
|
||||
get { deletePusherWithReceivedInvocationsLock.withLock { deletePusherWithUnderlyingReceivedInvocations } }
|
||||
set { deletePusherWithReceivedInvocationsLock.withLock { deletePusherWithUnderlyingReceivedInvocations = newValue } }
|
||||
}
|
||||
nonisolated(unsafe) var deletePusherWithClosure: ((PusherIdentifiers) async throws -> Void)?
|
||||
|
||||
@concurrent func deletePusher(with identifiers: PusherIdentifiers) async throws {
|
||||
if let error = deletePusherWithThrowableError {
|
||||
throw error
|
||||
}
|
||||
deletePusherWithCallsCountLock.withLock { deletePusherWithUnderlyingCallsCount += 1 }
|
||||
deletePusherWithReceivedIdentifiers = identifiers
|
||||
deletePusherWithReceivedInvocationsLock.withLock { deletePusherWithUnderlyingReceivedInvocations.append(identifiers) }
|
||||
try await deletePusherWithClosure?(identifiers)
|
||||
}
|
||||
//MARK: - searchUsers
|
||||
|
||||
private let searchUsersSearchTermLimitCallsCountLock = NSLock()
|
||||
@@ -8842,24 +8877,13 @@ nonisolated class NotificationManagerMock: NotificationManagerProtocol, @uncheck
|
||||
get { registerWithReceivedInvocationsLock.withLock { registerWithUnderlyingReceivedInvocations } }
|
||||
set { registerWithReceivedInvocationsLock.withLock { registerWithUnderlyingReceivedInvocations = newValue } }
|
||||
}
|
||||
nonisolated(unsafe) var registerWithClosure: ((Data) async -> Void)?
|
||||
|
||||
private let registerWithReturnValueLock = NSLock()
|
||||
private nonisolated(unsafe) var registerWithUnderlyingReturnValue: Bool!
|
||||
var registerWithReturnValue: Bool! {
|
||||
get { registerWithReturnValueLock.withLock { registerWithUnderlyingReturnValue } }
|
||||
set { registerWithReturnValueLock.withLock { registerWithUnderlyingReturnValue = newValue } }
|
||||
}
|
||||
nonisolated(unsafe) var registerWithClosure: ((Data) async -> Bool)?
|
||||
|
||||
@concurrent func register(with deviceToken: Data) async -> Bool {
|
||||
@concurrent func register(with deviceToken: Data) async {
|
||||
registerWithCallsCountLock.withLock { registerWithUnderlyingCallsCount += 1 }
|
||||
registerWithReceivedDeviceToken = deviceToken
|
||||
registerWithReceivedInvocationsLock.withLock { registerWithUnderlyingReceivedInvocations.append(deviceToken) }
|
||||
if let registerWithClosure = registerWithClosure {
|
||||
return await registerWithClosure(deviceToken)
|
||||
} else {
|
||||
return registerWithReturnValue
|
||||
}
|
||||
await registerWithClosure?(deviceToken)
|
||||
}
|
||||
//MARK: - registrationFailed
|
||||
|
||||
@@ -8923,36 +8947,138 @@ nonisolated class NotificationManagerMock: NotificationManagerProtocol, @uncheck
|
||||
showLocalNotificationWithSubtitleReceivedInvocationsLock.withLock { showLocalNotificationWithSubtitleUnderlyingReceivedInvocations.append((title: title, subtitle: subtitle)) }
|
||||
await showLocalNotificationWithSubtitleClosure?(title, subtitle)
|
||||
}
|
||||
//MARK: - setUserSession
|
||||
//MARK: - add
|
||||
|
||||
private let setUserSessionCallsCountLock = NSLock()
|
||||
private nonisolated(unsafe) var setUserSessionUnderlyingCallsCount = 0
|
||||
var setUserSessionCallsCount: Int {
|
||||
get { setUserSessionCallsCountLock.withLock { setUserSessionUnderlyingCallsCount } }
|
||||
set { setUserSessionCallsCountLock.withLock { setUserSessionUnderlyingCallsCount = newValue } }
|
||||
private let addCallsCountLock = NSLock()
|
||||
private nonisolated(unsafe) var addUnderlyingCallsCount = 0
|
||||
var addCallsCount: Int {
|
||||
get { addCallsCountLock.withLock { addUnderlyingCallsCount } }
|
||||
set { addCallsCountLock.withLock { addUnderlyingCallsCount = newValue } }
|
||||
}
|
||||
var setUserSessionCalled: Bool {
|
||||
return setUserSessionCallsCount > 0
|
||||
var addCalled: Bool {
|
||||
return addCallsCount > 0
|
||||
}
|
||||
private let setUserSessionReceivedUserSessionLock = NSLock()
|
||||
private nonisolated(unsafe) var setUserSessionUnderlyingReceivedUserSession: UserSessionProtocol?
|
||||
var setUserSessionReceivedUserSession: UserSessionProtocol? {
|
||||
get { setUserSessionReceivedUserSessionLock.withLock { setUserSessionUnderlyingReceivedUserSession } }
|
||||
set { setUserSessionReceivedUserSessionLock.withLock { setUserSessionUnderlyingReceivedUserSession = newValue } }
|
||||
private let addReceivedServiceLock = NSLock()
|
||||
private nonisolated(unsafe) var addUnderlyingReceivedService: NotificationServiceProtocol?
|
||||
var addReceivedService: NotificationServiceProtocol? {
|
||||
get { addReceivedServiceLock.withLock { addUnderlyingReceivedService } }
|
||||
set { addReceivedServiceLock.withLock { addUnderlyingReceivedService = newValue } }
|
||||
}
|
||||
private let setUserSessionReceivedInvocationsLock = NSLock()
|
||||
private nonisolated(unsafe) var setUserSessionUnderlyingReceivedInvocations: [UserSessionProtocol?] = []
|
||||
var setUserSessionReceivedInvocations: [UserSessionProtocol?] {
|
||||
get { setUserSessionReceivedInvocationsLock.withLock { setUserSessionUnderlyingReceivedInvocations } }
|
||||
set { setUserSessionReceivedInvocationsLock.withLock { setUserSessionUnderlyingReceivedInvocations = newValue } }
|
||||
private let addReceivedInvocationsLock = NSLock()
|
||||
private nonisolated(unsafe) var addUnderlyingReceivedInvocations: [NotificationServiceProtocol] = []
|
||||
var addReceivedInvocations: [NotificationServiceProtocol] {
|
||||
get { addReceivedInvocationsLock.withLock { addUnderlyingReceivedInvocations } }
|
||||
set { addReceivedInvocationsLock.withLock { addUnderlyingReceivedInvocations = newValue } }
|
||||
}
|
||||
nonisolated(unsafe) var setUserSessionClosure: ((UserSessionProtocol?) -> Void)?
|
||||
nonisolated(unsafe) var addClosure: ((NotificationServiceProtocol) -> Void)?
|
||||
|
||||
func setUserSession(_ userSession: UserSessionProtocol?) {
|
||||
setUserSessionCallsCountLock.withLock { setUserSessionUnderlyingCallsCount += 1 }
|
||||
setUserSessionReceivedUserSession = userSession
|
||||
setUserSessionReceivedInvocationsLock.withLock { setUserSessionUnderlyingReceivedInvocations.append(userSession) }
|
||||
setUserSessionClosure?(userSession)
|
||||
func add(_ service: NotificationServiceProtocol) {
|
||||
addCallsCountLock.withLock { addUnderlyingCallsCount += 1 }
|
||||
addReceivedService = service
|
||||
addReceivedInvocationsLock.withLock { addUnderlyingReceivedInvocations.append(service) }
|
||||
addClosure?(service)
|
||||
}
|
||||
//MARK: - remove
|
||||
|
||||
private let removeUserIDCallsCountLock = NSLock()
|
||||
private nonisolated(unsafe) var removeUserIDUnderlyingCallsCount = 0
|
||||
var removeUserIDCallsCount: Int {
|
||||
get { removeUserIDCallsCountLock.withLock { removeUserIDUnderlyingCallsCount } }
|
||||
set { removeUserIDCallsCountLock.withLock { removeUserIDUnderlyingCallsCount = newValue } }
|
||||
}
|
||||
var removeUserIDCalled: Bool {
|
||||
return removeUserIDCallsCount > 0
|
||||
}
|
||||
private let removeUserIDReceivedUserIDLock = NSLock()
|
||||
private nonisolated(unsafe) var removeUserIDUnderlyingReceivedUserID: String?
|
||||
var removeUserIDReceivedUserID: String? {
|
||||
get { removeUserIDReceivedUserIDLock.withLock { removeUserIDUnderlyingReceivedUserID } }
|
||||
set { removeUserIDReceivedUserIDLock.withLock { removeUserIDUnderlyingReceivedUserID = newValue } }
|
||||
}
|
||||
private let removeUserIDReceivedInvocationsLock = NSLock()
|
||||
private nonisolated(unsafe) var removeUserIDUnderlyingReceivedInvocations: [String] = []
|
||||
var removeUserIDReceivedInvocations: [String] {
|
||||
get { removeUserIDReceivedInvocationsLock.withLock { removeUserIDUnderlyingReceivedInvocations } }
|
||||
set { removeUserIDReceivedInvocationsLock.withLock { removeUserIDUnderlyingReceivedInvocations = newValue } }
|
||||
}
|
||||
nonisolated(unsafe) var removeUserIDClosure: ((String) -> Void)?
|
||||
|
||||
func remove(userID: String) {
|
||||
removeUserIDCallsCountLock.withLock { removeUserIDUnderlyingCallsCount += 1 }
|
||||
removeUserIDReceivedUserID = userID
|
||||
removeUserIDReceivedInvocationsLock.withLock { removeUserIDUnderlyingReceivedInvocations.append(userID) }
|
||||
removeUserIDClosure?(userID)
|
||||
}
|
||||
//MARK: - reset
|
||||
|
||||
private let resetCallsCountLock = NSLock()
|
||||
private nonisolated(unsafe) var resetUnderlyingCallsCount = 0
|
||||
var resetCallsCount: Int {
|
||||
get { resetCallsCountLock.withLock { resetUnderlyingCallsCount } }
|
||||
set { resetCallsCountLock.withLock { resetUnderlyingCallsCount = newValue } }
|
||||
}
|
||||
var resetCalled: Bool {
|
||||
return resetCallsCount > 0
|
||||
}
|
||||
nonisolated(unsafe) var resetClosure: (() -> Void)?
|
||||
|
||||
func reset() {
|
||||
resetCallsCountLock.withLock { resetUnderlyingCallsCount += 1 }
|
||||
resetClosure?()
|
||||
}
|
||||
}
|
||||
nonisolated class NotificationServiceMock: NotificationServiceProtocol, @unchecked Sendable {
|
||||
var userID: String {
|
||||
get { return underlyingUserID }
|
||||
set(value) { underlyingUserID = value }
|
||||
}
|
||||
nonisolated(unsafe) var underlyingUserID: String!
|
||||
var actionsPublisher: AnyPublisher<NotificationServiceAction, Never> {
|
||||
get { return underlyingActionsPublisher }
|
||||
set(value) { underlyingActionsPublisher = value }
|
||||
}
|
||||
nonisolated(unsafe) var underlyingActionsPublisher: AnyPublisher<NotificationServiceAction, Never>!
|
||||
var isEnabled: Bool {
|
||||
get { return underlyingIsEnabled }
|
||||
set(value) { underlyingIsEnabled = value }
|
||||
}
|
||||
nonisolated(unsafe) var underlyingIsEnabled: Bool!
|
||||
var badgeCountPublisher: CurrentValuePublisher<Int, Never> {
|
||||
get { return underlyingBadgeCountPublisher }
|
||||
set(value) { underlyingBadgeCountPublisher = value }
|
||||
}
|
||||
nonisolated(unsafe) var underlyingBadgeCountPublisher: CurrentValuePublisher<Int, Never>!
|
||||
|
||||
//MARK: - register
|
||||
|
||||
private let registerDeviceTokenCallsCountLock = NSLock()
|
||||
private nonisolated(unsafe) var registerDeviceTokenUnderlyingCallsCount = 0
|
||||
var registerDeviceTokenCallsCount: Int {
|
||||
get { registerDeviceTokenCallsCountLock.withLock { registerDeviceTokenUnderlyingCallsCount } }
|
||||
set { registerDeviceTokenCallsCountLock.withLock { registerDeviceTokenUnderlyingCallsCount = newValue } }
|
||||
}
|
||||
var registerDeviceTokenCalled: Bool {
|
||||
return registerDeviceTokenCallsCount > 0
|
||||
}
|
||||
private let registerDeviceTokenReceivedDeviceTokenLock = NSLock()
|
||||
private nonisolated(unsafe) var registerDeviceTokenUnderlyingReceivedDeviceToken: Data?
|
||||
var registerDeviceTokenReceivedDeviceToken: Data? {
|
||||
get { registerDeviceTokenReceivedDeviceTokenLock.withLock { registerDeviceTokenUnderlyingReceivedDeviceToken } }
|
||||
set { registerDeviceTokenReceivedDeviceTokenLock.withLock { registerDeviceTokenUnderlyingReceivedDeviceToken = newValue } }
|
||||
}
|
||||
private let registerDeviceTokenReceivedInvocationsLock = NSLock()
|
||||
private nonisolated(unsafe) var registerDeviceTokenUnderlyingReceivedInvocations: [Data] = []
|
||||
var registerDeviceTokenReceivedInvocations: [Data] {
|
||||
get { registerDeviceTokenReceivedInvocationsLock.withLock { registerDeviceTokenUnderlyingReceivedInvocations } }
|
||||
set { registerDeviceTokenReceivedInvocationsLock.withLock { registerDeviceTokenUnderlyingReceivedInvocations = newValue } }
|
||||
}
|
||||
nonisolated(unsafe) var registerDeviceTokenClosure: ((Data) async -> Void)?
|
||||
|
||||
@concurrent func register(deviceToken: Data) async {
|
||||
registerDeviceTokenCallsCountLock.withLock { registerDeviceTokenUnderlyingCallsCount += 1 }
|
||||
registerDeviceTokenReceivedDeviceToken = deviceToken
|
||||
registerDeviceTokenReceivedInvocationsLock.withLock { registerDeviceTokenUnderlyingReceivedInvocations.append(deviceToken) }
|
||||
await registerDeviceTokenClosure?(deviceToken)
|
||||
}
|
||||
//MARK: - requestAuthorization
|
||||
|
||||
@@ -8994,75 +9120,30 @@ nonisolated class NotificationManagerMock: NotificationManagerProtocol, @uncheck
|
||||
get { removeDeliveredMessageNotificationsForReceivedInvocationsLock.withLock { removeDeliveredMessageNotificationsForUnderlyingReceivedInvocations } }
|
||||
set { removeDeliveredMessageNotificationsForReceivedInvocationsLock.withLock { removeDeliveredMessageNotificationsForUnderlyingReceivedInvocations = newValue } }
|
||||
}
|
||||
nonisolated(unsafe) var removeDeliveredMessageNotificationsForClosure: ((String) async -> Void)?
|
||||
nonisolated(unsafe) var removeDeliveredMessageNotificationsForClosure: ((String) -> Void)?
|
||||
|
||||
@concurrent func removeDeliveredMessageNotifications(for roomID: String) async {
|
||||
func removeDeliveredMessageNotifications(for roomID: String) {
|
||||
removeDeliveredMessageNotificationsForCallsCountLock.withLock { removeDeliveredMessageNotificationsForUnderlyingCallsCount += 1 }
|
||||
removeDeliveredMessageNotificationsForReceivedRoomID = roomID
|
||||
removeDeliveredMessageNotificationsForReceivedInvocationsLock.withLock { removeDeliveredMessageNotificationsForUnderlyingReceivedInvocations.append(roomID) }
|
||||
await removeDeliveredMessageNotificationsForClosure?(roomID)
|
||||
removeDeliveredMessageNotificationsForClosure?(roomID)
|
||||
}
|
||||
//MARK: - removeDeliveredNotificationsForFullyReadRooms
|
||||
//MARK: - tearDown
|
||||
|
||||
private let removeDeliveredNotificationsForFullyReadRoomsCallsCountLock = NSLock()
|
||||
private nonisolated(unsafe) var removeDeliveredNotificationsForFullyReadRoomsUnderlyingCallsCount = 0
|
||||
var removeDeliveredNotificationsForFullyReadRoomsCallsCount: Int {
|
||||
get { removeDeliveredNotificationsForFullyReadRoomsCallsCountLock.withLock { removeDeliveredNotificationsForFullyReadRoomsUnderlyingCallsCount } }
|
||||
set { removeDeliveredNotificationsForFullyReadRoomsCallsCountLock.withLock { removeDeliveredNotificationsForFullyReadRoomsUnderlyingCallsCount = newValue } }
|
||||
private let tearDownCallsCountLock = NSLock()
|
||||
private nonisolated(unsafe) var tearDownUnderlyingCallsCount = 0
|
||||
var tearDownCallsCount: Int {
|
||||
get { tearDownCallsCountLock.withLock { tearDownUnderlyingCallsCount } }
|
||||
set { tearDownCallsCountLock.withLock { tearDownUnderlyingCallsCount = newValue } }
|
||||
}
|
||||
var removeDeliveredNotificationsForFullyReadRoomsCalled: Bool {
|
||||
return removeDeliveredNotificationsForFullyReadRoomsCallsCount > 0
|
||||
var tearDownCalled: Bool {
|
||||
return tearDownCallsCount > 0
|
||||
}
|
||||
private let removeDeliveredNotificationsForFullyReadRoomsReceivedRoomsLock = NSLock()
|
||||
private nonisolated(unsafe) var removeDeliveredNotificationsForFullyReadRoomsUnderlyingReceivedRooms: [RoomSummary]?
|
||||
var removeDeliveredNotificationsForFullyReadRoomsReceivedRooms: [RoomSummary]? {
|
||||
get { removeDeliveredNotificationsForFullyReadRoomsReceivedRoomsLock.withLock { removeDeliveredNotificationsForFullyReadRoomsUnderlyingReceivedRooms } }
|
||||
set { removeDeliveredNotificationsForFullyReadRoomsReceivedRoomsLock.withLock { removeDeliveredNotificationsForFullyReadRoomsUnderlyingReceivedRooms = newValue } }
|
||||
}
|
||||
private let removeDeliveredNotificationsForFullyReadRoomsReceivedInvocationsLock = NSLock()
|
||||
private nonisolated(unsafe) var removeDeliveredNotificationsForFullyReadRoomsUnderlyingReceivedInvocations: [[RoomSummary]] = []
|
||||
var removeDeliveredNotificationsForFullyReadRoomsReceivedInvocations: [[RoomSummary]] {
|
||||
get { removeDeliveredNotificationsForFullyReadRoomsReceivedInvocationsLock.withLock { removeDeliveredNotificationsForFullyReadRoomsUnderlyingReceivedInvocations } }
|
||||
set { removeDeliveredNotificationsForFullyReadRoomsReceivedInvocationsLock.withLock { removeDeliveredNotificationsForFullyReadRoomsUnderlyingReceivedInvocations = newValue } }
|
||||
}
|
||||
nonisolated(unsafe) var removeDeliveredNotificationsForFullyReadRoomsClosure: (([RoomSummary]) async -> Void)?
|
||||
nonisolated(unsafe) var tearDownClosure: (() async -> Void)?
|
||||
|
||||
@concurrent func removeDeliveredNotificationsForFullyReadRooms(_ rooms: [RoomSummary]) async {
|
||||
removeDeliveredNotificationsForFullyReadRoomsCallsCountLock.withLock { removeDeliveredNotificationsForFullyReadRoomsUnderlyingCallsCount += 1 }
|
||||
removeDeliveredNotificationsForFullyReadRoomsReceivedRooms = rooms
|
||||
removeDeliveredNotificationsForFullyReadRoomsReceivedInvocationsLock.withLock { removeDeliveredNotificationsForFullyReadRoomsUnderlyingReceivedInvocations.append(rooms) }
|
||||
await removeDeliveredNotificationsForFullyReadRoomsClosure?(rooms)
|
||||
}
|
||||
//MARK: - updateAppBadgeCount
|
||||
|
||||
private let updateAppBadgeCountCallsCountLock = NSLock()
|
||||
private nonisolated(unsafe) var updateAppBadgeCountUnderlyingCallsCount = 0
|
||||
var updateAppBadgeCountCallsCount: Int {
|
||||
get { updateAppBadgeCountCallsCountLock.withLock { updateAppBadgeCountUnderlyingCallsCount } }
|
||||
set { updateAppBadgeCountCallsCountLock.withLock { updateAppBadgeCountUnderlyingCallsCount = newValue } }
|
||||
}
|
||||
var updateAppBadgeCountCalled: Bool {
|
||||
return updateAppBadgeCountCallsCount > 0
|
||||
}
|
||||
private let updateAppBadgeCountReceivedBadgeCountLock = NSLock()
|
||||
private nonisolated(unsafe) var updateAppBadgeCountUnderlyingReceivedBadgeCount: Int?
|
||||
var updateAppBadgeCountReceivedBadgeCount: Int? {
|
||||
get { updateAppBadgeCountReceivedBadgeCountLock.withLock { updateAppBadgeCountUnderlyingReceivedBadgeCount } }
|
||||
set { updateAppBadgeCountReceivedBadgeCountLock.withLock { updateAppBadgeCountUnderlyingReceivedBadgeCount = newValue } }
|
||||
}
|
||||
private let updateAppBadgeCountReceivedInvocationsLock = NSLock()
|
||||
private nonisolated(unsafe) var updateAppBadgeCountUnderlyingReceivedInvocations: [Int] = []
|
||||
var updateAppBadgeCountReceivedInvocations: [Int] {
|
||||
get { updateAppBadgeCountReceivedInvocationsLock.withLock { updateAppBadgeCountUnderlyingReceivedInvocations } }
|
||||
set { updateAppBadgeCountReceivedInvocationsLock.withLock { updateAppBadgeCountUnderlyingReceivedInvocations = newValue } }
|
||||
}
|
||||
nonisolated(unsafe) var updateAppBadgeCountClosure: ((Int) async -> Void)?
|
||||
|
||||
@concurrent func updateAppBadgeCount(_ badgeCount: Int) async {
|
||||
updateAppBadgeCountCallsCountLock.withLock { updateAppBadgeCountUnderlyingCallsCount += 1 }
|
||||
updateAppBadgeCountReceivedBadgeCount = badgeCount
|
||||
updateAppBadgeCountReceivedInvocationsLock.withLock { updateAppBadgeCountUnderlyingReceivedInvocations.append(badgeCount) }
|
||||
await updateAppBadgeCountClosure?(badgeCount)
|
||||
@concurrent func tearDown() async {
|
||||
tearDownCallsCountLock.withLock { tearDownUnderlyingCallsCount += 1 }
|
||||
await tearDownClosure?()
|
||||
}
|
||||
}
|
||||
nonisolated class NotificationSettingsProxyMock: NotificationSettingsProxyProtocol, @unchecked Sendable {
|
||||
@@ -15196,6 +15277,11 @@ nonisolated class UserSessionMock: UserSessionProtocol, @unchecked Sendable {
|
||||
}
|
||||
nonisolated(unsafe) var underlyingLiveLocationManager: LiveLocationManagerProtocol!
|
||||
nonisolated(unsafe) var contentScannerService: ContentScannerServiceProtocol?
|
||||
var notificationService: NotificationServiceProtocol {
|
||||
get { return underlyingNotificationService }
|
||||
set(value) { underlyingNotificationService = value }
|
||||
}
|
||||
nonisolated(unsafe) var underlyingNotificationService: NotificationServiceProtocol!
|
||||
var sessionSecurityStatePublisher: CurrentValuePublisher<SessionSecurityState, Never> {
|
||||
get { return underlyingSessionSecurityStatePublisher }
|
||||
set(value) { underlyingSessionSecurityStatePublisher = value }
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
//
|
||||
// Copyright 2026 Element Creations Ltd.
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial.
|
||||
// Please see LICENSE files in the repository root for full details.
|
||||
//
|
||||
|
||||
import Combine
|
||||
import Foundation
|
||||
|
||||
struct NotificationServiceMockConfiguration {
|
||||
var userID = "@alice:matrix.org"
|
||||
var isEnabled = true
|
||||
var badgeCount = 0
|
||||
}
|
||||
|
||||
extension NotificationServiceMock {
|
||||
convenience init(_ configuration: NotificationServiceMockConfiguration) {
|
||||
self.init()
|
||||
|
||||
userID = configuration.userID
|
||||
isEnabled = configuration.isEnabled
|
||||
actionsPublisher = PassthroughSubject<NotificationServiceAction, Never>().eraseToAnyPublisher()
|
||||
badgeCountPublisher = CurrentValueSubject(configuration.badgeCount).asCurrentValuePublisher()
|
||||
}
|
||||
}
|
||||
@@ -61,6 +61,7 @@ nonisolated extension ClientSDKMock {
|
||||
}
|
||||
|
||||
userIdReturnValue = configuration.userID
|
||||
totalUnreadNotificationsReturnValue = 0
|
||||
deviceIdReturnValue = configuration.deviceID
|
||||
sessionReturnValue = configuration.session
|
||||
getUrlUrlClosure = { url in
|
||||
|
||||
@@ -15,6 +15,7 @@ struct UserSessionMockConfiguration {
|
||||
var userHooks = UserHooks()
|
||||
var contentScannerService: ContentScannerServiceProtocol?
|
||||
var liveLocationManager: LiveLocationManagerProtocol = LiveLocationManagerMock(.init())
|
||||
var notificationService: NotificationServiceProtocol = NotificationServiceMock(.init())
|
||||
}
|
||||
|
||||
@MainActor extension UserSessionMock {
|
||||
@@ -33,5 +34,6 @@ struct UserSessionMockConfiguration {
|
||||
sessionSecurityStatePublisher = CurrentValueSubject<SessionSecurityState, Never>(.init(verificationState: .verified, recoveryState: .enabled)).asCurrentValuePublisher()
|
||||
|
||||
liveLocationManager = configuration.liveLocationManager
|
||||
notificationService = configuration.notificationService
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,7 +15,6 @@ struct HomeScreenCoordinatorParameters {
|
||||
let bugReportService: BugReportServiceProtocol
|
||||
let selectedRoomPublisher: CurrentValuePublisher<String?, Never>
|
||||
let analyticsService: AnalyticsServiceProtocol
|
||||
let notificationManager: NotificationManagerProtocol
|
||||
let userIndicatorController: UserIndicatorControllerProtocol
|
||||
}
|
||||
|
||||
@@ -53,7 +52,6 @@ final class HomeScreenCoordinator: CoordinatorProtocol {
|
||||
selectedRoomPublisher: parameters.selectedRoomPublisher,
|
||||
analyticsService: parameters.analyticsService,
|
||||
bugReportService: parameters.bugReportService,
|
||||
notificationManager: parameters.notificationManager,
|
||||
userIndicatorController: parameters.userIndicatorController)
|
||||
|
||||
viewModel.actions
|
||||
|
||||
@@ -20,7 +20,6 @@ class HomeScreenViewModel: HomeScreenViewModelType, HomeScreenViewModelProtocol
|
||||
private let analyticsService: AnalyticsServiceProtocol
|
||||
private let bugReportService: BugReportServiceProtocol
|
||||
private let userSettings: UserSettings
|
||||
private let notificationManager: NotificationManagerProtocol
|
||||
private let userIndicatorController: UserIndicatorControllerProtocol
|
||||
|
||||
private let roomSummaryProvider: RoomSummaryProviderProtocol?
|
||||
@@ -36,14 +35,12 @@ class HomeScreenViewModel: HomeScreenViewModelType, HomeScreenViewModelProtocol
|
||||
selectedRoomPublisher: CurrentValuePublisher<String?, Never>,
|
||||
analyticsService: AnalyticsServiceProtocol,
|
||||
bugReportService: BugReportServiceProtocol,
|
||||
notificationManager: NotificationManagerProtocol,
|
||||
userIndicatorController: UserIndicatorControllerProtocol) {
|
||||
self.userSession = userSession
|
||||
self.availableSessionsPublisher = availableSessionsPublisher
|
||||
self.analyticsService = analyticsService
|
||||
self.bugReportService = bugReportService
|
||||
userSettings = userSession.userSettings
|
||||
self.notificationManager = notificationManager
|
||||
self.userIndicatorController = userIndicatorController
|
||||
|
||||
spaceFilterSubject = CurrentValueSubject<SpaceServiceFilter?, Never>(nil)
|
||||
@@ -602,7 +599,7 @@ class HomeScreenViewModel: HomeScreenViewModelType, HomeScreenViewModelProtocol
|
||||
|
||||
switch result {
|
||||
case .success:
|
||||
await notificationManager.removeDeliveredMessageNotifications(for: roomID) // Normally handled by the room flow, but that's never presented in this case.
|
||||
userSession.notificationService.removeDeliveredMessageNotifications(for: roomID) // Normally handled by the room flow, but that's never presented in this case.
|
||||
userSettings.app.seenInvites.remove(roomID)
|
||||
case .failure:
|
||||
displayError()
|
||||
|
||||
@@ -240,7 +240,6 @@ struct HomeScreen_Previews: PreviewProvider, TestablePreview {
|
||||
selectedRoomPublisher: CurrentValueSubject<String?, Never>(nil).asCurrentValuePublisher(),
|
||||
analyticsService: AnalyticsServiceMock(.init()),
|
||||
bugReportService: BugReportServiceMock(.init()),
|
||||
notificationManager: NotificationManagerMock(),
|
||||
userIndicatorController: UserIndicatorControllerMock())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -148,7 +148,6 @@ struct HomeScreenEmptyStateView_Previews: PreviewProvider, TestablePreview {
|
||||
selectedRoomPublisher: CurrentValueSubject<String?, Never>(nil).asCurrentValuePublisher(),
|
||||
analyticsService: AnalyticsServiceMock(.init()),
|
||||
bugReportService: BugReportServiceMock(.init()),
|
||||
notificationManager: NotificationManagerMock(),
|
||||
userIndicatorController: UserIndicatorControllerMock())
|
||||
}()
|
||||
}
|
||||
|
||||
@@ -204,7 +204,6 @@ struct HomeScreenInviteCell_Previews: PreviewProvider, TestablePreview {
|
||||
selectedRoomPublisher: CurrentValueSubject<String?, Never>(nil).asCurrentValuePublisher(),
|
||||
analyticsService: AnalyticsServiceMock(.init()),
|
||||
bugReportService: BugReportServiceMock(.init()),
|
||||
notificationManager: NotificationManagerMock(),
|
||||
userIndicatorController: UserIndicatorControllerMock())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -136,7 +136,6 @@ struct HomeScreenKnockedCell_Previews: PreviewProvider, TestablePreview {
|
||||
selectedRoomPublisher: CurrentValueSubject<String?, Never>(nil).asCurrentValuePublisher(),
|
||||
analyticsService: AnalyticsServiceMock(.init()),
|
||||
bugReportService: BugReportServiceMock(.init()),
|
||||
notificationManager: NotificationManagerMock(),
|
||||
userIndicatorController: UserIndicatorControllerMock())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -125,7 +125,6 @@ struct HomeScreenRecoveryKeyConfirmationBanner_Previews: PreviewProvider, Testab
|
||||
selectedRoomPublisher: CurrentValueSubject<String?, Never>(nil).asCurrentValuePublisher(),
|
||||
analyticsService: AnalyticsServiceMock(.init()),
|
||||
bugReportService: BugReportServiceMock(.init()),
|
||||
notificationManager: NotificationManagerMock(),
|
||||
userIndicatorController: UserIndicatorControllerMock())
|
||||
}
|
||||
}
|
||||
|
||||
+2
-2
@@ -10,7 +10,7 @@ import Combine
|
||||
import SwiftUI
|
||||
|
||||
struct NotificationPermissionsScreenCoordinatorParameters {
|
||||
let notificationManager: NotificationManagerProtocol
|
||||
let notificationService: NotificationServiceProtocol
|
||||
}
|
||||
|
||||
enum NotificationPermissionsScreenCoordinatorAction {
|
||||
@@ -27,7 +27,7 @@ final class NotificationPermissionsScreenCoordinator: CoordinatorProtocol {
|
||||
}
|
||||
|
||||
init(parameters: NotificationPermissionsScreenCoordinatorParameters) {
|
||||
viewModel = NotificationPermissionsScreenViewModel(notificationManager: parameters.notificationManager)
|
||||
viewModel = NotificationPermissionsScreenViewModel(notificationService: parameters.notificationService)
|
||||
}
|
||||
|
||||
// MARK: - Public
|
||||
|
||||
+4
-4
@@ -12,15 +12,15 @@ import SwiftUI
|
||||
typealias NotificationPermissionsScreenViewModelType = StateStoreViewModel<NotificationPermissionsScreenViewState, NotificationPermissionsScreenViewAction>
|
||||
|
||||
class NotificationPermissionsScreenViewModel: NotificationPermissionsScreenViewModelType, NotificationPermissionsScreenViewModelProtocol {
|
||||
private let notificationManager: NotificationManagerProtocol
|
||||
private let notificationService: NotificationServiceProtocol
|
||||
|
||||
private var actionsSubject: PassthroughSubject<NotificationPermissionsScreenViewModelAction, Never> = .init()
|
||||
var actionsPublisher: AnyPublisher<NotificationPermissionsScreenViewModelAction, Never> {
|
||||
actionsSubject.eraseToAnyPublisher()
|
||||
}
|
||||
|
||||
init(notificationManager: NotificationManagerProtocol) {
|
||||
self.notificationManager = notificationManager
|
||||
init(notificationService: NotificationServiceProtocol) {
|
||||
self.notificationService = notificationService
|
||||
|
||||
super.init(initialViewState: .init())
|
||||
}
|
||||
@@ -30,7 +30,7 @@ class NotificationPermissionsScreenViewModel: NotificationPermissionsScreenViewM
|
||||
override func process(viewAction: NotificationPermissionsScreenViewAction) {
|
||||
switch viewAction {
|
||||
case .enable:
|
||||
notificationManager.requestAuthorization()
|
||||
notificationService.requestAuthorization()
|
||||
|
||||
actionsSubject.send(.done)
|
||||
case .notNow:
|
||||
|
||||
+1
-1
@@ -67,7 +67,7 @@ struct NotificationPermissionsScreen: View {
|
||||
// MARK: - Previews
|
||||
|
||||
struct NotificationPermissionsScreen_Previews: PreviewProvider, TestablePreview {
|
||||
static let viewModel = NotificationPermissionsScreenViewModel(notificationManager: NotificationManagerMock())
|
||||
static let viewModel = NotificationPermissionsScreenViewModel(notificationService: NotificationServiceMock(.init()))
|
||||
static var previews: some View {
|
||||
NotificationPermissionsScreen(context: viewModel.context)
|
||||
}
|
||||
|
||||
+3
-3
@@ -38,7 +38,7 @@ class NotificationSettingsScreenViewModel: NotificationSettingsScreenViewModelTy
|
||||
notificationTonePreviewer = AudioPlayer()
|
||||
self.notificationToneManager = notificationToneManager
|
||||
|
||||
let bindings = NotificationSettingsScreenViewStateBindings(enableNotifications: userSettings.app.enableNotifications,
|
||||
let bindings = NotificationSettingsScreenViewStateBindings(enableNotifications: userSettings.account.enableNotifications,
|
||||
showAllRoomListActivity: userSettings.account.showAllRoomListActivity)
|
||||
super.init(initialViewState: NotificationSettingsScreenViewState(bindings: bindings,
|
||||
isModallyPresented: isModallyPresented,
|
||||
@@ -48,7 +48,7 @@ class NotificationSettingsScreenViewModel: NotificationSettingsScreenViewModelTy
|
||||
customToneSelectionEnabled: !ProcessInfo.processInfo.isiOSAppOnMac))
|
||||
|
||||
// Listen for changes to UserSettings.
|
||||
userSettings.app.enableNotificationsPublisher
|
||||
userSettings.account.enableNotificationsPublisher
|
||||
.weakAssign(to: \.state.bindings.enableNotifications, on: self)
|
||||
.store(in: &cancellables)
|
||||
|
||||
@@ -127,7 +127,7 @@ class NotificationSettingsScreenViewModel: NotificationSettingsScreenViewModelTy
|
||||
}
|
||||
|
||||
func toggleNotifications() {
|
||||
userSettings.app.enableNotifications.toggle()
|
||||
userSettings.account.enableNotifications.toggle()
|
||||
}
|
||||
|
||||
private func setupDidBecomeActiveSubscription() {
|
||||
|
||||
@@ -846,7 +846,11 @@ class ClientProxy: ClientProxyProtocol {
|
||||
deviceDisplayName: configuration.deviceDisplayName,
|
||||
profileTag: configuration.profileTag,
|
||||
lang: configuration.lang,
|
||||
append: false)
|
||||
append: configuration.append)
|
||||
}
|
||||
|
||||
func deletePusher(with identifiers: PusherIdentifiers) async throws {
|
||||
try await client.deletePusher(identifiers: identifiers)
|
||||
}
|
||||
|
||||
func searchUsers(searchTerm: String, limit: UInt) async -> Result<SearchUsersResults, ClientProxyError> {
|
||||
|
||||
@@ -75,13 +75,15 @@ enum CreateRoomAccessType: Equatable {
|
||||
/// This struct represents the configuration that we are using to register the application through Pusher to Sygnal
|
||||
/// using the Matrix Rust SDK, more info here:
|
||||
/// https://github.com/matrix-org/sygnal
|
||||
struct PusherConfiguration {
|
||||
struct PusherConfiguration: Equatable {
|
||||
let identifiers: PusherIdentifiers
|
||||
let kind: PusherKind
|
||||
let appDisplayName: String
|
||||
let deviceDisplayName: String
|
||||
let profileTag: String?
|
||||
let lang: String
|
||||
/// Whether to keep the pushers of the other accounts using the same pushkey on this device.
|
||||
let append: Bool
|
||||
}
|
||||
|
||||
enum SessionVerificationState {
|
||||
@@ -253,6 +255,8 @@ protocol ClientProxyProtocol: AnyObject {
|
||||
|
||||
func setPusher(with configuration: PusherConfiguration) async throws
|
||||
|
||||
func deletePusher(with identifiers: PusherIdentifiers) async throws
|
||||
|
||||
func searchUsers(searchTerm: String, limit: UInt) async -> Result<SearchUsersResults, ClientProxyError>
|
||||
|
||||
func profile(for userID: String) async -> Result<UserProfile, ClientProxyError>
|
||||
|
||||
@@ -7,21 +7,26 @@
|
||||
//
|
||||
|
||||
import Combine
|
||||
import Foundation
|
||||
import UIKit
|
||||
import SwiftUI
|
||||
import UserNotifications
|
||||
|
||||
/// Handles the app's notifications: the notification center, the APNs token, the permission and the app badge.
|
||||
/// Each live account's ``NotificationService`` decides what concerns its account and asks for it through actions.
|
||||
final class NotificationManager: NSObject, NotificationManagerProtocol {
|
||||
private let notificationCenter: UserNotificationCenterProtocol
|
||||
private let appSettings: AppSettings
|
||||
|
||||
private var userSession: UserSessionProtocol?
|
||||
|
||||
/// The APNs token, kept for the accounts added after it arrived.
|
||||
private var deviceToken: Data?
|
||||
private var services: [String: NotificationServiceProtocol] = [:]
|
||||
private var serviceCancellables: [String: Set<AnyCancellable>] = [:]
|
||||
private var cancellables = Set<AnyCancellable>()
|
||||
private var notificationsEnabled = false
|
||||
|
||||
init(notificationCenter: UserNotificationCenterProtocol,
|
||||
appSettings: AppSettings) {
|
||||
private var isAnyAccountEnabled: Bool {
|
||||
services.values.contains { $0.isEnabled }
|
||||
}
|
||||
|
||||
init(notificationCenter: UserNotificationCenterProtocol, appSettings: AppSettings) {
|
||||
self.notificationCenter = notificationCenter
|
||||
self.appSettings = appSettings
|
||||
super.init()
|
||||
@@ -47,66 +52,25 @@ final class NotificationManager: NSObject, NotificationManagerProtocol {
|
||||
notificationCenter.setNotificationCategories([messageCategory, inviteCategory])
|
||||
notificationCenter.delegate = self
|
||||
|
||||
notificationsEnabled = appSettings.enableNotifications
|
||||
MXLog.info("App setting 'enableNotifications' is '\(notificationsEnabled)'")
|
||||
|
||||
// Listen for changes to AppSettings.enableNotifications
|
||||
appSettings.enableNotificationsPublisher
|
||||
.sink { [weak self] newValue in
|
||||
self?.enableNotifications(newValue)
|
||||
}
|
||||
.store(in: &cancellables)
|
||||
|
||||
NotificationCenter.default.publisher(for: UIApplication.didBecomeActiveNotification)
|
||||
.sink { [weak self] _ in
|
||||
self?.removeReceivedWhileOfflineNotification()
|
||||
}
|
||||
.store(in: &cancellables)
|
||||
}
|
||||
|
||||
func requestAuthorization() {
|
||||
guard appSettings.enableNotifications, !userSession.isNil else { return }
|
||||
Task {
|
||||
do {
|
||||
let permissionGranted = try await notificationCenter.requestAuthorization(options: [.alert, .sound, .badge])
|
||||
MXLog.info("Permission granted: \(permissionGranted)")
|
||||
await MainActor.run {
|
||||
if permissionGranted {
|
||||
self.delegate?.registerForRemoteNotifications()
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
MXLog.error("Request authorization failed: \(error)")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func register(with deviceToken: Data) async -> Bool {
|
||||
guard let userSession else {
|
||||
return false
|
||||
}
|
||||
return await setPusher(with: deviceToken, clientProxy: userSession.clientProxy)
|
||||
}
|
||||
|
||||
func setUserSession(_ userSession: UserSessionProtocol?) {
|
||||
self.userSession = userSession
|
||||
|
||||
// If notification permissions were given previously then attempt re-registering
|
||||
// for remote notifications on startup. Otherwise let the onboarding flow handle it
|
||||
Task { [weak self] in
|
||||
guard let self else { return }
|
||||
|
||||
if await notificationCenter.authorizationStatus() == .authorized, appSettings.enableNotifications {
|
||||
await MainActor.run { [weak self] in
|
||||
self?.delegate?.registerForRemoteNotifications()
|
||||
}
|
||||
}
|
||||
|
||||
Task {
|
||||
let settings = await notificationCenter.notificationSettings()
|
||||
MXLog.info("Notification sound enabled: \(settings.soundSetting == .enabled)")
|
||||
}
|
||||
}
|
||||
|
||||
func register(with deviceToken: Data) async {
|
||||
self.deviceToken = deviceToken
|
||||
for service in services.values {
|
||||
await service.register(deviceToken: deviceToken)
|
||||
}
|
||||
}
|
||||
|
||||
func registrationFailed(with error: Error) {
|
||||
MXLog.error("Device token registration failed with error: \(error)")
|
||||
}
|
||||
@@ -128,106 +92,115 @@ final class NotificationManager: NSObject, NotificationManagerProtocol {
|
||||
}
|
||||
}
|
||||
|
||||
func removeDeliveredMessageNotifications(for roomID: String) async {
|
||||
let notificationsIdentifiers = await notificationCenter
|
||||
.deliveredNotifications()
|
||||
.filter { $0.request.content.roomID == roomID }
|
||||
.map(\.request.identifier)
|
||||
notificationCenter.removeDeliveredNotifications(withIdentifiers: notificationsIdentifiers)
|
||||
func add(_ service: NotificationServiceProtocol) {
|
||||
let userID = service.userID
|
||||
services[userID] = service
|
||||
serviceCancellables[userID] = [
|
||||
service.actionsPublisher.sink { [weak self] action in
|
||||
self?.handle(action, from: userID)
|
||||
},
|
||||
service.badgeCountPublisher.sink { [weak self] _ in
|
||||
self?.updateAppBadgeCount()
|
||||
}
|
||||
]
|
||||
|
||||
if let deviceToken {
|
||||
Task { await service.register(deviceToken: deviceToken) }
|
||||
} else {
|
||||
registerForRemoteNotificationsIfAuthorized()
|
||||
}
|
||||
}
|
||||
|
||||
func removeDeliveredNotificationsForFullyReadRooms(_ rooms: [RoomSummary]) async {
|
||||
let roomsToLastMessageDates = rooms
|
||||
.filter { $0.hasUnreadMessages == false }
|
||||
.reduce(into: [:]) { partialResult, roomSummary in
|
||||
partialResult[roomSummary.id] = roomSummary.lastMessageDate
|
||||
}
|
||||
func remove(userID: String) {
|
||||
serviceCancellables[userID] = nil
|
||||
guard services.removeValue(forKey: userID) != nil else { return }
|
||||
|
||||
let notificationsIdentifiers = await notificationCenter
|
||||
.deliveredNotifications()
|
||||
.filter { notification in
|
||||
guard let roomID = notification.request.content.roomID,
|
||||
let lastMessageDate = roomsToLastMessageDates[roomID] else {
|
||||
return false
|
||||
if services.isEmpty {
|
||||
// Signing out of the last account unregisters from APNs, so the next account registers again.
|
||||
deviceToken = nil
|
||||
} else {
|
||||
updateAppBadgeCount()
|
||||
}
|
||||
}
|
||||
|
||||
func reset() {
|
||||
appSettings.lastKnownBadgeCount = 0
|
||||
Task {
|
||||
do {
|
||||
try await notificationCenter.setBadgeCount(0)
|
||||
} catch {
|
||||
MXLog.error("Failed resetting the app badge count with error: \(error)")
|
||||
}
|
||||
}
|
||||
delegate?.unregisterForRemoteNotifications()
|
||||
}
|
||||
|
||||
// MARK: - Private
|
||||
|
||||
private func handle(_ action: NotificationServiceAction, from userID: String) {
|
||||
switch action {
|
||||
case .removeDeliveredNotifications(let isIncluded):
|
||||
Task { await removeDeliveredNotifications(of: userID, where: isIncluded) }
|
||||
case .requestAuthorization:
|
||||
requestAuthorization()
|
||||
}
|
||||
}
|
||||
|
||||
private func requestAuthorization() {
|
||||
guard isAnyAccountEnabled else { return }
|
||||
Task {
|
||||
do {
|
||||
let permissionGranted = try await notificationCenter.requestAuthorization(options: [.alert, .sound, .badge])
|
||||
MXLog.info("Permission granted: \(permissionGranted)")
|
||||
if permissionGranted {
|
||||
delegate?.registerForRemoteNotifications()
|
||||
}
|
||||
|
||||
// The delivery date is later than the event's so only use it for notifications without an event date.
|
||||
let notificationDate = notification.request.content.eventDate ?? notification.date
|
||||
// Truncated to seconds to match `RoomSummary.lastMessageDate`.
|
||||
return notificationDate.timeIntervalSince1970.rounded(.down) <= lastMessageDate.timeIntervalSince1970
|
||||
} catch {
|
||||
MXLog.error("Request authorization failed: \(error)")
|
||||
}
|
||||
.map(\.request.identifier)
|
||||
|
||||
notificationCenter.removeDeliveredNotifications(withIdentifiers: notificationsIdentifiers)
|
||||
}
|
||||
}
|
||||
|
||||
func updateAppBadgeCount(_ badgeCount: Int) async {
|
||||
guard let userSession else { return }
|
||||
/// Registers again when permission was given before, otherwise the onboarding flow asks for it.
|
||||
/// Accounts that are turned off need the token too, to delete any pusher left on their homeserver.
|
||||
private func registerForRemoteNotificationsIfAuthorized() {
|
||||
Task {
|
||||
guard await notificationCenter.authorizationStatus() == .authorized else { return }
|
||||
delegate?.registerForRemoteNotifications()
|
||||
}
|
||||
}
|
||||
|
||||
private func updateAppBadgeCount() {
|
||||
// Signing out of the last account resets the badge.
|
||||
guard !services.isEmpty else { return }
|
||||
|
||||
let badgeCount = services.values.map(\.badgeCountPublisher.value).reduce(0, +)
|
||||
appSettings.lastKnownBadgeCount = badgeCount
|
||||
|
||||
MXLog.debug("Updating app badge count to \(badgeCount)")
|
||||
|
||||
do {
|
||||
try await notificationCenter.setBadgeCount(badgeCount)
|
||||
} catch {
|
||||
MXLog.error("Failed updating the app badge count with error: \(error)")
|
||||
Task {
|
||||
do {
|
||||
try await notificationCenter.setBadgeCount(badgeCount)
|
||||
} catch {
|
||||
MXLog.error("Failed updating the app badge count with error: \(error)")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func removeDeliveredNotifications(of userID: String, where isIncluded: (UNNotification) -> Bool) async {
|
||||
let identifiers = await notificationCenter.deliveredNotifications()
|
||||
// A room can be shared by several accounts. Notifications without a receiver weren't processed by the extension, so any account may clear them.
|
||||
.filter { ($0.request.content.receiverID ?? userID) == userID }
|
||||
.filter(isIncluded)
|
||||
.map(\.request.identifier)
|
||||
guard !identifiers.isEmpty else { return }
|
||||
|
||||
notificationCenter.removeDeliveredNotifications(withIdentifiers: identifiers)
|
||||
}
|
||||
|
||||
private func removeReceivedWhileOfflineNotification() {
|
||||
notificationCenter.removeDeliveredNotifications(withIdentifiers: [NotificationServiceExtensionActor.receivedWhileOfflineNotificationID])
|
||||
}
|
||||
|
||||
private func setPusher(with deviceToken: Data, clientProxy: ClientProxyProtocol) async -> Bool {
|
||||
do {
|
||||
let defaultPayload = APNSPayload(aps: APSInfo(mutableContent: 1,
|
||||
alert: APSAlert(locKey: "Notification",
|
||||
locArgs: [])),
|
||||
pusherNotificationClientIdentifier: clientProxy.pusherNotificationClientIdentifier)
|
||||
|
||||
let configuration = try PusherConfiguration(identifiers: .init(pushkey: deviceToken.base64EncodedString(),
|
||||
appId: appSettings.pusherAppID),
|
||||
kind: .http(data: .init(url: appSettings.pushGatewayNotifyEndpoint.absoluteString,
|
||||
format: .eventIdOnly,
|
||||
defaultPayload: defaultPayload.toJsonString())),
|
||||
appDisplayName: "\(InfoPlistReader.main.bundleDisplayName) (iOS)",
|
||||
deviceDisplayName: UIDevice.current.name,
|
||||
profileTag: pusherProfileTag(),
|
||||
lang: Bundle.app.preferredLocalizations.first ?? "en")
|
||||
try await clientProxy.setPusher(with: configuration)
|
||||
MXLog.info("Set pusher succeeded")
|
||||
return true
|
||||
} catch {
|
||||
MXLog.error("Set pusher failed: \(error)")
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
private func pusherProfileTag() -> String {
|
||||
if let currentTag = appSettings.pusherProfileTag {
|
||||
return currentTag
|
||||
}
|
||||
let chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
|
||||
let newTag = (0..<16).map { _ in
|
||||
let offset = Int.random(in: 0..<chars.count)
|
||||
return String(chars[chars.index(chars.startIndex, offsetBy: offset)])
|
||||
}.joined()
|
||||
|
||||
appSettings.pusherProfileTag = newTag
|
||||
return newTag
|
||||
}
|
||||
|
||||
private func enableNotifications(_ enable: Bool) {
|
||||
guard notificationsEnabled != enable else { return }
|
||||
notificationsEnabled = enable
|
||||
MXLog.info("App setting 'enableNotifications' changed to '\(enable)'")
|
||||
if enable {
|
||||
requestAuthorization()
|
||||
} else {
|
||||
delegate?.unregisterForRemoteNotifications()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - UNUserNotificationCenterDelegate
|
||||
|
||||
@@ -26,16 +26,13 @@ protocol NotificationManagerProtocol: AnyObject {
|
||||
var delegate: NotificationManagerDelegate? { get set }
|
||||
|
||||
func start()
|
||||
func register(with deviceToken: Data) async -> Bool
|
||||
func register(with deviceToken: Data) async
|
||||
func registrationFailed(with error: Error)
|
||||
func showLocalNotification(with title: String, subtitle: String?) async
|
||||
func setUserSession(_ userSession: UserSessionProtocol?)
|
||||
|
||||
func requestAuthorization()
|
||||
|
||||
func removeDeliveredMessageNotifications(for roomID: String) async
|
||||
|
||||
func removeDeliveredNotificationsForFullyReadRooms(_ rooms: [RoomSummary]) async
|
||||
|
||||
func updateAppBadgeCount(_ badgeCount: Int) async
|
||||
/// Starts handling a live account's notifications, replacing the service it had before (e.g. after clearing the cache).
|
||||
func add(_ service: NotificationServiceProtocol)
|
||||
func remove(userID: String)
|
||||
/// Resets the app badge and stops receiving notifications, once no account is signed in.
|
||||
func reset()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,177 @@
|
||||
//
|
||||
// Copyright 2026 Element Creations Ltd.
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial.
|
||||
// Please see LICENSE files in the repository root for full details.
|
||||
//
|
||||
|
||||
import Combine
|
||||
import MatrixRustSDK
|
||||
import SwiftUI
|
||||
import UserNotifications
|
||||
|
||||
/// Handles one account's notifications: its pusher, whether they're on, its unread count and which of its
|
||||
/// delivered notifications to remove. The `NotificationManager` does the removing, through this service's actions.
|
||||
final class NotificationService: NotificationServiceProtocol {
|
||||
private let clientProxy: ClientProxyProtocol
|
||||
private let userSettings: UserSettings
|
||||
|
||||
/// The APNs token, unknown until the app registers for remote notifications.
|
||||
private var deviceToken: Data?
|
||||
private var cancellables = Set<AnyCancellable>()
|
||||
|
||||
private let actionsSubject = PassthroughSubject<NotificationServiceAction, Never>()
|
||||
var actionsPublisher: AnyPublisher<NotificationServiceAction, Never> {
|
||||
actionsSubject.eraseToAnyPublisher()
|
||||
}
|
||||
|
||||
private let badgeCountSubject: CurrentValueSubject<Int, Never>
|
||||
var badgeCountPublisher: CurrentValuePublisher<Int, Never> {
|
||||
badgeCountSubject.asCurrentValuePublisher()
|
||||
}
|
||||
|
||||
var userID: String {
|
||||
clientProxy.userID
|
||||
}
|
||||
|
||||
var isEnabled: Bool {
|
||||
userSettings.account.enableNotifications
|
||||
}
|
||||
|
||||
init(clientProxy: ClientProxyProtocol, userSettings: UserSettings) {
|
||||
self.clientProxy = clientProxy
|
||||
self.userSettings = userSettings
|
||||
badgeCountSubject = .init(Int(clientProxy.totalUnreadNotifications))
|
||||
|
||||
setupSubscriptions()
|
||||
}
|
||||
|
||||
func register(deviceToken: Data) async {
|
||||
self.deviceToken = deviceToken
|
||||
// A failure is retried on the next launch, which registers the token again.
|
||||
await updatePusher(isEnabled: isEnabled)
|
||||
}
|
||||
|
||||
func requestAuthorization() {
|
||||
actionsSubject.send(.requestAuthorization)
|
||||
}
|
||||
|
||||
func removeDeliveredMessageNotifications(for roomID: String) {
|
||||
actionsSubject.send(.removeDeliveredNotifications { $0.request.content.roomID == roomID })
|
||||
}
|
||||
|
||||
func removeDeliveredNotificationsForFullyReadRooms(_ rooms: [RoomSummary]) {
|
||||
let roomsToLastMessageDates = rooms
|
||||
.filter { $0.hasUnreadMessages == false }
|
||||
.reduce(into: [:]) { partialResult, roomSummary in
|
||||
partialResult[roomSummary.id] = roomSummary.lastMessageDate
|
||||
}
|
||||
guard !roomsToLastMessageDates.isEmpty else { return }
|
||||
|
||||
actionsSubject.send(.removeDeliveredNotifications { notification in
|
||||
guard let roomID = notification.request.content.roomID,
|
||||
let lastMessageDate = roomsToLastMessageDates[roomID] else {
|
||||
return false
|
||||
}
|
||||
|
||||
// The delivery date is later than the event's so only use it for notifications without an event date.
|
||||
let notificationDate = notification.request.content.eventDate ?? notification.date
|
||||
// Truncated to seconds to match `RoomSummary.lastMessageDate`.
|
||||
return notificationDate.timeIntervalSince1970.rounded(.down) <= lastMessageDate.timeIntervalSince1970
|
||||
})
|
||||
}
|
||||
|
||||
func tearDown() async {
|
||||
await updatePusher(isEnabled: false)
|
||||
actionsSubject.send(.removeDeliveredNotifications { _ in true })
|
||||
}
|
||||
|
||||
// MARK: - Private
|
||||
|
||||
private func setupSubscriptions() {
|
||||
let roomListPublisher = clientProxy.staticRoomSummaryProvider.roomListPublisher
|
||||
|
||||
Task { [weak self] in
|
||||
for await roomSummaries in roomListPublisher.values {
|
||||
guard let self else { return }
|
||||
|
||||
updateBadgeCount(Int(clientProxy.totalUnreadNotifications))
|
||||
removeDeliveredNotificationsForFullyReadRooms(roomSummaries)
|
||||
}
|
||||
}
|
||||
.store(in: &cancellables)
|
||||
|
||||
// The settings screen turns notifications on and off through `AccountSettings.enableNotifications`.
|
||||
userSettings.account.enableNotificationsPublisher
|
||||
.dropFirst()
|
||||
.sink { [weak self] isEnabled in
|
||||
self?.enableNotificationsChanged(to: isEnabled)
|
||||
}
|
||||
.store(in: &cancellables)
|
||||
}
|
||||
|
||||
private func enableNotificationsChanged(to isEnabled: Bool) {
|
||||
MXLog.info("Notifications turned \(isEnabled ? "on" : "off") for \(userID)")
|
||||
// The extension drops pushes for an account turned off, so a pusher that fails to update is fixed on the next launch.
|
||||
Task { await updatePusher(isEnabled: isEnabled) }
|
||||
|
||||
if isEnabled {
|
||||
requestAuthorization()
|
||||
}
|
||||
}
|
||||
|
||||
private func updateBadgeCount(_ badgeCount: Int) {
|
||||
guard badgeCount != badgeCountSubject.value else { return }
|
||||
badgeCountSubject.send(badgeCount)
|
||||
}
|
||||
|
||||
/// Sets the pusher when enabled and deletes it otherwise. Nothing to update until the device token is known.
|
||||
private func updatePusher(isEnabled: Bool) async {
|
||||
guard let deviceToken else { return }
|
||||
|
||||
let identifiers = PusherIdentifiers(pushkey: deviceToken.base64EncodedString(), appId: userSettings.app.pusherAppID)
|
||||
do {
|
||||
if isEnabled {
|
||||
try await clientProxy.setPusher(with: pusherConfiguration(for: identifiers))
|
||||
MXLog.info("Set pusher succeeded")
|
||||
} else {
|
||||
try await clientProxy.deletePusher(with: identifiers)
|
||||
MXLog.info("Delete pusher succeeded")
|
||||
}
|
||||
} catch {
|
||||
MXLog.error("Updating the pusher failed: \(error)")
|
||||
}
|
||||
}
|
||||
|
||||
private func pusherConfiguration(for identifiers: PusherIdentifiers) throws -> PusherConfiguration {
|
||||
let defaultPayload = APNSPayload(aps: APSInfo(mutableContent: 1,
|
||||
alert: APSAlert(locKey: "Notification",
|
||||
locArgs: [])),
|
||||
pusherNotificationClientIdentifier: clientProxy.pusherNotificationClientIdentifier)
|
||||
|
||||
return try PusherConfiguration(identifiers: identifiers,
|
||||
kind: .http(data: .init(url: userSettings.app.pushGatewayNotifyEndpoint.absoluteString,
|
||||
format: .eventIdOnly,
|
||||
defaultPayload: defaultPayload.toJsonString())),
|
||||
appDisplayName: "\(InfoPlistReader.main.bundleDisplayName) (iOS)",
|
||||
deviceDisplayName: UIDevice.current.name,
|
||||
profileTag: pusherProfileTag(),
|
||||
lang: Bundle.app.preferredLocalizations.first ?? "en",
|
||||
// Otherwise accounts on the same homeserver delete each other's pusher.
|
||||
append: userSettings.app.multiAccountEnabled)
|
||||
}
|
||||
|
||||
private func pusherProfileTag() -> String {
|
||||
if let currentTag = userSettings.app.pusherProfileTag {
|
||||
return currentTag
|
||||
}
|
||||
let chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
|
||||
let newTag = (0..<16).map { _ in
|
||||
let offset = Int.random(in: 0..<chars.count)
|
||||
return String(chars[chars.index(chars.startIndex, offsetBy: offset)])
|
||||
}.joined()
|
||||
|
||||
userSettings.app.pusherProfileTag = newTag
|
||||
return newTag
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
//
|
||||
// Copyright 2026 Element Creations Ltd.
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial.
|
||||
// Please see LICENSE files in the repository root for full details.
|
||||
//
|
||||
|
||||
import Combine
|
||||
import UserNotifications
|
||||
|
||||
/// What an account's service asks of the `NotificationManager`, which owns the notification center.
|
||||
enum NotificationServiceAction {
|
||||
/// Removes the account's delivered notifications that match.
|
||||
case removeDeliveredNotifications(where: (UNNotification) -> Bool)
|
||||
case requestAuthorization
|
||||
}
|
||||
|
||||
// sourcery: AutoMockable
|
||||
protocol NotificationServiceProtocol: AnyObject {
|
||||
var userID: String { get }
|
||||
var actionsPublisher: AnyPublisher<NotificationServiceAction, Never> { get }
|
||||
|
||||
/// Whether this account's notifications are on, see `AccountSettings.enableNotifications`.
|
||||
var isEnabled: Bool { get }
|
||||
/// This account's unread notification count.
|
||||
var badgeCountPublisher: CurrentValuePublisher<Int, Never> { get }
|
||||
|
||||
/// Sets the pusher when notifications are on, otherwise deletes it. The pusher follows the switch from then on.
|
||||
func register(deviceToken: Data) async
|
||||
func requestAuthorization()
|
||||
func removeDeliveredMessageNotifications(for roomID: String)
|
||||
/// Deletes the pusher and this account's delivered notifications, before signing out.
|
||||
func tearDown() async
|
||||
}
|
||||
@@ -23,6 +23,7 @@ class UserSession: UserSessionProtocol {
|
||||
let liveLocationManager: LiveLocationManagerProtocol
|
||||
/// Scans media content, `nil` when no content scanner is configured for the server.
|
||||
let contentScannerService: ContentScannerServiceProtocol?
|
||||
let notificationService: NotificationServiceProtocol
|
||||
|
||||
let callbacks = PassthroughSubject<UserSessionCallback, Never>()
|
||||
|
||||
@@ -36,7 +37,8 @@ class UserSession: UserSessionProtocol {
|
||||
userHooks: UserHooks,
|
||||
mediaProvider: MediaProviderProtocol,
|
||||
voiceMessageMediaManager: VoiceMessageMediaManagerProtocol,
|
||||
liveLocationManager: LiveLocationManagerProtocol) {
|
||||
liveLocationManager: LiveLocationManagerProtocol,
|
||||
notificationService: NotificationServiceProtocol) {
|
||||
self.clientProxy = clientProxy
|
||||
self.userSettings = userSettings
|
||||
self.userHooks = userHooks
|
||||
@@ -44,6 +46,7 @@ class UserSession: UserSessionProtocol {
|
||||
self.mediaProvider = mediaProvider
|
||||
self.voiceMessageMediaManager = voiceMessageMediaManager
|
||||
self.liveLocationManager = liveLocationManager
|
||||
self.notificationService = notificationService
|
||||
contentScannerService = clientProxy.contentScanner.map(ContentScannerService.init)
|
||||
|
||||
authErrorCancellable = clientProxy.actionsPublisher
|
||||
|
||||
@@ -29,6 +29,7 @@ protocol UserSessionProtocol: Sendable {
|
||||
var liveLocationManager: LiveLocationManagerProtocol { get }
|
||||
/// Scans media content, `nil` when no content scanner is configured for the server.
|
||||
var contentScannerService: ContentScannerServiceProtocol? { get }
|
||||
var notificationService: NotificationServiceProtocol { get }
|
||||
|
||||
var sessionSecurityStatePublisher: CurrentValuePublisher<SessionSecurityState, Never> { get }
|
||||
|
||||
|
||||
@@ -17,6 +17,7 @@ import OrderedCollections
|
||||
final class UserSessionManager: UserSessionManagerProtocol {
|
||||
private let userSessionStore: UserSessionStoreProtocol
|
||||
private let appSettings: AppSettings
|
||||
private let notificationManager: NotificationManagerProtocol
|
||||
|
||||
private let sessionsSubject = CurrentValueSubject<[UserSessionProtocol], Never>([])
|
||||
/// Whether the services are running, so that the sessions restored meanwhile are resumed too.
|
||||
@@ -68,9 +69,10 @@ final class UserSessionManager: UserSessionManagerProtocol {
|
||||
accounts.contains { userID, userSession in userSession != nil && !clearedUserIDs.contains(userID) }
|
||||
}
|
||||
|
||||
init(userSessionStore: UserSessionStoreProtocol, appSettings: AppSettings) {
|
||||
init(userSessionStore: UserSessionStoreProtocol, appSettings: AppSettings, notificationManager: NotificationManagerProtocol) {
|
||||
self.userSessionStore = userSessionStore
|
||||
self.appSettings = appSettings
|
||||
self.notificationManager = notificationManager
|
||||
|
||||
let userIDs = userSessionStore.userIDs
|
||||
.map { (userID: $0, lastSelectedDate: appSettings.userSettings(for: $0).account.lastSelectedDate) }
|
||||
@@ -138,6 +140,8 @@ final class UserSessionManager: UserSessionManagerProtocol {
|
||||
appSettings.userSettings(for: userID).account.lastSelectedDate = .now
|
||||
accounts.updateValue(userSession, forKey: userID, insertingAt: 0)
|
||||
}
|
||||
|
||||
notificationManager.add(userSession.notificationService)
|
||||
}
|
||||
|
||||
func remove(userID: String) {
|
||||
@@ -149,9 +153,13 @@ final class UserSessionManager: UserSessionManagerProtocol {
|
||||
userSessionStore.logout(userSession: userSession)
|
||||
clearedUserIDs.remove(userID)
|
||||
accounts.removeValue(forKey: userID)
|
||||
notificationManager.remove(userID: userID)
|
||||
}
|
||||
|
||||
func reset() {
|
||||
for userID in accounts.keys {
|
||||
notificationManager.remove(userID: userID)
|
||||
}
|
||||
userSessionStore.reset()
|
||||
clearedUserIDs.removeAll()
|
||||
accounts.removeAll()
|
||||
@@ -202,6 +210,7 @@ final class UserSessionManager: UserSessionManagerProtocol {
|
||||
MXLog.error("Failed restoring \(userID): \(error)")
|
||||
clearedUserIDs.remove(userID)
|
||||
accounts.removeValue(forKey: userID)
|
||||
notificationManager.remove(userID: userID)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
@@ -124,12 +124,15 @@ class UserSessionStore: UserSessionStoreProtocol {
|
||||
userSettings: userSettings)
|
||||
}
|
||||
|
||||
let notificationService = NotificationService(clientProxy: clientProxy, userSettings: userSettings)
|
||||
|
||||
return UserSession(clientProxy: clientProxy,
|
||||
userSettings: userSettings,
|
||||
userHooks: appHooks.userSessionHook.makeUserHooks(for: clientProxy),
|
||||
mediaProvider: mediaProvider,
|
||||
voiceMessageMediaManager: voiceMessageMediaManager,
|
||||
liveLocationManager: liveLocationManager)
|
||||
liveLocationManager: liveLocationManager,
|
||||
notificationService: notificationService)
|
||||
}
|
||||
|
||||
private func restorePreviousLogin(_ credentials: KeychainCredentials, userSettings: UserSettings) async -> Result<ClientProxyProtocol, UserSessionStoreError> {
|
||||
|
||||
@@ -637,7 +637,6 @@ class MockScreen: Identifiable {
|
||||
appHooks: AppHooks(),
|
||||
analytics: analytics,
|
||||
userIndicatorController: UserIndicatorControllerMock(),
|
||||
notificationManager: NotificationManagerMock(),
|
||||
stateMachineFactory: StateMachineFactory()))
|
||||
|
||||
flowCoordinator.start()
|
||||
@@ -690,7 +689,6 @@ class MockScreen: Identifiable {
|
||||
appHooks: AppHooks(),
|
||||
analytics: analytics,
|
||||
userIndicatorController: UserIndicatorControllerMock(),
|
||||
notificationManager: NotificationManagerMock(),
|
||||
stateMachineFactory: StateMachineFactory()))
|
||||
flowCoordinator.actionsPublisher
|
||||
.sink { [weak self] action in
|
||||
@@ -790,7 +788,6 @@ class MockScreen: Identifiable {
|
||||
appHooks: AppHooks(),
|
||||
analytics: analytics,
|
||||
userIndicatorController: UserIndicatorControllerMock(),
|
||||
notificationManager: NotificationManagerMock(),
|
||||
stateMachineFactory: StateMachineFactory()))
|
||||
flowCoordinator.actionsPublisher
|
||||
.sink { [weak self] action in
|
||||
@@ -847,7 +844,6 @@ class MockScreen: Identifiable {
|
||||
appHooks: AppHooks(),
|
||||
analytics: analytics,
|
||||
userIndicatorController: UserIndicatorControllerMock(),
|
||||
notificationManager: NotificationManagerMock(),
|
||||
stateMachineFactory: StateMachineFactory()))
|
||||
|
||||
flowCoordinator.start()
|
||||
|
||||
Reference in New Issue
Block a user