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:
@@ -17,7 +17,7 @@ struct ChatsTabFlowCoordinatorTests {
|
||||
var timelineControllerFactory: TimelineControllerFactoryMock!
|
||||
var chatsTabFlowCoordinator: ChatsTabFlowCoordinator!
|
||||
var splitCoordinator: NavigationSplitCoordinator!
|
||||
var notificationManager: NotificationManagerMock!
|
||||
var notificationService: NotificationServiceMock!
|
||||
let stateMachineFactory = PublishedStateMachineFactory()
|
||||
|
||||
var detailCoordinator: CoordinatorProtocol? {
|
||||
@@ -34,9 +34,9 @@ struct ChatsTabFlowCoordinatorTests {
|
||||
|
||||
splitCoordinator = NavigationSplitCoordinator(placeholderCoordinator: PlaceholderScreenCoordinator(hideBrandChrome: false))
|
||||
|
||||
notificationManager = NotificationManagerMock()
|
||||
notificationService = NotificationServiceMock(.init())
|
||||
|
||||
let userSession = UserSessionMock(.init(clientProxy: clientProxy))
|
||||
let userSession = UserSessionMock(.init(clientProxy: clientProxy, notificationService: notificationService))
|
||||
let flowParameters = CommonFlowParameters(userSession: userSession,
|
||||
availableSessionsPublisher: .init([.init(userSession: userSession)]),
|
||||
bugReportService: BugReportServiceMock(.init()),
|
||||
@@ -48,7 +48,6 @@ struct ChatsTabFlowCoordinatorTests {
|
||||
appHooks: AppHooks(),
|
||||
analytics: AnalyticsServiceMock(.init()),
|
||||
userIndicatorController: UserIndicatorControllerMock(),
|
||||
notificationManager: notificationManager,
|
||||
stateMachineFactory: stateMachineFactory)
|
||||
chatsTabFlowCoordinator = ChatsTabFlowCoordinator(navigationSplitCoordinator: splitCoordinator,
|
||||
flowParameters: flowParameters)
|
||||
@@ -80,7 +79,7 @@ struct ChatsTabFlowCoordinatorTests {
|
||||
#expect(detailNavigationStack?.rootCoordinator == nil)
|
||||
#expect(detailCoordinator == nil)
|
||||
|
||||
#expect(notificationManager.removeDeliveredMessageNotificationsForReceivedInvocations == ["1", "1", "2"])
|
||||
#expect(notificationService.removeDeliveredMessageNotificationsForReceivedInvocations == ["1", "1", "2"])
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -109,7 +108,7 @@ struct ChatsTabFlowCoordinatorTests {
|
||||
#expect(detailNavigationStack?.rootCoordinator == nil)
|
||||
#expect(detailCoordinator == nil)
|
||||
|
||||
#expect(notificationManager.removeDeliveredMessageNotificationsForReceivedInvocations == ["1", "1", "2"])
|
||||
#expect(notificationService.removeDeliveredMessageNotificationsForReceivedInvocations == ["1", "1", "2"])
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -19,7 +19,7 @@ final class HomeScreenViewModelTests {
|
||||
|
||||
var clientProxy: ClientProxyMock!
|
||||
var roomSummaryProvider: RoomSummaryProviderMock!
|
||||
var notificationManager: NotificationManagerMock!
|
||||
var notificationService: NotificationServiceMock!
|
||||
private let userSettings: UserSettings
|
||||
|
||||
var cancellables = Set<AnyCancellable>()
|
||||
@@ -297,7 +297,7 @@ final class HomeScreenViewModelTests {
|
||||
try await deferred.fulfill()
|
||||
|
||||
#expect(userSettings.app.seenInvites == [invitedRoomIDs[1]])
|
||||
#expect(!notificationManager.removeDeliveredMessageNotificationsForCalled, "The notification will be dismissed when opening the room.")
|
||||
#expect(!notificationService.removeDeliveredMessageNotificationsForCalled, "The notification will be dismissed when opening the room.")
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -315,7 +315,7 @@ final class HomeScreenViewModelTests {
|
||||
try await deferred.fulfill()
|
||||
|
||||
#expect(userSettings.app.seenInvites == [invitedRoomIDs[1]])
|
||||
#expect(!notificationManager.removeDeliveredMessageNotificationsForCalled, "The notification will be dismissed when opening the room.")
|
||||
#expect(!notificationService.removeDeliveredMessageNotificationsForCalled, "The notification will be dismissed when opening the room.")
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -346,8 +346,8 @@ final class HomeScreenViewModelTests {
|
||||
#expect(rejectCalled)
|
||||
|
||||
#expect(userSettings.app.seenInvites == [invitedRoomIDs[1]])
|
||||
#expect(notificationManager.removeDeliveredMessageNotificationsForCalled)
|
||||
#expect(notificationManager.removeDeliveredMessageNotificationsForReceivedInvocations == [invitedRoomIDs[0]])
|
||||
#expect(notificationService.removeDeliveredMessageNotificationsForCalled)
|
||||
#expect(notificationService.removeDeliveredMessageNotificationsForReceivedInvocations == [invitedRoomIDs[0]])
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -601,13 +601,12 @@ final class HomeScreenViewModelTests {
|
||||
break
|
||||
}
|
||||
|
||||
let userSession = UserSessionMock(.init(clientProxy: clientProxy, userSettings: userSettings))
|
||||
notificationService = NotificationServiceMock(.init())
|
||||
let userSession = UserSessionMock(.init(clientProxy: clientProxy, userSettings: userSettings, notificationService: notificationService))
|
||||
if let securityStatePublisher {
|
||||
userSession.sessionSecurityStatePublisher = securityStatePublisher
|
||||
}
|
||||
|
||||
notificationManager = NotificationManagerMock()
|
||||
|
||||
let sessionDetails = [UserSessionDetails(userSession: userSession)] + otherAccountUserIDs.map { UserSessionDetails(userID: $0) }
|
||||
|
||||
viewModel = HomeScreenViewModel(userSession: userSession,
|
||||
@@ -615,7 +614,6 @@ final class HomeScreenViewModelTests {
|
||||
selectedRoomPublisher: CurrentValueSubject<String?, Never>(nil).asCurrentValuePublisher(),
|
||||
analyticsService: AnalyticsServiceMock(.init()),
|
||||
bugReportService: BugReportServiceMock(.init()),
|
||||
notificationManager: notificationManager,
|
||||
userIndicatorController: UserIndicatorControllerMock())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,26 +15,25 @@ import Testing
|
||||
@MainActor
|
||||
final class NotificationManagerTests {
|
||||
var notificationManager: NotificationManager!
|
||||
private let clientProxy = ClientProxyMock(.init(userID: "@test:user.net"))
|
||||
private lazy var mockUserSession = UserSessionMock(.init(clientProxy: clientProxy))
|
||||
private var notificationCenter: UserNotificationCenterMock!
|
||||
private let appSettings: AppSettings
|
||||
private var authorizationStatusWasGranted = false
|
||||
private var shouldDisplayInAppNotificationReturnValue = false
|
||||
private var handleInlineReplyDelegateCalled = false
|
||||
private var notificationTappedDelegateCalled = false
|
||||
private var registerForRemoteNotificationsDelegateCalled: (() -> Void)?
|
||||
private let appSettings: AppSettings
|
||||
private var unregisterForRemoteNotificationsDelegateCalled = false
|
||||
|
||||
init() {
|
||||
appSettings = AppSettings.volatile()
|
||||
notificationCenter = UserNotificationCenterMock()
|
||||
notificationCenter.requestAuthorizationOptionsReturnValue = true
|
||||
notificationCenter.authorizationStatusReturnValue = .authorized
|
||||
notificationCenter.deliveredNotificationsReturnValue = []
|
||||
notificationCenter.notificationSettingsClosure = { await UNUserNotificationCenter.current().notificationSettings() }
|
||||
|
||||
notificationManager = NotificationManager(notificationCenter: notificationCenter, appSettings: appSettings)
|
||||
notificationManager.start()
|
||||
notificationManager.setUserSession(mockUserSession)
|
||||
}
|
||||
|
||||
isolated deinit {
|
||||
@@ -42,73 +41,239 @@ final class NotificationManagerTests {
|
||||
notificationManager = nil
|
||||
}
|
||||
|
||||
// MARK: - Device token
|
||||
|
||||
@Test
|
||||
func whenRegistered_pusherIsCalled() async {
|
||||
_ = await notificationManager.register(with: Data())
|
||||
func registeringHandsTheTokenToEveryAccount() async {
|
||||
let alice = makeService("@alice:example.com")
|
||||
let bob = makeService("@bob:example.com")
|
||||
notificationManager.add(alice.service)
|
||||
notificationManager.add(bob.service)
|
||||
let deviceToken = Data("1234".utf8)
|
||||
|
||||
#expect(clientProxy.setPusherWithCalled)
|
||||
await notificationManager.register(with: deviceToken)
|
||||
|
||||
#expect(alice.service.registerDeviceTokenReceivedDeviceToken == deviceToken)
|
||||
#expect(bob.service.registerDeviceTokenReceivedDeviceToken == deviceToken)
|
||||
}
|
||||
|
||||
@Test
|
||||
func whenRegisteredSuccess_completionSuccessIsCalled() async {
|
||||
let success = await notificationManager.register(with: Data())
|
||||
#expect(success)
|
||||
}
|
||||
|
||||
@Test
|
||||
func whenRegisteredAndPusherThrowsError_completionFalseIsCalled() async {
|
||||
enum TestError: Error {
|
||||
case someError
|
||||
func anAccountAddedAfterwardsGetsTheSavedToken() async {
|
||||
let deviceToken = Data("1234".utf8)
|
||||
await notificationManager.register(with: deviceToken)
|
||||
let alice = makeService("@alice:example.com")
|
||||
|
||||
await waitForConfirmation("The saved token should be registered", timeout: .seconds(10)) { confirm in
|
||||
alice.service.registerDeviceTokenClosure = { _ in confirm() }
|
||||
notificationManager.add(alice.service)
|
||||
}
|
||||
|
||||
clientProxy.setPusherWithThrowableError = TestError.someError
|
||||
let success = await notificationManager.register(with: Data())
|
||||
#expect(!success)
|
||||
#expect(alice.service.registerDeviceTokenReceivedDeviceToken == deviceToken)
|
||||
}
|
||||
|
||||
@Test
|
||||
func whenRegistered_pusherIsCalledWithCorrectValues() async throws {
|
||||
let pushkeyData = Data("1234".utf8)
|
||||
_ = await notificationManager.register(with: pushkeyData)
|
||||
func aReplacedServiceRegistersAgainAndTheOldOneIsIgnored() async {
|
||||
let oldBadgeCountSubject = CurrentValueSubject<Int, Never>(3)
|
||||
let oldAlice = makeService("@alice:example.com")
|
||||
oldAlice.service.badgeCountPublisher = oldBadgeCountSubject.asCurrentValuePublisher()
|
||||
notificationManager.add(oldAlice.service)
|
||||
await notificationManager.register(with: Data("1234".utf8))
|
||||
let newAlice = makeService("@alice:example.com", badgeCount: 1)
|
||||
|
||||
guard let configuration = clientProxy.setPusherWithReceivedInvocations.first else {
|
||||
Issue.record("Invalid pusher configuration sent")
|
||||
return
|
||||
await waitForConfirmation("The new service should register", timeout: .seconds(10)) { confirm in
|
||||
newAlice.service.registerDeviceTokenClosure = { _ in confirm() }
|
||||
notificationManager.add(newAlice.service)
|
||||
}
|
||||
oldBadgeCountSubject.send(5)
|
||||
|
||||
#expect(oldAlice.service.registerDeviceTokenCallsCount == 1)
|
||||
#expect(appSettings.lastKnownBadgeCount == 1)
|
||||
}
|
||||
|
||||
@Test
|
||||
func theTokenIsForgottenOnceTheLastAccountIsRemoved() async throws {
|
||||
notificationManager.add(makeService("@alice:example.com").service)
|
||||
await notificationManager.register(with: Data("1234".utf8))
|
||||
notificationManager.remove(userID: "@alice:example.com")
|
||||
let bob = makeService("@bob:example.com")
|
||||
|
||||
// The app unregisters from APNs when signing out of the last account, so the old token is dead.
|
||||
notificationManager.add(bob.service)
|
||||
try await Task.sleep(for: .milliseconds(500))
|
||||
|
||||
#expect(!bob.service.registerDeviceTokenCalled)
|
||||
}
|
||||
|
||||
// MARK: - Permission
|
||||
|
||||
@Test
|
||||
func addingAnAccountRegistersWhenPermissionWasGiven() async {
|
||||
notificationManager.delegate = self
|
||||
|
||||
await waitForConfirmation("registerForRemoteNotifications should be called", timeout: .seconds(10)) { confirm in
|
||||
registerForRemoteNotificationsDelegateCalled = { confirm() }
|
||||
notificationManager.add(makeService("@alice:example.com").service)
|
||||
}
|
||||
|
||||
#expect(configuration.identifiers.pushkey == pushkeyData.base64EncodedString())
|
||||
#expect(configuration.identifiers.appId == appSettings.pusherAppID)
|
||||
#expect(configuration.appDisplayName == "\(InfoPlistReader.main.bundleDisplayName) (iOS)")
|
||||
#expect(configuration.deviceDisplayName == UIDevice.current.name)
|
||||
#expect(configuration.profileTag != nil)
|
||||
#expect(configuration.lang == Bundle.app.preferredLocalizations.first)
|
||||
guard case let .http(data) = configuration.kind else {
|
||||
Issue.record("Http kind expected")
|
||||
return
|
||||
#expect(authorizationStatusWasGranted)
|
||||
}
|
||||
|
||||
@Test
|
||||
func addingAnAccountRegistersEvenWhenItIsOff() async {
|
||||
notificationManager.delegate = self
|
||||
|
||||
// So that accounts turned off delete any pusher left on their homeserver.
|
||||
await waitForConfirmation("registerForRemoteNotifications should be called", timeout: .seconds(10)) { confirm in
|
||||
registerForRemoteNotificationsDelegateCalled = { confirm() }
|
||||
notificationManager.add(makeService("@alice:example.com", isEnabled: false).service)
|
||||
}
|
||||
#expect(data.url == appSettings.pushGatewayNotifyEndpoint.absoluteString)
|
||||
#expect(data.format == .eventIdOnly)
|
||||
let defaultPayload = APNSPayload(aps: APSInfo(mutableContent: 1,
|
||||
alert: APSAlert(locKey: "Notification",
|
||||
locArgs: [])),
|
||||
pusherNotificationClientIdentifier: nil)
|
||||
#expect(try data.defaultPayload == (defaultPayload.toJsonString()))
|
||||
|
||||
#expect(authorizationStatusWasGranted)
|
||||
}
|
||||
|
||||
@Test
|
||||
func whenRegisteredAndPusherTagNotSetInSettings_tagGeneratedAndSavedInSettings() async {
|
||||
appSettings.pusherProfileTag = nil
|
||||
_ = await notificationManager.register(with: Data())
|
||||
#expect(appSettings.pusherProfileTag != nil)
|
||||
func addingAnAccountNeverAsksForPermission() async throws {
|
||||
notificationCenter.authorizationStatusReturnValue = .notDetermined
|
||||
notificationManager.delegate = self
|
||||
|
||||
notificationManager.add(makeService("@alice:example.com").service)
|
||||
try await Task.sleep(for: .seconds(1))
|
||||
|
||||
#expect(!notificationCenter.requestAuthorizationOptionsCalled)
|
||||
#expect(!authorizationStatusWasGranted)
|
||||
}
|
||||
|
||||
@Test
|
||||
func whenRegisteredAndPusherTagIsSetInSettings_tagNotGenerated() async {
|
||||
appSettings.pusherProfileTag = "12345"
|
||||
_ = await notificationManager.register(with: Data())
|
||||
#expect(appSettings.pusherProfileTag == "12345")
|
||||
func anAccountAskingForPermissionRequestsAuthorization() async {
|
||||
let alice = makeService("@alice:example.com")
|
||||
notificationManager.add(alice.service)
|
||||
|
||||
await waitForConfirmation("requestAuthorization should be called", timeout: .seconds(10)) { confirm in
|
||||
notificationCenter.requestAuthorizationOptionsClosure = { _ in
|
||||
confirm()
|
||||
return true
|
||||
}
|
||||
alice.actions.send(.requestAuthorization)
|
||||
}
|
||||
|
||||
#expect(notificationCenter.requestAuthorizationOptionsReceivedOptions == [.alert, .sound, .badge])
|
||||
}
|
||||
|
||||
@Test
|
||||
func grantingPermissionRegistersForRemoteNotifications() async {
|
||||
notificationCenter.authorizationStatusReturnValue = .notDetermined
|
||||
notificationManager.delegate = self
|
||||
let alice = makeService("@alice:example.com")
|
||||
notificationManager.add(alice.service)
|
||||
|
||||
await waitForConfirmation("registerForRemoteNotifications should be called", timeout: .seconds(10)) { confirm in
|
||||
registerForRemoteNotificationsDelegateCalled = { confirm() }
|
||||
alice.actions.send(.requestAuthorization)
|
||||
}
|
||||
|
||||
#expect(notificationCenter.requestAuthorizationOptionsReceivedOptions == [.alert, .sound, .badge])
|
||||
}
|
||||
|
||||
@Test
|
||||
func askingForPermissionWithEveryAccountOffDoesNothing() async throws {
|
||||
let alice = makeService("@alice:example.com", isEnabled: false)
|
||||
notificationManager.add(alice.service)
|
||||
|
||||
alice.actions.send(.requestAuthorization)
|
||||
try await Task.sleep(for: .seconds(1))
|
||||
|
||||
#expect(!notificationCenter.requestAuthorizationOptionsCalled)
|
||||
}
|
||||
|
||||
// MARK: - Badge
|
||||
|
||||
@Test
|
||||
func appBadgeSumsEveryAccount() {
|
||||
notificationManager.add(makeService("@alice:example.com", badgeCount: 3).service)
|
||||
notificationManager.add(makeService("@bob:example.com", badgeCount: 2).service)
|
||||
|
||||
#expect(appSettings.lastKnownBadgeCount == 5)
|
||||
}
|
||||
|
||||
@Test
|
||||
func appBadgeFollowsAnAccountsCount() {
|
||||
let badgeCountSubject = CurrentValueSubject<Int, Never>(3)
|
||||
let alice = makeService("@alice:example.com")
|
||||
alice.service.badgeCountPublisher = badgeCountSubject.asCurrentValuePublisher()
|
||||
notificationManager.add(alice.service)
|
||||
|
||||
badgeCountSubject.send(7)
|
||||
|
||||
#expect(appSettings.lastKnownBadgeCount == 7)
|
||||
}
|
||||
|
||||
@Test
|
||||
func appBadgeDropsARemovedAccount() {
|
||||
notificationManager.add(makeService("@alice:example.com", badgeCount: 3).service)
|
||||
notificationManager.add(makeService("@bob:example.com", badgeCount: 2).service)
|
||||
|
||||
notificationManager.remove(userID: "@bob:example.com")
|
||||
|
||||
#expect(appSettings.lastKnownBadgeCount == 3)
|
||||
}
|
||||
|
||||
@Test
|
||||
func appBadgeIsLeftAloneWithoutAnAccount() {
|
||||
appSettings.lastKnownBadgeCount = 4
|
||||
|
||||
notificationManager.remove(userID: "@alice:example.com")
|
||||
|
||||
#expect(appSettings.lastKnownBadgeCount == 4)
|
||||
#expect(!notificationCenter.setBadgeCountCalled)
|
||||
}
|
||||
|
||||
@Test
|
||||
func updatingTheAppBadge() async {
|
||||
await waitForConfirmation("The app badge should be set", timeout: .seconds(10)) { confirm in
|
||||
notificationCenter.setBadgeCountClosure = { _ in confirm() }
|
||||
notificationManager.add(makeService("@alice:example.com", badgeCount: 7).service)
|
||||
}
|
||||
|
||||
#expect(notificationCenter.setBadgeCountReceivedNewBadgeCount == 7)
|
||||
}
|
||||
|
||||
@Test
|
||||
func resettingStopsReceivingNotifications() async {
|
||||
notificationManager.delegate = self
|
||||
appSettings.lastKnownBadgeCount = 4
|
||||
|
||||
await waitForConfirmation("The app badge should be reset", timeout: .seconds(10)) { confirm in
|
||||
notificationCenter.setBadgeCountClosure = { _ in confirm() }
|
||||
notificationManager.reset()
|
||||
}
|
||||
|
||||
#expect(notificationCenter.setBadgeCountReceivedNewBadgeCount == 0)
|
||||
#expect(appSettings.lastKnownBadgeCount == 0)
|
||||
#expect(unregisterForRemoteNotificationsDelegateCalled)
|
||||
}
|
||||
|
||||
// MARK: - Delivered notifications
|
||||
|
||||
@Test
|
||||
func removingNotificationsOnlyTouchesThatAccount() async throws {
|
||||
notificationCenter.deliveredNotificationsReturnValue = try [notification("alice room", roomID: "!room:example.com", receiverID: "@alice:example.com"),
|
||||
notification("bob room", roomID: "!room:example.com", receiverID: "@bob:example.com"),
|
||||
notification("alice other", roomID: "!other:example.com", receiverID: "@alice:example.com"),
|
||||
notification("legacy room", roomID: "!room:example.com", receiverID: nil)]
|
||||
let alice = makeService("@alice:example.com")
|
||||
notificationManager.add(alice.service)
|
||||
|
||||
await waitForConfirmation("Notifications should be removed", timeout: .seconds(10)) { confirm in
|
||||
notificationCenter.removeDeliveredNotificationsWithIdentifiersClosure = { _ in confirm() }
|
||||
alice.actions.send(.removeDeliveredNotifications { $0.request.content.roomID == "!room:example.com" })
|
||||
}
|
||||
|
||||
// Notifications without a receiver weren't processed by the extension, so any account may clear them.
|
||||
#expect(notificationCenter.removeDeliveredNotificationsWithIdentifiersReceivedIdentifiers == ["alice room", "legacy room"])
|
||||
}
|
||||
|
||||
// MARK: - System
|
||||
|
||||
@Test
|
||||
func whenShowLocalNotification_notificationRequestGetsAdded() async throws {
|
||||
await notificationManager.showLocalNotification(with: "Title", subtitle: "Subtitle")
|
||||
@@ -140,81 +305,6 @@ final class NotificationManagerTests {
|
||||
#expect(delegate.isEqual(notificationManager))
|
||||
}
|
||||
|
||||
@Test
|
||||
func whenStart_requestAuthorizationCalledWithCorrectParams() async {
|
||||
await waitForConfirmation("requestAuthorization should be called", timeout: .seconds(10)) { confirm in
|
||||
notificationCenter.requestAuthorizationOptionsClosure = { _ in
|
||||
confirm()
|
||||
return true
|
||||
}
|
||||
notificationManager.requestAuthorization()
|
||||
}
|
||||
#expect(notificationCenter.requestAuthorizationOptionsReceivedOptions == [.alert, .sound, .badge])
|
||||
}
|
||||
|
||||
@Test
|
||||
func whenStartAndAuthorizationGranted_delegateCalled() async {
|
||||
authorizationStatusWasGranted = false
|
||||
notificationManager.delegate = self
|
||||
await waitForConfirmation("registerForRemoteNotifications delegate function should be called", timeout: .seconds(10)) { confirm in
|
||||
registerForRemoteNotificationsDelegateCalled = {
|
||||
confirm()
|
||||
}
|
||||
notificationManager.requestAuthorization()
|
||||
}
|
||||
#expect(authorizationStatusWasGranted)
|
||||
}
|
||||
|
||||
@Test
|
||||
func whenStartAndAuthorizedAndNotificationDisabled_registerForRemoteNotificationsNotCalled() async throws {
|
||||
appSettings.enableNotifications = false
|
||||
notificationCenter.authorizationStatusReturnValue = .authorized
|
||||
notificationManager.delegate = self
|
||||
|
||||
notificationManager.setUserSession(UserSessionMock(.init()))
|
||||
try await Task.sleep(for: .seconds(1))
|
||||
|
||||
#expect(!authorizationStatusWasGranted)
|
||||
}
|
||||
|
||||
@Test
|
||||
func whenStartAndAuthorized_registerForRemoteNotificationsCalled() async {
|
||||
appSettings.enableNotifications = true
|
||||
notificationCenter.authorizationStatusReturnValue = .authorized
|
||||
notificationManager.delegate = self
|
||||
|
||||
await waitForConfirmation("registerForRemoteNotifications delegate function should be called", timeout: .seconds(10)) { confirm in
|
||||
registerForRemoteNotificationsDelegateCalled = {
|
||||
confirm()
|
||||
}
|
||||
notificationManager.setUserSession(UserSessionMock(.init()))
|
||||
}
|
||||
|
||||
#expect(authorizationStatusWasGranted)
|
||||
}
|
||||
|
||||
@Test
|
||||
func removeDeliveredNotificationsForFullyReadRooms() async throws {
|
||||
let room = RoomSummary(room: RoomSDKMock(), id: "!room:matrix.org", settingsMode: .allMessages,
|
||||
hasUnreadMessages: false, hasUnreadMentions: false, hasUnreadNotifications: false)
|
||||
let lastMessageDate = try #require(room.lastMessageDate)
|
||||
|
||||
// Delivered after the last message was sent, which is always the case for the last message's notification.
|
||||
let readNotification = try UNNotification.with(userInfo: [NotificationConstants.UserInfoKey.roomIdentifier: room.id,
|
||||
NotificationConstants.UserInfoKey.eventDate: lastMessageDate.addingTimeInterval(0.5)],
|
||||
identifier: "read",
|
||||
date: lastMessageDate.addingTimeInterval(5))
|
||||
let newerNotification = try UNNotification.with(userInfo: [NotificationConstants.UserInfoKey.roomIdentifier: room.id,
|
||||
NotificationConstants.UserInfoKey.eventDate: lastMessageDate.addingTimeInterval(1)],
|
||||
identifier: "newer",
|
||||
date: lastMessageDate.addingTimeInterval(5))
|
||||
notificationCenter.deliveredNotificationsReturnValue = [readNotification, newerNotification]
|
||||
|
||||
await notificationManager.removeDeliveredNotificationsForFullyReadRooms([room])
|
||||
|
||||
#expect(notificationCenter.removeDeliveredNotificationsWithIdentifiersReceivedIdentifiers == ["read"])
|
||||
}
|
||||
|
||||
@Test
|
||||
func whenWillPresentNotificationsDelegateNotSet_CorrectPresentationOptionsReturned() async throws {
|
||||
let archiver = MockCoder(requiringSecureCoding: false)
|
||||
@@ -261,21 +351,19 @@ final class NotificationManagerTests {
|
||||
#expect(notificationTappedDelegateCalled)
|
||||
}
|
||||
|
||||
@Test
|
||||
func updatingAppBadgeCount() async {
|
||||
await notificationManager.updateAppBadgeCount(7)
|
||||
|
||||
#expect(notificationCenter.setBadgeCountReceivedNewBadgeCount == 7)
|
||||
#expect(appSettings.lastKnownBadgeCount == 7)
|
||||
// MARK: - Helpers
|
||||
|
||||
private func makeService(_ userID: String, isEnabled: Bool = true, badgeCount: Int = 0) -> (service: NotificationServiceMock, actions: PassthroughSubject<NotificationServiceAction, Never>) {
|
||||
let actions = PassthroughSubject<NotificationServiceAction, Never>()
|
||||
let service = NotificationServiceMock(.init(userID: userID, isEnabled: isEnabled, badgeCount: badgeCount))
|
||||
service.actionsPublisher = actions.eraseToAnyPublisher()
|
||||
return (service, actions)
|
||||
}
|
||||
|
||||
@Test
|
||||
func updatingAppBadgeCountWithoutASessionDoesNothing() async {
|
||||
notificationManager.setUserSession(nil)
|
||||
|
||||
await notificationManager.updateAppBadgeCount(7)
|
||||
|
||||
#expect(!notificationCenter.setBadgeCountCalled)
|
||||
private func notification(_ identifier: String, roomID: String, receiverID: String?) throws -> UNNotification {
|
||||
var userInfo: [AnyHashable: Any] = [NotificationConstants.UserInfoKey.roomIdentifier: roomID]
|
||||
userInfo[NotificationConstants.UserInfoKey.receiverIdentifier] = receiverID
|
||||
return try UNNotification.with(userInfo: userInfo, identifier: identifier)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -286,7 +374,7 @@ extension NotificationManagerTests: @MainActor NotificationManagerDelegate {
|
||||
}
|
||||
|
||||
func unregisterForRemoteNotifications() {
|
||||
authorizationStatusWasGranted = false
|
||||
unregisterForRemoteNotificationsDelegateCalled = true
|
||||
}
|
||||
|
||||
func shouldDisplayInAppNotification(content: UNNotificationContent) -> Bool {
|
||||
|
||||
@@ -0,0 +1,254 @@
|
||||
//
|
||||
// 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
|
||||
@testable import ElementX
|
||||
import MatrixRustSDK
|
||||
import MatrixRustSDKMocks
|
||||
import SwiftUI
|
||||
import Testing
|
||||
import UserNotifications
|
||||
|
||||
@MainActor
|
||||
final class NotificationServiceTests {
|
||||
private let clientProxy = ClientProxyMock(.init(userID: "@alice:example.com"))
|
||||
private let appSettings = AppSettings.volatile()
|
||||
private let userSettings: UserSettings
|
||||
private var actions: [NotificationServiceAction] = []
|
||||
private var cancellables = Set<AnyCancellable>()
|
||||
|
||||
init() {
|
||||
userSettings = appSettings.userSettings(for: "@alice:example.com")
|
||||
}
|
||||
|
||||
// MARK: - Pushers
|
||||
|
||||
@Test
|
||||
func registeringSetsThePusher() async throws {
|
||||
let service = makeService()
|
||||
let deviceToken = Data("1234".utf8)
|
||||
|
||||
await service.register(deviceToken: deviceToken)
|
||||
|
||||
let defaultPayload = APNSPayload(aps: APSInfo(mutableContent: 1,
|
||||
alert: APSAlert(locKey: "Notification", locArgs: [])),
|
||||
pusherNotificationClientIdentifier: nil)
|
||||
let expectedConfiguration = 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: appSettings.pusherProfileTag,
|
||||
lang: Bundle.app.preferredLocalizations.first ?? "en",
|
||||
append: false)
|
||||
#expect(clientProxy.setPusherWithReceivedInvocations == [expectedConfiguration])
|
||||
}
|
||||
|
||||
@Test
|
||||
func pushersAppendWithMultipleAccounts() async throws {
|
||||
appSettings.multiAccountEnabled = true
|
||||
let service = makeService()
|
||||
|
||||
await service.register(deviceToken: Data())
|
||||
|
||||
let configuration = try #require(clientProxy.setPusherWithReceivedInvocations.first)
|
||||
#expect(configuration.append)
|
||||
}
|
||||
|
||||
@Test
|
||||
func registeringGeneratesAndSavesTheProfileTag() async {
|
||||
appSettings.pusherProfileTag = nil
|
||||
|
||||
await makeService().register(deviceToken: Data())
|
||||
|
||||
#expect(appSettings.pusherProfileTag != nil)
|
||||
}
|
||||
|
||||
@Test
|
||||
func registeringKeepsTheSavedProfileTag() async {
|
||||
appSettings.pusherProfileTag = "12345"
|
||||
|
||||
await makeService().register(deviceToken: Data())
|
||||
|
||||
#expect(appSettings.pusherProfileTag == "12345")
|
||||
}
|
||||
|
||||
@Test
|
||||
func registeringWhileTurnedOffDeletesThePusher() async throws {
|
||||
let service = makeService(isEnabled: false)
|
||||
let deviceToken = Data("1234".utf8)
|
||||
|
||||
await service.register(deviceToken: deviceToken)
|
||||
|
||||
#expect(!clientProxy.setPusherWithCalled)
|
||||
let identifiers = try #require(clientProxy.deletePusherWithReceivedIdentifiers)
|
||||
#expect(identifiers.pushkey == deviceToken.base64EncodedString())
|
||||
#expect(identifiers.appId == appSettings.pusherAppID)
|
||||
}
|
||||
|
||||
// MARK: - Switch
|
||||
|
||||
@Test
|
||||
func turningOffDeletesThePusher() async {
|
||||
let service = makeService()
|
||||
await service.register(deviceToken: Data("1234".utf8))
|
||||
|
||||
await waitForConfirmation("The pusher should be deleted", timeout: .seconds(10)) { confirm in
|
||||
clientProxy.deletePusherWithClosure = { _ in confirm() }
|
||||
userSettings.account.enableNotifications = false
|
||||
}
|
||||
|
||||
#expect(!service.isEnabled)
|
||||
}
|
||||
|
||||
@Test
|
||||
func turningOnSetsThePusherAndAsksForPermission() async {
|
||||
let service = makeService(isEnabled: false)
|
||||
await service.register(deviceToken: Data("1234".utf8))
|
||||
|
||||
await waitForConfirmation("The pusher should be set", timeout: .seconds(10)) { confirm in
|
||||
clientProxy.setPusherWithClosure = { _ in confirm() }
|
||||
userSettings.account.enableNotifications = true
|
||||
}
|
||||
|
||||
#expect(service.isEnabled)
|
||||
#expect(isRequestAuthorization(actions.last))
|
||||
}
|
||||
|
||||
@Test
|
||||
func turningOnBeforeRegisteringOnlyAsksForPermission() {
|
||||
let service = makeService(isEnabled: false)
|
||||
|
||||
userSettings.account.enableNotifications = true
|
||||
|
||||
#expect(service.isEnabled)
|
||||
#expect(!clientProxy.setPusherWithCalled)
|
||||
#expect(isRequestAuthorization(actions.last))
|
||||
}
|
||||
|
||||
@Test
|
||||
func requestingAuthorizationAsksTheManager() {
|
||||
let service = makeService()
|
||||
|
||||
service.requestAuthorization()
|
||||
|
||||
#expect(isRequestAuthorization(actions.last))
|
||||
}
|
||||
|
||||
// MARK: - Badge
|
||||
|
||||
@Test
|
||||
func badgeCountStartsFromTheUnreadCount() {
|
||||
clientProxy.totalUnreadNotifications = 3
|
||||
|
||||
let service = makeService()
|
||||
|
||||
#expect(service.badgeCountPublisher.value == 3)
|
||||
}
|
||||
|
||||
@Test
|
||||
func roomListChangesUpdateTheBadgeCount() async throws {
|
||||
let roomListSubject = CurrentValueSubject<[RoomSummary], Never>([])
|
||||
let roomSummaryProvider = RoomSummaryProviderMock(.init())
|
||||
roomSummaryProvider.roomListPublisher = roomListSubject.asCurrentValuePublisher()
|
||||
clientProxy.staticRoomSummaryProvider = roomSummaryProvider
|
||||
let service = makeService()
|
||||
|
||||
let deferred = deferFulfillment(service.badgeCountPublisher) { $0 == 7 }
|
||||
clientProxy.totalUnreadNotifications = 7
|
||||
roomListSubject.send([])
|
||||
try await deferred.fulfill()
|
||||
}
|
||||
|
||||
// MARK: - Delivered notifications
|
||||
|
||||
@Test
|
||||
func clearingARoomOnlyMatchesThatRoom() throws {
|
||||
let service = makeService()
|
||||
|
||||
service.removeDeliveredMessageNotifications(for: "!room:example.com")
|
||||
|
||||
let rule = try #require(removalRules.last)
|
||||
#expect(try rule(notification(roomID: "!room:example.com")))
|
||||
#expect(try !rule(notification(roomID: "!other:example.com")))
|
||||
}
|
||||
|
||||
@Test
|
||||
func clearingFullyReadRoomsOnlyMatchesReadNotifications() throws {
|
||||
let room = RoomSummary(room: RoomSDKMock(), id: "!room:matrix.org", settingsMode: .allMessages,
|
||||
hasUnreadMessages: false, hasUnreadMentions: false, hasUnreadNotifications: false)
|
||||
let lastMessageDate = try #require(room.lastMessageDate)
|
||||
let service = makeService()
|
||||
|
||||
service.removeDeliveredNotificationsForFullyReadRooms([room])
|
||||
|
||||
let rule = try #require(removalRules.last)
|
||||
// Delivered after the last message was sent, which is always the case for the last message's notification.
|
||||
let readNotification = try UNNotification.with(userInfo: [NotificationConstants.UserInfoKey.roomIdentifier: room.id,
|
||||
NotificationConstants.UserInfoKey.eventDate: lastMessageDate.addingTimeInterval(0.5)],
|
||||
date: lastMessageDate.addingTimeInterval(5))
|
||||
let newerNotification = try UNNotification.with(userInfo: [NotificationConstants.UserInfoKey.roomIdentifier: room.id,
|
||||
NotificationConstants.UserInfoKey.eventDate: lastMessageDate.addingTimeInterval(1)],
|
||||
date: lastMessageDate.addingTimeInterval(5))
|
||||
#expect(rule(readNotification))
|
||||
#expect(!rule(newerNotification))
|
||||
#expect(try !rule(notification(roomID: "!other:example.com")))
|
||||
}
|
||||
|
||||
@Test
|
||||
func clearingWithoutFullyReadRoomsAsksNothing() {
|
||||
let room = RoomSummary(room: RoomSDKMock(), id: "!room:matrix.org", settingsMode: .allMessages,
|
||||
hasUnreadMessages: true, hasUnreadMentions: false, hasUnreadNotifications: true)
|
||||
let service = makeService()
|
||||
|
||||
service.removeDeliveredNotificationsForFullyReadRooms([room])
|
||||
|
||||
#expect(removalRules.isEmpty)
|
||||
}
|
||||
|
||||
@Test
|
||||
func tearingDownDeletesThePusherAndRemovesEveryNotification() async throws {
|
||||
let service = makeService()
|
||||
await service.register(deviceToken: Data())
|
||||
|
||||
await service.tearDown()
|
||||
|
||||
#expect(clientProxy.deletePusherWithCalled)
|
||||
let rule = try #require(removalRules.last)
|
||||
#expect(try rule(notification(roomID: "!any:example.com")))
|
||||
}
|
||||
|
||||
// MARK: - Helpers
|
||||
|
||||
private func makeService(isEnabled: Bool = true) -> NotificationService {
|
||||
userSettings.account.enableNotifications = isEnabled
|
||||
let service = NotificationService(clientProxy: clientProxy, userSettings: userSettings)
|
||||
service.actionsPublisher
|
||||
.sink { [weak self] action in
|
||||
self?.actions.append(action)
|
||||
}
|
||||
.store(in: &cancellables)
|
||||
return service
|
||||
}
|
||||
|
||||
private func notification(roomID: String) throws -> UNNotification {
|
||||
try UNNotification.with(userInfo: [NotificationConstants.UserInfoKey.roomIdentifier: roomID])
|
||||
}
|
||||
|
||||
private var removalRules: [(UNNotification) -> Bool] {
|
||||
actions.compactMap { action in
|
||||
guard case let .removeDeliveredNotifications(rule) = action else { return nil }
|
||||
return rule
|
||||
}
|
||||
}
|
||||
|
||||
private func isRequestAuthorization(_ action: NotificationServiceAction?) -> Bool {
|
||||
guard case .requestAuthorization = action else { return false }
|
||||
return true
|
||||
}
|
||||
}
|
||||
@@ -42,16 +42,16 @@ struct NotificationSettingsScreenViewModelTests {
|
||||
|
||||
@Test
|
||||
func enableNotifications() {
|
||||
userSettings.app.enableNotifications = false
|
||||
userSettings.account.enableNotifications = false
|
||||
context.send(viewAction: .changedEnableNotifications)
|
||||
#expect(userSettings.app.enableNotifications)
|
||||
#expect(userSettings.account.enableNotifications)
|
||||
}
|
||||
|
||||
@Test
|
||||
func disableNotifications() {
|
||||
userSettings.app.enableNotifications = true
|
||||
userSettings.account.enableNotifications = true
|
||||
context.send(viewAction: .changedEnableNotifications)
|
||||
#expect(!userSettings.app.enableNotifications)
|
||||
#expect(!userSettings.account.enableNotifications)
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -534,7 +534,6 @@ final class RoomFlowCoordinatorTests {
|
||||
appHooks: AppHooks(),
|
||||
analytics: AnalyticsServiceMock(.init()),
|
||||
userIndicatorController: UserIndicatorControllerMock(),
|
||||
notificationManager: NotificationManagerMock(),
|
||||
stateMachineFactory: StateMachineFactory())
|
||||
|
||||
roomFlowCoordinator = RoomFlowCoordinator(roomID: roomID,
|
||||
|
||||
@@ -64,7 +64,6 @@ struct RoomMembersFlowCoordinatorTests {
|
||||
appHooks: AppHooks(),
|
||||
analytics: AnalyticsServiceMock(.init()),
|
||||
userIndicatorController: UserIndicatorControllerMock(),
|
||||
notificationManager: NotificationManagerMock(),
|
||||
stateMachineFactory: stateMachineFactory)
|
||||
|
||||
let roomProxy = JoinedRoomProxyMock(.init())
|
||||
|
||||
@@ -61,7 +61,6 @@ struct UserSessionFlowCoordinatorTests {
|
||||
appHooks: AppHooks(),
|
||||
analytics: AnalyticsServiceMock(.init()),
|
||||
userIndicatorController: userIndicatorController,
|
||||
notificationManager: NotificationManagerMock(),
|
||||
stateMachineFactory: stateMachineFactory)
|
||||
|
||||
userSessionFlowCoordinator = UserSessionFlowCoordinator(isNewLogin: false,
|
||||
|
||||
@@ -12,6 +12,7 @@ import Testing
|
||||
struct UserSessionManagerTests {
|
||||
let userSessionStore = UserSessionStoreMock()
|
||||
let appSettings = AppSettings.volatile()
|
||||
let notificationManager = NotificationManagerMock()
|
||||
|
||||
@Test
|
||||
func ordersAccountsByWhenTheyWereLastSelected() {
|
||||
@@ -233,6 +234,46 @@ struct UserSessionManagerTests {
|
||||
#expect(manager.activeSession == nil)
|
||||
}
|
||||
|
||||
@Test
|
||||
func addingASessionConnectsItsNotificationService() {
|
||||
let manager = makeManager(userIDs: [])
|
||||
let alice = makeUserSession(userID: "@alice:matrix.org")
|
||||
|
||||
manager.add(alice)
|
||||
|
||||
#expect(notificationManager.addReceivedService === alice.notificationService)
|
||||
}
|
||||
|
||||
@Test
|
||||
func removingAnAccountDisconnectsItsNotificationService() {
|
||||
let manager = makeManager(userIDs: ["@alice:matrix.org"])
|
||||
manager.add(makeUserSession(userID: "@alice:matrix.org"))
|
||||
|
||||
manager.remove(userID: "@alice:matrix.org")
|
||||
|
||||
#expect(notificationManager.removeUserIDReceivedInvocations == ["@alice:matrix.org"])
|
||||
}
|
||||
|
||||
@Test
|
||||
func resettingDisconnectsEveryNotificationService() {
|
||||
let manager = makeManager(userIDs: ["@alice:matrix.org", "@bob:matrix.org"])
|
||||
manager.add(makeUserSession(userID: "@alice:matrix.org"))
|
||||
|
||||
manager.reset()
|
||||
|
||||
#expect(Set(notificationManager.removeUserIDReceivedInvocations) == ["@alice:matrix.org", "@bob:matrix.org"])
|
||||
}
|
||||
|
||||
@Test
|
||||
func aFailedRestoreDisconnectsTheAccountsNotificationService() async {
|
||||
let manager = makeManager(userIDs: ["@alice:matrix.org"])
|
||||
userSessionStore.restoreUserSessionUserIDReturnValue = .failure(.failedRestoringLogin)
|
||||
|
||||
await manager.restoreSessions { _ in } didAdd: { _ in }
|
||||
|
||||
#expect(notificationManager.removeUserIDReceivedInvocations == ["@alice:matrix.org"])
|
||||
}
|
||||
|
||||
@Test
|
||||
func resumingAndPausingReachEverySession() async {
|
||||
let manager = makeManager(userIDs: ["@alice:matrix.org", "@bob:matrix.org"])
|
||||
@@ -272,7 +313,7 @@ struct UserSessionManagerTests {
|
||||
|
||||
private func makeManager(userIDs: [String]) -> UserSessionManager {
|
||||
userSessionStore.userIDs = userIDs
|
||||
return UserSessionManager(userSessionStore: userSessionStore, appSettings: appSettings)
|
||||
return UserSessionManager(userSessionStore: userSessionStore, appSettings: appSettings, notificationManager: notificationManager)
|
||||
}
|
||||
|
||||
private func makeUserSession(userID: String) -> UserSessionMock {
|
||||
|
||||
Reference in New Issue
Block a user