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
|
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)?
|
|
|
|
private var notificationContent: UNMutableNotificationContent?
|
2020-04-07 01:33:29 +02:00
|
|
|
|
2020-12-01 09:45:42 +01:00
|
|
|
private static let isFromRemoteKey = "remote"
|
|
|
|
private static let threadIdKey = "Signal.AppNotificationsUserInfoKey.threadId"
|
2020-03-24 01:28:53 +01:00
|
|
|
|
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
|
2020-12-01 09:45:42 +01:00
|
|
|
self.notificationContent = request.content.mutableCopy() as? UNMutableNotificationContent
|
2021-07-28 08:13:43 +02:00
|
|
|
let userPublicKey = SNGeneralUtilities.getUserPublicKey()
|
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 {
|
2020-12-01 09:45:42 +01:00
|
|
|
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)
|
2020-09-22 05:54:58 +02:00
|
|
|
}
|
2020-12-01 09:45:42 +01:00
|
|
|
Storage.write { transaction in // Intentionally capture self
|
|
|
|
do {
|
|
|
|
let (message, proto) = try MessageReceiver.parse(envelopeAsData, openGroupMessageServerID: nil, using: transaction)
|
2020-12-03 23:40:58 +01:00
|
|
|
let senderPublicKey = message.sender!
|
2021-02-26 05:56:41 +01:00
|
|
|
var senderDisplayName = Storage.shared.getContact(with: senderPublicKey)?.displayName(for: .regular) ?? senderPublicKey
|
2020-12-04 00:00:06 +01:00
|
|
|
let snippet: String
|
|
|
|
var userInfo: [String:Any] = [ NotificationServiceExtension.isFromRemoteKey : true ]
|
|
|
|
switch message {
|
|
|
|
case let visibleMessage as VisibleMessage:
|
2020-12-07 01:21:24 +01:00
|
|
|
let tsIncomingMessageID = try MessageReceiver.handleVisibleMessage(visibleMessage, associatedWithProto: proto, openGroupID: nil, isBackgroundPoll: false, using: transaction)
|
2021-09-17 03:26:26 +02:00
|
|
|
guard let tsMessage = TSMessage.fetch(uniqueId: tsIncomingMessageID, transaction: transaction) else {
|
2021-05-05 00:47:33 +02:00
|
|
|
return self.completeSilenty()
|
|
|
|
}
|
2021-09-17 03:26:26 +02:00
|
|
|
let thread = tsMessage.thread(with: transaction)
|
2021-05-05 00:47:33 +02:00
|
|
|
let threadID = thread.uniqueId!
|
2020-12-04 00:00:06 +01:00
|
|
|
userInfo[NotificationServiceExtension.threadIdKey] = threadID
|
2021-09-17 03:26:26 +02:00
|
|
|
snippet = tsMessage.previewText(with: transaction).filterForDisplay?.replacingMentions(for: threadID, using: transaction)
|
2020-12-04 00:00:06 +01:00
|
|
|
?? "You've got a new message"
|
2021-09-17 03:26:26 +02:00
|
|
|
if let tsIncomingMessage = tsMessage as? TSIncomingMessage {
|
|
|
|
if thread.isMuted {
|
|
|
|
// Ignore PNs if the thread is muted
|
2021-07-28 08:13:43 +02:00
|
|
|
return self.completeSilenty()
|
|
|
|
}
|
2021-09-17 03:26:26 +02:00
|
|
|
if let thread = TSThread.fetch(uniqueId: threadID, transaction: transaction), let group = thread as? TSGroupThread,
|
|
|
|
group.groupModel.groupType == .closedGroup { // Should always be true because we don't get PNs for open groups
|
|
|
|
senderDisplayName = String(format: NotificationStrings.incomingGroupMessageTitleFormat, senderDisplayName, group.groupModel.groupName ?? MessageStrings.newGroupDefaultTitle)
|
|
|
|
if group.isOnlyNotifyingForMentions && !tsIncomingMessage.isUserMentioned {
|
|
|
|
// Ignore PNs if the group is set to only notify for mentions
|
|
|
|
return self.completeSilenty()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
// Store the notification ID for unsend requests to later cancel this notification
|
|
|
|
tsIncomingMessage.setNotificationIdentifier(request.identifier, transaction: transaction)
|
|
|
|
} else {
|
|
|
|
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
|
|
|
}
|
2021-10-19 06:11:47 +02:00
|
|
|
notificationContent.sound = OWSSounds.notificationSound(for: thread).notificationSound(isQuiet: false)
|
2021-08-04 07:57:37 +02:00
|
|
|
case let unsendRequest as UnsendRequest:
|
|
|
|
MessageReceiver.handleUnsendRequest(unsendRequest, using: transaction)
|
|
|
|
return self.completeSilenty()
|
2021-01-22 00:28:26 +01:00
|
|
|
case let closedGroupControlMessage as ClosedGroupControlMessage:
|
2020-12-04 00:00:06 +01:00
|
|
|
// TODO: We could consider actually handling the update here. Not sure if there's enough time though, seeing as though
|
|
|
|
// in some cases we need to send messages (e.g. our sender key) to a number of other users.
|
2021-01-22 00:28:26 +01:00
|
|
|
switch closedGroupControlMessage.kind {
|
2021-06-10 03:51:38 +02:00
|
|
|
case .new(_, let name, _, _, _, _): snippet = "\(senderDisplayName) added you to \(name)"
|
2021-05-05 00:47:33 +02:00
|
|
|
default: return self.completeSilenty()
|
2020-12-04 00:00:06 +01:00
|
|
|
}
|
2021-10-11 06:23:19 +02:00
|
|
|
case let callMessage as CallMessage:
|
|
|
|
MessageReceiver.handleCallMessage(callMessage, using: transaction)
|
|
|
|
notificationContent.userInfo = userInfo
|
|
|
|
notificationContent.badge = 1
|
|
|
|
notificationContent.title = "Session"
|
|
|
|
notificationContent.body = "\(senderDisplayName) is calling..."
|
2021-10-29 07:32:50 +02:00
|
|
|
return self.handleSuccessForIncomingCall(for: notificationContent, callID: callMessage.uuid!)
|
2021-05-05 00:47:33 +02:00
|
|
|
default: return self.completeSilenty()
|
2020-12-03 23:40:58 +01:00
|
|
|
}
|
2021-09-15 02:02:07 +02:00
|
|
|
if (senderPublicKey == userPublicKey) {
|
|
|
|
// Ignore PNs for messages sent by the current user
|
|
|
|
// after handling the message. Otherwise the closed
|
|
|
|
// group self-send messages won't show.
|
|
|
|
return self.completeSilenty()
|
|
|
|
}
|
2020-12-01 09:45:42 +01:00
|
|
|
notificationContent.userInfo = userInfo
|
|
|
|
notificationContent.badge = 1
|
|
|
|
let notificationsPreference = Environment.shared.preferences!.notificationPreviewType()
|
|
|
|
switch notificationsPreference {
|
|
|
|
case .namePreview:
|
|
|
|
notificationContent.title = senderDisplayName
|
2020-12-03 23:16:40 +01:00
|
|
|
notificationContent.body = snippet
|
2020-12-01 09:45:42 +01:00
|
|
|
case .nameNoPreview:
|
|
|
|
notificationContent.title = senderDisplayName
|
2021-10-15 01:02:00 +02:00
|
|
|
notificationContent.body = NotificationStrings.incomingMessageBody
|
2020-12-01 09:45:42 +01:00
|
|
|
case .noNameNoPreview:
|
|
|
|
notificationContent.title = "Session"
|
2021-10-15 01:02:00 +02:00
|
|
|
notificationContent.body = NotificationStrings.incomingMessageBody
|
2020-12-01 09:45:42 +01:00
|
|
|
default: break
|
|
|
|
}
|
2021-08-30 02:00:19 +02:00
|
|
|
self.handleSuccess(for: notificationContent)
|
2020-12-01 09:45:42 +01:00
|
|
|
} catch {
|
2021-10-12 07:43:30 +02:00
|
|
|
if let error = error as? MessageReceiver.Error, error.isRetryable {
|
|
|
|
self.handleFailure(for: notificationContent)
|
|
|
|
}
|
|
|
|
self.completeSilenty()
|
2020-12-01 09:45:42 +01:00
|
|
|
}
|
2020-08-05 08:55:55 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2020-04-07 01:33:29 +02: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: {
|
2020-11-11 21:55:24 +01:00
|
|
|
SSKEnvironment.shared.notificationsManager = NoopNotificationsManager()
|
2020-03-24 01:28:53 +01:00
|
|
|
},
|
|
|
|
migrationCompletion: { [weak self] in
|
|
|
|
self?.versionMigrationsDidComplete()
|
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
|
|
|
}
|
|
|
|
|
2020-12-03 05:08:29 +01:00
|
|
|
override public func serviceExtensionTimeWillExpire() {
|
2020-03-24 01:28:53 +01:00
|
|
|
// 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.
|
2020-12-01 09:45:42 +01:00
|
|
|
let userInfo: [String:Any] = [ NotificationServiceExtension.isFromRemoteKey : true ]
|
|
|
|
let notificationContent = self.notificationContent!
|
|
|
|
notificationContent.userInfo = userInfo
|
|
|
|
notificationContent.badge = 1
|
|
|
|
notificationContent.title = "Session"
|
2020-12-03 23:16:40 +01:00
|
|
|
notificationContent.body = "You've got a new message"
|
2020-12-01 09:45:42 +01:00
|
|
|
handleSuccess(for: notificationContent)
|
2020-03-24 01:28:53 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
@objc
|
2020-12-03 05:08:29 +01:00
|
|
|
private func versionMigrationsDidComplete() {
|
2020-03-24 01:28:53 +01:00
|
|
|
AssertIsOnMainThread()
|
|
|
|
|
|
|
|
areVersionMigrationsComplete = true
|
|
|
|
|
|
|
|
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()
|
|
|
|
}
|
|
|
|
|
2021-05-05 00:47:33 +02:00
|
|
|
private func completeSilenty() {
|
2020-12-01 09:45:42 +01:00
|
|
|
contentHandler!(.init())
|
2020-03-24 01:28:53 +01:00
|
|
|
}
|
2021-10-12 07:43:30 +02:00
|
|
|
|
2021-10-29 07:32:50 +02:00
|
|
|
private func handleSuccessForIncomingCall(for content: UNMutableNotificationContent, callID: String) {
|
2021-10-12 07:43:30 +02:00
|
|
|
// TODO: poll for the real offer, play incoming call ring
|
2021-10-29 07:32:50 +02:00
|
|
|
if #available(iOSApplicationExtension 14.5, *) {
|
|
|
|
CXProvider.reportNewIncomingVoIPPushPayload(["uuid": callID]) { error in
|
|
|
|
if let error = error {
|
|
|
|
owsFailDebug("Failed to notify main app of call message: \(error)")
|
|
|
|
} else {
|
|
|
|
Logger.info("Successfully notified main app of call message.")
|
|
|
|
}
|
|
|
|
self.contentHandler!(content)
|
|
|
|
}
|
|
|
|
}
|
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
|
|
|
|
|
|
|
private extension String {
|
|
|
|
|
|
|
|
func replacingMentions(for threadID: String, using transaction: YapDatabaseReadWriteTransaction) -> String {
|
|
|
|
MentionsManager.populateUserPublicKeyCacheIfNeeded(for: threadID, in: transaction)
|
|
|
|
var result = self
|
2021-08-03 06:25:10 +02:00
|
|
|
let regex = try! NSRegularExpression(pattern: "@[0-9a-fA-F]{66}", options: [])
|
2020-12-03 23:16:40 +01:00
|
|
|
let knownPublicKeys = MentionsManager.userPublicKeyCache[threadID] ?? []
|
|
|
|
var mentions: [(range: NSRange, publicKey: String)] = []
|
|
|
|
var m0 = regex.firstMatch(in: result, options: .withoutAnchoringBounds, range: NSRange(location: 0, length: result.utf16.count))
|
|
|
|
while let m1 = m0 {
|
|
|
|
let publicKey = String((result as NSString).substring(with: m1.range).dropFirst()) // Drop the @
|
|
|
|
var matchEnd = m1.range.location + m1.range.length
|
|
|
|
if knownPublicKeys.contains(publicKey) {
|
2021-02-26 05:56:41 +01:00
|
|
|
let displayName = Storage.shared.getContact(with: publicKey)?.displayName(for: .regular)
|
2020-12-03 23:16:40 +01:00
|
|
|
if let displayName = displayName {
|
|
|
|
result = (result as NSString).replacingCharacters(in: m1.range, with: "@\(displayName)")
|
|
|
|
mentions.append((range: NSRange(location: m1.range.location, length: displayName.utf16.count + 1), publicKey: publicKey)) // + 1 to include the @
|
|
|
|
matchEnd = m1.range.location + displayName.utf16.count
|
|
|
|
}
|
|
|
|
}
|
|
|
|
m0 = regex.firstMatch(in: result, options: .withoutAnchoringBounds, range: NSRange(location: matchEnd, length: result.utf16.count - matchEnd))
|
|
|
|
}
|
|
|
|
return result
|
|
|
|
}
|
|
|
|
}
|