session-ios/SignalServiceKit/src/Loki/API/LokiAPI.swift

132 lines
6.9 KiB
Swift
Raw Normal View History

2019-04-30 06:27:39 +02:00
import PromiseKit
2019-05-08 01:29:07 +02:00
@objc public final class LokiAPI : NSObject {
internal static let storage = OWSPrimaryStorage.shared()
2019-04-30 06:27:39 +02:00
2019-05-21 05:44:46 +02:00
// MARK: Settings
2019-05-08 01:29:07 +02:00
private static let version = "v1"
2019-05-27 01:58:34 +02:00
private static let maxRetryCount: UInt = 3
2019-05-27 04:26:37 +02:00
public static let defaultMessageTTL: UInt64 = 1 * 24 * 60 * 60 * 1000
2019-04-30 06:27:39 +02:00
// MARK: Types
2019-05-07 05:53:31 +02:00
public typealias RawResponse = Any
2019-04-30 06:27:39 +02:00
2019-05-07 02:10:15 +02:00
public enum Error : LocalizedError {
2019-05-22 08:04:51 +02:00
/// Only applicable to snode targets as proof of work isn't required for P2P messaging.
2019-05-07 02:10:15 +02:00
case proofOfWorkCalculationFailed
2019-05-27 04:26:37 +02:00
case messageConversionFailed
2019-05-07 02:10:15 +02:00
public var errorDescription: String? {
switch self {
case .proofOfWorkCalculationFailed: return NSLocalizedString("Failed to calculate proof of work.", comment: "")
2019-05-27 04:26:37 +02:00
case .messageConversionFailed: return "Failed to convert Signal message to Loki message."
2019-05-07 02:10:15 +02:00
}
}
}
2019-04-30 06:27:39 +02:00
// MARK: Lifecycle
2019-05-06 08:13:32 +02:00
override private init() { }
2019-04-30 06:27:39 +02:00
2019-05-21 05:26:51 +02:00
// MARK: Internal API
internal static func invoke(_ method: Target.Method, on target: Target, associatedWith hexEncodedPublicKey: String, parameters: [String:Any] = [:]) -> Promise<RawResponse> {
2019-05-08 01:29:07 +02:00
let url = URL(string: "\(target.address):\(target.port)/\(version)/storage_rpc")!
2019-04-30 06:27:39 +02:00
let request = TSRequest(url: url, method: "POST", parameters: [ "method" : method.rawValue, "params" : parameters ])
2019-05-24 03:24:27 +02:00
return TSNetworkManager.shared().makePromise(request: request).map { $0.responseObject }
.handlingSwarmSpecificErrorsIfNeeded(for: target, associatedWith: hexEncodedPublicKey).recoveringNetworkErrorsIfNeeded()
2019-04-30 06:27:39 +02:00
}
2019-05-07 02:29:44 +02:00
2019-05-21 05:26:51 +02:00
// MARK: Public API
public static func getMessages() -> Promise<Set<Promise<[SSKProtoEnvelope]>>> {
2019-05-27 04:26:37 +02:00
let hexEncodedPublicKey = OWSIdentityManager.shared().identityKeyPair()!.hexEncodedPublicKey
return getTargetSnodes(for: hexEncodedPublicKey).mapValues { targetSnode in
let lastHash = getLastMessageHashValue(for: targetSnode) ?? ""
2019-05-27 04:26:37 +02:00
let parameters: [String:Any] = [ "pubKey" : hexEncodedPublicKey, "lastHash" : lastHash ]
return invoke(.getMessages, on: targetSnode, associatedWith: hexEncodedPublicKey, parameters: parameters).map { rawResponse in
guard let json = rawResponse as? JSON, let rawMessages = json["messages"] as? [JSON] else { return [] }
updateLastMessageHashValueIfPossible(for: targetSnode, from: rawMessages)
let newRawMessages = removeDuplicates(from: rawMessages)
return parseProtoEnvelopes(from: newRawMessages)
2019-05-21 05:48:42 +02:00
}
2019-05-27 01:58:34 +02:00
}.retryingIfNeeded(maxRetryCount: maxRetryCount).map { Set($0) }
2019-05-07 08:03:57 +02:00
}
2019-05-27 04:26:37 +02:00
public static func sendSignalMessage(_ signalMessage: SignalMessage, to destination: String, with timestamp: UInt64) -> Promise<Set<Promise<RawResponse>>> {
guard let lokiMessage = Message.from(signalMessage: signalMessage, timestamp: timestamp) else { return Promise(error: Error.messageConversionFailed) }
let destination = lokiMessage.destination
func sendLokiMessage(_ lokiMessage: Message, to targets: [Target]) -> Promise<Set<Promise<RawResponse>>> {
let parameters = lokiMessage.toJSON()
return Promise.value(targets).mapValues { invoke(.sendMessage, on: $0, associatedWith: destination, parameters: parameters) }.map { Set($0) }
}
2019-05-27 04:26:37 +02:00
func sendLokiMessageUsingSwarmAPI() -> Promise<Set<Promise<RawResponse>>> {
return lokiMessage.calculatePoW().then { updatedLokiMessage -> Promise<Set<Promise<RawResponse>>> in
return getTargetSnodes(for: destination).then { sendLokiMessage(updatedLokiMessage, to: $0) }
}
}
2019-05-27 04:26:37 +02:00
if let p2pDetails = LokiP2PManager.getDetails(forContact: destination), (lokiMessage.isPing || p2pDetails.isOnline) {
return sendLokiMessage(lokiMessage, to: [ p2pDetails.target ]).get { _ in
2019-05-27 01:50:37 +02:00
LokiP2PManager.setOnline(true, forContact: destination)
2019-05-24 08:26:58 +02:00
}.recover { error -> Promise<Set<Promise<RawResponse>>> in
2019-05-27 01:50:37 +02:00
LokiP2PManager.setOnline(false, forContact: destination)
2019-05-27 04:26:37 +02:00
if lokiMessage.isPing {
Logger.warn("[Loki] Failed to ping \(destination); marking contact as offline.")
if let nsError = error as? NSError {
nsError.isRetryable = false
throw nsError
} else {
throw error
}
2019-05-24 08:07:00 +02:00
}
2019-05-27 04:26:37 +02:00
return sendLokiMessageUsingSwarmAPI()
2019-05-24 08:07:00 +02:00
}
2019-05-27 04:26:37 +02:00
} else {
return sendLokiMessageUsingSwarmAPI()
}
2019-05-22 08:04:51 +02:00
}
2019-05-27 04:26:37 +02:00
// MARK: Public API (Obj-C)
@objc public static func objc_sendSignalMessage(_ signalMessage: SignalMessage, to destination: String, with timestamp: UInt64) -> AnyPromise {
let promise = sendSignalMessage(signalMessage, to: destination, with: timestamp).mapValues { AnyPromise.from($0) }.map { Set($0) }
return AnyPromise.from(promise)
2019-05-08 02:04:19 +02:00
}
// MARK: Parsing
// The parsing utilities below use a best attempt approach to parsing; they warn for parsing failures but don't throw exceptions.
private static func updateLastMessageHashValueIfPossible(for target: Target, from rawMessages: [JSON]) {
guard let lastMessage = rawMessages.last, let hashValue = lastMessage["hash"] as? String, let expiresAt = lastMessage["expiration"] as? Int else {
Logger.warn("[Loki] Failed to update last message hash value from: \(rawMessages).")
return
2019-05-21 07:21:51 +02:00
}
setLastMessageHashValue(for: target, hashValue: hashValue, expiresAt: UInt64(expiresAt))
2019-05-21 07:21:51 +02:00
}
private static func removeDuplicates(from rawMessages: [JSON]) -> [JSON] {
var receivedMessageHashValues = getReceivedMessageHashValues() ?? []
return rawMessages.filter { rawMessage in
guard let hashValue = rawMessage["hash"] as? String else {
Logger.warn("[Loki] Missing hash value for message: \(rawMessage).")
return false
}
let isDuplicate = receivedMessageHashValues.contains(hashValue)
receivedMessageHashValues.insert(hashValue)
setReceivedMessageHashValues(to: receivedMessageHashValues)
return !isDuplicate
}
2019-05-21 07:21:51 +02:00
}
private static func parseProtoEnvelopes(from rawMessages: [JSON]) -> [SSKProtoEnvelope] {
return rawMessages.compactMap { rawMessage in
guard let base64EncodedData = rawMessage["data"] as? String, let data = Data(base64Encoded: base64EncodedData) else {
Logger.warn("[Loki] Failed to decode data for message: \(rawMessage).")
2019-05-21 05:26:51 +02:00
return nil
}
guard let envelope = try? LokiMessageWrapper.unwrap(data: data) else {
Logger.warn("[Loki] Failed to unwrap data for message: \(rawMessage).")
2019-05-21 05:26:51 +02:00
return nil
}
return envelope
}
}
2019-05-08 08:02:53 +02:00
}