From 37865bab966e2e9c0cf0ca15f4dd335abfbbcdd8 Mon Sep 17 00:00:00 2001 From: gmbnt Date: Tue, 7 Apr 2020 09:33:29 +1000 Subject: [PATCH] Minor refactoring --- .../NotificationService.swift | 62 +++++++++---------- SignalServiceKit/src/Loki/API/LokiAPI.swift | 1 + .../LokiPushNotificationManager.swift | 23 ++++--- .../src/Messages/OWSMessageManager.m | 4 -- .../OWSPrimaryStorage+SessionStore.m | 5 +- SignalServiceKit/src/Util/FeatureFlags.swift | 5 -- 6 files changed, 43 insertions(+), 57 deletions(-) diff --git a/LokiPushNotificationService/NotificationService.swift b/LokiPushNotificationService/NotificationService.swift index e8959d747..d105fe087 100644 --- a/LokiPushNotificationService/NotificationService.swift +++ b/LokiPushNotificationService/NotificationService.swift @@ -2,10 +2,12 @@ import UserNotifications import SignalServiceKit import SignalMessaging -class NotificationService: UNNotificationServiceExtension { - - static let threadIdKey = "Signal.AppNotificationsUserInfoKey.threadId" +final class NotificationService : UNNotificationServiceExtension { static let isFromRemoteKey = "remote" + static let threadIdKey = "Signal.AppNotificationsUserInfoKey.threadId" + + private var didPerformSetup = false + var areVersionMigrationsComplete = false var contentHandler: ((UNNotificationContent) -> Void)? var notificationContent: UNMutableNotificationContent? @@ -14,7 +16,7 @@ class NotificationService: UNNotificationServiceExtension { self.contentHandler = contentHandler notificationContent = (request.content.mutableCopy() as? UNMutableNotificationContent) - DispatchQueue.main.sync { self.setupIfNecessary() } + DispatchQueue.main.sync { self.setUpIfNecessary() } if let notificationContent = notificationContent { // Modify the notification content here... @@ -24,31 +26,33 @@ class NotificationService: UNNotificationServiceExtension { let envelopeData = try? envelope?.serializedData() let decrypter = SSKEnvironment.shared.messageDecrypter if (envelope != nil && envelopeData != nil) { - decrypter.decryptEnvelope(envelope!, envelopeData: envelopeData!, - successBlock: { result,transaction in - if (try? SSKProtoEnvelope.parseData(result.envelopeData)) != nil { - self.handelDecryptionResult(result: result, notificationContent: notificationContent, transaction: transaction) - } else { - self.completeWithFailure(content: notificationContent) - } - }, + decrypter.decryptEnvelope(envelope!, + envelopeData: envelopeData!, + successBlock: { result, transaction in + if (try? SSKProtoEnvelope.parseData(result.envelopeData)) != nil { + self.handleDecryptionResult(result: result, notificationContent: notificationContent, transaction: transaction) + } else { + self.completeWithFailure(content: notificationContent) + } + }, failureBlock: { - self.completeWithFailure(content: notificationContent) - }) + self.completeWithFailure(content: notificationContent) + } + ) } else { self.completeWithFailure(content: notificationContent) } } } - func handelDecryptionResult(result: OWSMessageDecryptResult, notificationContent: UNMutableNotificationContent, transaction: YapDatabaseReadWriteTransaction) { + func handleDecryptionResult(result: OWSMessageDecryptResult, notificationContent: UNMutableNotificationContent, transaction: YapDatabaseReadWriteTransaction) { let contentProto = try? SSKProtoContent.parseData(result.plaintextData!) var thread: TSThread var newNotificationBody = "" - let masterHexEncodedPublicKey: String = OWSPrimaryStorage.shared().getMasterHexEncodedPublicKey(for: result.source, in: transaction) ?? result.source + let masterHexEncodedPublicKey = OWSPrimaryStorage.shared().getMasterHexEncodedPublicKey(for: result.source, in: transaction) ?? result.source var displayName = masterHexEncodedPublicKey - if let groupId = contentProto?.dataMessage?.group?.id { - thread = TSGroupThread.getOrCreateThread(withGroupId: groupId, groupType: .closedGroup, transaction: transaction) + if let groupID = contentProto?.dataMessage?.group?.id { + thread = TSGroupThread.getOrCreateThread(withGroupId: groupID, groupType: .closedGroup, transaction: transaction) displayName = thread.name() if displayName.count < 1 { displayName = MessageStrings.newGroupDefaultTitle @@ -79,8 +83,7 @@ class NotificationService: UNNotificationServiceExtension { thread = TSContactThread.getOrCreateThread(withContactId: result.source, transaction: transaction) displayName = contentProto?.dataMessage?.profile?.displayName ?? displayName } - let userInfo: [String: Any] = [NotificationService.threadIdKey: thread.uniqueId!, - NotificationService.isFromRemoteKey: true] + let userInfo: [String:Any] = [ NotificationService.threadIdKey : thread.uniqueId!, NotificationService.isFromRemoteKey : true ] notificationContent.title = displayName notificationContent.userInfo = userInfo notificationContent.badge = 1 @@ -94,17 +97,16 @@ class NotificationService: UNNotificationServiceExtension { self.contentHandler!(notificationContent) } } - - private var hasSetup = false - func setupIfNecessary() { + + func setUpIfNecessary() { AssertIsOnMainThread() // The NSE will often re-use the same process, so if we're - // already setup we want to do nothing. We're already ready + // already set up we want to do nothing; we're already ready // to process new messages. - guard !hasSetup else { return } + guard !didPerformSetup else { return } - hasSetup = true + didPerformSetup = true // This should be the first thing we do. SetCurrentAppContext(NotificationServiceExtensionContext()) @@ -142,9 +144,6 @@ class NotificationService: UNNotificationServiceExtension { selector: #selector(storageIsReady), name: .StorageIsReady, object: nil) - - Logger.info("completed.") - } override func serviceExtensionTimeWillExpire() { @@ -191,8 +190,6 @@ class NotificationService: UNNotificationServiceExtension { // Note that this does much more than set a flag; it will also run all deferred blocks. AppReadiness.setAppIsReady() - -// AppVersion.sharedInstance().nseLaunchDidComplete() } func completeSilenty() { @@ -202,9 +199,8 @@ class NotificationService: UNNotificationServiceExtension { func completeWithFailure(content: UNMutableNotificationContent) { content.body = "You've got a new message." content.title = "Session" - let userInfo: [String: Any] = [NotificationService.isFromRemoteKey: true] + let userInfo: [String:Any] = [NotificationService.isFromRemoteKey : true] content.userInfo = userInfo contentHandler?(content) } - } diff --git a/SignalServiceKit/src/Loki/API/LokiAPI.swift b/SignalServiceKit/src/Loki/API/LokiAPI.swift index 58b70507f..6ae7dfbbf 100644 --- a/SignalServiceKit/src/Loki/API/LokiAPI.swift +++ b/SignalServiceKit/src/Loki/API/LokiAPI.swift @@ -269,6 +269,7 @@ public final class LokiAPI : NSObject { private static func updateLastMessageHashValueIfPossible(for target: LokiAPITarget, from rawMessages: [JSON]) { if let lastMessage = rawMessages.last, let hashValue = lastMessage["hash"] as? String, let expirationDate = lastMessage["expiration"] as? Int { setLastMessageHashValue(for: target, hashValue: hashValue, expirationDate: UInt64(expirationDate)) + // FIXME: Move this out of here if UserDefaults.standard[.isUsingFullAPNs] { LokiPushNotificationManager.acknowledgeDelivery(forMessageWithHash: hashValue, expiration: expirationDate, hexEncodedPublicKey: userHexEncodedPublicKey) } diff --git a/SignalServiceKit/src/Loki/Utilities/LokiPushNotificationManager.swift b/SignalServiceKit/src/Loki/Utilities/LokiPushNotificationManager.swift index b13a3fafb..946c2ef1d 100644 --- a/SignalServiceKit/src/Loki/Utilities/LokiPushNotificationManager.swift +++ b/SignalServiceKit/src/Loki/Utilities/LokiPushNotificationManager.swift @@ -1,3 +1,4 @@ + @objc(LKPushNotificationManager) final class LokiPushNotificationManager : NSObject { @@ -13,8 +14,8 @@ final class LokiPushNotificationManager : NSObject { private override init() { } // MARK: Registration - /** This method is for users to register for Silent Push Notification. - We only need the device token to make the SPN work.*/ + /// Registers the user for silent push notifications (that then trigger the app + /// into fetching messages). Only the user's device token is needed for this. @objc(registerWithToken:) static func register(with token: Data) { let hexEncodedToken = token.toHexString() @@ -47,9 +48,9 @@ final class LokiPushNotificationManager : NSObject { print("[Loki] Couldn't register device token.") }) } - - /** This method is for users to register for Normal Push Notification. - We need the device token and user's public key (session id) to make the NPN work.*/ + + /// Registers the user for normal push notifications. Requires the user's device + /// token and their Session ID. @objc(registerWithToken:hexEncodedPublicKey:) static func register(with token: Data, hexEncodedPublicKey: String) { let hexEncodedToken = token.toHexString() @@ -75,22 +76,20 @@ final class LokiPushNotificationManager : NSObject { } @objc(acknowledgeDeliveryForMessageWithHash:expiration:hexEncodedPublicKey:) - static func acknowledgeDelivery(forMessageWithHash hash: String, expiration:Int, hexEncodedPublicKey: String) { - let parameters: JSON = [ "lastHash" : hash, - "pubKey" : hexEncodedPublicKey, - "expiration": expiration] + static func acknowledgeDelivery(forMessageWithHash hash: String, expiration: Int, hexEncodedPublicKey: String) { + let parameters: JSON = [ "lastHash" : hash, "pubKey" : hexEncodedPublicKey, "expiration" : expiration] let url = URL(string: server + "acknowledge_message_delivery")! let request = TSRequest(url: url, method: "POST", parameters: parameters) request.allHTTPHeaderFields = [ "Content-Type" : "application/json" ] TSNetworkManager.shared().makeRequest(request, success: { _, response in guard let json = response as? JSON else { - return print("[Loki] Couldn't acknowledge the delivery for message with last hash: " + hash) + return print("[Loki] Couldn't acknowledge delivery for message with hash: \(hash).") } guard json["code"] as? Int != 0 else { - return print("[Loki] Couldn't acknowledge the delivery for message due to error: \(json["message"] as? String ?? "nil").") + return print("[Loki] Couldn't acknowledge delivery for message with hash: \(hash) due to error: \(json["message"] as? String ?? "nil").") } }, failure: { _, error in - print("[Loki] Couldn't acknowledge the delivery for message with last hash: " + hash) + print("[Loki] Couldn't acknowledge delivery for message with hash: \(hash).") }) } } diff --git a/SignalServiceKit/src/Messages/OWSMessageManager.m b/SignalServiceKit/src/Messages/OWSMessageManager.m index 23c507c53..9fef16f6f 100644 --- a/SignalServiceKit/src/Messages/OWSMessageManager.m +++ b/SignalServiceKit/src/Messages/OWSMessageManager.m @@ -255,10 +255,6 @@ NS_ASSUME_NONNULL_BEGIN OWSFailDebug(@"Not registered."); return; } -// if (!CurrentAppContext().isMainApp) { -// OWSFail(@"Not the main app."); -// return; -// } OWSLogInfo(@"Handling decrypted envelope: %@.", [self descriptionForEnvelope:envelope]); diff --git a/SignalServiceKit/src/Storage/AxolotlStore/OWSPrimaryStorage+SessionStore.m b/SignalServiceKit/src/Storage/AxolotlStore/OWSPrimaryStorage+SessionStore.m index ef0d28cf9..568ff7742 100644 --- a/SignalServiceKit/src/Storage/AxolotlStore/OWSPrimaryStorage+SessionStore.m +++ b/SignalServiceKit/src/Storage/AxolotlStore/OWSPrimaryStorage+SessionStore.m @@ -88,9 +88,8 @@ NSString *const kSessionStoreDBConnectionKey = @"kSessionStoreDBConnectionKey"; OWSAssertDebug(contactIdentifier.length > 0); OWSAssertDebug(deviceId >= 0); OWSAssertDebug([protocolContext isKindOfClass:[YapDatabaseReadWriteTransaction class]]); - if (!CurrentAppContext().isMainApp) { - return; - } + // TODO: Needs a comment from Ryan + if (!CurrentAppContext().isMainApp) { return; } YapDatabaseReadWriteTransaction *transaction = protocolContext; diff --git a/SignalServiceKit/src/Util/FeatureFlags.swift b/SignalServiceKit/src/Util/FeatureFlags.swift index e8595dd26..0d78affd1 100644 --- a/SignalServiceKit/src/Util/FeatureFlags.swift +++ b/SignalServiceKit/src/Util/FeatureFlags.swift @@ -29,9 +29,4 @@ public class FeatureFlags: NSObject { public static var useCustomPhotoCapture: Bool { return true } - - @objc - public static var notificationServiceExtension: Bool { - return true - } }