Files
element-x-ios/ElementX/Sources/Screens/Settings/NotificationSettingsScreen/NotificationSettingsScreenViewModel.swift
Mauro 268d6c8ead 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.
2026-10-15 13:10:26 +02:00

323 lines
16 KiB
Swift

//
// Copyright 2025 Element Creations Ltd.
// Copyright 2022-2025 New Vector 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 SwiftUI
typealias NotificationSettingsScreenViewModelType = StateStoreViewModelV2<NotificationSettingsScreenViewState, NotificationSettingsScreenViewAction>
class NotificationSettingsScreenViewModel: NotificationSettingsScreenViewModelType, NotificationSettingsScreenViewModelProtocol {
private var actionsSubject: PassthroughSubject<NotificationSettingsScreenViewModelAction, Never> = .init()
private let userSettings: UserSettings
private let userNotificationCenter: UserNotificationCenterProtocol
private let notificationSettingsProxy: NotificationSettingsProxyProtocol
private let userIndicatorController: UserIndicatorControllerProtocol
@CancellableTask private var fetchSettingsTask: Task<Void, Error>?
private let notificationTonePreviewer: AudioPlayerProtocol
private let notificationToneManager: NotificationToneManagerProtocol
var actions: AnyPublisher<NotificationSettingsScreenViewModelAction, Never> {
actionsSubject.eraseToAnyPublisher()
}
init(userSettings: UserSettings,
userNotificationCenter: UserNotificationCenterProtocol,
notificationToneManager: NotificationToneManagerProtocol,
notificationSettingsProxy: NotificationSettingsProxyProtocol,
userIndicatorController: UserIndicatorControllerProtocol,
isModallyPresented: Bool) {
self.userSettings = userSettings
self.userNotificationCenter = userNotificationCenter
self.notificationSettingsProxy = notificationSettingsProxy
self.userIndicatorController = userIndicatorController
notificationTonePreviewer = AudioPlayer()
self.notificationToneManager = notificationToneManager
let bindings = NotificationSettingsScreenViewStateBindings(enableNotifications: userSettings.account.enableNotifications,
showAllRoomListActivity: userSettings.account.showAllRoomListActivity)
super.init(initialViewState: NotificationSettingsScreenViewState(bindings: bindings,
isModallyPresented: isModallyPresented,
selectedAlertTone: userSettings.account.selectedNotificationTone ?? userSettings.account.defaultNotificationTone.publisher.value,
availableCustomTones: notificationToneManager.customTones(),
// macos lacks default sounds and its sandbox Sounds directory is immutable
customToneSelectionEnabled: !ProcessInfo.processInfo.isiOSAppOnMac))
// Listen for changes to UserSettings.
userSettings.account.enableNotificationsPublisher
.weakAssign(to: \.state.bindings.enableNotifications, on: self)
.store(in: &cancellables)
userSettings.account.selectedNotificationTonePublisher
.map { $0 ?? userSettings.account.defaultNotificationTone.publisher.value }
.weakAssign(to: \.state.selectedAlertTone, on: self)
.store(in: &cancellables)
setupDidBecomeActiveSubscription()
setupNotificationSettingsSubscription()
notificationTonePreviewer.actions
.receive(on: DispatchQueue.main)
.sink { action in
guard case .didFailWithError(let error) = action else {
return
}
let userIndicator = UserIndicator(type: .toast,
title: L10n.screenNotificationSettingsSoundPreviewSoundErrorTitle)
userIndicatorController.submitIndicator(userIndicator)
MXLog.error("Error previewing alert tone: \(error)")
}
.store(in: &cancellables)
}
func fetchInitialContent() {
fetchSettings()
}
// MARK: - Public
override func process(viewAction: NotificationSettingsScreenViewAction) {
switch viewAction {
case .changedEnableNotifications:
toggleNotifications()
case .groupChatsTapped:
actionsSubject.send(.editDefaultMode(chatType: .groupChat))
case .directChatsTapped:
actionsSubject.send(.editDefaultMode(chatType: .oneToOneChat))
case .roomMentionChanged:
guard let settings = state.settings, settings.roomMentionsEnabled != state.bindings.roomMentionsEnabled else {
return
}
Task { await enableRoomMention(state.bindings.roomMentionsEnabled) }
case .callsChanged:
guard let settings = state.settings, settings.callsEnabled != state.bindings.callsEnabled else {
return
}
Task { await enableCalls(state.bindings.callsEnabled) }
case .invitationsChanged:
guard let settings = state.settings, settings.invitationsEnabled != state.bindings.invitationsEnabled else {
return
}
Task { await enableInvitations(state.bindings.invitationsEnabled) }
case .showAllRoomListActivityChanged:
userSettings.account.showAllRoomListActivity = state.bindings.showAllRoomListActivity
case .close:
actionsSubject.send(.close)
case .fixConfigurationMismatchTapped:
Task { await fixConfigurationMismatch() }
case .selectAlertTone(let alertTone):
setSelectedTone(alertTone)
case .addedCustomAlertTone(let result):
Task {
await self.addCustomAlertTone(from: result)
}
case .deleteCustomAlertTones(let tones):
deleteAlertTones(tones)
}
}
// MARK: - Private
func readSystemAuthorizationStatus() async {
state.isUserPermissionGranted = await userNotificationCenter.authorizationStatus() == .authorized
}
func toggleNotifications() {
userSettings.account.enableNotifications.toggle()
}
private func setupDidBecomeActiveSubscription() {
// Refresh authorization status uppon UIApplication.didBecomeActiveNotification notification
NotificationCenter.default.publisher(for: UIApplication.didBecomeActiveNotification)
.sink { [weak self] _ in
Task {
await self?.readSystemAuthorizationStatus()
}
}
.store(in: &cancellables)
Task {
await readSystemAuthorizationStatus()
}
}
private func setupNotificationSettingsSubscription() {
notificationSettingsProxy.callbacks
.receive(on: DispatchQueue.main)
.sink { [weak self] callback in
guard let self else { return }
switch callback {
case .settingsDidChange:
self.fetchSettings()
}
}
.store(in: &cancellables)
}
private func fetchSettings() {
fetchSettingsTask = Task {
var inconsistentSettings: [NotificationSettingsScreenInvalidSetting] = []
// Group chats
var groupChatsMode = await notificationSettingsProxy.getDefaultRoomNotificationMode(isEncrypted: false, isOneToOne: false)
let encryptedGroupChatsMode = await notificationSettingsProxy.getDefaultRoomNotificationMode(isEncrypted: true, isOneToOne: false)
// Direct chats
var directChatsMode = await notificationSettingsProxy.getDefaultRoomNotificationMode(isEncrypted: false, isOneToOne: true)
let encryptedDirectChatsMode = await notificationSettingsProxy.getDefaultRoomNotificationMode(isEncrypted: true, isOneToOne: true)
// Old clients were having specific settings for encrypted and unencrypted rooms,
// so it's possible for `group chats` and `direct chats` settings to be inconsistent (e.g. encrypted `direct chats` can have a different mode that unencrypted `direct chats`)
if groupChatsMode != encryptedGroupChatsMode {
groupChatsMode = .allMessages
// a default setting for a chat can only be `.allMessages` or `.mentionsAndKeywordsOnly`.
inconsistentSettings.append(.init(chatType: .groupChat, isEncrypted: encryptedGroupChatsMode != .allMessages))
}
if directChatsMode != encryptedDirectChatsMode {
directChatsMode = .allMessages
// a default setting for a chat can only be `.allMessages` or `.mentionsAndKeywordsOnly`.
inconsistentSettings.append(.init(chatType: .oneToOneChat, isEncrypted: encryptedDirectChatsMode != .allMessages))
}
// The following calls may fail if the associated push rule doesn't exist
let roomMentionsEnabled = try? await notificationSettingsProxy.isRoomMentionEnabled()
let callEnabled = try? await notificationSettingsProxy.isCallEnabled()
let invitationsEnabled = try? await notificationSettingsProxy.isInviteForMeEnabled()
guard !Task.isCancelled else { return }
let notificationSettings = NotificationSettingsScreenSettings(groupChatsMode: groupChatsMode,
directChatsMode: directChatsMode,
roomMentionsEnabled: roomMentionsEnabled,
callsEnabled: callEnabled,
invitationsEnabled: invitationsEnabled,
inconsistentSettings: inconsistentSettings)
state.settings = notificationSettings
state.bindings.roomMentionsEnabled = notificationSettings.roomMentionsEnabled ?? false
state.bindings.callsEnabled = notificationSettings.callsEnabled ?? false
state.bindings.invitationsEnabled = notificationSettings.invitationsEnabled ?? false
}
}
private func fixConfigurationMismatch() async {
guard let settings = state.settings, !settings.inconsistentSettings.isEmpty, !state.fixingConfigurationMismatch else { return }
state.fixingConfigurationMismatch = true
var failures: [NotificationSettingsScreenInvalidSetting] = []
for inconsistentSetting in settings.inconsistentSettings {
do {
try await notificationSettingsProxy.setDefaultRoomNotificationMode(isEncrypted: inconsistentSetting.isEncrypted, isOneToOne: inconsistentSetting.chatType == .oneToOneChat, mode: .allMessages)
} catch {
failures.append(inconsistentSetting)
}
}
if !failures.isEmpty {
state.bindings.alertInfo = AlertInfo(id: .fixMismatchConfigurationFailed,
title: L10n.commonError,
message: L10n.screenNotificationSettingsFailedFixingConfiguration,
primaryButton: .init(title: L10n.actionOk, action: nil))
}
state.fixingConfigurationMismatch = false
}
private func enableRoomMention(_ enable: Bool) async {
guard let notificationSettings = state.settings else { return }
do {
state.applyingChange = true
MXLog.info("setRoomMentionEnabled(\(enable))")
try await notificationSettingsProxy.setRoomMentionEnabled(enabled: enable)
} catch {
state.bindings.alertInfo = AlertInfo(id: .alert)
state.bindings.roomMentionsEnabled = notificationSettings.roomMentionsEnabled ?? false
}
state.applyingChange = false
}
func enableCalls(_ enable: Bool) async {
guard let notificationSettings = state.settings else { return }
do {
state.applyingChange = true
MXLog.info("setCallEnabled(\(enable))")
try await notificationSettingsProxy.setCallEnabled(enabled: enable)
} catch {
state.bindings.alertInfo = AlertInfo(id: .alert)
state.bindings.callsEnabled = notificationSettings.callsEnabled ?? false
}
state.applyingChange = false
}
func enableInvitations(_ enable: Bool) async {
guard let notificationSettings = state.settings else { return }
do {
state.applyingChange = true
MXLog.info("setInviteForMeEnabled(\(enable))")
try await notificationSettingsProxy.setInviteForMeEnabled(enabled: enable)
} catch {
state.bindings.alertInfo = AlertInfo(id: .alert)
state.bindings.callsEnabled = notificationSettings.invitationsEnabled ?? false
}
state.applyingChange = false
}
/// Imports the audio file at the given sandboxed URL into the tone library, refreshing the available custom tones on success.
private func addCustomAlertTone(from urlResult: Result<URL, Error>) async {
do {
let url = try urlResult.get()
guard url.startAccessingSecurityScopedResource() else {
throw NotificationToneManager.ManagerError.couldNotAccessSandboxedResource
}
defer { url.stopAccessingSecurityScopedResource() }
try await notificationToneManager.addNewToneToLibrary(from: url)
state.availableCustomTones = notificationToneManager.customTones()
} catch {
MXLog.error("Error importing custom tone url: \(error)")
userIndicatorController.submitIndicator(.init(type: .toast,
title: L10n.screenNotificationSettingsSoundImportSoundErrorTitle))
}
}
private func setSelectedTone(_ alertTone: NotificationTone) {
do {
let toneLocation = try notificationToneManager.setSelectedTone(alertTone)
notificationTonePreviewer.load(sourceURL: toneLocation, playbackURL: toneLocation, autoplay: true)
MXLog.info("Successfully set selected tone: \(alertTone.label)")
} catch {
let userIndicator = UserIndicator(type: .toast,
title: L10n.screenNotificationSettingsSoundSetSoundErrorTitle)
userIndicatorController.submitIndicator(userIndicator)
MXLog.error("Error setting selected alert tone to designated location in filesystem: \(error)")
}
}
/// Deletes the given tones from the library. If the active tone is deleted, the selection resets to the default.
private func deleteAlertTones(_ tones: [NotificationTone]) {
for tone in tones {
do {
try notificationToneManager.deleteCustomTone(tone)
if tone == state.selectedAlertTone {
userSettings.account.selectedNotificationTone = nil
}
} catch {
MXLog.error("Error deleting alert tone \(tone.label): \(error)")
userIndicatorController.submitIndicator(.init(type: .toast,
title: L10n.screenNotificationSettingsSoundDeleteSoundErrorTitle))
}
}
state.availableCustomTones = notificationToneManager.customTones()
MXLog.info("Successfully deleted custom tone(s): \(tones.map(\.label))")
}
}
extension UNUserNotificationCenter {
func authorizationStatus() async -> UNAuthorizationStatus {
await notificationSettings().authorizationStatus
}
}