pull/187/head
nielsandriesse 5 years ago
parent e61be12bc1
commit f929f10a7f

@ -14,7 +14,6 @@ public final class LokiAPI : NSObject {
internal static let workQueue = DispatchQueue(label: "LokiAPI.workQueue", qos: .userInitiated) internal static let workQueue = DispatchQueue(label: "LokiAPI.workQueue", qos: .userInitiated)
internal static var storage: OWSPrimaryStorage { OWSPrimaryStorage.shared() } internal static var storage: OWSPrimaryStorage { OWSPrimaryStorage.shared() }
internal static var userHexEncodedPublicKey: String { getUserHexEncodedPublicKey() }
// MARK: Settings // MARK: Settings
private static let maxRetryCount: UInt = 4 private static let maxRetryCount: UInt = 4
@ -63,16 +62,16 @@ public final class LokiAPI : NSObject {
internal static func getRawMessages(from target: LokiAPITarget, usingLongPolling useLongPolling: Bool) -> RawResponsePromise { internal static func getRawMessages(from target: LokiAPITarget, usingLongPolling useLongPolling: Bool) -> RawResponsePromise {
let lastHashValue = getLastMessageHashValue(for: target) ?? "" let lastHashValue = getLastMessageHashValue(for: target) ?? ""
let parameters = [ "pubKey" : userHexEncodedPublicKey, "lastHash" : lastHashValue ] let parameters = [ "pubKey" : getUserHexEncodedPublicKey(), "lastHash" : lastHashValue ]
let headers: [String:String]? = useLongPolling ? [ "X-Loki-Long-Poll" : "true" ] : nil let headers: [String:String]? = useLongPolling ? [ "X-Loki-Long-Poll" : "true" ] : nil
let timeout: TimeInterval? = useLongPolling ? longPollingTimeout : nil let timeout: TimeInterval? = useLongPolling ? longPollingTimeout : nil
return invoke(.getMessages, on: target, associatedWith: userHexEncodedPublicKey, parameters: parameters, headers: headers, timeout: timeout) return invoke(.getMessages, on: target, associatedWith: getUserHexEncodedPublicKey(), parameters: parameters, headers: headers, timeout: timeout)
} }
// MARK: Public API // MARK: Public API
public static func getMessages() -> Promise<Set<MessageListPromise>> { public static func getMessages() -> Promise<Set<MessageListPromise>> {
return attempt(maxRetryCount: maxRetryCount, recoveringOn: workQueue) { return attempt(maxRetryCount: maxRetryCount, recoveringOn: workQueue) {
getTargetSnodes(for: userHexEncodedPublicKey).mapValues { targetSnode in getTargetSnodes(for: getUserHexEncodedPublicKey()).mapValues { targetSnode in
getRawMessages(from: targetSnode, usingLongPolling: false).map { parseRawMessagesResponse($0, from: targetSnode) } getRawMessages(from: targetSnode, usingLongPolling: false).map { parseRawMessagesResponse($0, from: targetSnode) }
}.map { Set($0) } }.map { Set($0) }
} }
@ -157,7 +156,7 @@ public final class LokiAPI : NSObject {
setLastMessageHashValue(for: target, hashValue: hashValue, expirationDate: UInt64(expirationDate)) setLastMessageHashValue(for: target, hashValue: hashValue, expirationDate: UInt64(expirationDate))
// FIXME: Move this out of here // FIXME: Move this out of here
if UserDefaults.standard[.isUsingFullAPNs] { if UserDefaults.standard[.isUsingFullAPNs] {
LokiPushNotificationManager.acknowledgeDelivery(forMessageWithHash: hashValue, expiration: expirationDate, hexEncodedPublicKey: userHexEncodedPublicKey) LokiPushNotificationManager.acknowledgeDelivery(forMessageWithHash: hashValue, expiration: expirationDate, hexEncodedPublicKey: getUserHexEncodedPublicKey())
} }
} else if (!rawMessages.isEmpty) { } else if (!rawMessages.isEmpty) {
print("[Loki] Failed to update last message hash value from: \(rawMessages).") print("[Loki] Failed to update last message hash value from: \(rawMessages).")

@ -6,7 +6,6 @@ public class LokiDotNetAPI : NSObject {
internal static var storage: OWSPrimaryStorage { OWSPrimaryStorage.shared() } internal static var storage: OWSPrimaryStorage { OWSPrimaryStorage.shared() }
internal static var userKeyPair: ECKeyPair { OWSIdentityManager.shared().identityKeyPair()! } internal static var userKeyPair: ECKeyPair { OWSIdentityManager.shared().identityKeyPair()! }
internal static var userHexEncodedPublicKey: String { userKeyPair.hexEncodedPublicKey }
// MARK: Settings // MARK: Settings
private static let attachmentType = "network.loki" private static let attachmentType = "network.loki"
@ -60,7 +59,7 @@ public class LokiDotNetAPI : NSObject {
// MARK: Private API // MARK: Private API
private static func requestNewAuthToken(for server: String) -> Promise<String> { private static func requestNewAuthToken(for server: String) -> Promise<String> {
print("[Loki] Requesting auth token for server: \(server).") print("[Loki] Requesting auth token for server: \(server).")
let queryParameters = "pubKey=\(userHexEncodedPublicKey)" let queryParameters = "pubKey=\(getUserHexEncodedPublicKey())"
let url = URL(string: "\(server)/loki/v1/get_challenge?\(queryParameters)")! let url = URL(string: "\(server)/loki/v1/get_challenge?\(queryParameters)")!
let request = TSRequest(url: url) let request = TSRequest(url: url)
return LokiFileServerProxy(for: server).perform(request, withCompletionQueue: LokiAPI.workQueue).map(on: LokiAPI.workQueue) { rawResponse in return LokiFileServerProxy(for: server).perform(request, withCompletionQueue: LokiAPI.workQueue).map(on: LokiAPI.workQueue) { rawResponse in
@ -85,7 +84,7 @@ public class LokiDotNetAPI : NSObject {
private static func submitAuthToken(_ token: String, for server: String) -> Promise<String> { private static func submitAuthToken(_ token: String, for server: String) -> Promise<String> {
print("[Loki] Submitting auth token for server: \(server).") print("[Loki] Submitting auth token for server: \(server).")
let url = URL(string: "\(server)/loki/v1/submit_challenge")! let url = URL(string: "\(server)/loki/v1/submit_challenge")!
let parameters = [ "pubKey" : userHexEncodedPublicKey, "token" : token ] let parameters = [ "pubKey" : getUserHexEncodedPublicKey(), "token" : token ]
let request = TSRequest(url: url, method: "POST", parameters: parameters) let request = TSRequest(url: url, method: "POST", parameters: parameters)
return LokiFileServerProxy(for: server).perform(request, withCompletionQueue: DispatchQueue.global()).map(on: DispatchQueue.global()) { _ in token } return LokiFileServerProxy(for: server).perform(request, withCompletionQueue: DispatchQueue.global()).map(on: DispatchQueue.global()) { _ in token }
} }

@ -103,7 +103,7 @@ public final class LokiFileServerAPI : LokiDotNetAPI {
public static func setDeviceLinks(_ deviceLinks: Set<DeviceLink>) -> Promise<Void> { public static func setDeviceLinks(_ deviceLinks: Set<DeviceLink>) -> Promise<Void> {
print("[Loki] Updating device links.") print("[Loki] Updating device links.")
return getAuthToken(for: server).then { token -> Promise<Void> in return getAuthToken(for: server).then { token -> Promise<Void> in
let isMaster = deviceLinks.contains { $0.master.hexEncodedPublicKey == userHexEncodedPublicKey } let isMaster = deviceLinks.contains { $0.master.hexEncodedPublicKey == getUserHexEncodedPublicKey() }
let deviceLinksAsJSON = deviceLinks.map { $0.toJSON() } let deviceLinksAsJSON = deviceLinks.map { $0.toJSON() }
let value = !deviceLinksAsJSON.isEmpty ? [ "isPrimary" : isMaster ? 1 : 0, "authorisations" : deviceLinksAsJSON ] : nil let value = !deviceLinksAsJSON.isEmpty ? [ "isPrimary" : isMaster ? 1 : 0, "authorisations" : deviceLinksAsJSON ] : nil
let annotation: JSON = [ "type" : deviceLinkType, "value" : value ] let annotation: JSON = [ "type" : deviceLinkType, "value" : value ]
@ -124,7 +124,7 @@ public final class LokiFileServerAPI : LokiDotNetAPI {
public static func addDeviceLink(_ deviceLink: DeviceLink) -> Promise<Void> { public static func addDeviceLink(_ deviceLink: DeviceLink) -> Promise<Void> {
var deviceLinks: Set<DeviceLink> = [] var deviceLinks: Set<DeviceLink> = []
storage.dbReadConnection.read { transaction in storage.dbReadConnection.read { transaction in
deviceLinks = storage.getDeviceLinks(for: userHexEncodedPublicKey, in: transaction) deviceLinks = storage.getDeviceLinks(for: getUserHexEncodedPublicKey(), in: transaction)
} }
deviceLinks.insert(deviceLink) deviceLinks.insert(deviceLink)
return setDeviceLinks(deviceLinks).then(on: LokiAPI.workQueue) { _ -> Promise<Void> in return setDeviceLinks(deviceLinks).then(on: LokiAPI.workQueue) { _ -> Promise<Void> in
@ -144,7 +144,7 @@ public final class LokiFileServerAPI : LokiDotNetAPI {
public static func removeDeviceLink(_ deviceLink: DeviceLink) -> Promise<Void> { public static func removeDeviceLink(_ deviceLink: DeviceLink) -> Promise<Void> {
var deviceLinks: Set<DeviceLink> = [] var deviceLinks: Set<DeviceLink> = []
storage.dbReadConnection.read { transaction in storage.dbReadConnection.read { transaction in
deviceLinks = storage.getDeviceLinks(for: userHexEncodedPublicKey, in: transaction) deviceLinks = storage.getDeviceLinks(for: getUserHexEncodedPublicKey(), in: transaction)
} }
deviceLinks.remove(deviceLink) deviceLinks.remove(deviceLink)
return setDeviceLinks(deviceLinks).then(on: LokiAPI.workQueue) { _ -> Promise<Void> in return setDeviceLinks(deviceLinks).then(on: LokiAPI.workQueue) { _ -> Promise<Void> in

@ -19,7 +19,7 @@ public final class LokiPublicChatAPI : LokiDotNetAPI {
// MARK: Convenience // MARK: Convenience
private static var userDisplayName: String { private static var userDisplayName: String {
return SSKEnvironment.shared.contactsManager.displayName(forPhoneIdentifier: userHexEncodedPublicKey) ?? "Anonymous" return SSKEnvironment.shared.contactsManager.displayName(forPhoneIdentifier: getUserHexEncodedPublicKey()) ?? "Anonymous"
} }
// MARK: Database // MARK: Database
@ -187,7 +187,7 @@ public final class LokiPublicChatAPI : LokiDotNetAPI {
throw LokiDotNetAPIError.parsingFailed throw LokiDotNetAPIError.parsingFailed
} }
let timestamp = UInt64(date.timeIntervalSince1970) * 1000 let timestamp = UInt64(date.timeIntervalSince1970) * 1000
return LokiPublicChatMessage(serverID: serverID, hexEncodedPublicKey: userHexEncodedPublicKey, displayName: displayName, profilePicture: signedMessage.profilePicture, body: body, type: publicChatMessageType, timestamp: timestamp, quote: signedMessage.quote, attachments: signedMessage.attachments, signature: signedMessage.signature) return LokiPublicChatMessage(serverID: serverID, hexEncodedPublicKey: getUserHexEncodedPublicKey(), displayName: displayName, profilePicture: signedMessage.profilePicture, body: body, type: publicChatMessageType, timestamp: timestamp, quote: signedMessage.quote, attachments: signedMessage.attachments, signature: signedMessage.signature)
} }
}.recover { error -> Promise<LokiPublicChatMessage> in }.recover { error -> Promise<LokiPublicChatMessage> in
if let error = error as? NetworkManagerError, error.statusCode == 401 { if let error = error as? NetworkManagerError, error.statusCode == 401 {

@ -215,7 +215,7 @@ public final class SessionManagementProtocol : NSObject {
// If we received a friend request (i.e. also a new pre key bundle), but we were already friends with the other user, reset the session. // If we received a friend request (i.e. also a new pre key bundle), but we were already friends with the other user, reset the session.
// The envelope type is set during UD decryption. // The envelope type is set during UD decryption.
// TODO: Should this ignore session requests? // TODO: Should this ignore session requests?
if envelope.type == .friendRequest, if envelope.type == .friendRequest, // TODO: Should this check that the envelope doesn't have the session request flag set?
let thread = TSContactThread.getWithContactId(hexEncodedPublicKey, transaction: transaction), // TODO: Should this be getOrCreate? let thread = TSContactThread.getWithContactId(hexEncodedPublicKey, transaction: transaction), // TODO: Should this be getOrCreate?
thread.isContactFriend { thread.isContactFriend {
receiving_startSessionReset(in: thread, using: transaction) receiving_startSessionReset(in: thread, using: transaction)

Loading…
Cancel
Save