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 SignalServiceKit
import SignalMessaging import SignalMessaging
class NotificationService: UNNotificationServiceExtension { final class NotificationService : UNNotificationServiceExtension {
static let threadIdKey = "Signal.AppNotificationsUserInfoKey.threadId"
static let isFromRemoteKey = "remote" static let isFromRemoteKey = "remote"
static let threadIdKey = "Signal.AppNotificationsUserInfoKey.threadId"
private var didPerformSetup = false
var areVersionMigrationsComplete = false var areVersionMigrationsComplete = false
var contentHandler: ((UNNotificationContent) -> Void)? var contentHandler: ((UNNotificationContent) -> Void)?
var notificationContent: UNMutableNotificationContent? var notificationContent: UNMutableNotificationContent?
@ -14,7 +16,7 @@ class NotificationService: UNNotificationServiceExtension {
self.contentHandler = contentHandler self.contentHandler = contentHandler
notificationContent = (request.content.mutableCopy() as? UNMutableNotificationContent) notificationContent = (request.content.mutableCopy() as? UNMutableNotificationContent)
DispatchQueue.main.sync { self.setupIfNecessary() } DispatchQueue.main.sync { self.setUpIfNecessary() }
if let notificationContent = notificationContent { if let notificationContent = notificationContent {
// Modify the notification content here... // Modify the notification content here...
@ -24,31 +26,33 @@ class NotificationService: UNNotificationServiceExtension {
let envelopeData = try? envelope?.serializedData() let envelopeData = try? envelope?.serializedData()
let decrypter = SSKEnvironment.shared.messageDecrypter let decrypter = SSKEnvironment.shared.messageDecrypter
if (envelope != nil && envelopeData != nil) { if (envelope != nil && envelopeData != nil) {
decrypter.decryptEnvelope(envelope!, envelopeData: envelopeData!, decrypter.decryptEnvelope(envelope!,
successBlock: { result,transaction in envelopeData: envelopeData!,
if (try? SSKProtoEnvelope.parseData(result.envelopeData)) != nil { successBlock: { result, transaction in
self.handelDecryptionResult(result: result, notificationContent: notificationContent, transaction: transaction) if (try? SSKProtoEnvelope.parseData(result.envelopeData)) != nil {
} else { self.handleDecryptionResult(result: result, notificationContent: notificationContent, transaction: transaction)
self.completeWithFailure(content: notificationContent) } else {
} self.completeWithFailure(content: notificationContent)
}, }
},
failureBlock: { failureBlock: {
self.completeWithFailure(content: notificationContent) self.completeWithFailure(content: notificationContent)
}) }
)
} else { } else {
self.completeWithFailure(content: notificationContent) 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!) let contentProto = try? SSKProtoContent.parseData(result.plaintextData!)
var thread: TSThread var thread: TSThread
var newNotificationBody = "" 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 var displayName = masterHexEncodedPublicKey
if let groupId = contentProto?.dataMessage?.group?.id { if let groupID = contentProto?.dataMessage?.group?.id {
thread = TSGroupThread.getOrCreateThread(withGroupId: groupId, groupType: .closedGroup, transaction: transaction) thread = TSGroupThread.getOrCreateThread(withGroupId: groupID, groupType: .closedGroup, transaction: transaction)
displayName = thread.name() displayName = thread.name()
if displayName.count < 1 { if displayName.count < 1 {
displayName = MessageStrings.newGroupDefaultTitle displayName = MessageStrings.newGroupDefaultTitle
@ -79,8 +83,7 @@ class NotificationService: UNNotificationServiceExtension {
thread = TSContactThread.getOrCreateThread(withContactId: result.source, transaction: transaction) thread = TSContactThread.getOrCreateThread(withContactId: result.source, transaction: transaction)
displayName = contentProto?.dataMessage?.profile?.displayName ?? displayName displayName = contentProto?.dataMessage?.profile?.displayName ?? displayName
} }
let userInfo: [String: Any] = [NotificationService.threadIdKey: thread.uniqueId!, let userInfo: [String:Any] = [ NotificationService.threadIdKey : thread.uniqueId!, NotificationService.isFromRemoteKey : true ]
NotificationService.isFromRemoteKey: true]
notificationContent.title = displayName notificationContent.title = displayName
notificationContent.userInfo = userInfo notificationContent.userInfo = userInfo
notificationContent.badge = 1 notificationContent.badge = 1
@ -94,17 +97,16 @@ class NotificationService: UNNotificationServiceExtension {
self.contentHandler!(notificationContent) self.contentHandler!(notificationContent)
} }
} }
private var hasSetup = false func setUpIfNecessary() {
func setupIfNecessary() {
AssertIsOnMainThread() AssertIsOnMainThread()
// The NSE will often re-use the same process, so if we're // 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. // to process new messages.
guard !hasSetup else { return } guard !didPerformSetup else { return }
hasSetup = true didPerformSetup = true
// This should be the first thing we do. // This should be the first thing we do.
SetCurrentAppContext(NotificationServiceExtensionContext()) SetCurrentAppContext(NotificationServiceExtensionContext())
@ -142,9 +144,6 @@ class NotificationService: UNNotificationServiceExtension {
selector: #selector(storageIsReady), selector: #selector(storageIsReady),
name: .StorageIsReady, name: .StorageIsReady,
object: nil) object: nil)
Logger.info("completed.")
} }
override func serviceExtensionTimeWillExpire() { 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. // Note that this does much more than set a flag; it will also run all deferred blocks.
AppReadiness.setAppIsReady() AppReadiness.setAppIsReady()
// AppVersion.sharedInstance().nseLaunchDidComplete()
} }
func completeSilenty() { func completeSilenty() {
@ -202,9 +199,8 @@ class NotificationService: UNNotificationServiceExtension {
func completeWithFailure(content: UNMutableNotificationContent) { func completeWithFailure(content: UNMutableNotificationContent) {
content.body = "You've got a new message." content.body = "You've got a new message."
content.title = "Session" content.title = "Session"
let userInfo: [String: Any] = [NotificationService.isFromRemoteKey: true] let userInfo: [String:Any] = [NotificationService.isFromRemoteKey : true]
content.userInfo = userInfo content.userInfo = userInfo
contentHandler?(content) contentHandler?(content)
} }
} }

View File

@ -269,6 +269,7 @@ public final class LokiAPI : NSObject {
private static func updateLastMessageHashValueIfPossible(for target: LokiAPITarget, from rawMessages: [JSON]) { 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 { 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)) setLastMessageHashValue(for: target, hashValue: hashValue, expirationDate: UInt64(expirationDate))
// FIXME: Move this out of here
if UserDefaults.standard[.isUsingFullAPNs] { if UserDefaults.standard[.isUsingFullAPNs] {
LokiPushNotificationManager.acknowledgeDelivery(forMessageWithHash: hashValue, expiration: expirationDate, hexEncodedPublicKey: userHexEncodedPublicKey) LokiPushNotificationManager.acknowledgeDelivery(forMessageWithHash: hashValue, expiration: expirationDate, hexEncodedPublicKey: userHexEncodedPublicKey)
} }

View File

@ -1,3 +1,4 @@
@objc(LKPushNotificationManager) @objc(LKPushNotificationManager)
final class LokiPushNotificationManager : NSObject { final class LokiPushNotificationManager : NSObject {
@ -13,8 +14,8 @@ final class LokiPushNotificationManager : NSObject {
private override init() { } private override init() { }
// MARK: Registration // MARK: Registration
/** This method is for users to register for Silent Push Notification. /// Registers the user for silent push notifications (that then trigger the app
We only need the device token to make the SPN work.*/ /// into fetching messages). Only the user's device token is needed for this.
@objc(registerWithToken:) @objc(registerWithToken:)
static func register(with token: Data) { static func register(with token: Data) {
let hexEncodedToken = token.toHexString() let hexEncodedToken = token.toHexString()
@ -47,9 +48,9 @@ final class LokiPushNotificationManager : NSObject {
print("[Loki] Couldn't register device token.") print("[Loki] Couldn't register device token.")
}) })
} }
/** This method is for users to register for Normal Push Notification. /// Registers the user for normal push notifications. Requires the user's device
We need the device token and user's public key (session id) to make the NPN work.*/ /// token and their Session ID.
@objc(registerWithToken:hexEncodedPublicKey:) @objc(registerWithToken:hexEncodedPublicKey:)
static func register(with token: Data, hexEncodedPublicKey: String) { static func register(with token: Data, hexEncodedPublicKey: String) {
let hexEncodedToken = token.toHexString() let hexEncodedToken = token.toHexString()
@ -75,22 +76,20 @@ final class LokiPushNotificationManager : NSObject {
} }
@objc(acknowledgeDeliveryForMessageWithHash:expiration:hexEncodedPublicKey:) @objc(acknowledgeDeliveryForMessageWithHash:expiration:hexEncodedPublicKey:)
static func acknowledgeDelivery(forMessageWithHash hash: String, expiration:Int, hexEncodedPublicKey: String) { static func acknowledgeDelivery(forMessageWithHash hash: String, expiration: Int, hexEncodedPublicKey: String) {
let parameters: JSON = [ "lastHash" : hash, let parameters: JSON = [ "lastHash" : hash, "pubKey" : hexEncodedPublicKey, "expiration" : expiration]
"pubKey" : hexEncodedPublicKey,
"expiration": expiration]
let url = URL(string: server + "acknowledge_message_delivery")! let url = URL(string: server + "acknowledge_message_delivery")!
let request = TSRequest(url: url, method: "POST", parameters: parameters) let request = TSRequest(url: url, method: "POST", parameters: parameters)
request.allHTTPHeaderFields = [ "Content-Type" : "application/json" ] request.allHTTPHeaderFields = [ "Content-Type" : "application/json" ]
TSNetworkManager.shared().makeRequest(request, success: { _, response in TSNetworkManager.shared().makeRequest(request, success: { _, response in
guard let json = response as? JSON else { 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 { 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 }, 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."); OWSFailDebug(@"Not registered.");
return; return;
} }
// if (!CurrentAppContext().isMainApp) {
// OWSFail(@"Not the main app.");
// return;
// }
OWSLogInfo(@"Handling decrypted envelope: %@.", [self descriptionForEnvelope:envelope]); OWSLogInfo(@"Handling decrypted envelope: %@.", [self descriptionForEnvelope:envelope]);

View File

@ -88,9 +88,8 @@ NSString *const kSessionStoreDBConnectionKey = @"kSessionStoreDBConnectionKey";
OWSAssertDebug(contactIdentifier.length > 0); OWSAssertDebug(contactIdentifier.length > 0);
OWSAssertDebug(deviceId >= 0); OWSAssertDebug(deviceId >= 0);
OWSAssertDebug([protocolContext isKindOfClass:[YapDatabaseReadWriteTransaction class]]); OWSAssertDebug([protocolContext isKindOfClass:[YapDatabaseReadWriteTransaction class]]);
if (!CurrentAppContext().isMainApp) { // TODO: Needs a comment from Ryan
return; if (!CurrentAppContext().isMainApp) { return; }
}
YapDatabaseReadWriteTransaction *transaction = protocolContext; YapDatabaseReadWriteTransaction *transaction = protocolContext;

View File

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