pull/242/head
nielsandriesse 5 years ago
parent 548a0dc4e7
commit 7de8fbf66a

@ -135,7 +135,7 @@ final class HomeVC : BaseVC, UITableViewDataSource, UITableViewDelegate, UIScrol
newConversationButtonSet.center(.horizontal, in: view) newConversationButtonSet.center(.horizontal, in: view)
newConversationButtonSet.pin(.bottom, to: .bottom, of: view, withInset: -Values.newConversationButtonBottomOffset) // Negative due to how the constraint is set up newConversationButtonSet.pin(.bottom, to: .bottom, of: view, withInset: -Values.newConversationButtonBottomOffset) // Negative due to how the constraint is set up
// Set up previewing // Set up previewing
if (traitCollection.forceTouchCapability == .available) { if traitCollection.forceTouchCapability == .available {
registerForPreviewing(with: self, sourceView: tableView) registerForPreviewing(with: self, sourceView: tableView)
} }
// Listen for notifications // Listen for notifications

@ -0,0 +1,148 @@
import PromiseKit
public extension FileServerAPI {
/// Gets the device links associated with the given hex encoded public key from the
/// server and stores and returns the valid ones.
///
/// - Note: Deprecated.
public static func getDeviceLinks(associatedWith hexEncodedPublicKey: String) -> Promise<Set<DeviceLink>> {
return getDeviceLinks(associatedWith: [ hexEncodedPublicKey ])
}
/// Gets the device links associated with the given hex encoded public keys from the
/// server and stores and returns the valid ones.
///
/// - Note: Deprecated.
public static func getDeviceLinks(associatedWith hexEncodedPublicKeys: Set<String>) -> Promise<Set<DeviceLink>> {
return Promise.value([])
/*
let hexEncodedPublicKeysDescription = "[ \(hexEncodedPublicKeys.joined(separator: ", ")) ]"
print("[Loki] Getting device links for: \(hexEncodedPublicKeysDescription).")
return getAuthToken(for: server).then2 { token -> Promise<Set<DeviceLink>> in
let queryParameters = "ids=\(hexEncodedPublicKeys.map { "@\($0)" }.joined(separator: ","))&include_user_annotations=1"
let url = URL(string: "\(server)/users?\(queryParameters)")!
let request = TSRequest(url: url)
return OnionRequestAPI.sendOnionRequest(request, to: server, using: fileServerPublicKey).map2 { rawResponse -> Set<DeviceLink> in
guard let data = rawResponse["data"] as? [JSON] else {
print("[Loki] Couldn't parse device links for users: \(hexEncodedPublicKeys) from: \(rawResponse).")
throw DotNetAPIError.parsingFailed
}
return Set(data.flatMap { data -> [DeviceLink] in
guard let annotations = data["annotations"] as? [JSON], !annotations.isEmpty else { return [] }
guard let annotation = annotations.first(where: { $0["type"] as? String == deviceLinkType }),
let value = annotation["value"] as? JSON, let rawDeviceLinks = value["authorisations"] as? [JSON],
let hexEncodedPublicKey = data["username"] as? String else {
print("[Loki] Couldn't parse device links from: \(rawResponse).")
return []
}
return rawDeviceLinks.compactMap { rawDeviceLink in
guard let masterPublicKey = rawDeviceLink["primaryDevicePubKey"] as? String, let slavePublicKey = rawDeviceLink["secondaryDevicePubKey"] as? String,
let base64EncodedSlaveSignature = rawDeviceLink["requestSignature"] as? String else {
print("[Loki] Couldn't parse device link for user: \(hexEncodedPublicKey) from: \(rawResponse).")
return nil
}
let masterSignature: Data?
if let base64EncodedMasterSignature = rawDeviceLink["grantSignature"] as? String {
masterSignature = Data(base64Encoded: base64EncodedMasterSignature)
} else {
masterSignature = nil
}
let slaveSignature = Data(base64Encoded: base64EncodedSlaveSignature)
let master = DeviceLink.Device(publicKey: masterPublicKey, signature: masterSignature)
let slave = DeviceLink.Device(publicKey: slavePublicKey, signature: slaveSignature)
let deviceLink = DeviceLink(between: master, and: slave)
if let masterSignature = masterSignature {
guard DeviceLinkingUtilities.hasValidMasterSignature(deviceLink) else {
print("[Loki] Received a device link with an invalid master signature.")
return nil
}
}
guard DeviceLinkingUtilities.hasValidSlaveSignature(deviceLink) else {
print("[Loki] Received a device link with an invalid slave signature.")
return nil
}
return deviceLink
}
})
}.map2 { deviceLinks in
storage.setDeviceLinks(deviceLinks)
return deviceLinks
}
}.handlingInvalidAuthTokenIfNeeded(for: server)
*/
}
/// - Note: Deprecated.
public static func setDeviceLinks(_ deviceLinks: Set<DeviceLink>) -> Promise<Void> {
return Promise.value(())
/*
print("[Loki] Updating device links.")
return getAuthToken(for: server).then2 { token -> Promise<Void> in
let isMaster = deviceLinks.contains { $0.master.publicKey == getUserHexEncodedPublicKey() }
let deviceLinksAsJSON = deviceLinks.map { $0.toJSON() }
let value = !deviceLinksAsJSON.isEmpty ? [ "isPrimary" : isMaster ? 1 : 0, "authorisations" : deviceLinksAsJSON ] : nil
let annotation: JSON = [ "type" : deviceLinkType, "value" : value ]
let parameters: JSON = [ "annotations" : [ annotation ] ]
let url = URL(string: "\(server)/users/me")!
let request = TSRequest(url: url, method: "PATCH", parameters: parameters)
request.allHTTPHeaderFields = [ "Content-Type" : "application/json", "Authorization" : "Bearer \(token)" ]
return attempt(maxRetryCount: 8, recoveringOn: SnodeAPI.workQueue) {
OnionRequestAPI.sendOnionRequest(request, to: server, using: fileServerPublicKey).map2 { _ in }
}.handlingInvalidAuthTokenIfNeeded(for: server).recover2 { error in
print("[Loki] Couldn't update device links due to error: \(error).")
throw error
}
}
*/
}
/// Adds the given device link to the user's device mapping on the server.
///
/// - Note: Deprecated.
public static func addDeviceLink(_ deviceLink: DeviceLink) -> Promise<Void> {
return Promise.value(())
/*
var deviceLinks: Set<DeviceLink> = []
storage.dbReadConnection.read { transaction in
deviceLinks = storage.getDeviceLinks(for: getUserHexEncodedPublicKey(), in: transaction)
}
deviceLinks.insert(deviceLink)
return setDeviceLinks(deviceLinks).map2 { _ in
storage.addDeviceLink(deviceLink)
}
*/
}
/// Removes the given device link from the user's device mapping on the server.
///
/// - Note: Deprecated.
public static func removeDeviceLink(_ deviceLink: DeviceLink) -> Promise<Void> {
return Promise.value(())
/*
var deviceLinks: Set<DeviceLink> = []
storage.dbReadConnection.read { transaction in
deviceLinks = storage.getDeviceLinks(for: getUserHexEncodedPublicKey(), in: transaction)
}
deviceLinks.remove(deviceLink)
return setDeviceLinks(deviceLinks).map2 { _ in
storage.removeDeviceLink(deviceLink)
}
*/
}
}
@objc public extension FileServerAPI {
/// - Note: Deprecated.
@objc(getDeviceLinksAssociatedWithHexEncodedPublicKey:)
public static func objc_getDeviceLinks(associatedWith hexEncodedPublicKey: String) -> AnyPromise {
return AnyPromise.from(getDeviceLinks(associatedWith: hexEncodedPublicKey))
}
/// - Note: Deprecated.
@objc(getDeviceLinksAssociatedWithHexEncodedPublicKeys:)
public static func objc_getDeviceLinks(associatedWith hexEncodedPublicKeys: Set<String>) -> AnyPromise {
return AnyPromise.from(getDeviceLinks(associatedWith: hexEncodedPublicKeys))
}
}

