Minor refactoring

This commit is contained in:
gmbnt 2020-04-07 09:33:29 +10:00
parent 0555578d68
commit 37865bab96
6 changed files with 43 additions and 57 deletions

View File

@ -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)
}
}

View File

@ -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)
}

View File

@ -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).")
})
}
}

View File

@ -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]);

View File

@ -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;

View File

@ -29,9 +29,4 @@ public class FeatureFlags: NSObject {
public static var useCustomPhotoCapture: Bool {
return true
}
@objc
public static var notificationServiceExtension: Bool {
return true
}
}