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

152 lines
6.4 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-21 05:44:46 +02:00
// MARK: Caching
private static var swarmCache: [String:Set<Target>] = [:]
// MARK: Settings
2019-05-08 01:29:07 +02:00
private static let version = "v1"
2019-05-21 05:26:51 +02:00
private static let targetSnodeCount = 2
2019-05-08 01:29:07 +02:00
public static let defaultMessageTTL: UInt64 = 4 * 24 * 60 * 60
2019-04-30 06:27:39 +02:00
// MARK: Types
2019-05-21 05:48:42 +02:00
fileprivate struct Target : Hashable {
2019-05-07 07:03:54 +02:00
let address: String
let port: UInt16
2019-05-21 05:26:51 +02:00
enum Method : String {
case getSwarm = "get_snodes_for_pubkey"
case getMessages = "retrieve"
case sendMessage = "store"
}
2019-05-07 07:03:54 +02:00
}
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-05-21 05:44:46 +02:00
public typealias MessagesPromise = Promise<[SSKProtoEnvelope]>
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
private static func invoke(_ method: Target.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-21 05:26:51 +02:00
private static func getRandomSnode() -> Promise<Target> {
2019-05-07 08:03:57 +02:00
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
}
2019-05-21 05:26:51 +02:00
private static func getSwarm(for hexEncodedPublicKey: String) -> Promise<Set<Target>> {
2019-05-21 05:44:46 +02:00
if let cachedSwarm = swarmCache[hexEncodedPublicKey], cachedSwarm.count >= targetSnodeCount {
return Promise<Set<Target>> { $0.fulfill(cachedSwarm) }
} else {
return getRandomSnode().then { invoke(.getSwarm, on: $0, with: [ "pubKey" : hexEncodedPublicKey ]) }.map { rawResponse in
return [] // TODO: Parse targets from raw response
}.get { swarmCache[hexEncodedPublicKey] = $0 }
}
2019-05-21 05:26:51 +02:00
}
private static func getTargetSnodes(for hexEncodedPublicKey: String) -> Promise<Set<Target>> {
return getSwarm(for: hexEncodedPublicKey).map { Set(Array($0).shuffled().prefix(targetSnodeCount)) }
}
// MARK: Public API
public static func getMessages() -> Promise<[MessagesPromise]> {
let hexEncodedPublicKey = OWSIdentityManager.shared().identityKeyPair()!.hexEncodedPublicKey
return getTargetSnodes(for: hexEncodedPublicKey).mapValues { targetSnode in
2019-05-21 05:48:42 +02:00
let lastHash = getLastHash(for: targetSnode) ?? ""
let parameters: [String:Any] = [ "pubKey" : hexEncodedPublicKey, "lastHash" : lastHash ]
return invoke(.getMessages, on: targetSnode, with: parameters).map { response in
if let json = response as? JSON, let messages = json["messages"] as? [JSON], let lastMessage = messages.last,
let hash = lastMessage["hash"] as? String, let expiresAt = lastMessage["expiration"] as? Int {
updateLastHash(for: targetSnode, hash: hash, expiresAt: UInt64(expiresAt))
}
return parseProtoEnvelopes(from: response)
}
}
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-21 05:26:51 +02:00
// MARK: Public API (Obj-C)
@objc public static func objc_sendSignalMessage(_ signalMessage: SignalMessage, to destination: String, timestamp: UInt64, requiringPoW isPoWRequired: Bool) -> AnyPromise {
2019-05-21 05:26:51 +02:00
let promise = Message.from(signalMessage: signalMessage, timestamp: timestamp, requiringPoW: isPoWRequired).then(sendMessage).recoverNetworkErrorIfNeeded(on: DispatchQueue.global())
let anyPromise = AnyPromise(promise)
anyPromise.retainUntilComplete()
return anyPromise
2019-05-07 02:29:44 +02:00
}
2019-05-21 05:26:51 +02:00
// MARK: Convenience
private static func parseProtoEnvelopes(from rawResponse: Any) -> [SSKProtoEnvelope] {
guard let json = rawResponse as? JSON, let messages = json["messages"] as? [JSON] else { return [] }
return messages.compactMap { message in
guard let base64EncodedData = message["data"] as? String, let data = Data(base64Encoded: base64EncodedData) else {
Logger.warn("[Loki] Failed to decode data for message: \(message).")
return nil
}
guard let envelope = try? unwrap(data: data) else {
Logger.warn("[Loki] Failed to unwrap data for message: \(message).")
return nil
}
return envelope
}
}
2019-04-30 06:27:39 +02:00
}
2019-05-08 08:02:53 +02:00
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-21 05:44:46 +02:00
return recover(on: queue) { error -> Promise<T> in
2019-05-08 08:02:53 +02:00
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
}
}
}
}
2019-05-21 05:06:46 +02:00
// MARK: Last Hash
2019-05-21 05:48:42 +02:00
fileprivate extension LokiAPI {
2019-05-21 05:06:46 +02:00
2019-05-21 05:48:42 +02:00
private static var primaryStorage: OWSPrimaryStorage {
2019-05-21 05:06:46 +02:00
return OWSPrimaryStorage.shared()
}
2019-05-21 05:48:42 +02:00
fileprivate static func updateLastHash(for node: Target, hash: String, expiresAt: UInt64) {
2019-05-21 05:06:46 +02:00
primaryStorage.dbReadWriteConnection.readWrite { transaction in
self.primaryStorage.setLastMessageHash(hash, expiresAt: expiresAt, serviceNode: node.address, transaction: transaction)
}
}
2019-05-21 05:48:42 +02:00
fileprivate static func getLastHash(for node: Target) -> String? {
2019-05-21 05:06:46 +02:00
var lastHash: String? = nil
primaryStorage.dbReadWriteConnection.readWrite { transaction in
lastHash = self.primaryStorage.getLastMessageHash(forServiceNode: node.address, transaction: transaction)
}
return lastHash
}
}