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

105 lines
4.3 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 {
2019-04-30 06:27:39 +02:00
2019-05-08 01:29:07 +02:00
private static let version = "v1"
public static let defaultMessageTTL: UInt64 = 4 * 24 * 60 * 60
2019-04-30 06:27:39 +02:00
// MARK: Types
private enum Method : String {
2019-05-07 08:03:57 +02:00
case getMessages = "retrieve"
2019-05-06 08:13:32 +02:00
case sendMessage = "store"
2019-05-07 08:03:57 +02:00
case getSwarm = "get_snodes_for_pubkey"
2019-04-30 06:27:39 +02:00
}
2019-05-08 01:29:07 +02:00
public struct Target : Hashable {
2019-05-07 07:03:54 +02:00
let address: String
let port: UInt16
}
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 {
case proofOfWorkCalculationFailed
public var errorDescription: String? {
switch self {
case .proofOfWorkCalculationFailed: return NSLocalizedString("Failed to calculate proof of work.", comment: "")
}
}
}
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
// MARK: API
2019-05-10 05:38:00 +02:00
private static func invoke(_ method: Method, on target: Target, with 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-07 05:53:31 +02:00
return TSNetworkManager.shared().makePromise(request: request).map { $0.responseObject }
2019-04-30 06:27:39 +02:00
}
2019-05-07 02:29:44 +02:00
2019-05-07 08:03:57 +02:00
public static func getRandomSnode() -> Promise<Target> {
return Promise<Target> { seal in
seal.fulfill(Target(address: "http://13.238.53.205", port: 8080)) // TODO: Temporary
}
2019-04-30 06:27:39 +02:00
}
public static func getMessages() -> Promise<[SSKProtoEnvelope]> {
2019-04-30 07:12:15 +02:00
let parameters = [
"pubKey" : OWSIdentityManager.shared().identityKeyPair()!.hexEncodedPublicKey,
2019-05-06 08:13:32 +02:00
"lastHash" : "" // TODO: Implement
2019-04-30 07:12:15 +02:00
]
2019-05-10 05:38:00 +02:00
return getRandomSnode().then { invoke(.getMessages, on: $0, with: parameters) }.map { rawResponse in // TODO: Use getSwarm()
guard let json = rawResponse as? JSON, let messages = json["messages"] as? [JSON] else { return [] }
2019-05-10 04:41:49 +02:00
return messages.compactMap { message in
guard let base64EncodedData = message["data"] as? String, let data = Data(base64Encoded: base64EncodedData) else {
2019-05-21 03:40:29 +02:00
Logger.warn("[Loki] Failed to decode data for message: \(message).")
2019-05-10 04:41:49 +02:00
return nil
}
guard let envelope = try? unwrap(data: data) else {
2019-05-21 03:40:29 +02:00
Logger.warn("[Loki] Failed to unwrap data for message: \(message).")
2019-05-10 04:41:49 +02:00
return nil
}
return envelope
}
}
2019-05-07 08:03:57 +02:00
}
2019-05-10 04:41:49 +02:00
public static func sendMessage(_ lokiMessage: Message) -> Promise<RawResponse> {
2019-05-08 01:29:07 +02:00
return getRandomSnode().then { invoke(.sendMessage, on: $0, with: lokiMessage.toJSON()) } // TODO: Use getSwarm()
2019-05-07 08:03:57 +02:00
}
2019-05-08 02:04:19 +02:00
public static func ping(_ hexEncodedPublicKey: String) -> Promise<RawResponse> {
2019-05-08 08:50:41 +02:00
return getRandomSnode().then { invoke(.sendMessage, on: $0, with: [ "pubKey" : hexEncodedPublicKey ]) } // TODO: Use getSwarm() and figure out correct parameters
2019-05-08 02:04:19 +02:00
}
2019-05-08 01:29:07 +02:00
public static func getSwarm(for hexEncodedPublicKey: String) -> Promise<Set<Target>> {
return getRandomSnode().then { invoke(.getSwarm, on: $0, with: [ "pubKey" : hexEncodedPublicKey ]) }.map { rawResponse in return [] } // TODO: Parse targets from raw response
2019-04-30 06:27:39 +02:00
}
2019-05-07 02:29:44 +02:00
// MARK: Obj-C API
@objc public static func objc_sendSignalMessage(_ signalMessage: SignalMessage, to destination: String, timestamp: UInt64, requiringPoW isPoWRequired: Bool) -> AnyPromise {
2019-05-10 04:41:49 +02:00
let promise = Message.from(signalMessage: signalMessage, timestamp: timestamp, requiringPoW: isPoWRequired)
2019-05-08 07:32:10 +02:00
.then(sendMessage)
2019-05-21 03:40:29 +02:00
.recoverNetworkErrorIfNeeded(on: DispatchQueue.global())
let anyPromise = AnyPromise(promise)
anyPromise.retainUntilComplete()
return anyPromise
2019-05-07 02:29:44 +02:00
}
2019-04-30 06:27:39 +02:00
}
2019-05-08 08:02:53 +02:00
// MARK: - Convenience
private extension Promise {
2019-05-08 08:02:53 +02:00
2019-05-21 03:40:29 +02:00
func recoverNetworkErrorIfNeeded(on queue: DispatchQueue) -> Promise<T> {
2019-05-08 08:02:53 +02:00
return self.recover(on: queue) { error -> Promise<T> in
switch error {
2019-05-21 03:40:29 +02:00
case NetworkManagerError.taskError(_, let underlyingError): throw underlyingError
default: throw error
2019-05-08 08:02:53 +02:00
}
}
}
}