Files
element-x-ios/NSE/Sources/NotificationHandler.swift
T
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

272 lines
13 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 CallKit
import MatrixRustSDK
import Synchronization
import UserNotifications
nonisolated class NotificationHandler {
private let userSession: NSEUserSession
private let contentHandler: (UNNotificationContent) -> Void
private var notificationContent: UNMutableNotificationContent
private let tag: String
private let notificationContentBuilder: NotificationContentBuilder
/// Whether this handler has already counted its notification towards the app icon badge.
private var hasCountedTowardsBadge = false
private var userSettings: UserSettings {
userSession.userSettings
}
init(userSession: NSEUserSession,
contentHandler: @escaping (UNNotificationContent) -> Void,
notificationContent: UNMutableNotificationContent,
tag: String) {
self.userSession = userSession
self.contentHandler = contentHandler
self.notificationContent = notificationContent
self.tag = tag
let eventStringBuilder = RoomMessageEventStringBuilder(attributedStringBuilder: AttributedStringBuilder(mentionBuilder: PlainMentionBuilder()),
style: .plain)
notificationContentBuilder = NotificationContentBuilder(messageEventStringBuilder: eventStringBuilder,
userSession: userSession)
}
func processEvent(_ eventID: String, roomID: String) async {
MXLog.info("\(tag) Processing event: \(eventID) in room: \(roomID)")
// The pusher of an account with its notifications off can outlive a failed deletion.
guard userSettings.account.enableNotifications else {
MXLog.error("\(tag) Received a push for an account with notifications off, discarding.")
discardNotification()
return
}
guard let notificationItemProxy = await userSession.notificationItemProxy(roomID: roomID, eventID: eventID) else {
MXLog.error("\(tag) Failed retrieving notification item")
discardNotification()
return
}
switch await preprocessNotification(notificationItemProxy) {
case .processedShouldDiscard, .unsupportedShouldDiscard:
discardNotification()
case .shouldDisplay:
if userSettings.app.hideQuietNotificationAlerts, !notificationItemProxy.isNoisy {
discardNotification()
return
}
await notificationContentBuilder.process(notificationContent: &notificationContent,
notificationItem: notificationItemProxy,
mediaProvider: userSession.mediaProvider)
deliverNotification()
}
}
func handleTimeExpiration() {
// Called just before the extension will be terminated by the system.
// Use this as an opportunity to deliver your "best attempt" at modified content
MXLog.info("\(tag) Extension time will expire")
deliverNotification()
}
// MARK: - Private
private func deliverNotification() {
notificationContent.badge = NSNumber(value: incrementBadgeCount())
MXLog.info("\(tag) Delivering notification, new badge value: \(userSettings.app.lastKnownBadgeCount)")
contentHandler(notificationContent)
}
private func incrementBadgeCount() -> Int {
// `handleTimeExpiration` can deliver a notification this handler already delivered.
guard !hasCountedTowardsBadge else {
return userSettings.app.lastKnownBadgeCount
}
hasCountedTowardsBadge = true
userSettings.app.lastKnownBadgeCount += 1
return userSettings.app.lastKnownBadgeCount
}
private func discardNotification() {
MXLog.info("\(tag) Discarding notification")
let content = UNMutableNotificationContent()
// Nothing new is shown to the user, so leave the badge where the app last put it.
content.badge = NSNumber(value: userSettings.app.lastKnownBadgeCount)
MXLog.info("\(tag) New badge value: \(content.badge?.stringValue ?? "nil")")
contentHandler(content)
}
private func preprocessNotification(_ itemProxy: NotificationItemProxyProtocol) async -> NotificationProcessingResult {
guard case let .timeline(event) = itemProxy.event else {
return .shouldDisplay
}
switch try? event.content() {
case .messageLike(let messageContent):
switch messageContent {
case .poll,
.roomEncrypted,
.sticker:
return .shouldDisplay
case .roomMessage(let messageType, _):
switch messageType {
case .emote, .image, .audio, .video, .file, .notice, .text, .location, .gallery:
return .shouldDisplay
case .other:
return .unsupportedShouldDiscard
}
case .roomRedaction(let redactedEventID, _):
guard let redactedEventID else {
MXLog.error("Unable to handle redact notification due to missing event ID")
return .processedShouldDiscard
}
let deliveredNotifications = await UNUserNotificationCenter.current().deliveredNotifications()
if let targetNotification = deliveredNotifications.first(where: { $0.request.content.eventID == redactedEventID }) {
UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: [targetNotification.request.identifier])
userSettings.app.lastKnownBadgeCount = max(0, userSettings.app.lastKnownBadgeCount - 1)
}
return .processedShouldDiscard
case .rtcNotification(let notificationType, let expirationTimestamp, let callIntent):
return await handleCallNotification(notificationType: notificationType,
rtcNotifyEventID: event.eventId(),
timestamp: event.timestamp(),
expirationTimestamp: expirationTimestamp,
roomID: itemProxy.roomID,
roomDisplayName: itemProxy.roomDisplayName,
callIntent: callIntent)
case .callAnswer,
.callInvite,
.callHangup,
.callCandidates,
.keyVerificationReady,
.keyVerificationStart,
.keyVerificationCancel,
.keyVerificationAccept,
.keyVerificationKey,
.keyVerificationMac,
.keyVerificationDone,
.reactionContent,
.beacon:
return .unsupportedShouldDiscard
}
case .state(let stateContent):
switch stateContent {
case .beaconInfo:
return .shouldDisplay
default:
return .unsupportedShouldDiscard
}
case .none:
return .unsupportedShouldDiscard
}
}
/// Handle incoming call notifications.
/// - Returns: A boolean indicating whether the notification was handled and should now be discarded.
private func handleCallNotification(notificationType: RtcNotificationType,
rtcNotifyEventID: String,
timestamp: Timestamp,
expirationTimestamp: Timestamp,
roomID: String,
roomDisplayName: String, callIntent: RtcCallIntent?) async -> NotificationProcessingResult {
// Handle incoming VoIP calls, show the native OS call screen
// https://developer.apple.com/documentation/callkit/sending-end-to-end-encrypted-voip-calls
//
// The way this works is the following:
// - the NSE receives the notification and decrypts it
// - checks if it's still time relevant (max 10 seconds old) and whether it should ring
// - otherwise it goes on to show it as a normal notification
// - if it should ring then it discards the notification but invokes `reportNewIncomingVoIPPushPayload`
// so that the main app can handle it
// - the main app picks this up in `PKPushRegistry.didReceiveIncomingPushWith` and
// `CXProvider.reportNewIncomingCall` to show the system UI and handle actions on it.
// N.B. this flow works properly only when background processing capabilities are enabled
guard notificationType == .ring else {
MXLog.info("Non-ringing call notification, handling as push notification")
return .shouldDisplay
}
// Check to see if a call is still ongoing
if let room = userSession.roomForIdentifier(roomID) { // Try to get call details from the room info
if !room.hasActiveRoomCall() { // If I don't have an active call wait a bit and make sure
// Local `Mutex` holder for the SDK subscription token — keeps it alive across the
// await without needing `[weak self]`, which would force this class to be `Sendable`.
let observationToken = Mutex<TaskHandle?>(nil)
let expiringTask = ExpiringTaskRunner {
await withCheckedContinuation { (continuation: CheckedContinuation<Void, Never>) in
observationToken.withLock { state in
state = room.subscribeToRoomInfoUpdates(listener: SDKListener { info in
if info.hasRoomCall {
MXLog.info("Received room info update and the room has an active call now.")
continuation.resume()
} else {
MXLog.info("Received a room info update but the room still doesn't have an ongoing call.")
}
})
}
}
}
try? await expiringTask.run(timeout: Duration.seconds(5)) // Wait 5 seconds or just use whatever is available
// Release the SDK subscription explicitly once we no longer need updates.
observationToken.withLock { $0 = nil }
guard room.hasActiveRoomCall() else {
MXLog.info("The room no longer has an ongoing call, handling as push notification")
return .shouldDisplay
}
}
} else { // Otherwise fallback to the old timeout mechanism
let timestamp = Date(timeIntervalSince1970: TimeInterval(timestamp / 1000))
guard abs(timestamp.timeIntervalSinceNow) < ElementCallServiceNotificationDiscardDelta else {
MXLog.info("Call notification is too old, handling as push notification")
return .shouldDisplay
}
}
let expirationDate = Date(timeIntervalSince1970: TimeInterval(expirationTimestamp / 1000))
let payload = [ElementCallServiceNotificationKey.roomID.rawValue: roomID,
ElementCallServiceNotificationKey.roomDisplayName.rawValue: roomDisplayName,
ElementCallServiceNotificationKey.expirationDate.rawValue: expirationDate,
ElementCallServiceNotificationKey.rtcNotifyEventID.rawValue: rtcNotifyEventID,
ElementCallServiceNotificationKey.isVoiceCall.rawValue: callIntent == RtcCallIntent.audio] as [String: Any]
do {
try await CXProvider.reportNewIncomingVoIPPushPayload(payload)
MXLog.info("Call notification delegated to CallKit")
} catch {
MXLog.error("Failed reporting voip call with error: \(error). Handling as push notification")
return .shouldDisplay
}
return .processedShouldDiscard
}
private enum NotificationProcessingResult {
case shouldDisplay
case processedShouldDiscard
case unsupportedShouldDiscard
}
}