session-ios/SessionNotificationServiceExtension/NotificationServiceExtension.swift

191 lines
8.3 KiB
Swift
Raw Normal View History

import UserNotifications
import SessionMessagingKit
2020-11-11 07:45:50 +01:00
import SignalUtilitiesKit
2022-02-17 04:55:32 +01:00
import PromiseKit
2020-12-03 05:08:29 +01:00
public final class NotificationServiceExtension : UNNotificationServiceExtension {
2020-04-07 01:33:29 +02:00
private var didPerformSetup = false
private var areVersionMigrationsComplete = false
private var contentHandler: ((UNNotificationContent) -> Void)?
private var notificationContent: UNMutableNotificationContent?
2020-04-07 01:33:29 +02:00
2022-02-17 04:55:32 +01:00
public static let isFromRemoteKey = "remote"
public static let threadIdKey = "Signal.AppNotificationsUserInfoKey.threadId"
2022-02-17 04:55:32 +01:00
// MARK: Did receive a remote push notification request
2020-12-03 05:08:29 +01:00
override public func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
self.contentHandler = contentHandler
self.notificationContent = request.content.mutableCopy() as? UNMutableNotificationContent
// Abort if the main app is running
2020-12-03 00:12:29 +01:00
var isMainAppAndActive = false
if let sharedUserDefaults = UserDefaults(suiteName: "group.com.loki-project.loki-messenger") {
2020-12-03 00:12:29 +01:00
isMainAppAndActive = sharedUserDefaults.bool(forKey: "isMainAppActive")
}
2021-05-05 00:47:33 +02:00
guard !isMainAppAndActive else { return self.completeSilenty() }
// Perform main setup
DispatchQueue.main.sync { self.setUpIfNecessary() { } }
// Handle the push notification
2020-07-28 02:25:48 +02:00
AppReadiness.runNowOrWhenAppDidBecomeReady {
2022-02-17 04:55:32 +01:00
let openGorupPollingPromises = self.pollForOpneGorups()
defer {
when(resolved: openGorupPollingPromises).done { _ in
self.completeSilenty()
}
}
let notificationContent = self.notificationContent!
guard let base64EncodedData = notificationContent.userInfo["ENCRYPTED_DATA"] as! String?, let data = Data(base64Encoded: base64EncodedData),
let envelope = try? MessageWrapper.unwrap(data: data), let envelopeAsData = try? envelope.serializedData() else {
return self.handleFailure(for: notificationContent)
}
Storage.write { transaction in // Intentionally capture self
do {
let (message, proto) = try MessageReceiver.parse(envelopeAsData, openGroupMessageServerID: nil, using: transaction)
2020-12-04 00:00:06 +01:00
switch message {
case let visibleMessage as VisibleMessage:
2022-02-17 04:55:32 +01:00
let tsMessageID = try MessageReceiver.handleVisibleMessage(visibleMessage, associatedWithProto: proto, openGroupID: nil, isBackgroundPoll: false, using: transaction)
// Remove the notificaitons if there is an outgoing messages from a linked device
if let tsMessage = TSMessage.fetch(uniqueId: tsMessageID, transaction: transaction), tsMessage.isKind(of: TSOutgoingMessage.self), let threadID = tsMessage.thread(with: transaction).uniqueId {
let semaphore = DispatchSemaphore(value: 0)
let center = UNUserNotificationCenter.current()
center.getDeliveredNotifications { notifications in
let matchingNotifications = notifications.filter({ $0.request.content.userInfo[NotificationServiceExtension.threadIdKey] as? String == threadID})
center.removeDeliveredNotifications(withIdentifiers: matchingNotifications.map({ $0.request.identifier }))
// Hack: removeDeliveredNotifications seems to be async,need to wait for some time before the delivered notifications can be removed.
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { semaphore.signal() }
}
semaphore.wait()
2020-12-04 00:00:06 +01:00
}
2022-02-17 04:55:32 +01:00
2021-08-04 07:57:37 +02:00
case let unsendRequest as UnsendRequest:
MessageReceiver.handleUnsendRequest(unsendRequest, using: transaction)
case let closedGroupControlMessage as ClosedGroupControlMessage:
2022-02-17 04:55:32 +01:00
MessageReceiver.handleClosedGroupControlMessage(closedGroupControlMessage, using: transaction)
default: break
}
} catch {
2021-10-15 00:27:45 +02:00
if let error = error as? MessageReceiver.Error, error.isRetryable {
self.handleFailure(for: notificationContent)
}
}
2020-08-05 08:55:55 +02:00
}
}
}
2020-04-07 01:33:29 +02:00
2022-02-17 04:55:32 +01:00
// MARK: Setup
2020-12-03 05:08:29 +01:00
private func setUpIfNecessary(completion: @escaping () -> Void) {
AssertIsOnMainThread()
// The NSE will often re-use the same process, so if we're
2020-04-07 01:33:29 +02:00
// already set up we want to do nothing; we're already ready
// to process new messages.
2020-04-07 01:33:29 +02:00
guard !didPerformSetup else { return }
2020-04-07 01:33:29 +02:00
didPerformSetup = true
// This should be the first thing we do.
SetCurrentAppContext(NotificationServiceExtensionContext())
_ = AppVersion.sharedInstance()
Cryptography.seedRandom()
// We should never receive a non-voip notification on an app that doesn't support
// app extensions since we have to inform the service we wanted these, so in theory
// this path should never occur. However, the service does have our push token
// so it is possible that could change in the future. If it does, do nothing
// and don't disturb the user. Messages will be processed when they open the app.
guard OWSPreferences.isReadyForAppExtensions() else { return completeSilenty() }
AppSetup.setupEnvironment(
appSpecificSingletonBlock: {
2022-02-17 04:55:32 +01:00
SSKEnvironment.shared.notificationsManager = NSENotificationPresenter()
},
migrationCompletion: { [weak self] in
self?.versionMigrationsDidComplete()
2020-07-23 07:41:47 +02:00
completion()
}
)
NotificationCenter.default.addObserver(self, selector: #selector(storageIsReady), name: .StorageIsReady, object: nil)
}
@objc
2020-12-03 05:08:29 +01:00
private func versionMigrationsDidComplete() {
AssertIsOnMainThread()
areVersionMigrationsComplete = true
checkIsAppReady()
}
@objc
2020-12-03 05:08:29 +01:00
private func storageIsReady() {
AssertIsOnMainThread()
checkIsAppReady()
}
@objc
2020-12-03 05:08:29 +01:00
private func checkIsAppReady() {
AssertIsOnMainThread()
// Only mark the app as ready once.
guard !AppReadiness.isAppReady() else { return }
// App isn't ready until storage is ready AND all version migrations are complete.
guard OWSStorage.isStorageReady() && areVersionMigrationsComplete else { return }
2020-12-02 06:46:12 +01:00
SignalUtilitiesKit.Configuration.performMainSetup()
// Note that this does much more than set a flag; it will also run all deferred blocks.
AppReadiness.setAppIsReady()
}
2022-02-17 04:55:32 +01:00
// MARK: Handle completion
override public 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.
completeSilenty()
}
2021-05-05 00:47:33 +02:00
private func completeSilenty() {
2022-02-17 04:55:32 +01:00
SNLog("Complete silenty")
self.contentHandler!(.init())
}
2020-12-03 05:08:29 +01:00
private func handleSuccess(for content: UNMutableNotificationContent) {
contentHandler!(content)
}
2020-12-03 05:08:29 +01:00
private func handleFailure(for content: UNMutableNotificationContent) {
2020-12-03 23:16:40 +01:00
content.body = "You've got a new message"
content.title = "Session"
let userInfo: [String:Any] = [ NotificationServiceExtension.isFromRemoteKey : true ]
content.userInfo = userInfo
contentHandler!(content)
}
2020-12-03 23:16:40 +01:00
2022-02-17 04:55:32 +01:00
// MARK: Poll for open groups
private func pollForOpneGorups() -> [Promise<Void>] {
var promises: [Promise<Void>] = []
let servers = Set(Storage.shared.getAllV2OpenGroups().values.map { $0.server })
servers.forEach { server in
let poller = OpenGroupPollerV2(for: server)
let promise = poller.poll().timeout(seconds: 20, timeoutError: NotificationServiceError.timeout)
promises.append(promise)
2020-12-03 23:16:40 +01:00
}
2022-02-17 04:55:32 +01:00
return promises
}
private enum NotificationServiceError: Error {
case timeout
2020-12-03 23:16:40 +01:00
}
}