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

435 lines
23 KiB
Swift
Raw Normal View History

2019-04-30 06:27:39 +02:00
import PromiseKit
@objc(LKAPI)
public final class LokiAPI : NSObject {
2020-04-02 06:48:42 +02:00
private static let stateQueue = DispatchQueue(label: "LokiAPI.stateQueue")
2020-03-27 01:52:42 +01:00
2020-02-19 00:00:49 +01:00
/// Only ever modified from the message processing queue (`OWSBatchMessageProcessor.processingQueue`).
2019-11-27 04:54:45 +01:00
private static var syncMessageTimestamps: [String:Set<UInt64>] = [:]
2020-02-19 00:00:49 +01:00
2020-03-27 01:52:42 +01:00
private static var _lastDeviceLinkUpdate: [String:Date] = [:]
2020-02-19 00:00:49 +01:00
/// A mapping from hex encoded public key to date updated.
public static var lastDeviceLinkUpdate: [String:Date] {
get { stateQueue.sync { _lastDeviceLinkUpdate } }
set { stateQueue.sync { _lastDeviceLinkUpdate = newValue } }
}
private static var _userHexEncodedPublicKeyCache: [String:Set<String>] = [:]
/// A mapping from thread ID to set of user hex encoded public keys.
@objc public static var userHexEncodedPublicKeyCache: [String:Set<String>] {
get { stateQueue.sync { _userHexEncodedPublicKeyCache } }
set { stateQueue.sync { _userHexEncodedPublicKeyCache = newValue } }
}
/// All service node related errors must be handled on this queue to avoid race conditions maintaining e.g. failure counts.
2020-04-02 06:48:42 +02:00
public static let errorHandlingQueue = DispatchQueue(label: "LokiAPI.errorHandlingQueue")
2019-04-30 06:27:39 +02:00
2019-09-17 01:56:47 +02:00
// MARK: Convenience
2019-09-26 03:32:47 +02:00
internal static let storage = OWSPrimaryStorage.shared()
2020-01-30 10:09:02 +01:00
internal static let userHexEncodedPublicKey = getUserHexEncodedPublicKey()
2019-06-12 06:44:28 +02:00
2019-05-21 05:44:46 +02:00
// MARK: Settings
private static let useOnionRequests = true
2020-04-06 03:11:24 +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
2019-10-09 01:37:44 +02:00
private static var userIDScanLimit: UInt = 4096
2020-04-06 03:11:24 +02:00
internal static var powDifficulty: UInt = 2
2019-10-09 01:37:44 +02:00
public static let defaultMessageTTL: UInt64 = 24 * 60 * 60 * 1000
2020-02-13 06:40:20 +01:00
public static let deviceLinkUpdateInterval: TimeInterval = 20
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
@objc public class LokiAPIError : NSError { // Not called `Error` for Obj-C interoperablity
@objc public static let proofOfWorkCalculationFailed = LokiAPIError(domain: "LokiAPIErrorDomain", code: 1, userInfo: [ NSLocalizedDescriptionKey : "Failed to calculate proof of work." ])
@objc public static let messageConversionFailed = LokiAPIError(domain: "LokiAPIErrorDomain", code: 2, userInfo: [ NSLocalizedDescriptionKey : "Failed to construct message." ])
@objc public static let clockOutOfSync = LokiAPIError(domain: "LokiAPIErrorDomain", code: 3, userInfo: [ NSLocalizedDescriptionKey : "Your clock is out of sync with the service node network." ])
@objc public static let randomSnodePoolUpdatingFailed = LokiAPIError(domain: "LokiAPIErrorDomain", code: 4, userInfo: [ NSLocalizedDescriptionKey : "Failed to update random service node pool." ])
@objc public static let missingSnodeVersion = LokiAPIError(domain: "LokiAPIErrorDomain", code: 5, userInfo: [ NSLocalizedDescriptionKey : "Missing service node version." ])
2019-05-07 02:10:15 +02:00
}
2019-09-30 04:08:55 +02:00
@objc(LKDestination)
public final class Destination : NSObject {
@objc public let hexEncodedPublicKey: String
@objc(kind)
public let objc_kind: String
public var kind: Kind {
return Kind(rawValue: objc_kind)!
}
2019-09-30 04:08:55 +02:00
public enum Kind : String { case master, slave }
public init(hexEncodedPublicKey: String, kind: Kind) {
self.hexEncodedPublicKey = hexEncodedPublicKey
self.objc_kind = kind.rawValue
}
@objc public init(hexEncodedPublicKey: String, kind: String) {
self.hexEncodedPublicKey = hexEncodedPublicKey
self.objc_kind = kind
}
2019-10-03 08:46:08 +02:00
override public func isEqual(_ other: Any?) -> Bool {
guard let other = other as? Destination else { return false }
return hexEncodedPublicKey == other.hexEncodedPublicKey && kind == other.kind
}
override public var hash: Int { // Override NSObject.hash and not Hashable.hashValue or Hashable.hash(into:)
return hexEncodedPublicKey.hashValue ^ kind.hashValue
}
override public var description: String { return "\(kind.rawValue)(\(hexEncodedPublicKey))" }
}
2019-05-28 01:57:54 +02:00
public typealias MessageListPromise = Promise<[SSKProtoEnvelope]>
2020-02-19 00:00:49 +01:00
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,
2020-04-06 03:11:24 +02:00
parameters: JSON, headers: [String:String]? = nil, timeout: TimeInterval? = nil) -> RawResponsePromise {
let url = URL(string: "\(target.address):\(target.port)/storage_rpc/v1")!
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
if useOnionRequests {
2020-04-06 05:26:26 +02:00
return OnionRequestAPI.sendOnionRequest(invoking: method, on: target, with: parameters, associatedWith: hexEncodedPublicKey).map { $0 as Any }
} else {
return TSNetworkManager.shared().perform(request, withCompletionQueue: DispatchQueue.global())
.map { $0.responseObject }
.handlingSnodeErrorsIfNeeded(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)
}
2019-09-30 04:08:55 +02:00
// MARK: Public API
public static func getMessages() -> Promise<Set<MessageListPromise>> {
return getTargetSnodes(for: userHexEncodedPublicKey).mapValues { targetSnode in
return getRawMessages(from: targetSnode, usingLongPolling: false).map { parseRawMessagesResponse($0, from: targetSnode) }
}.map { Set($0) }.retryingIfNeeded(maxRetryCount: maxRetryCount)
}
public static func getDestinations(for hexEncodedPublicKey: String) -> Promise<[Destination]> {
var result: Promise<[Destination]>!
2020-03-06 05:56:05 +01:00
storage.dbReadWriteConnection.readWrite { transaction in
result = getDestinations(for: hexEncodedPublicKey, in: transaction)
}
return result
}
public static func getDestinations(for hexEncodedPublicKey: String, in transaction: YapDatabaseReadWriteTransaction) -> Promise<[Destination]> {
// All of this has to happen on DispatchQueue.global() due to the way OWSMessageManager works
let (promise, seal) = Promise<[Destination]>.pending()
func getDestinations(in transaction: YapDatabaseReadTransaction? = nil) {
func getDestinationsInternal(in transaction: YapDatabaseReadTransaction) {
var destinations: [Destination] = []
let masterHexEncodedPublicKey = storage.getMasterHexEncodedPublicKey(for: hexEncodedPublicKey, in: transaction) ?? hexEncodedPublicKey
let masterDestination = Destination(hexEncodedPublicKey: masterHexEncodedPublicKey, kind: .master)
destinations.append(masterDestination)
let deviceLinks = storage.getDeviceLinks(for: masterHexEncodedPublicKey, in: transaction)
let slaveDestinations = deviceLinks.map { Destination(hexEncodedPublicKey: $0.slave.hexEncodedPublicKey, kind: .slave) }
destinations.append(contentsOf: slaveDestinations)
2019-09-30 04:08:55 +02:00
seal.fulfill(destinations)
}
2020-02-26 03:58:36 +01:00
if let transaction = transaction, transaction.connection.pendingTransactionCount != 0 {
getDestinationsInternal(in: transaction)
} else {
storage.dbReadConnection.read { transaction in
getDestinationsInternal(in: transaction)
}
}
2019-09-30 04:08:55 +02:00
}
let timeSinceLastUpdate: TimeInterval
if let lastDeviceLinkUpdate = lastDeviceLinkUpdate[hexEncodedPublicKey] {
timeSinceLastUpdate = Date().timeIntervalSince(lastDeviceLinkUpdate)
} else {
timeSinceLastUpdate = .infinity
}
if timeSinceLastUpdate > deviceLinkUpdateInterval {
let masterHexEncodedPublicKey = storage.getMasterHexEncodedPublicKey(for: hexEncodedPublicKey, in: transaction) ?? hexEncodedPublicKey
LokiFileServerAPI.getDeviceLinks(associatedWith: masterHexEncodedPublicKey, in: transaction).done(on: DispatchQueue.global()) { _ in
getDestinations()
lastDeviceLinkUpdate[hexEncodedPublicKey] = Date()
}.catch(on: DispatchQueue.global()) { error in
if (error as? LokiDotNetAPI.LokiDotNetAPIError) == LokiDotNetAPI.LokiDotNetAPIError.parsingFailed {
// Don't immediately re-fetch in case of failure due to a parsing error
2019-10-08 01:48:12 +02:00
lastDeviceLinkUpdate[hexEncodedPublicKey] = Date()
getDestinations()
} else {
2020-03-11 04:35:55 +01:00
print("[Loki] Failed to get device links due to error: \(error).")
seal.reject(error)
2019-10-08 01:48:12 +02:00
}
2019-09-30 04:08:55 +02:00
}
} else {
getDestinations(in: transaction)
2019-09-30 04:08:55 +02:00
}
return promise
}
public static func sendSignalMessage(_ signalMessage: SignalMessage, onP2PSuccess: @escaping () -> Void) -> Promise<Set<RawResponsePromise>> {
guard let lokiMessage = LokiMessage.from(signalMessage: signalMessage) else { return Promise(error: LokiAPIError.messageConversionFailed) }
let notificationCenter = NotificationCenter.default
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>> {
notificationCenter.post(name: .calculatingPoW, object: NSNumber(value: signalMessage.timestamp))
return lokiMessage.calculatePoW().then { lokiMessageWithPoW -> Promise<Set<RawResponsePromise>> in
2020-02-20 03:30:30 +01:00
notificationCenter.post(name: .routing, object: NSNumber(value: signalMessage.timestamp))
2019-08-02 01:28:04 +02:00
return getTargetSnodes(for: destination).map { swarm in
return Set(swarm.map { target in
2020-02-20 03:30:30 +01:00
notificationCenter.post(name: .messageSending, object: NSNumber(value: signalMessage.timestamp))
return sendLokiMessage(lokiMessageWithPoW, to: target).map { rawResponse in
2019-08-02 01:28:04 +02:00
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
2020-04-06 05:53:19 +02:00
}.retryingIfNeeded(maxRetryCount: maxRetryCount)
2019-08-02 01:28:04 +02:00
})
}.retryingIfNeeded(maxRetryCount: maxRetryCount)
}
}
if let peer = LokiP2PAPI.getInfo(for: destination), (lokiMessage.isPing || peer.isOnline) {
2020-01-24 03:59:47 +01:00
let target = LokiAPITarget(address: peer.address, port: peer.port, publicKeySet: nil)
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-09-30 04:08:55 +02:00
// MARK: Public API (Obj-C)
@objc(getDestinationsFor:)
public static func objc_getDestinations(for hexEncodedPublicKey: String) -> AnyPromise {
let promise = getDestinations(for: hexEncodedPublicKey)
return AnyPromise.from(promise)
}
@objc(getDestinationsFor:inTransaction:)
public static func objc_getDestinations(for hexEncodedPublicKey: String, in transaction: YapDatabaseReadWriteTransaction) -> AnyPromise {
let promise = getDestinations(for: hexEncodedPublicKey, in: transaction)
return AnyPromise.from(promise)
}
@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
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))
2020-04-07 01:33:29 +02:00
// FIXME: Move this out of here
if UserDefaults.standard[.isUsingFullAPNs] {
2020-04-06 04:02:55 +02:00
LokiPushNotificationManager.acknowledgeDelivery(forMessageWithHash: hashValue, expiration: expirationDate, hexEncodedPublicKey: userHexEncodedPublicKey)
}
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-11-27 04:54:45 +01:00
@objc public static func isDuplicateSyncMessage(_ syncMessage: SSKProtoSyncMessageSent, from hexEncodedPublicKey: String) -> Bool {
var timestamps: Set<UInt64> = syncMessageTimestamps[hexEncodedPublicKey] ?? []
2019-11-27 06:26:15 +01:00
let hasTimestamp = syncMessage.timestamp != 0
guard hasTimestamp else { return false }
2019-11-27 04:54:45 +01:00
let result = timestamps.contains(syncMessage.timestamp)
timestamps.insert(syncMessage.timestamp)
syncMessageTimestamps[hexEncodedPublicKey] = timestamps
return result
}
2019-08-29 07:52:51 +02:00
2019-10-09 01:37:44 +02:00
// MARK: Message Hash Caching
2019-08-29 07:52:51 +02:00
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)
}
}
2020-02-19 00:00:49 +01:00
private static let receivedMessageHashValuesKey = "receivedMessageHashValuesKey"
private static let receivedMessageHashValuesCollection = "receivedMessageHashValuesCollection"
2019-08-29 07:52:51 +02:00
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)
}
}
2019-10-08 06:02:03 +02:00
// MARK: User ID Caching
2019-10-11 06:52:56 +02:00
@objc public static func cache(_ hexEncodedPublicKey: String, for threadID: String) {
if let cache = userHexEncodedPublicKeyCache[threadID] {
userHexEncodedPublicKeyCache[threadID] = cache.union([ hexEncodedPublicKey ])
2019-10-08 06:02:03 +02:00
} else {
2019-10-11 06:52:56 +02:00
userHexEncodedPublicKeyCache[threadID] = [ hexEncodedPublicKey ]
2019-10-09 01:37:44 +02:00
}
}
2019-10-11 06:52:56 +02:00
@objc public static func getMentionCandidates(for query: String, in threadID: String) -> [Mention] {
2019-10-09 05:46:21 +02:00
// Prepare
2019-10-11 06:52:56 +02:00
guard let cache = userHexEncodedPublicKeyCache[threadID] else { return [] }
var candidates: [Mention] = []
2019-10-09 05:46:21 +02:00
// Gather candidates
2019-10-15 01:29:41 +02:00
var publicChat: LokiPublicChat?
2019-10-15 00:43:58 +02:00
storage.dbReadConnection.read { transaction in
2019-10-15 01:29:41 +02:00
publicChat = LokiDatabaseUtilities.getPublicChat(for: threadID, in: transaction)
2019-10-14 05:40:18 +02:00
}
2019-10-09 05:46:21 +02:00
storage.dbReadConnection.read { transaction in
2019-10-11 06:52:56 +02:00
candidates = cache.flatMap { hexEncodedPublicKey in
2019-10-14 05:40:18 +02:00
let uncheckedDisplayName: String?
2019-10-15 01:29:41 +02:00
if let publicChat = publicChat {
2020-01-30 23:42:36 +01:00
uncheckedDisplayName = UserDisplayNameUtilities.getPublicChatDisplayName(for: hexEncodedPublicKey, in: publicChat.channel, on: publicChat.server)
2019-10-14 05:40:18 +02:00
} else {
2020-01-30 23:42:36 +01:00
uncheckedDisplayName = UserDisplayNameUtilities.getPrivateChatDisplayName(for: hexEncodedPublicKey)
2019-10-14 05:40:18 +02:00
}
guard let displayName = uncheckedDisplayName else { return nil }
2019-10-11 06:52:56 +02:00
guard !displayName.hasPrefix("Anonymous") else { return nil }
return Mention(hexEncodedPublicKey: hexEncodedPublicKey, displayName: displayName)
2019-10-09 05:46:21 +02:00
}
}
2019-10-15 02:23:03 +02:00
candidates = candidates.filter { $0.hexEncodedPublicKey != userHexEncodedPublicKey }
2019-10-09 05:46:21 +02:00
// Sort alphabetically first
candidates.sort { $0.displayName < $1.displayName }
if query.count >= 2 {
// Filter out any non-matching candidates
2019-10-10 06:29:44 +02:00
candidates = candidates.filter { $0.displayName.lowercased().contains(query.lowercased()) }
2019-10-09 05:46:21 +02:00
// Sort based on where in the candidate the query occurs
2019-10-10 06:29:44 +02:00
candidates.sort {
$0.displayName.lowercased().range(of: query.lowercased())!.lowerBound < $1.displayName.lowercased().range(of: query.lowercased())!.lowerBound
}
2019-10-09 05:46:21 +02:00
}
// Return
2019-10-11 06:52:56 +02:00
return candidates
2019-10-09 05:46:21 +02:00
}
2019-10-11 06:52:56 +02:00
@objc public static func populateUserHexEncodedPublicKeyCacheIfNeeded(for threadID: String, in transaction: YapDatabaseReadWriteTransaction? = nil) {
guard userHexEncodedPublicKeyCache[threadID] == nil else { return }
2019-10-09 01:37:44 +02:00
var result: Set<String> = []
2019-10-09 02:16:10 +02:00
func populate(in transaction: YapDatabaseReadWriteTransaction) {
2019-10-09 01:37:44 +02:00
guard let thread = TSThread.fetch(uniqueId: threadID, transaction: transaction) else { return }
let interactions = transaction.ext(TSMessageDatabaseViewExtensionName) as! YapDatabaseViewTransaction
interactions.enumerateKeysAndObjects(inGroup: threadID) { _, _, object, index, _ in
guard let message = object as? TSIncomingMessage, index < userIDScanLimit else { return }
result.insert(message.authorId)
}
2019-10-08 06:02:03 +02:00
}
2019-10-09 02:16:10 +02:00
if let transaction = transaction {
populate(in: transaction)
} else {
storage.dbReadWriteConnection.readWrite { transaction in
populate(in: transaction)
}
}
2019-10-09 01:37:44 +02:00
result.insert(userHexEncodedPublicKey)
2019-10-11 06:52:56 +02:00
userHexEncodedPublicKeyCache[threadID] = result
2019-10-08 06:02:03 +02:00
}
2019-08-29 07:52:51 +02:00
}
// MARK: Error Handling
private extension Promise {
fileprivate func recoveringNetworkErrorsIfNeeded() -> Promise<T> {
return recover { error -> Promise<T> in
2019-08-29 07:52:51 +02:00
switch error {
case NetworkManagerError.taskError(_, let underlyingError): throw underlyingError
2020-01-24 05:55:07 +01:00
case LokiHTTPClient.HTTPError.networkError(_, _, let underlyingError): throw underlyingError ?? error
2019-08-29 07:52:51 +02:00
default: throw error
}
}
}
2019-05-08 08:02:53 +02:00
}