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

224 lines
12 KiB
Swift
Raw Normal View History

2019-04-30 06:27:39 +02:00
import PromiseKit
@objc(LKAPI)
public final class LokiAPI : NSObject {
internal static let storage = OWSPrimaryStorage.shared()
2019-04-30 06:27:39 +02:00
2019-07-25 05:09:22 +02:00
internal static var userHexEncodedPublicKey: String { return OWSIdentityManager.shared().identityKeyPair()!.hexEncodedPublicKey }
2019-06-12 06:44:28 +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-08-02 01:23:03 +02:00
private static let maxRetryCount: UInt = 4
2019-06-18 08:01:53 +02:00
private static let defaultTimeout: TimeInterval = 20
2019-06-12 06:23:01 +02:00
private static let longPollingTimeout: TimeInterval = 40
public static let defaultMessageTTL: UInt64 = 24 * 60 * 60 * 1000
2019-08-28 08:38:20 +02:00
internal static var powDifficulty: UInt = 40
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-05-28 01:57:54 +02:00
public typealias MessageListPromise = Promise<[SSKProtoEnvelope]>
public typealias RawResponsePromise = Promise<RawResponse>
2019-05-27 02:27:49 +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
2019-06-12 06:23:01 +02:00
internal static func invoke(_ method: LokiAPITarget.Method, on target: LokiAPITarget, associatedWith hexEncodedPublicKey: String,
parameters: [String:Any], headers: [String:String]? = nil, timeout: TimeInterval? = nil) -> RawResponsePromise {
2019-06-26 07:09:03 +02:00
let url = URL(string: "\(target.address):\(target.port)/storage_rpc/\(version)")!
2019-06-12 06:23:01 +02:00
let request = TSRequest(url: url, method: "POST", parameters: [ "method" : method.rawValue, "params" : parameters ])
if let headers = headers { request.allHTTPHeaderFields = headers }
2019-06-18 03:27:19 +02:00
request.timeoutInterval = timeout ?? defaultTimeout
2019-06-13 06:34:19 +02:00
let headers = request.allHTTPHeaderFields ?? [:]
let headersDescription = headers.isEmpty ? "no custom headers specified" : headers.prettifiedDescription
print("[Loki] Invoking \(method.rawValue) on \(target) with \(parameters.prettifiedDescription) (\(headersDescription)).")
2019-06-12 06:23:01 +02:00
return TSNetworkManager.shared().makePromise(request: request).map { $0.responseObject }
.handlingSwarmSpecificErrorsIfNeeded(for: target, associatedWith: hexEncodedPublicKey).recoveringNetworkErrorsIfNeeded()
2019-06-12 04:36:34 +02:00
}
2019-06-12 06:44:28 +02:00
internal static func getRawMessages(from target: LokiAPITarget, usingLongPolling useLongPolling: Bool) -> RawResponsePromise {
2019-06-11 08:22:35 +02:00
let lastHashValue = getLastMessageHashValue(for: target) ?? ""
2019-07-25 05:09:22 +02:00
let parameters = [ "pubKey" : userHexEncodedPublicKey, "lastHash" : lastHashValue ]
2019-06-12 06:23:01 +02:00
let headers: [String:String]? = useLongPolling ? [ "X-Loki-Long-Poll" : "true" ] : nil
let timeout: TimeInterval? = useLongPolling ? longPollingTimeout : nil
2019-07-25 05:09:22 +02:00
return invoke(.getMessages, on: target, associatedWith: userHexEncodedPublicKey, parameters: parameters, headers: headers, timeout: timeout)
}
// MARK: Public API
public static func getMessages() -> Promise<Set<MessageListPromise>> {
2019-07-25 05:09:22 +02:00
return getTargetSnodes(for: userHexEncodedPublicKey).mapValues { targetSnode in
2019-06-12 06:44:28 +02:00
return getRawMessages(from: targetSnode, usingLongPolling: false).map { parseRawMessagesResponse($0, from: targetSnode) }
}.map { Set($0) }.retryingIfNeeded(maxRetryCount: maxRetryCount)
}
public static func sendSignalMessage(_ signalMessage: SignalMessage, onP2PSuccess: @escaping () -> Void) -> Promise<Set<RawResponsePromise>> {
2019-06-12 06:44:28 +02:00
guard let lokiMessage = LokiMessage.from(signalMessage: signalMessage) else { return Promise(error: Error.messageConversionFailed) }
2019-05-27 04:26:37 +02:00
let destination = lokiMessage.destination
2019-06-12 06:44:28 +02:00
func sendLokiMessage(_ lokiMessage: LokiMessage, to target: LokiAPITarget) -> RawResponsePromise {
2019-05-27 04:26:37 +02:00
let parameters = lokiMessage.toJSON()
2019-05-27 04:50:30 +02:00
return invoke(.sendMessage, on: target, associatedWith: destination, parameters: parameters)
}
func sendLokiMessageUsingSwarmAPI() -> Promise<Set<RawResponsePromise>> {
2019-08-02 01:28:04 +02:00
return lokiMessage.calculatePoW().then { lokiMessageWithPoW in
return getTargetSnodes(for: destination).map { swarm in
return Set(swarm.map { target in
sendLokiMessage(lokiMessageWithPoW, to: target).map { rawResponse in
if let json = rawResponse as? JSON, let powDifficulty = json["difficulty"] as? Int {
guard powDifficulty != LokiAPI.powDifficulty else { return rawResponse }
print("[Loki] Setting proof of work difficulty to \(powDifficulty).")
LokiAPI.powDifficulty = UInt(powDifficulty)
} else {
print("[Loki] Failed to update proof of work difficulty from: \(rawResponse).")
}
return rawResponse
2019-06-14 02:04:07 +02:00
}
2019-08-02 01:28:04 +02:00
})
}.retryingIfNeeded(maxRetryCount: maxRetryCount)
}
}
if let peer = LokiP2PAPI.getInfo(for: destination), (lokiMessage.isPing || peer.isOnline) {
2019-06-12 03:55:01 +02:00
let target = LokiAPITarget(address: peer.address, port: peer.port)
2019-05-27 05:50:22 +02:00
return Promise.value([ target ]).mapValues { sendLokiMessage(lokiMessage, to: $0) }.map { Set($0) }.retryingIfNeeded(maxRetryCount: maxRetryCount).get { _ in
LokiP2PAPI.markOnline(destination)
2019-05-27 07:06:54 +02:00
onP2PSuccess()
}.recover { error -> Promise<Set<RawResponsePromise>> in
LokiP2PAPI.markOffline(destination)
2019-05-27 04:26:37 +02:00
if lokiMessage.isPing {
2019-06-13 06:34:19 +02:00
print("[Loki] Failed to ping \(destination); marking contact as offline.")
2019-05-27 08:30:28 +02:00
if let error = error as? NSError {
error.isRetryable = false
throw error
2019-05-27 04:26:37 +02:00
} else {
throw error
}
2019-05-24 08:07:00 +02:00
}
2019-05-27 07:06:54 +02:00
return sendLokiMessageUsingSwarmAPI()
2019-05-24 08:07:00 +02:00
}
2019-05-27 04:26:37 +02:00
} else {
2019-05-27 07:06:54 +02:00
return sendLokiMessageUsingSwarmAPI()
}
2019-05-22 08:04:51 +02:00
}
2019-05-27 04:26:37 +02:00
// MARK: Public API (Obj-C)
@objc(sendSignalMessage:onP2PSuccess:)
public static func objc_sendSignalMessage(_ signalMessage: SignalMessage, onP2PSuccess: @escaping () -> Void) -> AnyPromise {
let promise = sendSignalMessage(signalMessage, onP2PSuccess: onP2PSuccess).mapValues { AnyPromise.from($0) }.map { Set($0) }
2019-05-27 04:26:37 +02:00
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.
2019-06-12 06:23:01 +02:00
internal static func parseRawMessagesResponse(_ rawResponse: Any, from target: LokiAPITarget) -> [SSKProtoEnvelope] {
guard let json = rawResponse as? JSON, let rawMessages = json["messages"] as? [JSON] else { return [] }
updateLastMessageHashValueIfPossible(for: target, from: rawMessages)
let newRawMessages = removeDuplicates(from: rawMessages)
2019-07-25 05:09:22 +02:00
let newMessages = parseProtoEnvelopes(from: newRawMessages)
let newMessageCount = newMessages.count
if newMessageCount == 1 {
print("[Loki] Retrieved 1 new message.")
} else if (newMessageCount != 0) {
print("[Loki] Retrieved \(newMessageCount) new messages.")
}
return newMessages
2019-06-12 06:23:01 +02:00
}
2019-06-12 03:55:01 +02:00
private static func updateLastMessageHashValueIfPossible(for target: LokiAPITarget, from rawMessages: [JSON]) {
2019-06-12 06:23:01 +02:00
if let lastMessage = rawMessages.last, let hashValue = lastMessage["hash"] as? String, let expirationDate = lastMessage["expiration"] as? Int {
2019-06-12 06:44:28 +02:00
setLastMessageHashValue(for: target, hashValue: hashValue, expirationDate: UInt64(expirationDate))
2019-06-12 06:23:01 +02:00
} else if (!rawMessages.isEmpty) {
2019-06-13 06:34:19 +02:00
print("[Loki] Failed to update last message hash value from: \(rawMessages).")
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 {
2019-06-13 06:34:19 +02:00
print("[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 {
2019-06-13 06:34:19 +02:00
print("[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 {
2019-06-13 06:34:19 +02:00
print("[Loki] Failed to unwrap data for message: \(rawMessage).")
2019-05-21 05:26:51 +02:00
return nil
}
return envelope
}
}
2019-08-29 07:52:51 +02:00
// MARK: Caching
private static let receivedMessageHashValuesKey = "receivedMessageHashValuesKey"
private static let receivedMessageHashValuesCollection = "receivedMessageHashValuesCollection"
private static func getLastMessageHashValue(for target: LokiAPITarget) -> String? {
var result: String? = nil
// Uses a read/write connection because getting the last message hash value also removes expired messages as needed
// TODO: This shouldn't be the case; a getter shouldn't have an unexpected side effect
storage.dbReadWriteConnection.readWrite { transaction in
result = storage.getLastMessageHash(forServiceNode: target.address, transaction: transaction)
}
return result
}
private static func setLastMessageHashValue(for target: LokiAPITarget, hashValue: String, expirationDate: UInt64) {
storage.dbReadWriteConnection.readWrite { transaction in
storage.setLastMessageHash(forServiceNode: target.address, hash: hashValue, expiresAt: expirationDate, transaction: transaction)
}
}
private static func getReceivedMessageHashValues() -> Set<String>? {
var result: Set<String>? = nil
storage.dbReadConnection.read { transaction in
result = transaction.object(forKey: receivedMessageHashValuesKey, inCollection: receivedMessageHashValuesCollection) as! Set<String>?
}
return result
}
private static func setReceivedMessageHashValues(to receivedMessageHashValues: Set<String>) {
storage.dbReadWriteConnection.readWrite { transaction in
transaction.setObject(receivedMessageHashValues, forKey: receivedMessageHashValuesKey, inCollection: receivedMessageHashValuesCollection)
}
}
}
// MARK: Error Handling
private extension Promise {
fileprivate func recoveringNetworkErrorsIfNeeded() -> Promise<T> {
return recover() { error -> Promise<T> in
switch error {
case NetworkManagerError.taskError(_, let underlyingError): throw underlyingError
default: throw error
}
}
}
2019-05-08 08:02:53 +02:00
}