diff --git a/Signal/src/AppDelegate.m b/Signal/src/AppDelegate.m index d52da76a0..5afd920bb 100644 --- a/Signal/src/AppDelegate.m +++ b/Signal/src/AppDelegate.m @@ -172,7 +172,7 @@ static NSTimeInterval launchStartedAt; [DDLog flushLog]; - [LokiAPI stopLongPolling]; + [LKAPI stopLongPolling]; } - (void)applicationWillEnterForeground:(UIApplication *)application @@ -191,7 +191,7 @@ static NSTimeInterval launchStartedAt; [DDLog flushLog]; - [LokiAPI stopLongPolling]; + [LKAPI stopLongPolling]; if (self.lokiP2PServer) { [self.lokiP2PServer stop]; } } @@ -327,7 +327,7 @@ static NSTimeInterval launchStartedAt; BOOL isStarted = [self.lokiP2PServer startOnPort:port.unsignedIntegerValue]; if (isStarted) { NSURL *serverURL = self.lokiP2PServer.serverURL; - [LokiP2PManager setOurP2PAddressWithUrl:self.lokiP2PServer.serverURL]; + [LKP2PAPI setOurP2PAddressWithUrl:self.lokiP2PServer.serverURL]; NSString *serverURLDescription = serverURL.absoluteString; if ([serverURLDescription hasSuffix:@"/"]) { serverURLDescription = [serverURLDescription substringToIndex:serverURLDescription.length - 1]; @@ -758,10 +758,10 @@ static NSTimeInterval launchStartedAt; [Environment.shared.contactsManager fetchSystemContactsOnceIfAlreadyAuthorized]; // Loki: Start long polling - [LokiAPI startLongPollingIfNecessary]; + [LKAPI startLongPollingIfNecessary]; // Loki: Tell our friends that we are online - [LokiP2PManager broadcastOnlineStatus]; + [LKP2PAPI broadcastOnlineStatus]; if (![UIApplication sharedApplication].isRegisteredForRemoteNotifications) { OWSLogInfo(@"Retrying to register for remote notifications since user hasn't registered yet."); @@ -1365,7 +1365,7 @@ static NSTimeInterval launchStartedAt; [self.readReceiptManager setAreReadReceiptsEnabled:YES]; // Start long polling - [LokiAPI startLongPollingIfNecessary]; + [LKAPI startLongPollingIfNecessary]; } } diff --git a/Signal/src/Loki/LokiP2PServer.swift b/Signal/src/Loki/LokiP2PServer.swift index 97b023584..90d0ddc2c 100644 --- a/Signal/src/Loki/LokiP2PServer.swift +++ b/Signal/src/Loki/LokiP2PServer.swift @@ -79,7 +79,7 @@ final class LokiP2PServer : NSObject { } // Pass it off to the message handler - LokiP2PMessageHandler.handleReceivedMessage(base64EncodedData: data) + LokiP2PAPI.handleReceivedMessage(base64EncodedData: data) // Send a response back return GCDWebServerResponse(statusCode: StatusCode.ok.rawValue) diff --git a/SignalMessaging/Views/AvatarImageView.swift b/SignalMessaging/Views/AvatarImageView.swift index e08f6cd79..e7187afe3 100644 --- a/SignalMessaging/Views/AvatarImageView.swift +++ b/SignalMessaging/Views/AvatarImageView.swift @@ -85,7 +85,7 @@ public class AvatarImageView: UIImageView { } @objc func updateOnlineStatusIndicator() { - let peerInfo = LokiP2PManager.getInfo(for: contactID) + let peerInfo = LokiP2PAPI.getInfo(for: contactID) let isOnline = peerInfo?.isOnline ?? false let color: UIColor = isOnline ? .ows_green : .ows_gray75 let currentUserID = OWSIdentityManager.shared().identityKeyPair()!.hexEncodedPublicKey diff --git a/SignalServiceKit/src/Loki/API/LokiAPI+Convenience.swift b/SignalServiceKit/src/Loki/API/LokiAPI+Convenience.swift index 2810e4777..0ebca88e4 100644 --- a/SignalServiceKit/src/Loki/API/LokiAPI+Convenience.swift +++ b/SignalServiceKit/src/Loki/API/LokiAPI+Convenience.swift @@ -17,7 +17,7 @@ internal extension LokiAPI { internal static func setLastMessageHashValue(for target: LokiAPITarget, hashValue: String, expirationDate: UInt64) { storage.dbReadWriteConnection.readWrite { transaction in - storage.setLastMessageHash(forServiceNode: target.address, hash: hashValue, expirationDate: expirationDate, transaction: transaction) + storage.setLastMessageHash(forServiceNode: target.address, hash: hashValue, expiresAt: expirationDate, transaction: transaction) } } diff --git a/SignalServiceKit/src/Loki/API/LokiAPI.swift b/SignalServiceKit/src/Loki/API/LokiAPI.swift index c75c8e62d..13b8e6acc 100644 --- a/SignalServiceKit/src/Loki/API/LokiAPI.swift +++ b/SignalServiceKit/src/Loki/API/LokiAPI.swift @@ -1,6 +1,7 @@ import PromiseKit -@objc public final class LokiAPI : NSObject { +@objc(LKAPI) +public final class LokiAPI : NSObject { internal static let storage = OWSPrimaryStorage.shared() private static var userPublicKey: String { return OWSIdentityManager.shared().identityKeyPair()!.hexEncodedPublicKey } @@ -73,13 +74,13 @@ import PromiseKit return Set(swarm.map { sendLokiMessage(lokiMessageWithPoW, to: $0) }) }.retryingIfNeeded(maxRetryCount: maxRetryCount) } - if let peer = LokiP2PManager.getInfo(for: destination), (lokiMessage.isPing || peer.isOnline) { + if let peer = LokiP2PAPI.getInfo(for: destination), (lokiMessage.isPing || peer.isOnline) { let target = LokiAPITarget(address: peer.address, port: peer.port) return Promise.value([ target ]).mapValues { sendLokiMessage(lokiMessage, to: $0) }.map { Set($0) }.retryingIfNeeded(maxRetryCount: maxRetryCount).get { _ in - LokiP2PManager.markOnline(destination) + LokiP2PAPI.markOnline(destination) onP2PSuccess() }.recover { error -> Promise> in - LokiP2PManager.markOffline(destination) + LokiP2PAPI.markOffline(destination) if lokiMessage.isPing { Logger.warn("[Loki] Failed to ping \(destination); marking contact as offline.") if let error = error as? NSError { diff --git a/SignalServiceKit/src/Loki/API/LokiP2PManager.swift b/SignalServiceKit/src/Loki/API/LokiP2PAPI.swift similarity index 88% rename from SignalServiceKit/src/Loki/API/LokiP2PManager.swift rename to SignalServiceKit/src/Loki/API/LokiP2PAPI.swift index 1ec75770e..8b9a251f2 100644 --- a/SignalServiceKit/src/Loki/API/LokiP2PManager.swift +++ b/SignalServiceKit/src/Loki/API/LokiP2PAPI.swift @@ -1,7 +1,9 @@ -@objc public class LokiP2PManager : NSObject { +@objc(LKP2PAPI) +public class LokiP2PAPI : NSObject { private static let storage = OWSPrimaryStorage.shared() private static let messageSender = SSKEnvironment.shared.messageSender + private static let messageReceiver = SSKEnvironment.shared.messageReceiver private static let ourHexEncodedPubKey = OWSIdentityManager.shared().identityKeyPair()!.hexEncodedPublicKey /// The amount of time before pinging when a user is set to offline @@ -71,6 +73,28 @@ } } + public static func handleReceivedMessage(base64EncodedData: String) { + guard let data = Data(base64Encoded: base64EncodedData) else { + Logger.warn("[Loki] Failed to decode data for P2P message.") + return + } + guard let envelope = try? LokiMessageWrapper.unwrap(data: data) else { + Logger.warn("[Loki] Failed to unwrap data for P2P message.") + return + } + // We need to set the P2P field on the envelope + let builder = envelope.asBuilder() + builder.setIsPtpMessage(true) + // Send it to the message receiver + do { + let newEnvelope = try builder.build() + let envelopeData = try newEnvelope.serializedData() + messageReceiver.handleReceivedEnvelopeData(envelopeData) + } catch let error { + Logger.warn("[Loki] Something went wrong during proto conversion: \(error).") + } + } + // MARK: - Internal functions /// Get the P2P details for the given contact. diff --git a/SignalServiceKit/src/Loki/API/LokiP2PMessageHandler.swift b/SignalServiceKit/src/Loki/API/LokiP2PMessageHandler.swift deleted file mode 100644 index 01cba74f9..000000000 --- a/SignalServiceKit/src/Loki/API/LokiP2PMessageHandler.swift +++ /dev/null @@ -1,31 +0,0 @@ - -public final class LokiP2PMessageHandler { - private static let messageReceiver = SSKEnvironment.shared.messageReceiver - - // MARK: Initialization - private init() { } - - // MARK: General - public static func handleReceivedMessage(base64EncodedData: String) { - guard let data = Data(base64Encoded: base64EncodedData) else { - Logger.warn("[Loki] Failed to decode data for P2P message.") - return - } - guard let envelope = try? LokiMessageWrapper.unwrap(data: data) else { - Logger.warn("[Loki] Failed to unwrap data for P2P message.") - return - } - // We need to set the P2P field on the envelope - let builder = envelope.asBuilder() - builder.setIsPtpMessage(true) - // Send it to the message receiver - do { - let newEnvelope = try builder.build() - let envelopeData = try newEnvelope.serializedData() - messageReceiver.handleReceivedEnvelopeData(envelopeData) - } catch let error { - Logger.warn("[Loki] Something went wrong during proto conversion: \(error).") - } - } - -} diff --git a/SignalServiceKit/src/Messages/OWSMessageManager.m b/SignalServiceKit/src/Messages/OWSMessageManager.m index 3b7a62eab..d18f97431 100644 --- a/SignalServiceKit/src/Messages/OWSMessageManager.m +++ b/SignalServiceKit/src/Messages/OWSMessageManager.m @@ -437,7 +437,7 @@ NS_ASSUME_NONNULL_BEGIN if (contentProto.lokiAddressMessage) { NSString *address = contentProto.lokiAddressMessage.ptpAddress; uint32_t port = contentProto.lokiAddressMessage.ptpPort; - [LokiP2PManager didReceiveLokiAddressMessageForContact:envelope.source address:address port:port receivedThroughP2P:envelope.isPtpMessage]; + [LKP2PAPI didReceiveLokiAddressMessageForContact:envelope.source address:address port:port receivedThroughP2P:envelope.isPtpMessage]; } if (contentProto.syncMessage) { @@ -1474,7 +1474,7 @@ NS_ASSUME_NONNULL_BEGIN uint64_t timestamp = envelope.timestamp; uint64_t now = NSDate.ows_millisecondTimeStamp; uint64_t ageInSeconds = (now - timestamp) / 1000; - if (ageInSeconds <= 120) { [LokiP2PManager pingContact:envelope.source]; } + if (ageInSeconds <= 120) { [LKP2PAPI pingContact:envelope.source]; } } [self finalizeIncomingMessage:incomingMessage @@ -1526,7 +1526,7 @@ NS_ASSUME_NONNULL_BEGIN [existingFriendRequestMessage saveFriendRequestStatus:LKMessageFriendRequestStatusAccepted withTransaction:transaction]; } // Send our P2P details - LKAddressMessage *_Nullable onlineMessage = [LokiP2PManager onlineBroadcastMessageForThread:thread]; + LKAddressMessage *_Nullable onlineMessage = [LKP2PAPI onlineBroadcastMessageForThread:thread]; if (onlineMessage != nil) { [self.messageSenderJobQueue addMessage:onlineMessage transaction:transaction]; } diff --git a/SignalServiceKit/src/Messages/OWSMessageSender.m b/SignalServiceKit/src/Messages/OWSMessageSender.m index 663f9e7e8..62df07abc 100644 --- a/SignalServiceKit/src/Messages/OWSMessageSender.m +++ b/SignalServiceKit/src/Messages/OWSMessageSender.m @@ -1153,7 +1153,7 @@ NSString *const OWSMessageSenderRateLimitedException = @"RateLimitedException"; [self messageSendDidFail:messageSend deviceMessages:deviceMessages statusCode:statusCode error:error responseData:responseData]; }; // Send the message using the Loki API - [[LokiAPI sendSignalMessage:signalMessage onP2PSuccess:onP2PSuccess] + [[LKAPI sendSignalMessage:signalMessage onP2PSuccess:onP2PSuccess] .thenOn(OWSDispatch.sendingQueue, ^(id result) { NSSet *promises = (NSSet *)result; __block BOOL isSuccess = NO;