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:
Mauro
2026-10-15 13:10:26 +02:00
committed by GitHub
parent 09ecec4306
commit 268d6c8ead
45 changed files with 1233 additions and 501 deletions
@@ -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> {