@ -4,7 +4,6 @@ import SessionMetadataKit
/// Base class for `FileServerAPI` and `PublicChatAPI`. /// Base class for `FileServerAPI` and `PublicChatAPI`.
public class DotNetAPI : NSObject { public class DotNetAPI : NSObject {
internal static var storage: OWSPrimaryStorage { OWSPrimaryStorage.shared() }
internal static var userKeyPair: ECKeyPair { OWSIdentityManager.shared().identityKeyPair()! } internal static var userKeyPair: ECKeyPair { OWSIdentityManager.shared().identityKeyPair()! }
// MARK: Settings // MARK: Settings
@ -41,11 +40,9 @@ public class DotNetAPI : NSObject {
private static func getAuthTokenFromDatabase(for server: String) -> String? { private static func getAuthTokenFromDatabase(for server: String) -> String? {
var result: String? = nil var result: String? = nil
storage.dbReadConnection.read { transaction in Storage.read { transaction in
if transaction.hasObject(forKey: server, inCollection: authTokenCollection) {
result = transaction.object(forKey: server, inCollection: authTokenCollection) as? String result = transaction.object(forKey: server, inCollection: authTokenCollection) as? String
} }
}
return result return result
} }
@ -53,7 +50,7 @@ public class DotNetAPI : NSObject {
transaction.setObject(newValue, forKey: server, inCollection: authTokenCollection) transaction.setObject(newValue, forKey: server, inCollection: authTokenCollection)
} }
public static func clearAuthToken(for server: String) { public static func removeAuthToken(for server: String) {
try! Storage.writeSync { transaction in try! Storage.writeSync { transaction in
transaction.removeObject(forKey: server, inCollection: authTokenCollection) transaction.removeObject(forKey: server, inCollection: authTokenCollection)
} }
@ -68,12 +65,12 @@ public class DotNetAPI : NSObject {
let queryParameters = "pubKey=\(getUserHexEncodedPublicKey())" 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)
let serverPublicKeyPromise = (server == FileServerAPI.server) ? Promise { $0.fulfill(FileServerAPI.fileServerPublicKey) } let serverPublicKeyPromise = (server == FileServerAPI.server) ? Promise.value(FileServerAPI.fileServerPublicKey)
: PublicChatAPI.getOpenGroupServerPublicKey(for: server) : PublicChatAPI.getOpenGroupServerPublicKey(for: server)
return serverPublicKeyPromise.then2 { serverPublicKey in return serverPublicKeyPromise.then2 { serverPublicKey in
OnionRequestAPI.sendOnionRequest(request, to: server, using: serverPublicKey) OnionRequestAPI.sendOnionRequest(request, to: server, using: serverPublicKey)
}.map2 { rawResponse in }.map2 { json in
guard let json = rawResponse as? JSON, let base64EncodedChallenge = json["cipherText64"] as? String, let base64EncodedServerPublicKey = json["serverPubKey64"] as? String, guard let base64EncodedChallenge = json["cipherText64"] as? String, let base64EncodedServerPublicKey = json["serverPubKey64"] as? String,
let challenge = Data(base64Encoded: base64EncodedChallenge), var serverPublicKey = Data(base64Encoded: base64EncodedServerPublicKey) else { let challenge = Data(base64Encoded: base64EncodedChallenge), var serverPublicKey = Data(base64Encoded: base64EncodedServerPublicKey) else {
throw DotNetAPIError.parsingFailed throw DotNetAPIError.parsingFailed
} }
@ -96,7 +93,7 @@ public class DotNetAPI : NSObject {
let url = URL(string: "\(server)/loki/v1/submit_challenge")! let url = URL(string: "\(server)/loki/v1/submit_challenge")!
let parameters = [ "pubKey" : getUserHexEncodedPublicKey(), "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)
let serverPublicKeyPromise = (server == FileServerAPI.server) ? Promise { $0.fulfill(FileServerAPI.fileServerPublicKey) } let serverPublicKeyPromise = (server == FileServerAPI.server) ? Promise.value(FileServerAPI.fileServerPublicKey)
: PublicChatAPI.getOpenGroupServerPublicKey(for: server) : PublicChatAPI.getOpenGroupServerPublicKey(for: server)
return serverPublicKeyPromise.then2 { serverPublicKey in return serverPublicKeyPromise.then2 { serverPublicKey in
OnionRequestAPI.sendOnionRequest(request, to: server, using: serverPublicKey) OnionRequestAPI.sendOnionRequest(request, to: server, using: serverPublicKey)
@ -134,7 +131,7 @@ public class DotNetAPI : NSObject {
data = unencryptedAttachmentData data = unencryptedAttachmentData
} }
// Check the file size if needed // Check the file size if needed
print("[Loki] File size: \(data.count)") print("[Loki] File size: \(data.count) bytes.")
if Double(data.count) > Double(FileServerAPI.maxFileSize) / FileServerAPI.fileSizeORMultiplier { if Double(data.count) > Double(FileServerAPI.maxFileSize) / FileServerAPI.fileSizeORMultiplier {
return seal.reject(DotNetAPIError.maxFileSizeExceeded) return seal.reject(DotNetAPIError.maxFileSizeExceeded)
} }
@ -144,7 +141,7 @@ public class DotNetAPI : NSObject {
var error: NSError? var error: NSError?
var request = AFHTTPRequestSerializer().multipartFormRequest(withMethod: "POST", urlString: url, parameters: parameters, constructingBodyWith: { formData in var request = AFHTTPRequestSerializer().multipartFormRequest(withMethod: "POST", urlString: url, parameters: parameters, constructingBodyWith: { formData in
let uuid = UUID().uuidString let uuid = UUID().uuidString
print("[Loki] File UUID: \(uuid)") print("[Loki] File UUID: \(uuid).")
formData.appendPart(withFileData: data, name: "content", fileName: uuid, mimeType: "application/binary") formData.appendPart(withFileData: data, name: "content", fileName: uuid, mimeType: "application/binary")
}, error: &error) }, error: &error)
request.addValue("Bearer \(token)", forHTTPHeaderField: "Authorization") request.addValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
@ -153,7 +150,7 @@ public class DotNetAPI : NSObject {
return seal.reject(error) return seal.reject(error)
} }
// Send the request // Send the request
let serverPublicKeyPromise = (server == FileServerAPI.server) ? Promise { $0.fulfill(FileServerAPI.fileServerPublicKey) } let serverPublicKeyPromise = (server == FileServerAPI.server) ? Promise.value(FileServerAPI.fileServerPublicKey)
: PublicChatAPI.getOpenGroupServerPublicKey(for: server) : PublicChatAPI.getOpenGroupServerPublicKey(for: server)
attachment.isUploaded = false attachment.isUploaded = false
attachment.save() attachment.save()
@ -198,7 +195,7 @@ internal extension Promise {
return recover2 { error -> Promise<T> in return recover2 { error -> Promise<T> in
if case HTTP.Error.httpRequestFailed(let statusCode, _) = error, statusCode == 401 || statusCode == 403 { if case HTTP.Error.httpRequestFailed(let statusCode, _) = error, statusCode == 401 || statusCode == 403 {
print("[Loki] Auth token for: \(server) expired; dropping it.") print("[Loki] Auth token for: \(server) expired; dropping it.")
DotNetAPI.clearAuthToken(for: server) DotNetAPI.removeAuthToken(for: server)
} }
throw error throw error
} }

@ -70,146 +70,4 @@ public final class FileServerAPI : DotNetAPI {
return hexEncodedPrefixedPublicKey.removing05PrefixIfNeeded() return hexEncodedPrefixedPublicKey.removing05PrefixIfNeeded()
} }
} }
// MARK: Deprecated
/// - Note: Deprecated.
@objc(getDeviceLinksAssociatedWithHexEncodedPublicKey:)
public static func objc_getDeviceLinks(associatedWith hexEncodedPublicKey: String) -> AnyPromise {
return AnyPromise.from(getDeviceLinks(associatedWith: hexEncodedPublicKey))
}
/// Gets the device links associated with the given hex encoded public key from the
/// server and stores and returns the valid ones.
///
/// - Note: Deprecated.
public static func getDeviceLinks(associatedWith hexEncodedPublicKey: String) -> Promise<Set<DeviceLink>> {
return getDeviceLinks(associatedWith: [ hexEncodedPublicKey ])
}
/// - Note: Deprecated.
@objc(getDeviceLinksAssociatedWithHexEncodedPublicKeys:)
public static func objc_getDeviceLinks(associatedWith hexEncodedPublicKeys: Set<String>) -> AnyPromise {
return AnyPromise.from(getDeviceLinks(associatedWith: hexEncodedPublicKeys))
}
/// Gets the device links associated with the given hex encoded public keys from the
/// server and stores and returns the valid ones.
///
/// - Note: Deprecated.
public static func getDeviceLinks(associatedWith hexEncodedPublicKeys: Set<String>) -> Promise<Set<DeviceLink>> {
return Promise { $0.fulfill([]) }
/*
let hexEncodedPublicKeysDescription = "[ \(hexEncodedPublicKeys.joined(separator: ", ")) ]"
print("[Loki] Getting device links for: \(hexEncodedPublicKeysDescription).")
return getAuthToken(for: server).then2 { token -> Promise<Set<DeviceLink>> in
let queryParameters = "ids=\(hexEncodedPublicKeys.map { "@\($0)" }.joined(separator: ","))&include_user_annotations=1"
let url = URL(string: "\(server)/users?\(queryParameters)")!
let request = TSRequest(url: url)
return OnionRequestAPI.sendOnionRequest(request, to: server, using: fileServerPublicKey).map2 { rawResponse -> Set<DeviceLink> in
guard let data = rawResponse["data"] as? [JSON] else {
print("[Loki] Couldn't parse device links for users: \(hexEncodedPublicKeys) from: \(rawResponse).")
throw DotNetAPIError.parsingFailed
}
return Set(data.flatMap { data -> [DeviceLink] in
guard let annotations = data["annotations"] as? [JSON], !annotations.isEmpty else { return [] }
guard let annotation = annotations.first(where: { $0["type"] as? String == deviceLinkType }),
let value = annotation["value"] as? JSON, let rawDeviceLinks = value["authorisations"] as? [JSON],
let hexEncodedPublicKey = data["username"] as? String else {
print("[Loki] Couldn't parse device links from: \(rawResponse).")
return []
}
return rawDeviceLinks.compactMap { rawDeviceLink in
guard let masterPublicKey = rawDeviceLink["primaryDevicePubKey"] as? String, let slavePublicKey = rawDeviceLink["secondaryDevicePubKey"] as? String,
let base64EncodedSlaveSignature = rawDeviceLink["requestSignature"] as? String else {
print("[Loki] Couldn't parse device link for user: \(hexEncodedPublicKey) from: \(rawResponse).")
return nil
}
let masterSignature: Data?
if let base64EncodedMasterSignature = rawDeviceLink["grantSignature"] as? String {
masterSignature = Data(base64Encoded: base64EncodedMasterSignature)
} else {
masterSignature = nil
}
let slaveSignature = Data(base64Encoded: base64EncodedSlaveSignature)
let master = DeviceLink.Device(publicKey: masterPublicKey, signature: masterSignature)
let slave = DeviceLink.Device(publicKey: slavePublicKey, signature: slaveSignature)
let deviceLink = DeviceLink(between: master, and: slave)
if let masterSignature = masterSignature {
guard DeviceLinkingUtilities.hasValidMasterSignature(deviceLink) else {
print("[Loki] Received a device link with an invalid master signature.")
return nil
}
}
guard DeviceLinkingUtilities.hasValidSlaveSignature(deviceLink) else {
print("[Loki] Received a device link with an invalid slave signature.")
return nil
}
return deviceLink
}
})
}.map2 { deviceLinks in
storage.setDeviceLinks(deviceLinks)
return deviceLinks
}
}.handlingInvalidAuthTokenIfNeeded(for: server)
*/
}
/// - Note: Deprecated.
public static func setDeviceLinks(_ deviceLinks: Set<DeviceLink>) -> Promise<Void> {
return Promise { $0.fulfill(()) }
/*
print("[Loki] Updating device links.")
return getAuthToken(for: server).then2 { token -> Promise<Void> in
let isMaster = deviceLinks.contains { $0.master.publicKey == getUserHexEncodedPublicKey() }
let deviceLinksAsJSON = deviceLinks.map { $0.toJSON() }
let value = !deviceLinksAsJSON.isEmpty ? [ "isPrimary" : isMaster ? 1 : 0, "authorisations" : deviceLinksAsJSON ] : nil
let annotation: JSON = [ "type" : deviceLinkType, "value" : value ]
let parameters: JSON = [ "annotations" : [ annotation ] ]
let url = URL(string: "\(server)/users/me")!
let request = TSRequest(url: url, method: "PATCH", parameters: parameters)
request.allHTTPHeaderFields = [ "Content-Type" : "application/json", "Authorization" : "Bearer \(token)" ]
return attempt(maxRetryCount: 8, recoveringOn: SnodeAPI.workQueue) {
OnionRequestAPI.sendOnionRequest(request, to: server, using: fileServerPublicKey).map2 { _ in }
}.handlingInvalidAuthTokenIfNeeded(for: server).recover2 { error in
print("[Loki] Couldn't update device links due to error: \(error).")
throw error
}
}
*/
}
/// Adds the given device link to the user's device mapping on the server.
///
/// - Note: Deprecated.
public static func addDeviceLink(_ deviceLink: DeviceLink) -> Promise<Void> {
return Promise { $0.fulfill(()) }
/*
var deviceLinks: Set<DeviceLink> = []
storage.dbReadConnection.read { transaction in
deviceLinks = storage.getDeviceLinks(for: getUserHexEncodedPublicKey(), in: transaction)
}
deviceLinks.insert(deviceLink)
return setDeviceLinks(deviceLinks).map2 { _ in
storage.addDeviceLink(deviceLink)
}
*/
}
/// Removes the given device link from the user's device mapping on the server.
///
/// - Note: Deprecated.
public static func removeDeviceLink(_ deviceLink: DeviceLink) -> Promise<Void> {
return Promise { $0.fulfill(()) }
/*
var deviceLinks: Set<DeviceLink> = []
storage.dbReadConnection.read { transaction in
deviceLinks = storage.getDeviceLinks(for: getUserHexEncodedPublicKey(), in: transaction)
}
deviceLinks.remove(deviceLink)
return setDeviceLinks(deviceLinks).map2 { _ in
storage.removeDeviceLink(deviceLink)
}
*/
}
} }

@ -290,8 +290,8 @@ public enum OnionRequestAPI {
let url = "\(guardSnode.address):\(guardSnode.port)/onion_req" let url = "\(guardSnode.address):\(guardSnode.port)/onion_req"
let finalEncryptionResult = intermediate.finalEncryptionResult let finalEncryptionResult = intermediate.finalEncryptionResult
let onion = finalEncryptionResult.ciphertext let onion = finalEncryptionResult.ciphertext
if case Destination.server = destination { if case Destination.server = destination, Double(onion.count) > 0.75 * (Double(FileServerAPI.maxFileSize) / FileServerAPI.fileSizeORMultiplier) {
print("[Loki] Onion request size: ~\(onion.count)") print("[Loki] Approaching request size limit: ~\(onion.count) bytes.")
} }
let parameters: JSON = [ let parameters: JSON = [
"ciphertext" : onion.base64EncodedString(), "ciphertext" : onion.base64EncodedString(),
@ -327,7 +327,7 @@ public enum OnionRequestAPI {
guard 200...299 ~= statusCode else { return seal.reject(Error.httpRequestFailedAtTargetSnode(statusCode: UInt(statusCode), json: json)) } guard 200...299 ~= statusCode else { return seal.reject(Error.httpRequestFailedAtTargetSnode(statusCode: UInt(statusCode), json: json)) }
seal.fulfill(json) seal.fulfill(json)
} }
} catch (let error) { } catch {
seal.reject(error) seal.reject(error)
} }
}.catch2 { error in }.catch2 { error in

@ -32,7 +32,7 @@ public final class PublicChatAPI : DotNetAPI {
private static func getLastMessageServerID(for group: UInt64, on server: String) -> UInt? { private static func getLastMessageServerID(for group: UInt64, on server: String) -> UInt? {
var result: UInt? = nil var result: UInt? = nil
storage.dbReadConnection.read { transaction in Storage.read { transaction in
result = transaction.object(forKey: "\(server).\(group)", inCollection: lastMessageServerIDCollection) as! UInt? result = transaction.object(forKey: "\(server).\(group)", inCollection: lastMessageServerIDCollection) as! UInt?
} }
return result return result
@ -52,7 +52,7 @@ public final class PublicChatAPI : DotNetAPI {
private static func getLastDeletionServerID(for group: UInt64, on server: String) -> UInt? { private static func getLastDeletionServerID(for group: UInt64, on server: String) -> UInt? {
var result: UInt? = nil var result: UInt? = nil
storage.dbReadConnection.read { transaction in Storage.read { transaction in
result = transaction.object(forKey: "\(server).\(group)", inCollection: lastDeletionServerIDCollection) as! UInt? result = transaction.object(forKey: "\(server).\(group)", inCollection: lastDeletionServerIDCollection) as! UInt?
} }
return result return result
@ -174,8 +174,8 @@ public final class PublicChatAPI : DotNetAPI {
return nil return nil
} }
var existingMessageID: String? = nil var existingMessageID: String? = nil
storage.dbReadConnection.read { transaction in Storage.read { transaction in
existingMessageID = storage.getIDForMessage(withServerID: UInt(result.serverID!), in: transaction) existingMessageID = OWSPrimaryStorage.shared().getIDForMessage(withServerID: UInt(result.serverID!), in: transaction)
} }
guard existingMessageID == nil else { guard existingMessageID == nil else {
print("[Loki] Ignoring duplicate public chat message.") print("[Loki] Ignoring duplicate public chat message.")

@ -60,16 +60,16 @@ public final class PublicChatPoller : NSObject {
let uniquePublicKeys = Set(messages.map { $0.senderPublicKey }) let uniquePublicKeys = Set(messages.map { $0.senderPublicKey })
func proceed() { func proceed() {
let storage = OWSPrimaryStorage.shared() let storage = OWSPrimaryStorage.shared()
var newDisplayNameUpdatees: Set<String> = []
/* /*
var newDisplayNameUpdatees: Set<String> = []
storage.dbReadConnection.read { transaction in storage.dbReadConnection.read { transaction in
newDisplayNameUpdatees = Set(uniquePublicKeys.filter { storage.getMasterHexEncodedPublicKey(for: $0, in: transaction) != $0 }.compactMap { storage.getMasterHexEncodedPublicKey(for: $0, in: transaction) }) newDisplayNameUpdatees = Set(uniquePublicKeys.filter { storage.getMasterHexEncodedPublicKey(for: $0, in: transaction) != $0 }.compactMap { storage.getMasterHexEncodedPublicKey(for: $0, in: transaction) })
} }
*/
if !newDisplayNameUpdatees.isEmpty { if !newDisplayNameUpdatees.isEmpty {
let displayNameUpdatees = PublicChatAPI.displayNameUpdatees[publicChat.id] ?? [] let displayNameUpdatees = PublicChatAPI.displayNameUpdatees[publicChat.id] ?? []
PublicChatAPI.displayNameUpdatees[publicChat.id] = displayNameUpdatees.union(newDisplayNameUpdatees) PublicChatAPI.displayNameUpdatees[publicChat.id] = displayNameUpdatees.union(newDisplayNameUpdatees)
} }
*/
// Sorting the messages by timestamp before importing them fixes an issue where messages that quote older messages can't find those older messages // Sorting the messages by timestamp before importing them fixes an issue where messages that quote older messages can't find those older messages
messages.sorted { $0.timestamp < $1.timestamp }.forEach { message in messages.sorted { $0.timestamp < $1.timestamp }.forEach { message in
var wasSentByCurrentUser = false var wasSentByCurrentUser = false

@ -119,7 +119,7 @@ public final class SnodeAPI : NSObject {
if let cachedSwarm = swarmCache[publicKey], cachedSwarm.count >= minimumSwarmSnodeCount && !isForcedReload { if let cachedSwarm = swarmCache[publicKey], cachedSwarm.count >= minimumSwarmSnodeCount && !isForcedReload {
return Promise<[Snode]> { $0.fulfill(cachedSwarm) } return Promise<[Snode]> { $0.fulfill(cachedSwarm) }
} else { } else {
print("[Loki] Getting swarm for: \(publicKey).") print("[Loki] Getting swarm for: \(publicKey == getUserHexEncodedPublicKey() ? "self" : publicKey).")
let parameters: [String:Any] = [ "pubKey" : publicKey ] let parameters: [String:Any] = [ "pubKey" : publicKey ]
return getRandomSnode().then2 { return getRandomSnode().then2 {
invoke(.getSwarm, on: $0, associatedWith: publicKey, parameters: parameters) invoke(.getSwarm, on: $0, associatedWith: publicKey, parameters: parameters)

@ -26,6 +26,8 @@ public final class LokiDatabaseUtilities : NSObject {
// MARK: - Device Links // MARK: - Device Links
@objc(getLinkedDeviceHexEncodedPublicKeysFor:in:) @objc(getLinkedDeviceHexEncodedPublicKeysFor:in:)
public static func getLinkedDeviceHexEncodedPublicKeys(for hexEncodedPublicKey: String, in transaction: YapDatabaseReadTransaction) -> Set<String> { public static func getLinkedDeviceHexEncodedPublicKeys(for hexEncodedPublicKey: String, in transaction: YapDatabaseReadTransaction) -> Set<String> {
return [ hexEncodedPublicKey ]
/*
let storage = OWSPrimaryStorage.shared() let storage = OWSPrimaryStorage.shared()
let masterHexEncodedPublicKey = storage.getMasterHexEncodedPublicKey(for: hexEncodedPublicKey, in: transaction) ?? hexEncodedPublicKey let masterHexEncodedPublicKey = storage.getMasterHexEncodedPublicKey(for: hexEncodedPublicKey, in: transaction) ?? hexEncodedPublicKey
var result = Set(storage.getDeviceLinks(for: masterHexEncodedPublicKey, in: transaction).flatMap { deviceLink in var result = Set(storage.getDeviceLinks(for: masterHexEncodedPublicKey, in: transaction).flatMap { deviceLink in
@ -33,28 +35,35 @@ public final class LokiDatabaseUtilities : NSObject {
}) })
result.insert(hexEncodedPublicKey) result.insert(hexEncodedPublicKey)
return result return result
*/
} }
@objc(getLinkedDeviceThreadsFor:in:) @objc(getLinkedDeviceThreadsFor:in:)
public static func getLinkedDeviceThreads(for hexEncodedPublicKey: String, in transaction: YapDatabaseReadTransaction) -> Set<TSContactThread> { public static func getLinkedDeviceThreads(for hexEncodedPublicKey: String, in transaction: YapDatabaseReadTransaction) -> Set<TSContactThread> {
return Set(getLinkedDeviceHexEncodedPublicKeys(for: hexEncodedPublicKey, in: transaction).compactMap { TSContactThread.getWithContactId($0, transaction: transaction) }) return Set([ TSContactThread.getWithContactId(hexEncodedPublicKey, transaction: transaction) ].compactMap { $0 })
// return Set(getLinkedDeviceHexEncodedPublicKeys(for: hexEncodedPublicKey, in: transaction).compactMap { TSContactThread.getWithContactId($0, transaction: transaction) })
} }
@objc(isUserLinkedDevice:in:) @objc(isUserLinkedDevice:in:)
public static func isUserLinkedDevice(_ hexEncodedPublicKey: String, transaction: YapDatabaseReadTransaction) -> Bool { public static func isUserLinkedDevice(_ hexEncodedPublicKey: String, transaction: YapDatabaseReadTransaction) -> Bool {
return hexEncodedPublicKey == getUserHexEncodedPublicKey()
/*
let userHexEncodedPublicKey = getUserHexEncodedPublicKey() let userHexEncodedPublicKey = getUserHexEncodedPublicKey()
let userLinkedDeviceHexEncodedPublicKeys = getLinkedDeviceHexEncodedPublicKeys(for: userHexEncodedPublicKey, in: transaction) let userLinkedDeviceHexEncodedPublicKeys = getLinkedDeviceHexEncodedPublicKeys(for: userHexEncodedPublicKey, in: transaction)
return userLinkedDeviceHexEncodedPublicKeys.contains(hexEncodedPublicKey) return userLinkedDeviceHexEncodedPublicKeys.contains(hexEncodedPublicKey)
*/
} }
@objc(getMasterHexEncodedPublicKeyFor:in:) @objc(getMasterHexEncodedPublicKeyFor:in:)
public static func objc_getMasterHexEncodedPublicKey(for slaveHexEncodedPublicKey: String, in transaction: YapDatabaseReadTransaction) -> String? { public static func objc_getMasterHexEncodedPublicKey(for slaveHexEncodedPublicKey: String, in transaction: YapDatabaseReadTransaction) -> String? {
return OWSPrimaryStorage.shared().getMasterHexEncodedPublicKey(for: slaveHexEncodedPublicKey, in: transaction) return nil
// return OWSPrimaryStorage.shared().getMasterHexEncodedPublicKey(for: slaveHexEncodedPublicKey, in: transaction)
} }
@objc(getDeviceLinksFor:in:) @objc(getDeviceLinksFor:in:)
public static func objc_getDeviceLinks(for masterHexEncodedPublicKey: String, in transaction: YapDatabaseReadTransaction) -> Set<DeviceLink> { public static func objc_getDeviceLinks(for masterHexEncodedPublicKey: String, in transaction: YapDatabaseReadTransaction) -> Set<DeviceLink> {
return OWSPrimaryStorage.shared().getDeviceLinks(for: masterHexEncodedPublicKey, in: transaction) return []
// return OWSPrimaryStorage.shared().getDeviceLinks(for: masterHexEncodedPublicKey, in: transaction)
} }

@ -30,7 +30,7 @@ public extension OWSPrimaryStorage {
// MARK: Swarm // MARK: Swarm
public func setSwarm(_ swarm: [Snode], for publicKey: String, in transaction: YapDatabaseReadWriteTransaction) { public func setSwarm(_ swarm: [Snode], for publicKey: String, in transaction: YapDatabaseReadWriteTransaction) {
print("[Loki] Caching swarm for: \(publicKey).") print("[Loki] Caching swarm for: \(publicKey == getUserHexEncodedPublicKey() ? "self" : publicKey).")
clearSwarm(for: publicKey, in: transaction) clearSwarm(for: publicKey, in: transaction)
let collection = Storage.getSwarmCollection(for: publicKey) let collection = Storage.getSwarmCollection(for: publicKey)
swarm.forEach { snode in swarm.forEach { snode in

@ -19,8 +19,7 @@ public final class SessionMetaProtocol : NSObject {
// MARK: Message Destination(s) // MARK: Message Destination(s)
@objc public static func getDestinationsForOutgoingSyncMessage() -> NSMutableSet { @objc public static func getDestinationsForOutgoingSyncMessage() -> NSMutableSet {
return NSMutableSet(set: [ getUserHexEncodedPublicKey() ]) return NSMutableSet(set: [ getUserHexEncodedPublicKey() ]) // return NSMutableSet(set: MultiDeviceProtocol.getUserLinkedDevices())
// return NSMutableSet(set: MultiDeviceProtocol.getUserLinkedDevices())
} }
@objc(getDestinationsForOutgoingGroupMessage:inThread:) @objc(getDestinationsForOutgoingGroupMessage:inThread:)
@ -42,8 +41,7 @@ public final class SessionMetaProtocol : NSObject {
} else { } else {
result = Set(outgoingGroupMessage.sendingRecipientIds()) result = Set(outgoingGroupMessage.sendingRecipientIds())
.intersection(thread.groupModel.groupMemberIds) .intersection(thread.groupModel.groupMemberIds)
.subtracting([ getUserHexEncodedPublicKey() ]) .subtracting([ getUserHexEncodedPublicKey() ]) // .subtracting(MultiDeviceProtocol.getUserLinkedDevices())
// .subtracting(MultiDeviceProtocol.getUserLinkedDevices())
} }
} }
return NSMutableSet(set: result) return NSMutableSet(set: result)
@ -54,11 +52,13 @@ public final class SessionMetaProtocol : NSObject {
public static func isThreadNoteToSelf(_ thread: TSThread) -> Bool { public static func isThreadNoteToSelf(_ thread: TSThread) -> Bool {
guard let thread = thread as? TSContactThread else { return false } guard let thread = thread as? TSContactThread else { return false }
return thread.contactIdentifier() == getUserHexEncodedPublicKey() return thread.contactIdentifier() == getUserHexEncodedPublicKey()
// var isNoteToSelf = false /*
// storage.dbReadConnection.read { transaction in var isNoteToSelf = false
// isNoteToSelf = LokiDatabaseUtilities.isUserLinkedDevice(thread.contactIdentifier(), transaction: transaction) storage.dbReadConnection.read { transaction in
// } isNoteToSelf = LokiDatabaseUtilities.isUserLinkedDevice(thread.contactIdentifier(), transaction: transaction)
// return isNoteToSelf }
return isNoteToSelf
*/
} }
// MARK: Transcripts // MARK: Transcripts
@ -69,12 +69,14 @@ public final class SessionMetaProtocol : NSObject {
let wouldSignalRequireTranscript = (AreRecipientUpdatesEnabled() || !message.hasSyncedTranscript) let wouldSignalRequireTranscript = (AreRecipientUpdatesEnabled() || !message.hasSyncedTranscript)
guard wouldSignalRequireTranscript && !isOpenGroupMessage else { return false } guard wouldSignalRequireTranscript && !isOpenGroupMessage else { return false }
return false return false
// var usesMultiDevice = false /*
// storage.dbReadConnection.read { transaction in var usesMultiDevice = false
// usesMultiDevice = !storage.getDeviceLinks(for: getUserHexEncodedPublicKey(), in: transaction).isEmpty storage.dbReadConnection.read { transaction in
// || UserDefaults.standard[.masterHexEncodedPublicKey] != nil usesMultiDevice = !storage.getDeviceLinks(for: getUserHexEncodedPublicKey(), in: transaction).isEmpty
// } || UserDefaults.standard[.masterHexEncodedPublicKey] != nil
// return usesMultiDevice }
return usesMultiDevice
*/
} }
// MARK: Typing Indicators // MARK: Typing Indicators
@ -96,12 +98,14 @@ public final class SessionMetaProtocol : NSObject {
@objc(shouldSkipMessageDecryptResult:wrappedIn:) @objc(shouldSkipMessageDecryptResult:wrappedIn:)
public static func shouldSkipMessageDecryptResult(_ result: OWSMessageDecryptResult, wrappedIn envelope: SSKProtoEnvelope) -> Bool { public static func shouldSkipMessageDecryptResult(_ result: OWSMessageDecryptResult, wrappedIn envelope: SSKProtoEnvelope) -> Bool {
return result.source == getUserHexEncodedPublicKey() return result.source == getUserHexEncodedPublicKey()
// if result.source == getUserHexEncodedPublicKey() { return true } /*
// var isLinkedDevice = false if result.source == getUserHexEncodedPublicKey() { return true }
// Storage.read { transaction in var isLinkedDevice = false
// isLinkedDevice = LokiDatabaseUtilities.isUserLinkedDevice(result.source, transaction: transaction) Storage.read { transaction in
// } isLinkedDevice = LokiDatabaseUtilities.isUserLinkedDevice(result.source, transaction: transaction)
// return isLinkedDevice && envelope.type == .closedGroupCiphertext }
return isLinkedDevice && envelope.type == .closedGroupCiphertext
*/
} }
@objc(updateDisplayNameIfNeededForPublicKey:using:transaction:) @objc(updateDisplayNameIfNeededForPublicKey:using:transaction:)
@ -127,8 +131,7 @@ public final class SessionMetaProtocol : NSObject {
public static func updateProfileKeyIfNeeded(for publicKey: String, using dataMessage: SSKProtoDataMessage) { public static func updateProfileKeyIfNeeded(for publicKey: String, using dataMessage: SSKProtoDataMessage) {
guard dataMessage.hasProfileKey, let profileKey = dataMessage.profileKey else { return } guard dataMessage.hasProfileKey, let profileKey = dataMessage.profileKey else { return }
guard profileKey.count == kAES256_KeyByteLength else { guard profileKey.count == kAES256_KeyByteLength else {
print("[Loki] Unexpected profile key size: \(profileKey.count).") return print("[Loki] Unexpected profile key size: \(profileKey.count).")
return
} }
let profilePictureURL = dataMessage.profile?.profilePicture let profilePictureURL = dataMessage.profile?.profilePicture
let profileManager = SSKEnvironment.shared.profileManager let profileManager = SSKEnvironment.shared.profileManager

@ -25,11 +25,7 @@ public final class LokiPushNotificationManager : NSObject {
let isUsingFullAPNs = userDefaults[.isUsingFullAPNs] let isUsingFullAPNs = userDefaults[.isUsingFullAPNs]
let now = Date().timeIntervalSince1970 let now = Date().timeIntervalSince1970
guard isForcedUpdate || hexEncodedToken != oldToken || now - lastUploadTime > tokenExpirationInterval else { guard isForcedUpdate || hexEncodedToken != oldToken || now - lastUploadTime > tokenExpirationInterval else {
print("[Loki] Device token hasn't changed; no need to re-upload.") print("[Loki] Device token hasn't changed or expired; no need to re-upload.")
return Promise<Void> { $0.fulfill(()) }
}
guard !isUsingFullAPNs else {
print("[Loki] Using full APNs; ignoring call to register(with:).")
return Promise<Void> { $0.fulfill(()) } return Promise<Void> { $0.fulfill(()) }
} }
let parameters = [ "token" : hexEncodedToken ] let parameters = [ "token" : hexEncodedToken ]
@ -70,7 +66,7 @@ public final class LokiPushNotificationManager : NSObject {
let lastUploadTime = userDefaults[.lastDeviceTokenUpload] let lastUploadTime = userDefaults[.lastDeviceTokenUpload]
let now = Date().timeIntervalSince1970 let now = Date().timeIntervalSince1970
guard isForcedUpdate || hexEncodedToken != oldToken || now - lastUploadTime > tokenExpirationInterval else { guard isForcedUpdate || hexEncodedToken != oldToken || now - lastUploadTime > tokenExpirationInterval else {
print("[Loki] Device token hasn't changed; no need to re-upload.") print("[Loki] Device token hasn't changed or expired; no need to re-upload.")
return Promise<Void> { $0.fulfill(()) } return Promise<Void> { $0.fulfill(()) }
} }
let parameters = [ "token" : hexEncodedToken, "pubKey" : hexEncodedPublicKey] let parameters = [ "token" : hexEncodedToken, "pubKey" : hexEncodedPublicKey]

@ -1511,9 +1511,9 @@ NS_ASSUME_NONNULL_BEGIN
serverTimestamp:serverTimestamp serverTimestamp:serverTimestamp
wasReceivedByUD:wasReceivedByUD]; wasReceivedByUD:wasReceivedByUD];
[LKSessionMetaProtocol updateDisplayNameIfNeededForPublicKey:incomingMessage.authorId using:dataMessage transaction:transaction]; [LKSessionMetaProtocol updateProfileKeyIfNeededForPublicKey:masterPublicKey using:dataMessage];
[LKSessionMetaProtocol updateProfileKeyIfNeededForPublicKey:thread.contactIdentifier using:dataMessage]; [LKSessionMetaProtocol updateDisplayNameIfNeededForPublicKey:masterPublicKey using:dataMessage transaction:transaction];
NSArray<TSAttachmentPointer *> *attachmentPointers = NSArray<TSAttachmentPointer *> *attachmentPointers =
[TSAttachmentPointer attachmentPointersFromProtos:dataMessage.attachments albumMessage:incomingMessage]; [TSAttachmentPointer attachmentPointersFromProtos:dataMessage.attachments albumMessage:incomingMessage];

@ -598,7 +598,7 @@ NSString *const OWSMessageSenderRateLimitedException = @"RateLimitedException";
resolve(error); resolve(error);
}]; }];
NSString *publicKey = recipients.firstObject.recipientId; // NSString *publicKey = recipients.firstObject.recipientId;
// if ([LKMultiDeviceProtocol isMultiDeviceRequiredForMessage:message toPublicKey:publicKey]) { // Avoid the write transaction if possible // if ([LKMultiDeviceProtocol isMultiDeviceRequiredForMessage:message toPublicKey:publicKey]) { // Avoid the write transaction if possible
// [self.primaryStorage.dbReadConnection readWithBlock:^(YapDatabaseReadTransaction *transaction) { // [self.primaryStorage.dbReadConnection readWithBlock:^(YapDatabaseReadTransaction *transaction) {
// [LKMultiDeviceProtocol sendMessageToDestinationAndLinkedDevices:messageSend transaction:transaction]; // [LKMultiDeviceProtocol sendMessageToDestinationAndLinkedDevices:messageSend transaction:transaction];

@ -397,7 +397,7 @@ public class TypingIndicatorsImpl: NSObject, TypingIndicators {
AssertIsOnMainThread() AssertIsOnMainThread()
displayTypingTimer?.invalidate() displayTypingTimer?.invalidate()
displayTypingTimer = Timer.weakScheduledTimer(withTimeInterval: 15, displayTypingTimer = Timer.weakScheduledTimer(withTimeInterval: 5,
target: self, target: self,
selector: #selector(IncomingIndicators.displayTypingTimerDidFire), selector: #selector(IncomingIndicators.displayTypingTimerDidFire),
userInfo: nil, userInfo: nil,

Loading…
Cancel
Save