Add boot detection in the NSE and use this to inform the user that there may be more notifications. (#5054)

* Add an initial implementation of the receivedWhileOfflineNotification.

* Only deliver a single receivedWhileOffline notification per boot and clarify the API.

* Add a 15-minute threshold for the receiveWhileOfflineNotification.
This commit is contained in:
Doug
2026-02-06 15:18:09 +00:00
committed by GitHub
parent bff328554a
commit 7532a792b7
11 changed files with 157 additions and 21 deletions
@@ -8,7 +8,7 @@
import Foundation
enum DataProtectionManager {
enum BootDetectionManager {
/// Detects after reboot, before unlocked state. Does this by trying to write a file to the filesystem (to the Caches directory) and read it back.
/// - Parameter containerURL: Container url to write the file.
/// - Returns: true if the state detected
@@ -34,4 +34,15 @@ enum DataProtectionManager {
}
return false
}
/// The time that the system was booted, as a Unix timestamp.
static func systemBootTime() -> TimeInterval? {
var bootTime = timeval()
var size = MemoryLayout<timeval>.size
var managementInformationBase: [Int32] = [CTL_KERN, KERN_BOOTTIME]
guard sysctl(&managementInformationBase, 2, &bootTime, &size, nil, 0) == 0 else { return nil }
return TimeInterval(bootTime.tv_sec) + TimeInterval(bootTime.tv_usec) / 1_000_000
}
}
+95 -7
View File
@@ -30,7 +30,13 @@ import UserNotifications
// notification.
class NotificationServiceExtension: UNNotificationServiceExtension {
static let receivedWhileOfflineNotificationID = "io.element.elementx.receivedWhileOfflineNotification"
private static var targetConfiguration: Target.ConfigurationResult?
private static var hasHandledFirstNotificationSinceBoot = false
private static let firstNotificationThreshold: TimeInterval = 15 * 60
private let settings: CommonSettingsProtocol = AppSettings()
private let appHooks: AppHooks
@@ -55,7 +61,7 @@ class NotificationServiceExtension: UNNotificationServiceExtension {
// the target configuration will fail. We could call exit(0) here, however with the
// notification filtering entitlement that results in the notification being discarded
// so we need to wait for the delegate method to be called and bail out there instead.
if !DataProtectionManager.isDeviceLockedAfterReboot(containerURL: URL.appGroupContainerDirectory),
if !BootDetectionManager.isDeviceLockedAfterReboot(containerURL: URL.appGroupContainerDirectory),
Self.targetConfiguration == nil {
Self.targetConfiguration = Target.nse.configure(logLevel: settings.logLevel,
traceLogPacks: settings.traceLogPacks,
@@ -72,14 +78,30 @@ class NotificationServiceExtension: UNNotificationServiceExtension {
}
private func handle(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) async {
// If we skipped configuring the target it means we can't write to the app group, so we're unlikely
// to be able to create a session (and even if we could, we would be missing the lightweightTokioRuntime),
// so instead lets deliver the default generic notification and avoid attempting to process the notification.
// If we skipped configuring the target it means we can't write to the app group, so we're unlikely to
// be able to create a session (and even if we could, we would be missing the lightweightTokioRuntime).
// Additionally, APNs servers only store the most recent notification when the device is powered off.
// So lets a) skip processing the notification and b) deliver a special "offline" notification as a workaround.
guard Self.targetConfiguration != nil else {
// MXLog isn't configured:
// swiftlint:disable:next print_deprecation
print("Device is locked after reboot, delivering the unmodified notification.")
return contentHandler(request.content)
print("Device is locked after reboot.")
if Self.hasHandledFirstNotificationSinceBoot {
return contentHandler(request.content)
} else {
Self.hasHandledFirstNotificationSinceBoot = true
deliverReceivedWhileOfflineNotification(for: request)
return contentHandler(.init())
}
}
guard !shouldDeliverReceivedWhileOfflineNotification() else {
// Don't log until the app hooks have been run:
// swiftlint:disable:next print_deprecation
print("Device is unlocked but may have missed notifications while offline.")
deliverReceivedWhileOfflineNotification(for: request)
return contentHandler(.init())
}
guard let roomID = request.content.roomID else {
@@ -149,7 +171,73 @@ class NotificationServiceExtension: UNNotificationServiceExtension {
notificationHandler?.handleTimeExpiration()
}
// MARK: - Private
// MARK: - Boot handling
/// The APNs servers only store the most recent notification when delivery fails. So when the user first boots
/// their phone we need to use some approximations to decide whether or not the first notification may potentially
/// represent more than one message. When that appears possible we replace the notification's content with the special
/// "received while offline" notification as a more prominent prompt for to the user to open the app and check all their chats.
///
/// Note that this only handles the first-boot case. When the SDK is able to compute the unread count, we should start to use the NSE,
/// remote-notifications (content-available) and background app refreshes to fetch and deliver our notifications as a more robust solution.
private func shouldDeliverReceivedWhileOfflineNotification() -> Bool {
if Self.hasHandledFirstNotificationSinceBoot {
// If we've already handled the first notification in this process there's no need to continue.
return false
}
Self.hasHandledFirstNotificationSinceBoot = true
guard let currentBootTime = BootDetectionManager.systemBootTime() else {
// There's not much we can do if the boot time is unknown, so don't show the offline notification.
return false
}
guard let lastKnownBootTime = settings.lastNotificationBootTime else {
// Assume a missing boot time indicates a fresh installation…
// So store the current boot time but let the notification through.
settings.lastNotificationBootTime = currentBootTime
return false
}
if abs(lastKnownBootTime - currentBootTime) < 1 {
return false
}
// This is the first notification since boot, store the boot time.
settings.lastNotificationBootTime = currentBootTime
// At this point it becomes a trade-off. Once the device has been powered on for a long enough amount
// of time it is a reasonable assumption that the device has now connected to a network and that any
// notification is actually new rather than having been sent whilst the device was powered off.
//
// Note: We could actually solve this by having Sygnal add a timestamp to the notification payload 🤔
if Date.now.timeIntervalSince(Date(timeIntervalSince1970: currentBootTime)) > Self.firstNotificationThreshold {
return false
} else {
return true
}
}
/// Delivers a generic notification informing the user that they have one or more new messages.
///
/// Note: it is safe to call this method multiple times as it simply replaces any existing instance of the notification
/// with a fresh copy, meaning it won't queue multiple copies but will still re-play the notification sound.
private func deliverReceivedWhileOfflineNotification(for originalRequest: UNNotificationRequest) {
// This is intended to be called before the app hooks have been run, so don't log:
// swiftlint:disable:next print_deprecation
print("Delivering the 'received while offline' notification.")
let content = UNMutableNotificationContent()
content.body = L10n.notificationReceivedWhileOfflineIos
content.badge = originalRequest.content.unreadCount as NSNumber?
content.sound = .init(named: .init("message.caf"))
let request = UNNotificationRequest(identifier: Self.receivedWhileOfflineNotificationID, content: content, trigger: nil)
UNUserNotificationCenter.current().add(request)
}
// MARK: - Logging
private var tag: String {
"[NSE][\(Unmanaged.passUnretained(self).toOpaque())][\(Unmanaged.passUnretained(Thread.current).toOpaque())][\(ProcessInfo.processInfo.processIdentifier)]"
@@ -28,6 +28,14 @@
<string>7D9E.1</string>
</array>
</dict>
<dict>
<key>NSPrivacyAccessedAPIType</key>
<string>NSPrivacyAccessedAPICategorySystemBootTime</string>
<key>NSPrivacyAccessedAPITypeReasons</key>
<array>
<string>8FFB.1</string>
</array>
</dict>
</array>
</dict>
</plist>