2020-03-24 01:28:53 +01:00
|
|
|
import UserNotifications
|
2021-10-12 07:43:30 +02:00
|
|
|
import BackgroundTasks
|
2020-12-01 09:45:42 +01:00
|
|
|
import SessionMessagingKit
|
2020-11-11 07:45:50 +01:00
|
|
|
import SignalUtilitiesKit
|
2021-10-29 07:32:50 +02:00
|
|
|
import CallKit
|
2022-02-17 04:55:32 +01:00
|
|
|
import PromiseKit
|
2020-03-24 01:28:53 +01:00
|
|
|
|
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
|
2020-12-01 09:45:42 +01:00
|
|
|
private var areVersionMigrationsComplete = false
|
|
|
|
private var contentHandler: ((UNNotificationContent) -> Void)?
|
2022-03-09 01:33:18 +01:00
|
|
|
private var request: UNNotificationRequest?
|
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"
|
2020-03-24 01:28:53 +01:00
|
|
|
|
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) {
|
2020-03-24 01:28:53 +01:00
|
|
|
self.contentHandler = contentHandler
|
2022-03-09 01:33:18 +01:00
|
|
|
self.request = request
|
|
|
|
guard let notificationContent = request.content.mutableCopy() as? UNMutableNotificationContent else { return self.completeSilenty() }
|
2020-12-01 09:45:42 +01:00
|
|
|
|
|
|
|
// Abort if the main app is running
|
2020-12-03 00:12:29 +01:00
|
|
|
var isMainAppAndActive = false
|
2020-07-31 06:20:09 +02:00
|
|
|
if let sharedUserDefaults = UserDefaults(suiteName: "group.com.loki-project.loki-messenger") {
|
2020-12-03 00:12:29 +01:00
|
|
|
isMainAppAndActive = sharedUserDefaults.bool(forKey: "isMainAppActive")
|
2020-07-31 06:20:09 +02:00
|
|
|
}
|
2021-05-05 00:47:33 +02:00
|
|
|
guard !isMainAppAndActive else { return self.completeSilenty() }
|
2020-12-01 09:45:42 +01:00
|
|
|
|
|
|
|
// Perform main setup
|
|
|
|
DispatchQueue.main.sync { self.setUpIfNecessary() { } }
|
|
|
|
|
|
|
|
// Handle the push notification
|
2020-07-28 02:25:48 +02:00
|
|
|
AppReadiness.runNowOrWhenAppDidBecomeReady {
|
2022-03-01 23:42:13 +01:00
|
|
|
let openGorupPollingPromises = self.pollForOpenGroups()
|
2022-02-17 04:55:32 +01:00
|
|
|
defer {
|
|
|
|
when(resolved: openGorupPollingPromises).done { _ in
|
|
|
|
self.completeSilenty()
|
|
|
|
}
|
|
|
|
}
|
2020-12-01 09:45:42 +01:00
|
|
|
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)
|
2020-09-22 05:54:58 +02:00
|
|
|
}
|
2022-03-21 03:55:51 +01:00
|
|
|
// HACK: It is important to use writeSync() here to avoid a race condition
|
|
|
|
// where the completeSilenty() is called before the local notification request
|
|
|
|
// is added to notification center.
|
|
|
|
Storage.writeSync { transaction in // Intentionally capture self
|
2020-12-01 09:45:42 +01:00
|
|
|
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)
|
2022-03-02 04:31:31 +01:00
|
|
|
|
2022-02-17 04:55:32 +01:00
|
|
|
// 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 {
|
2021-09-17 03:26:26 +02:00
|
|
|
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() }
|
2022-03-02 04:31:31 +01:00
|
|
|
}
|
2021-09-17 03:26:26 +02:00
|
|
|
semaphore.wait()
|
2020-12-04 00:00:06 +01:00
|
|
|
}
|
2022-03-02 04:31:31 +01:00
|
|
|
|
2021-08-04 07:57:37 +02:00
|
|
|
case let unsendRequest as UnsendRequest:
|
|
|
|
MessageReceiver.handleUnsendRequest(unsendRequest, using: transaction)
|
2021-01-22 00:28:26 +01:00
|
|
|
case let closedGroupControlMessage as ClosedGroupControlMessage:
|
2022-02-17 04:55:32 +01:00
|
|
|
MessageReceiver.handleClosedGroupControlMessage(closedGroupControlMessage, using: transaction)
|
2022-03-09 01:33:18 +01:00
|
|
|
case let callMessage as CallMessage:
|
|
|
|
MessageReceiver.handleCallMessage(callMessage, using: transaction)
|
|
|
|
guard case .preOffer = callMessage.kind else { return self.completeSilenty() }
|
|
|
|
if !SSKPreferences.areCallsEnabled {
|
|
|
|
if let sender = callMessage.sender, let thread = TSContactThread.fetch(for: sender, using: transaction), thread.hasOutgoingInteraction(with: transaction) {
|
|
|
|
let infoMessage = TSInfoMessage.from(callMessage, associatedWith: thread)
|
|
|
|
infoMessage.updateCallInfoMessage(.missed, using: transaction)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
self.handleSuccessForIncomingCall(for: callMessage, using: transaction)
|
2020-12-01 09:45:42 +01:00
|
|
|
default: break
|
|
|
|
}
|
|
|
|
} catch {
|
2021-10-12 07:43:30 +02:00
|
|
|
if let error = error as? MessageReceiver.Error, error.isRetryable {
|
|
|
|
self.handleFailure(for: notificationContent)
|
|
|
|
}
|
2020-12-01 09:45:42 +01:00
|
|
|
}
|
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
|
2022-03-09 01:33:18 +01:00
|
|
|
|
2020-12-03 05:08:29 +01:00
|
|
|
private func setUpIfNecessary(completion: @escaping () -> Void) {
|
2020-03-24 01:28:53 +01:00
|
|
|
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
|
2020-03-24 01:28:53 +01:00
|
|
|
// to process new messages.
|
2020-04-07 01:33:29 +02:00
|
|
|
guard !didPerformSetup else { return }
|
2020-03-24 01:28:53 +01:00
|
|
|
|
2020-04-07 01:33:29 +02:00
|
|
|
didPerformSetup = true
|
2020-03-24 01:28:53 +01:00
|
|
|
|
|
|
|
// 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()
|
2020-03-24 01:28:53 +01:00
|
|
|
},
|
2022-03-24 00:03:51 +01:00
|
|
|
migrationCompletion: { [weak self] _, needsConfigSync in
|
|
|
|
self?.versionMigrationsDidComplete(needsConfigSync: needsConfigSync)
|
2020-07-23 07:41:47 +02:00
|
|
|
completion()
|
2020-03-24 01:28:53 +01:00
|
|
|
}
|
|
|
|
)
|
|
|
|
|
2020-12-01 09:45:42 +01:00
|
|
|
NotificationCenter.default.addObserver(self, selector: #selector(storageIsReady), name: .StorageIsReady, object: nil)
|
2020-03-24 01:28:53 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
@objc
|
2022-03-24 00:03:51 +01:00
|
|
|
private func versionMigrationsDidComplete(needsConfigSync: Bool) {
|
2020-03-24 01:28:53 +01:00
|
|
|
AssertIsOnMainThread()
|
|
|
|
|
|
|
|
areVersionMigrationsComplete = true
|
2022-03-24 00:03:51 +01:00
|
|
|
|
|
|
|
// If we need a config sync then trigger it now
|
|
|
|
if needsConfigSync {
|
|
|
|
MessageSender.syncConfiguration(forceSyncNow: true).retainUntilComplete()
|
|
|
|
}
|
2020-03-24 01:28:53 +01:00
|
|
|
|
|
|
|
checkIsAppReady()
|
|
|
|
}
|
|
|
|
|
|
|
|
@objc
|
2020-12-03 05:08:29 +01:00
|
|
|
private func storageIsReady() {
|
2020-03-24 01:28:53 +01:00
|
|
|
AssertIsOnMainThread()
|
|
|
|
|
|
|
|
checkIsAppReady()
|
|
|
|
}
|
|
|
|
|
|
|
|
@objc
|
2020-12-03 05:08:29 +01:00
|
|
|
private func checkIsAppReady() {
|
2020-03-24 01:28:53 +01:00
|
|
|
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()
|
|
|
|
|
2020-03-24 01:28:53 +01:00
|
|
|
// 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
|
|
|
|
|
2021-12-08 07:12:17 +01:00
|
|
|
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.
|
2022-02-17 04:55:32 +01:00
|
|
|
completeSilenty()
|
2021-12-08 07:12:17 +01:00
|
|
|
}
|
|
|
|
|
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-03-24 01:28:53 +01:00
|
|
|
}
|
2021-10-12 07:43:30 +02:00
|
|
|
|
2022-03-09 01:33:18 +01:00
|
|
|
private func handleSuccessForIncomingCall(for callMessage: CallMessage, using transaction: YapDatabaseReadWriteTransaction) {
|
2021-10-29 07:32:50 +02:00
|
|
|
if #available(iOSApplicationExtension 14.5, *) {
|
2021-11-09 06:07:34 +01:00
|
|
|
if let uuid = callMessage.uuid, let caller = callMessage.sender, let timestamp = callMessage.sentTimestamp {
|
2021-11-09 06:12:08 +01:00
|
|
|
let payload: JSON = ["uuid": uuid, "caller": caller, "timestamp": timestamp]
|
2021-11-08 07:02:47 +01:00
|
|
|
CXProvider.reportNewIncomingVoIPPushPayload(payload) { error in
|
2021-11-03 05:31:50 +01:00
|
|
|
if let error = error {
|
2022-03-09 01:33:18 +01:00
|
|
|
self.handleFailureForVoIP(for: callMessage, using: transaction)
|
2022-02-14 01:21:32 +01:00
|
|
|
SNLog("Failed to notify main app of call message: \(error)")
|
2021-11-03 05:31:50 +01:00
|
|
|
} else {
|
2021-11-08 07:02:47 +01:00
|
|
|
self.completeSilenty()
|
2022-02-14 01:21:32 +01:00
|
|
|
SNLog("Successfully notified main app of call message.")
|
2021-11-03 05:31:50 +01:00
|
|
|
}
|
2021-10-29 07:32:50 +02:00
|
|
|
}
|
|
|
|
}
|
2021-11-08 07:02:47 +01:00
|
|
|
} else {
|
2022-03-09 01:33:18 +01:00
|
|
|
self.handleFailureForVoIP(for: callMessage, using: transaction)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
private func handleFailureForVoIP(for callMessage: CallMessage, using transaction: YapDatabaseReadWriteTransaction) {
|
|
|
|
let notificationContent = UNMutableNotificationContent()
|
|
|
|
notificationContent.userInfo = [ NotificationServiceExtension.isFromRemoteKey : true ]
|
|
|
|
notificationContent.title = "Session"
|
|
|
|
|
|
|
|
// Badge Number
|
|
|
|
let newBadgeNumber = CurrentAppContext().appUserDefaults().integer(forKey: "currentBadgeNumber") + 1
|
|
|
|
notificationContent.badge = NSNumber(value: newBadgeNumber)
|
|
|
|
CurrentAppContext().appUserDefaults().set(newBadgeNumber, forKey: "currentBadgeNumber")
|
|
|
|
|
|
|
|
if let sender = callMessage.sender, let contact = Storage.shared.getContact(with: sender, using: transaction) {
|
|
|
|
let senderDisplayName = contact.displayName(for: .regular) ?? sender
|
|
|
|
notificationContent.body = "\(senderDisplayName) is calling..."
|
|
|
|
} else {
|
|
|
|
notificationContent.body = "Incoming call..."
|
2021-10-29 07:32:50 +02:00
|
|
|
}
|
2022-03-09 01:33:18 +01:00
|
|
|
let identifier = self.request?.identifier ?? UUID().uuidString
|
|
|
|
let request = UNNotificationRequest(identifier: identifier, content: notificationContent, trigger: nil)
|
|
|
|
SNLog("Add remote notification request")
|
|
|
|
UNUserNotificationCenter.current().add(request)
|
2021-10-12 07:43:30 +02:00
|
|
|
}
|
2020-12-01 09:45:42 +01:00
|
|
|
|
2020-12-03 05:08:29 +01:00
|
|
|
private func handleSuccess(for content: UNMutableNotificationContent) {
|
2020-12-01 09:45:42 +01:00
|
|
|
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"
|
2020-03-24 01:28:53 +01:00
|
|
|
content.title = "Session"
|
2020-12-01 09:45:42 +01:00
|
|
|
let userInfo: [String:Any] = [ NotificationServiceExtension.isFromRemoteKey : true ]
|
2020-03-30 02:07:00 +02:00
|
|
|
content.userInfo = userInfo
|
2020-12-01 09:45:42 +01:00
|
|
|
contentHandler!(content)
|
2020-03-24 01:28:53 +01:00
|
|
|
}
|
2020-12-03 23:16:40 +01:00
|
|
|
|
2022-02-17 04:55:32 +01:00
|
|
|
// MARK: Poll for open groups
|
2022-03-01 23:42:13 +01:00
|
|
|
private func pollForOpenGroups() -> [Promise<Void>] {
|
2022-02-17 04:55:32 +01:00
|
|
|
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
|
|
|
}
|
|
|
|
}
|