Merge LokiP2PManager & LokiP2PMessageHandler

This commit is contained in:
Niels Andriesse 2019-06-12 14:50:36 +10:00
parent ee60dbd928
commit 820b0829bb
9 changed files with 43 additions and 49 deletions

View File

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

View File

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

View File

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

View File

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

View File

@ -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<Set<RawResponsePromise>> 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 {

View File

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

View File

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

View File

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

View File

@ -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<AnyPromise *> *promises = (NSSet<AnyPromise *> *)result;
__block BOOL isSuccess = NO;