Beam/NSE/Sources/NotificationServiceExtension.swift

150 lines
5.8 KiB
Swift
Raw Normal View History

2022-11-21 19:37:13 +03:00
//
// Copyright 2022 New Vector Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Intents
import MatrixRustSDK
import UserNotifications
class NotificationServiceExtension: UNNotificationServiceExtension {
private let settings = NSESettings()
Pill View (#1797) * provider can now check the current session * More testable code * created the test condition * it works but not always not sure why, need to dig deeper * sadly we need to use textkit 1 to solve this issue * removed developer option screen test * this experimental solution kinda works but I need a way to pill recomputation is weird * format * display improvement * better and faster solution * pilished the code * better coloring * swift format * just need to solve the caching issue * fix caching issue * tests done! * changelog * pr comments addressed * all pr comments addressed * docs * line lenght * updated tests and fixed a parsing permalink issue * MentionBuilder * pr comments * swiftformat * code blocks should not have links * Update ElementX/Sources/FlowCoordinators/RoomFlowCoordinator.swift Co-authored-by: Doug <6060466+pixlwave@users.noreply.github.com> * Update ElementX/Sources/Services/Client/ClientProxy.swift Co-authored-by: Doug <6060466+pixlwave@users.noreply.github.com> * Update UnitTests/Sources/AttributedStringBuilderTests.swift Co-authored-by: Doug <6060466+pixlwave@users.noreply.github.com> * Update ElementX/Sources/UITests/UITestsAppCoordinator.swift Co-authored-by: Doug <6060466+pixlwave@users.noreply.github.com> * Update ElementX/Sources/Other/Pills/PillAttachmentViewProvider.swift Co-authored-by: Doug <6060466+pixlwave@users.noreply.github.com> * Update ElementX/Sources/Other/Pills/MentionBuilder.swift Co-authored-by: Doug <6060466+pixlwave@users.noreply.github.com> * pr comments * swiftformat --------- Co-authored-by: Doug <6060466+pixlwave@users.noreply.github.com>
2023-09-27 19:27:07 +02:00
private let notificationContentBuilder = NotificationContentBuilder(messageEventStringBuilder: RoomMessageEventStringBuilder(attributedStringBuilder: AttributedStringBuilder(permalinkBaseURL: .homeDirectory, mentionBuilder: NSEMentionBuilder())))
2022-11-21 19:37:13 +03:00
private lazy var keychainController = KeychainController(service: .sessions,
accessGroup: InfoPlistReader.main.keychainAccessGroupIdentifier)
private var handler: ((UNNotificationContent) -> Void)?
private var modifiedContent: UNMutableNotificationContent?
private var userSession: NSEUserSession?
2022-11-21 19:37:13 +03:00
override func didReceive(_ request: UNNotificationRequest,
withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
guard !DataProtectionManager.isDeviceLockedAfterReboot(containerURL: URL.appGroupContainerDirectory),
let roomId = request.roomId,
let eventId = request.eventId,
let clientID = request.pusherNotificationClientIdentifier,
let credentials = keychainController.restorationTokens().first(where: { $0.restorationToken.pusherNotificationClientIdentifier == clientID }) else {
2022-11-21 19:37:13 +03:00
// We cannot process this notification, it might be due to one of these:
// - Device rebooted and locked
// - Not a Matrix notification
// - User is not signed in
// - NotificationID could not be resolved
2022-11-21 19:37:13 +03:00
return contentHandler(request.content)
}
handler = contentHandler
modifiedContent = request.content.mutableCopy() as? UNMutableNotificationContent
NSELogger.configure()
NSELogger.logMemory(with: tag)
MXLog.info("\(tag) #########################################")
MXLog.info("\(tag) Payload came: \(request.content.userInfo)")
2022-11-21 19:37:13 +03:00
Task {
await run(with: credentials,
roomId: roomId,
eventId: eventId,
unreadCount: request.unreadCount)
2022-11-21 19:37:13 +03:00
}
}
override func serviceExtensionTimeWillExpire() {
// Called just before the extension will be terminated by the system.
// Use this as an opportunity to deliver your "best attempt" at modified content, otherwise the original push payload will be used.
MXLog.warning("\(tag) serviceExtensionTimeWillExpire")
2022-11-21 19:37:13 +03:00
notify()
}
private func run(with credentials: KeychainCredentials,
roomId: String,
eventId: String,
unreadCount: Int?) async {
MXLog.info("\(tag) run with roomId: \(roomId), eventId: \(eventId)")
2022-11-21 19:37:13 +03:00
do {
let userSession = try NSEUserSession(credentials: credentials, clientSessionDelegate: keychainController)
self.userSession = userSession
guard let itemProxy = await userSession.notificationItemProxy(roomID: roomId, eventID: eventId) else {
MXLog.info("\(tag) no notification for the event, discard")
return discard()
}
// After the first processing, update the modified content
modifiedContent = try await notificationContentBuilder.content(for: itemProxy, mediaProvider: nil)
guard itemProxy.hasMedia else {
MXLog.info("\(tag) no media needed")
2022-11-21 19:37:13 +03:00
// We've processed the item and no media operations needed, so no need to go further
return notify()
}
2022-11-21 19:37:13 +03:00
MXLog.info("\(tag) process with media")
2022-11-21 19:37:13 +03:00
// There is some media to load, process it again
if let latestContent = try? await notificationContentBuilder.content(for: itemProxy, mediaProvider: userSession.mediaProvider) {
// Processing finished, hopefully with some media
modifiedContent = latestContent
}
// We still notify, but without the media attachment if it fails to load
// Finally update the app badge
if let unreadCount {
modifiedContent?.badge = NSNumber(value: unreadCount)
}
2022-11-21 19:37:13 +03:00
return notify()
} catch {
MXLog.error("NSE run error: \(error)")
2022-11-21 19:37:13 +03:00
return discard()
}
}
2022-11-21 19:37:13 +03:00
private func notify() {
MXLog.info("\(tag) notify")
2022-11-21 19:37:13 +03:00
guard let modifiedContent else {
MXLog.info("\(tag) notify: no modified content")
return discard()
2022-11-21 19:37:13 +03:00
}
2022-11-21 19:37:13 +03:00
handler?(modifiedContent)
cleanUp()
2022-11-21 19:37:13 +03:00
}
private func discard() {
MXLog.info("\(tag) discard")
2022-11-21 19:37:13 +03:00
handler?(UNMutableNotificationContent())
cleanUp()
2022-11-21 19:37:13 +03:00
}
private var tag: String {
"[NSE][\(Unmanaged.passUnretained(self).toOpaque())][\(Unmanaged.passUnretained(Thread.current).toOpaque())]"
}
private func cleanUp() {
handler = nil
modifiedContent = nil
}
2022-11-21 19:37:13 +03:00
deinit {
cleanUp()
2022-11-21 19:37:13 +03:00
NSELogger.logMemory(with: tag)
MXLog.info("\(tag) deinit")
2022-11-21 19:37:13 +03:00
}
}