Fix module linking issue

This commit is contained in:
nielsandriesse 2020-12-02 16:25:16 +11:00
parent ec4b26e76a
commit d6c115bc2a
29 changed files with 116 additions and 116 deletions

View File

@ -1,14 +1,14 @@
import SessionProtocolKit import SessionProtocolKit
@objc(SNMessagingKitConfiguration) @objc
public final class Configuration : NSObject { public final class SNMessagingKitConfiguration : NSObject {
public let storage: SessionMessagingKitStorageProtocol public let storage: SessionMessagingKitStorageProtocol
@objc public let signalStorage: SessionStore & PreKeyStore & SignedPreKeyStore @objc public let signalStorage: SessionStore & PreKeyStore & SignedPreKeyStore
public let identityKeyStore: IdentityKeyStore public let identityKeyStore: IdentityKeyStore
public let sessionRestorationImplementation: SessionRestorationProtocol public let sessionRestorationImplementation: SessionRestorationProtocol
public let certificateValidator: SMKCertificateValidator public let certificateValidator: SMKCertificateValidator
@objc public static var shared: Configuration! @objc public static var shared: SNMessagingKitConfiguration!
fileprivate init( fileprivate init(
storage: SessionMessagingKitStorageProtocol, storage: SessionMessagingKitStorageProtocol,
@ -34,7 +34,7 @@ public enum SNMessagingKit { // Just to make the external API nice
sessionRestorationImplementation: SessionRestorationProtocol, sessionRestorationImplementation: SessionRestorationProtocol,
certificateValidator: SMKCertificateValidator certificateValidator: SMKCertificateValidator
) { ) {
Configuration.shared = Configuration( SNMessagingKitConfiguration.shared = SNMessagingKitConfiguration(
storage: storage, storage: storage,
signalStorage: signalStorage, signalStorage: signalStorage,
identityKeyStore: identityKeyStore, identityKeyStore: identityKeyStore,

View File

@ -49,7 +49,7 @@ public final class FileServerAPI : DotNetAPI {
SNLog("Couldn't parse profile picture from: \(json).") SNLog("Couldn't parse profile picture from: \(json).")
throw Error.parsingFailed throw Error.parsingFailed
} }
Configuration.shared.storage.setLastProfilePictureUploadDate(Date()) SNMessagingKitConfiguration.shared.storage.setLastProfilePictureUploadDate(Date())
return downloadURL return downloadURL
} }
} }

View File

@ -52,7 +52,7 @@ public final class AttachmentDownloadJob : NSObject, Job, NSCoding { // NSObject
guard let pointer = TSAttachmentPointer.fetch(uniqueId: attachmentID) else { guard let pointer = TSAttachmentPointer.fetch(uniqueId: attachmentID) else {
return handleFailure(error: Error.noAttachment) return handleFailure(error: Error.noAttachment)
} }
let storage = Configuration.shared.storage let storage = SNMessagingKitConfiguration.shared.storage
storage.withAsync({ transaction in storage.withAsync({ transaction in
storage.setAttachmentState(to: .downloading, for: pointer, associatedWith: self.tsIncomingMessageID, using: transaction) storage.setAttachmentState(to: .downloading, for: pointer, associatedWith: self.tsIncomingMessageID, using: transaction)
}, completion: { }) }, completion: { })

View File

@ -61,7 +61,7 @@ public final class AttachmentUploadJob : NSObject, Job, NSCoding { // NSObject/N
return handleFailure(error: Error.noAttachment) return handleFailure(error: Error.noAttachment)
} }
guard !stream.isUploaded else { return handleSuccess() } // Should never occur guard !stream.isUploaded else { return handleSuccess() } // Should never occur
let openGroup = Configuration.shared.storage.getOpenGroup(for: threadID) let openGroup = SNMessagingKitConfiguration.shared.storage.getOpenGroup(for: threadID)
let server = openGroup?.server ?? FileServerAPI.server let server = openGroup?.server ?? FileServerAPI.server
// FIXME: A lot of what's currently happening in FileServerAPI should really be happening here // FIXME: A lot of what's currently happening in FileServerAPI should really be happening here
FileServerAPI.uploadAttachment(stream, with: attachmentID, to: server).done(on: DispatchQueue.global(qos: .userInitiated)) { // Intentionally capture self FileServerAPI.uploadAttachment(stream, with: attachmentID, to: server).done(on: DispatchQueue.global(qos: .userInitiated)) { // Intentionally capture self
@ -80,7 +80,7 @@ public final class AttachmentUploadJob : NSObject, Job, NSCoding { // NSObject/N
private func handleSuccess() { private func handleSuccess() {
SNLog("Attachment uploaded successfully.") SNLog("Attachment uploaded successfully.")
delegate?.handleJobSucceeded(self) delegate?.handleJobSucceeded(self)
Configuration.shared.storage.resumeMessageSendJobIfNeeded(messageSendJobID) SNMessagingKitConfiguration.shared.storage.resumeMessageSendJobIfNeeded(messageSendJobID)
Storage.shared.withAsync({ transaction in Storage.shared.withAsync({ transaction in
var interaction: TSInteraction? var interaction: TSInteraction?
let transaction = transaction as! YapDatabaseReadWriteTransaction let transaction = transaction as! YapDatabaseReadWriteTransaction
@ -106,7 +106,7 @@ public final class AttachmentUploadJob : NSObject, Job, NSCoding { // NSObject/N
} }
private func failAssociatedMessageSendJob(with error: Swift.Error) { private func failAssociatedMessageSendJob(with error: Swift.Error) {
let storage = Configuration.shared.storage let storage = SNMessagingKitConfiguration.shared.storage
let messageSendJob = storage.getMessageSendJob(for: messageSendJobID) let messageSendJob = storage.getMessageSendJob(for: messageSendJobID)
storage.withAsync({ transaction in // Intentionally capture self storage.withAsync({ transaction in // Intentionally capture self
MessageSender.handleFailedMessageSend(self.message, with: error, using: transaction) MessageSender.handleFailedMessageSend(self.message, with: error, using: transaction)

View File

@ -16,7 +16,7 @@ public final class JobQueue : NSObject, JobDelegate {
@objc public func addWithoutExecuting(_ job: Job, using transaction: Any) { @objc public func addWithoutExecuting(_ job: Job, using transaction: Any) {
job.id = String(NSDate.millisecondTimestamp()) job.id = String(NSDate.millisecondTimestamp())
Configuration.shared.storage.persist(job, using: transaction) SNMessagingKitConfiguration.shared.storage.persist(job, using: transaction)
job.delegate = self job.delegate = self
} }
@ -29,7 +29,7 @@ public final class JobQueue : NSObject, JobDelegate {
hasResumedPendingJobs = true hasResumedPendingJobs = true
let allJobTypes: [Job.Type] = [ AttachmentDownloadJob.self, AttachmentUploadJob.self, MessageReceiveJob.self, MessageSendJob.self, NotifyPNServerJob.self ] let allJobTypes: [Job.Type] = [ AttachmentDownloadJob.self, AttachmentUploadJob.self, MessageReceiveJob.self, MessageSendJob.self, NotifyPNServerJob.self ]
allJobTypes.forEach { type in allJobTypes.forEach { type in
let allPendingJobs = Configuration.shared.storage.getAllPendingJobs(of: type) let allPendingJobs = SNMessagingKitConfiguration.shared.storage.getAllPendingJobs(of: type)
allPendingJobs.sorted(by: { $0.id! < $1.id! }).forEach { job in // Retry the oldest jobs first allPendingJobs.sorted(by: { $0.id! < $1.id! }).forEach { job in // Retry the oldest jobs first
SNLog("Resuming pending job of type: \(type).") SNLog("Resuming pending job of type: \(type).")
job.delegate = self job.delegate = self
@ -39,8 +39,8 @@ public final class JobQueue : NSObject, JobDelegate {
} }
public func handleJobSucceeded(_ job: Job) { public func handleJobSucceeded(_ job: Job) {
Configuration.shared.storage.withAsync({ transaction in SNMessagingKitConfiguration.shared.storage.withAsync({ transaction in
Configuration.shared.storage.markJobAsSucceeded(job, using: transaction) SNMessagingKitConfiguration.shared.storage.markJobAsSucceeded(job, using: transaction)
}, completion: { }, completion: {
// Do nothing // Do nothing
}) })
@ -48,7 +48,7 @@ public final class JobQueue : NSObject, JobDelegate {
public func handleJobFailed(_ job: Job, with error: Error) { public func handleJobFailed(_ job: Job, with error: Error) {
job.failureCount += 1 job.failureCount += 1
let storage = Configuration.shared.storage let storage = SNMessagingKitConfiguration.shared.storage
guard !storage.isJobCanceled(job) else { return SNLog("\(type(of: job)) canceled.") } guard !storage.isJobCanceled(job) else { return SNLog("\(type(of: job)) canceled.") }
storage.withAsync({ transaction in storage.withAsync({ transaction in
storage.persist(job, using: transaction) storage.persist(job, using: transaction)
@ -69,7 +69,7 @@ public final class JobQueue : NSObject, JobDelegate {
public func handleJobFailedPermanently(_ job: Job, with error: Error) { public func handleJobFailedPermanently(_ job: Job, with error: Error) {
job.failureCount += 1 job.failureCount += 1
let storage = Configuration.shared.storage let storage = SNMessagingKitConfiguration.shared.storage
storage.withAsync({ transaction in storage.withAsync({ transaction in
storage.persist(job, using: transaction) storage.persist(job, using: transaction)
}, completion: { // Intentionally capture self }, completion: { // Intentionally capture self

View File

@ -44,7 +44,7 @@ public final class MessageReceiveJob : NSObject, Job, NSCoding { // NSObject/NSC
// MARK: Running // MARK: Running
public func execute() { public func execute() {
Configuration.shared.storage.withAsync({ transaction in // Intentionally capture self SNMessagingKitConfiguration.shared.storage.withAsync({ transaction in // Intentionally capture self
do { do {
let (message, proto) = try MessageReceiver.parse(self.data, openGroupMessageServerID: self.openGroupMessageServerID, using: transaction) let (message, proto) = try MessageReceiver.parse(self.data, openGroupMessageServerID: self.openGroupMessageServerID, using: transaction)
try MessageReceiver.handle(message, associatedWithProto: proto, openGroupID: self.openGroupID, using: transaction) try MessageReceiver.handle(message, associatedWithProto: proto, openGroupID: self.openGroupID, using: transaction)

View File

@ -61,7 +61,7 @@ public final class MessageSendJob : NSObject, Job, NSCoding { // NSObject/NSCodi
// MARK: Running // MARK: Running
public func execute() { public func execute() {
let storage = Configuration.shared.storage let storage = SNMessagingKitConfiguration.shared.storage
if let message = message as? VisibleMessage { if let message = message as? VisibleMessage {
guard TSOutgoingMessage.find(withTimestamp: message.sentTimestamp!) != nil else { return } // The message has been deleted guard TSOutgoingMessage.find(withTimestamp: message.sentTimestamp!) != nil else { return } // The message has been deleted
let attachments = message.attachmentIDs.compactMap { TSAttachmentStream.fetch(uniqueId: $0) } let attachments = message.attachmentIDs.compactMap { TSAttachmentStream.fetch(uniqueId: $0) }

View File

@ -34,8 +34,8 @@ public final class SessionRequest : ControlMessage {
public override class func fromProto(_ proto: SNProtoContent) -> SessionRequest? { public override class func fromProto(_ proto: SNProtoContent) -> SessionRequest? {
guard proto.nullMessage != nil, let preKeyBundleProto = proto.prekeyBundleMessage else { return nil } guard proto.nullMessage != nil, let preKeyBundleProto = proto.prekeyBundleMessage else { return nil }
var registrationID: UInt32 = 0 var registrationID: UInt32 = 0
Configuration.shared.storage.with { transaction in SNMessagingKitConfiguration.shared.storage.with { transaction in
registrationID = Configuration.shared.storage.getOrGenerateRegistrationID(using: transaction) registrationID = SNMessagingKitConfiguration.shared.storage.getOrGenerateRegistrationID(using: transaction)
} }
guard let preKeyBundle = PreKeyBundle( guard let preKeyBundle = PreKeyBundle(
registrationId: Int32(registrationID), registrationId: Int32(registrationID),

View File

@ -20,15 +20,15 @@ public final class OpenGroupAPI : DotNetAPI {
// MARK: Open Group Public Key Validation // MARK: Open Group Public Key Validation
public static func getOpenGroupServerPublicKey(for server: String) -> Promise<String> { public static func getOpenGroupServerPublicKey(for server: String) -> Promise<String> {
if let publicKey = Configuration.shared.storage.getOpenGroupPublicKey(for: server) { if let publicKey = SNMessagingKitConfiguration.shared.storage.getOpenGroupPublicKey(for: server) {
return Promise.value(publicKey) return Promise.value(publicKey)
} else { } else {
return FileServerAPI.getPublicKey(for: server).then(on: DispatchQueue.global(qos: .default)) { publicKey -> Promise<String> in return FileServerAPI.getPublicKey(for: server).then(on: DispatchQueue.global(qos: .default)) { publicKey -> Promise<String> in
let url = URL(string: server)! let url = URL(string: server)!
let request = TSRequest(url: url) let request = TSRequest(url: url)
return OnionRequestAPI.sendOnionRequest(request, to: server, using: publicKey, isJSONRequired: false).map(on: DispatchQueue.global(qos: .default)) { _ -> String in return OnionRequestAPI.sendOnionRequest(request, to: server, using: publicKey, isJSONRequired: false).map(on: DispatchQueue.global(qos: .default)) { _ -> String in
Configuration.shared.storage.with { transaction in SNMessagingKitConfiguration.shared.storage.with { transaction in
Configuration.shared.storage.setOpenGroupPublicKey(for: server, to: publicKey, using: transaction) SNMessagingKitConfiguration.shared.storage.setOpenGroupPublicKey(for: server, to: publicKey, using: transaction)
} }
return publicKey return publicKey
} }
@ -43,7 +43,7 @@ public final class OpenGroupAPI : DotNetAPI {
} }
public static func getMessages(for channel: UInt64, on server: String) -> Promise<[OpenGroupMessage]> { public static func getMessages(for channel: UInt64, on server: String) -> Promise<[OpenGroupMessage]> {
let storage = Configuration.shared.storage let storage = SNMessagingKitConfiguration.shared.storage
var queryParameters = "include_annotations=1" var queryParameters = "include_annotations=1"
if let lastMessageServerID = storage.getLastMessageServerID(for: channel, on: server) { if let lastMessageServerID = storage.getLastMessageServerID(for: channel, on: server) {
queryParameters += "&since_id=\(lastMessageServerID)" queryParameters += "&since_id=\(lastMessageServerID)"
@ -141,7 +141,7 @@ public final class OpenGroupAPI : DotNetAPI {
public static func sendMessage(_ message: OpenGroupMessage, to channel: UInt64, on server: String) -> Promise<OpenGroupMessage> { public static func sendMessage(_ message: OpenGroupMessage, to channel: UInt64, on server: String) -> Promise<OpenGroupMessage> {
SNLog("Sending message to open group channel with ID: \(channel) on server: \(server).") SNLog("Sending message to open group channel with ID: \(channel) on server: \(server).")
let storage = Configuration.shared.storage let storage = SNMessagingKitConfiguration.shared.storage
guard let userKeyPair = storage.getUserKeyPair() else { return Promise(error: Error.generic) } guard let userKeyPair = storage.getUserKeyPair() else { return Promise(error: Error.generic) }
guard let userDisplayName = storage.getUserDisplayName() else { return Promise(error: Error.generic) } guard let userDisplayName = storage.getUserDisplayName() else { return Promise(error: Error.generic) }
let (promise, seal) = Promise<OpenGroupMessage>.pending() let (promise, seal) = Promise<OpenGroupMessage>.pending()
@ -181,7 +181,7 @@ public final class OpenGroupAPI : DotNetAPI {
// MARK: Deletion // MARK: Deletion
public static func getDeletedMessageServerIDs(for channel: UInt64, on server: String) -> Promise<[UInt64]> { public static func getDeletedMessageServerIDs(for channel: UInt64, on server: String) -> Promise<[UInt64]> {
SNLog("Getting deleted messages for open group channel with ID: \(channel) on server: \(server).") SNLog("Getting deleted messages for open group channel with ID: \(channel) on server: \(server).")
let storage = Configuration.shared.storage let storage = SNMessagingKitConfiguration.shared.storage
let queryParameters: String let queryParameters: String
if let lastDeletionServerID = storage.getLastDeletionServerID(for: channel, on: server) { if let lastDeletionServerID = storage.getLastDeletionServerID(for: channel, on: server) {
queryParameters = "since_id=\(lastDeletionServerID)" queryParameters = "since_id=\(lastDeletionServerID)"
@ -255,7 +255,7 @@ public final class OpenGroupAPI : DotNetAPI {
SNLog("Couldn't parse display names for users: \(publicKeys) from: \(json).") SNLog("Couldn't parse display names for users: \(publicKeys) from: \(json).")
throw Error.parsingFailed throw Error.parsingFailed
} }
let storage = Configuration.shared.storage let storage = SNMessagingKitConfiguration.shared.storage
storage.with { transaction in storage.with { transaction in
data.forEach { data in data.forEach { data in
guard let user = data["user"] as? JSON, let hexEncodedPublicKey = user["username"] as? String, let rawDisplayName = user["name"] as? String else { return } guard let user = data["user"] as? JSON, let hexEncodedPublicKey = user["username"] as? String, let rawDisplayName = user["name"] as? String else { return }
@ -345,7 +345,7 @@ public final class OpenGroupAPI : DotNetAPI {
SNLog("Couldn't parse info for open group channel with ID: \(channel) on server: \(server) from: \(json).") SNLog("Couldn't parse info for open group channel with ID: \(channel) on server: \(server) from: \(json).")
throw Error.parsingFailed throw Error.parsingFailed
} }
let storage = Configuration.shared.storage let storage = SNMessagingKitConfiguration.shared.storage
storage.with { transaction in storage.with { transaction in
storage.setUserCount(to: memberCount, forOpenGroupWithID: "\(server).\(channel)", using: transaction) storage.setUserCount(to: memberCount, forOpenGroupWithID: "\(server).\(channel)", using: transaction)
} }
@ -473,7 +473,7 @@ internal extension Promise {
return recover(on: DispatchQueue.global(qos: .userInitiated)) { error -> Promise<T> in return recover(on: DispatchQueue.global(qos: .userInitiated)) { error -> Promise<T> in
if case OnionRequestAPI.Error.httpRequestFailedAtDestination(let statusCode, _) = error, statusCode == 401 || statusCode == 403 { if case OnionRequestAPI.Error.httpRequestFailedAtDestination(let statusCode, _) = error, statusCode == 401 || statusCode == 403 {
SNLog("Auth token for: \(server) expired; dropping it.") SNLog("Auth token for: \(server) expired; dropping it.")
let storage = Configuration.shared.storage let storage = SNMessagingKitConfiguration.shared.storage
storage.with { transaction in storage.with { transaction in
storage.removeAuthToken(for: server, using: transaction) storage.removeAuthToken(for: server, using: transaction)
} }

View File

@ -2,7 +2,7 @@
internal extension OpenGroupMessage { internal extension OpenGroupMessage {
static func from(_ message: VisibleMessage, for server: String, using transaction: YapDatabaseReadWriteTransaction) -> OpenGroupMessage? { static func from(_ message: VisibleMessage, for server: String, using transaction: YapDatabaseReadWriteTransaction) -> OpenGroupMessage? {
let storage = Configuration.shared.storage let storage = SNMessagingKitConfiguration.shared.storage
guard let userPublicKey = storage.getUserPublicKey() else { return nil } guard let userPublicKey = storage.getUserPublicKey() else { return nil }
var attachmentIDs = message.attachmentIDs var attachmentIDs = message.attachmentIDs
// Validation // Validation

View File

@ -117,7 +117,7 @@ public final class OpenGroupMessage : NSObject {
SNLog("Failed to sign open group message.") SNLog("Failed to sign open group message.")
return nil return nil
} }
let userKeyPair = Configuration.shared.storage.getUserKeyPair()! let userKeyPair = SNMessagingKitConfiguration.shared.storage.getUserKeyPair()!
guard let signatureData = try? Ed25519.sign(data, with: userKeyPair) else { guard let signatureData = try? Ed25519.sign(data, with: userKeyPair) else {
SNLog("Failed to sign open group message.") SNLog("Failed to sign open group message.")
return nil return nil

View File

@ -5,12 +5,12 @@ import SessionUtilitiesKit
internal extension MessageReceiver { internal extension MessageReceiver {
static func decryptWithSignalProtocol(envelope: SNProtoEnvelope, using transaction: Any) throws -> (plaintext: Data, senderPublicKey: String) { static func decryptWithSignalProtocol(envelope: SNProtoEnvelope, using transaction: Any) throws -> (plaintext: Data, senderPublicKey: String) {
let storage = Configuration.shared.signalStorage let storage = SNMessagingKitConfiguration.shared.signalStorage
let certificateValidator = Configuration.shared.certificateValidator let certificateValidator = SNMessagingKitConfiguration.shared.certificateValidator
guard let data = envelope.content else { throw Error.noData } guard let data = envelope.content else { throw Error.noData }
guard let userPublicKey = Configuration.shared.storage.getUserPublicKey() else { throw Error.noUserPublicKey } guard let userPublicKey = SNMessagingKitConfiguration.shared.storage.getUserPublicKey() else { throw Error.noUserPublicKey }
let cipher = try SMKSecretSessionCipher(sessionResetImplementation: Configuration.shared.sessionRestorationImplementation, let cipher = try SMKSecretSessionCipher(sessionResetImplementation: SNMessagingKitConfiguration.shared.sessionRestorationImplementation,
sessionStore: storage, preKeyStore: storage, signedPreKeyStore: storage, identityStore: Configuration.shared.identityKeyStore) sessionStore: storage, preKeyStore: storage, signedPreKeyStore: storage, identityStore: SNMessagingKitConfiguration.shared.identityKeyStore)
let result = try cipher.throwswrapped_decryptMessage(certificateValidator: certificateValidator, cipherTextData: data, let result = try cipher.throwswrapped_decryptMessage(certificateValidator: certificateValidator, cipherTextData: data,
timestamp: envelope.timestamp, localRecipientId: userPublicKey, localDeviceId: 1, protocolContext: transaction) timestamp: envelope.timestamp, localRecipientId: userPublicKey, localDeviceId: 1, protocolContext: transaction)
return (result.paddedPayload, result.senderRecipientId) return (result.paddedPayload, result.senderRecipientId)
@ -18,13 +18,13 @@ internal extension MessageReceiver {
static func decryptWithSharedSenderKeys(envelope: SNProtoEnvelope, using transaction: Any) throws -> (plaintext: Data, senderPublicKey: String) { static func decryptWithSharedSenderKeys(envelope: SNProtoEnvelope, using transaction: Any) throws -> (plaintext: Data, senderPublicKey: String) {
// 1. ) Check preconditions // 1. ) Check preconditions
guard let groupPublicKey = envelope.source, Configuration.shared.storage.isClosedGroup(groupPublicKey) else { guard let groupPublicKey = envelope.source, SNMessagingKitConfiguration.shared.storage.isClosedGroup(groupPublicKey) else {
throw Error.invalidGroupPublicKey throw Error.invalidGroupPublicKey
} }
guard let data = envelope.content else { guard let data = envelope.content else {
throw Error.noData throw Error.noData
} }
guard let hexEncodedGroupPrivateKey = Configuration.shared.storage.getClosedGroupPrivateKey(for: groupPublicKey) else { guard let hexEncodedGroupPrivateKey = SNMessagingKitConfiguration.shared.storage.getClosedGroupPrivateKey(for: groupPublicKey) else {
throw Error.noGroupPrivateKey throw Error.noGroupPrivateKey
} }
let groupPrivateKey = Data(hex: hexEncodedGroupPrivateKey) let groupPrivateKey = Data(hex: hexEncodedGroupPrivateKey)
@ -42,7 +42,7 @@ internal extension MessageReceiver {
// 4. ) Parse the closed group ciphertext message // 4. ) Parse the closed group ciphertext message
let closedGroupCiphertextMessage = ClosedGroupCiphertextMessage(_throws_with: closedGroupCiphertextMessageAsData) let closedGroupCiphertextMessage = ClosedGroupCiphertextMessage(_throws_with: closedGroupCiphertextMessageAsData)
let senderPublicKey = closedGroupCiphertextMessage.senderPublicKey.toHexString() let senderPublicKey = closedGroupCiphertextMessage.senderPublicKey.toHexString()
guard senderPublicKey != Configuration.shared.storage.getUserPublicKey() else { throw Error.selfSend } guard senderPublicKey != SNMessagingKitConfiguration.shared.storage.getUserPublicKey() else { throw Error.selfSend }
// 5. ) Use the info inside the closed group ciphertext message to decrypt the actual message content // 5. ) Use the info inside the closed group ciphertext message to decrypt the actual message content
let plaintext = try SharedSenderKeys.decrypt(closedGroupCiphertextMessage.ivAndCiphertext, for: groupPublicKey, let plaintext = try SharedSenderKeys.decrypt(closedGroupCiphertextMessage.ivAndCiphertext, for: groupPublicKey,
senderPublicKey: senderPublicKey, keyIndex: UInt(closedGroupCiphertextMessage.keyIndex), using: transaction) senderPublicKey: senderPublicKey, keyIndex: UInt(closedGroupCiphertextMessage.keyIndex), using: transaction)

View File

@ -137,7 +137,7 @@ extension MessageReceiver {
@discardableResult @discardableResult
public static func handleVisibleMessage(_ message: VisibleMessage, associatedWithProto proto: SNProtoContent, openGroupID: String?, using transaction: Any) throws -> String { public static func handleVisibleMessage(_ message: VisibleMessage, associatedWithProto proto: SNProtoContent, openGroupID: String?, using transaction: Any) throws -> String {
let storage = Configuration.shared.storage let storage = SNMessagingKitConfiguration.shared.storage
let transaction = transaction as! YapDatabaseReadWriteTransaction let transaction = transaction as! YapDatabaseReadWriteTransaction
// Parse & persist attachments // Parse & persist attachments
let attachments: [VisibleMessage.Attachment] = proto.dataMessage!.attachments.compactMap { proto in let attachments: [VisibleMessage.Attachment] = proto.dataMessage!.attachments.compactMap { proto in

View File

@ -44,11 +44,11 @@ public enum MessageReceiver {
} }
public static func parse(_ data: Data, openGroupMessageServerID: UInt64?, using transaction: Any) throws -> (Message, SNProtoContent) { public static func parse(_ data: Data, openGroupMessageServerID: UInt64?, using transaction: Any) throws -> (Message, SNProtoContent) {
let userPublicKey = Configuration.shared.storage.getUserPublicKey() let userPublicKey = SNMessagingKitConfiguration.shared.storage.getUserPublicKey()
let isOpenGroupMessage = (openGroupMessageServerID != nil) let isOpenGroupMessage = (openGroupMessageServerID != nil)
// Parse the envelope // Parse the envelope
let envelope = try SNProtoEnvelope.parseData(data) let envelope = try SNProtoEnvelope.parseData(data)
let storage = Configuration.shared.storage let storage = SNMessagingKitConfiguration.shared.storage
guard !Set(storage.getReceivedMessageTimestamps(using: transaction)).contains(envelope.timestamp) else { throw Error.duplicateMessage } guard !Set(storage.getReceivedMessageTimestamps(using: transaction)).contains(envelope.timestamp) else { throw Error.duplicateMessage }
storage.addReceivedMessageTimestamp(envelope.timestamp, using: transaction) storage.addReceivedMessageTimestamp(envelope.timestamp, using: transaction)
// Decrypt the contents // Decrypt the contents

View File

@ -4,17 +4,17 @@ import SessionUtilitiesKit
internal extension MessageSender { internal extension MessageSender {
static func encryptWithSignalProtocol(_ plaintext: Data, associatedWith message: Message, for publicKey: String, using transaction: Any) throws -> Data { static func encryptWithSignalProtocol(_ plaintext: Data, associatedWith message: Message, for publicKey: String, using transaction: Any) throws -> Data {
let storage = Configuration.shared.signalStorage let storage = SNMessagingKitConfiguration.shared.signalStorage
let cipher = try SMKSecretSessionCipher(sessionResetImplementation: Configuration.shared.sessionRestorationImplementation, let cipher = try SMKSecretSessionCipher(sessionResetImplementation: SNMessagingKitConfiguration.shared.sessionRestorationImplementation,
sessionStore: storage, preKeyStore: storage, signedPreKeyStore: storage, identityStore: Configuration.shared.identityKeyStore) sessionStore: storage, preKeyStore: storage, signedPreKeyStore: storage, identityStore: SNMessagingKitConfiguration.shared.identityKeyStore)
let certificate = SMKSenderCertificate(senderDeviceId: 1, senderRecipientId: Configuration.shared.storage.getUserPublicKey()!) let certificate = SMKSenderCertificate(senderDeviceId: 1, senderRecipientId: SNMessagingKitConfiguration.shared.storage.getUserPublicKey()!)
return try cipher.throwswrapped_encryptMessage(recipientPublicKey: publicKey, deviceID: 1, paddedPlaintext: (plaintext as NSData).paddedMessageBody(), return try cipher.throwswrapped_encryptMessage(recipientPublicKey: publicKey, deviceID: 1, paddedPlaintext: (plaintext as NSData).paddedMessageBody(),
senderCertificate: certificate, protocolContext: transaction, useFallbackSessionCipher: true) senderCertificate: certificate, protocolContext: transaction, useFallbackSessionCipher: true)
} }
static func encryptWithSharedSenderKeys(_ plaintext: Data, for groupPublicKey: String, using transaction: Any) throws -> Data { static func encryptWithSharedSenderKeys(_ plaintext: Data, for groupPublicKey: String, using transaction: Any) throws -> Data {
// 1. ) Encrypt the data with the user's sender key // 1. ) Encrypt the data with the user's sender key
guard let userPublicKey = Configuration.shared.storage.getUserPublicKey() else { guard let userPublicKey = SNMessagingKitConfiguration.shared.storage.getUserPublicKey() else {
SNLog("Couldn't find user key pair.") SNLog("Couldn't find user key pair.")
throw Error.noUserPublicKey throw Error.noUserPublicKey
} }

View File

@ -87,7 +87,7 @@ public final class MessageSender : NSObject {
// MARK: One-on-One Chats & Closed Groups // MARK: One-on-One Chats & Closed Groups
internal static func sendToSnodeDestination(_ destination: Message.Destination, message: Message, using transaction: Any) -> Promise<Void> { internal static func sendToSnodeDestination(_ destination: Message.Destination, message: Message, using transaction: Any) -> Promise<Void> {
let (promise, seal) = Promise<Void>.pending() let (promise, seal) = Promise<Void>.pending()
let storage = Configuration.shared.storage let storage = SNMessagingKitConfiguration.shared.storage
if message.sentTimestamp == nil { // Visible messages will already have their sent timestamp set if message.sentTimestamp == nil { // Visible messages will already have their sent timestamp set
message.sentTimestamp = NSDate.millisecondTimestamp() message.sentTimestamp = NSDate.millisecondTimestamp()
} }
@ -245,7 +245,7 @@ public final class MessageSender : NSObject {
// MARK: Open Groups // MARK: Open Groups
internal static func sendToOpenGroupDestination(_ destination: Message.Destination, message: Message, using transaction: Any) -> Promise<Void> { internal static func sendToOpenGroupDestination(_ destination: Message.Destination, message: Message, using transaction: Any) -> Promise<Void> {
let (promise, seal) = Promise<Void>.pending() let (promise, seal) = Promise<Void>.pending()
let storage = Configuration.shared.storage let storage = SNMessagingKitConfiguration.shared.storage
if message.sentTimestamp == nil { // Visible messages will already have their sent timestamp set if message.sentTimestamp == nil { // Visible messages will already have their sent timestamp set
message.sentTimestamp = NSDate.millisecondTimestamp() message.sentTimestamp = NSDate.millisecondTimestamp()
} }

View File

@ -46,7 +46,7 @@ public class DotNetAPI : 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> {
SNLog("Requesting auth token for server: \(server).") SNLog("Requesting auth token for server: \(server).")
guard let userKeyPair = Configuration.shared.storage.getUserKeyPair() else { return Promise(error: Error.generic) } guard let userKeyPair = SNMessagingKitConfiguration.shared.storage.getUserKeyPair() else { return Promise(error: Error.generic) }
let queryParameters = "pubKey=\(userKeyPair.publicKey.toHexString())" let queryParameters = "pubKey=\(userKeyPair.publicKey.toHexString())"
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)
@ -77,7 +77,7 @@ public class DotNetAPI : NSObject {
private static func submitAuthToken(_ token: String, for server: String) -> Promise<String> { private static func submitAuthToken(_ token: String, for server: String) -> Promise<String> {
SNLog("Submitting auth token for server: \(server).") SNLog("Submitting auth token for server: \(server).")
let url = URL(string: "\(server)/loki/v1/submit_challenge")! let url = URL(string: "\(server)/loki/v1/submit_challenge")!
guard let userPublicKey = Configuration.shared.storage.getUserPublicKey() else { return Promise(error: Error.generic) } guard let userPublicKey = SNMessagingKitConfiguration.shared.storage.getUserPublicKey() else { return Promise(error: Error.generic) }
let parameters = [ "pubKey" : userPublicKey, "token" : token ] let parameters = [ "pubKey" : userPublicKey, "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.value(FileServerAPI.publicKey) let serverPublicKeyPromise = (server == FileServerAPI.server) ? Promise.value(FileServerAPI.publicKey)
@ -89,7 +89,7 @@ public class DotNetAPI : NSObject {
// MARK: Public API // MARK: Public API
public static func getAuthToken(for server: String) -> Promise<String> { public static func getAuthToken(for server: String) -> Promise<String> {
let storage = Configuration.shared.storage let storage = SNMessagingKitConfiguration.shared.storage
if let token = storage.getAuthToken(for: server) { if let token = storage.getAuthToken(for: server) {
return Promise.value(token) return Promise.value(token)
} else { } else {

View File

@ -1,14 +1,14 @@
public struct Configuration { public struct SNProtocolKitConfiguration {
public let storage: SessionProtocolKitStorageProtocol public let storage: SessionProtocolKitStorageProtocol
public let sharedSenderKeysDelegate: SharedSenderKeysDelegate public let sharedSenderKeysDelegate: SharedSenderKeysDelegate
internal static var shared: Configuration! internal static var shared: SNProtocolKitConfiguration!
} }
public enum SessionProtocolKit { // Just to make the external API nice public enum SNProtocolKit { // Just to make the external API nice
public static func configure(storage: SessionProtocolKitStorageProtocol, sharedSenderKeysDelegate: SharedSenderKeysDelegate) { public static func configure(storage: SessionProtocolKitStorageProtocol, sharedSenderKeysDelegate: SharedSenderKeysDelegate) {
Configuration.shared = Configuration(storage: storage, sharedSenderKeysDelegate: sharedSenderKeysDelegate) SNProtocolKitConfiguration.shared = SNProtocolKitConfiguration(storage: storage, sharedSenderKeysDelegate: sharedSenderKeysDelegate)
} }
} }

View File

@ -30,7 +30,7 @@ public enum SharedSenderKeys {
public static func generateRatchet(for groupPublicKey: String, senderPublicKey: String, using transaction: Any) -> ClosedGroupRatchet { public static func generateRatchet(for groupPublicKey: String, senderPublicKey: String, using transaction: Any) -> ClosedGroupRatchet {
let rootChainKey = Data.getSecureRandomData(ofSize: 32)!.toHexString() let rootChainKey = Data.getSecureRandomData(ofSize: 32)!.toHexString()
let ratchet = ClosedGroupRatchet(chainKey: rootChainKey, keyIndex: 0, messageKeys: []) let ratchet = ClosedGroupRatchet(chainKey: rootChainKey, keyIndex: 0, messageKeys: [])
Configuration.shared.storage.setClosedGroupRatchet(for: groupPublicKey, senderPublicKey: senderPublicKey, ratchet: ratchet, in: .current, using: transaction) SNProtocolKitConfiguration.shared.storage.setClosedGroupRatchet(for: groupPublicKey, senderPublicKey: senderPublicKey, ratchet: ratchet, in: .current, using: transaction)
return ratchet return ratchet
} }
@ -47,14 +47,14 @@ public enum SharedSenderKeys {
#if DEBUG #if DEBUG
assert(!Thread.isMainThread) assert(!Thread.isMainThread)
#endif #endif
guard let ratchet = Configuration.shared.storage.getClosedGroupRatchet(for: groupPublicKey, senderPublicKey: senderPublicKey, from: .current) else { guard let ratchet = SNProtocolKitConfiguration.shared.storage.getClosedGroupRatchet(for: groupPublicKey, senderPublicKey: senderPublicKey, from: .current) else {
let error = RatchetingError.loadingFailed(groupPublicKey: groupPublicKey, senderPublicKey: senderPublicKey) let error = RatchetingError.loadingFailed(groupPublicKey: groupPublicKey, senderPublicKey: senderPublicKey)
SNLog("\(error.errorDescription!)") SNLog("\(error.errorDescription!)")
throw error throw error
} }
do { do {
let result = try step(ratchet) let result = try step(ratchet)
Configuration.shared.storage.setClosedGroupRatchet(for: groupPublicKey, senderPublicKey: senderPublicKey, ratchet: result, in: .current, using: transaction) SNProtocolKitConfiguration.shared.storage.setClosedGroupRatchet(for: groupPublicKey, senderPublicKey: senderPublicKey, ratchet: result, in: .current, using: transaction)
return result return result
} catch { } catch {
SNLog("Couldn't step ratchet due to error: \(error).") SNLog("Couldn't step ratchet due to error: \(error).")
@ -68,7 +68,7 @@ public enum SharedSenderKeys {
assert(!Thread.isMainThread) assert(!Thread.isMainThread)
#endif #endif
let collection: ClosedGroupRatchetCollectionType = (isRetry) ? .old : .current let collection: ClosedGroupRatchetCollectionType = (isRetry) ? .old : .current
guard let ratchet = Configuration.shared.storage.getClosedGroupRatchet(for: groupPublicKey, senderPublicKey: senderPublicKey, from: collection) else { guard let ratchet = SNProtocolKitConfiguration.shared.storage.getClosedGroupRatchet(for: groupPublicKey, senderPublicKey: senderPublicKey, from: collection) else {
let error = RatchetingError.loadingFailed(groupPublicKey: groupPublicKey, senderPublicKey: senderPublicKey) let error = RatchetingError.loadingFailed(groupPublicKey: groupPublicKey, senderPublicKey: senderPublicKey)
SNLog("\(error.errorDescription!)") SNLog("\(error.errorDescription!)")
throw error throw error
@ -94,7 +94,7 @@ public enum SharedSenderKeys {
} }
} }
let collection: ClosedGroupRatchetCollectionType = (isRetry) ? .old : .current let collection: ClosedGroupRatchetCollectionType = (isRetry) ? .old : .current
Configuration.shared.storage.setClosedGroupRatchet(for: groupPublicKey, senderPublicKey: senderPublicKey, ratchet: result, in: collection, using: transaction) SNProtocolKitConfiguration.shared.storage.setClosedGroupRatchet(for: groupPublicKey, senderPublicKey: senderPublicKey, ratchet: result, in: collection, using: transaction)
return result return result
} }
} }
@ -106,7 +106,7 @@ public enum SharedSenderKeys {
ratchet = try stepRatchetOnce(for: groupPublicKey, senderPublicKey: senderPublicKey, using: transaction) ratchet = try stepRatchetOnce(for: groupPublicKey, senderPublicKey: senderPublicKey, using: transaction)
} catch { } catch {
if case RatchetingError.loadingFailed(_, _) = error { if case RatchetingError.loadingFailed(_, _) = error {
Configuration.shared.sharedSenderKeysDelegate.requestSenderKey(for: groupPublicKey, senderPublicKey: senderPublicKey, using: transaction) SNProtocolKitConfiguration.shared.sharedSenderKeysDelegate.requestSenderKey(for: groupPublicKey, senderPublicKey: senderPublicKey, using: transaction)
} }
throw error throw error
} }
@ -127,7 +127,7 @@ public enum SharedSenderKeys {
return try decrypt(ivAndCiphertext, for: groupPublicKey, senderPublicKey: senderPublicKey, keyIndex: keyIndex, using: transaction, isRetry: true) return try decrypt(ivAndCiphertext, for: groupPublicKey, senderPublicKey: senderPublicKey, keyIndex: keyIndex, using: transaction, isRetry: true)
} else { } else {
if case RatchetingError.loadingFailed(_, _) = error { if case RatchetingError.loadingFailed(_, _) = error {
Configuration.shared.sharedSenderKeysDelegate.requestSenderKey(for: groupPublicKey, senderPublicKey: senderPublicKey, using: transaction) SNProtocolKitConfiguration.shared.sharedSenderKeysDelegate.requestSenderKey(for: groupPublicKey, senderPublicKey: senderPublicKey, using: transaction)
} }
throw error throw error
} }
@ -157,7 +157,7 @@ public enum SharedSenderKeys {
if !isRetry { if !isRetry {
return try decrypt(ivAndCiphertext, for: groupPublicKey, senderPublicKey: senderPublicKey, keyIndex: keyIndex, using: transaction, isRetry: true) return try decrypt(ivAndCiphertext, for: groupPublicKey, senderPublicKey: senderPublicKey, keyIndex: keyIndex, using: transaction, isRetry: true)
} else { } else {
Configuration.shared.sharedSenderKeysDelegate.requestSenderKey(for: groupPublicKey, senderPublicKey: senderPublicKey, using: transaction) SNProtocolKitConfiguration.shared.sharedSenderKeysDelegate.requestSenderKey(for: groupPublicKey, senderPublicKey: senderPublicKey, using: transaction)
throw error ?? RatchetingError.generic throw error ?? RatchetingError.generic
} }
} }

View File

@ -43,8 +43,6 @@ public class ShareViewController: UIViewController, ShareViewDelegate, SAEFailed
let appContext = ShareAppExtensionContext(rootViewController: self) let appContext = ShareAppExtensionContext(rootViewController: self)
SetCurrentAppContext(appContext) SetCurrentAppContext(appContext)
SignalUtilitiesKit.Configuration.performMainSetup()
AppModeManager.configure(delegate: self) AppModeManager.configure(delegate: self)
DebugLogger.shared().enableTTYLogging() DebugLogger.shared().enableTTYLogging()
@ -251,6 +249,8 @@ public class ShareViewController: UIViewController, ShareViewDelegate, SAEFailed
return return
} }
SignalUtilitiesKit.Configuration.performMainSetup()
Logger.debug("") Logger.debug("")
// TODO: Once "app ready" logic is moved into AppSetup, move this line there. // TODO: Once "app ready" logic is moved into AppSetup, move this line there.

View File

@ -1,13 +1,13 @@
public struct Configuration { public struct SNSnodeKitConfiguration {
public let storage: SessionSnodeKitStorageProtocol public let storage: SessionSnodeKitStorageProtocol
internal static var shared: Configuration! internal static var shared: SNSnodeKitConfiguration!
} }
public enum SessionSnodeKit { // Just to make the external API nice public enum SNSnodeKit { // Just to make the external API nice
public static func configure(storage: SessionSnodeKitStorageProtocol) { public static func configure(storage: SessionSnodeKitStorageProtocol) {
Configuration.shared = Configuration(storage: storage) SNSnodeKitConfiguration.shared = SNSnodeKitConfiguration(storage: storage)
} }
} }

View File

@ -137,9 +137,9 @@ public enum OnionRequestAPI {
} }
}.map2 { paths in }.map2 { paths in
OnionRequestAPI.paths = paths + reusablePaths OnionRequestAPI.paths = paths + reusablePaths
Configuration.shared.storage.with { transaction in SNSnodeKitConfiguration.shared.storage.with { transaction in
SNLog("Persisting onion request paths to database.") SNLog("Persisting onion request paths to database.")
Configuration.shared.storage.setOnionRequestPaths(to: paths, using: transaction) SNSnodeKitConfiguration.shared.storage.setOnionRequestPaths(to: paths, using: transaction)
} }
DispatchQueue.main.async { DispatchQueue.main.async {
NotificationCenter.default.post(name: .pathsBuilt, object: nil) NotificationCenter.default.post(name: .pathsBuilt, object: nil)
@ -154,7 +154,7 @@ public enum OnionRequestAPI {
guard pathSize >= 1 else { preconditionFailure("Can't build path of size zero.") } guard pathSize >= 1 else { preconditionFailure("Can't build path of size zero.") }
var paths = OnionRequestAPI.paths var paths = OnionRequestAPI.paths
if paths.isEmpty { if paths.isEmpty {
paths = Configuration.shared.storage.getOnionRequestPaths() paths = SNSnodeKitConfiguration.shared.storage.getOnionRequestPaths()
OnionRequestAPI.paths = paths OnionRequestAPI.paths = paths
if !paths.isEmpty { if !paths.isEmpty {
guardSnodes.formUnion([ paths[0][0] ]) guardSnodes.formUnion([ paths[0][0] ])
@ -217,9 +217,9 @@ public enum OnionRequestAPI {
oldPaths.remove(at: pathIndex) oldPaths.remove(at: pathIndex)
let newPaths = oldPaths + [ path ] let newPaths = oldPaths + [ path ]
paths = newPaths paths = newPaths
Configuration.shared.storage.with { transaction in SNSnodeKitConfiguration.shared.storage.with { transaction in
SNLog("Persisting onion request paths to database.") SNLog("Persisting onion request paths to database.")
Configuration.shared.storage.setOnionRequestPaths(to: newPaths, using: transaction) SNSnodeKitConfiguration.shared.storage.setOnionRequestPaths(to: newPaths, using: transaction)
} }
} }
@ -229,13 +229,13 @@ public enum OnionRequestAPI {
guard let pathIndex = paths.firstIndex(of: path) else { return } guard let pathIndex = paths.firstIndex(of: path) else { return }
paths.remove(at: pathIndex) paths.remove(at: pathIndex)
OnionRequestAPI.paths = paths OnionRequestAPI.paths = paths
Configuration.shared.storage.with { transaction in SNSnodeKitConfiguration.shared.storage.with { transaction in
if !paths.isEmpty { if !paths.isEmpty {
SNLog("Persisting onion request paths to database.") SNLog("Persisting onion request paths to database.")
Configuration.shared.storage.setOnionRequestPaths(to: paths, using: transaction) SNSnodeKitConfiguration.shared.storage.setOnionRequestPaths(to: paths, using: transaction)
} else { } else {
SNLog("Clearing onion request paths.") SNLog("Clearing onion request paths.")
Configuration.shared.storage.setOnionRequestPaths(to: [], using: transaction) SNSnodeKitConfiguration.shared.storage.setOnionRequestPaths(to: [], using: transaction)
} }
} }
} }

View File

@ -61,7 +61,7 @@ public final class SnodeAPI : NSObject {
internal static func getRandomSnode() -> Promise<Snode> { internal static func getRandomSnode() -> Promise<Snode> {
if snodePool.count < minimumSnodePoolCount { if snodePool.count < minimumSnodePoolCount {
snodePool = Configuration.shared.storage.getSnodePool() snodePool = SNSnodeKitConfiguration.shared.storage.getSnodePool()
} }
if snodePool.count < minimumSnodePoolCount { if snodePool.count < minimumSnodePoolCount {
let target = seedNodePool.randomElement()! let target = seedNodePool.randomElement()!
@ -97,9 +97,9 @@ public final class SnodeAPI : NSObject {
} }
}.done2 { snode in }.done2 { snode in
seal.fulfill(snode) seal.fulfill(snode)
Configuration.shared.storage.with { transaction in SNSnodeKitConfiguration.shared.storage.with { transaction in
SNLog("Persisting snode pool to database.") SNLog("Persisting snode pool to database.")
Configuration.shared.storage.setSnodePool(to: SnodeAPI.snodePool, using: transaction) SNSnodeKitConfiguration.shared.storage.setSnodePool(to: SnodeAPI.snodePool, using: transaction)
} }
}.catch2 { error in }.catch2 { error in
SNLog("Failed to contact seed node at: \(target).") SNLog("Failed to contact seed node at: \(target).")
@ -118,16 +118,16 @@ public final class SnodeAPI : NSObject {
var snodePool = SnodeAPI.snodePool var snodePool = SnodeAPI.snodePool
snodePool.remove(snode) snodePool.remove(snode)
SnodeAPI.snodePool = snodePool SnodeAPI.snodePool = snodePool
Configuration.shared.storage.with { transaction in SNSnodeKitConfiguration.shared.storage.with { transaction in
Configuration.shared.storage.setSnodePool(to: snodePool, using: transaction) SNSnodeKitConfiguration.shared.storage.setSnodePool(to: snodePool, using: transaction)
} }
} }
// MARK: Public API // MARK: Public API
@objc public static func clearSnodePool() { @objc public static func clearSnodePool() {
snodePool.removeAll() snodePool.removeAll()
Configuration.shared.storage.with { transaction in SNSnodeKitConfiguration.shared.storage.with { transaction in
Configuration.shared.storage.setSnodePool(to: [], using: transaction) SNSnodeKitConfiguration.shared.storage.setSnodePool(to: [], using: transaction)
} }
} }
@ -136,8 +136,8 @@ public final class SnodeAPI : NSObject {
if var swarm = swarm, let index = swarm.firstIndex(of: snode) { if var swarm = swarm, let index = swarm.firstIndex(of: snode) {
swarm.remove(at: index) swarm.remove(at: index)
SnodeAPI.swarmCache[publicKey] = swarm SnodeAPI.swarmCache[publicKey] = swarm
Configuration.shared.storage.with { transaction in SNSnodeKitConfiguration.shared.storage.with { transaction in
Configuration.shared.storage.setSwarm(to: swarm, for: publicKey, using: transaction) SNSnodeKitConfiguration.shared.storage.setSwarm(to: swarm, for: publicKey, using: transaction)
} }
} }
} }
@ -149,12 +149,12 @@ public final class SnodeAPI : NSObject {
public static func getSwarm(for publicKey: String, isForcedReload: Bool = false) -> Promise<Set<Snode>> { public static func getSwarm(for publicKey: String, isForcedReload: Bool = false) -> Promise<Set<Snode>> {
if swarmCache[publicKey] == nil { if swarmCache[publicKey] == nil {
swarmCache[publicKey] = Configuration.shared.storage.getSwarm(for: publicKey) swarmCache[publicKey] = SNSnodeKitConfiguration.shared.storage.getSwarm(for: publicKey)
} }
if let cachedSwarm = swarmCache[publicKey], cachedSwarm.count >= minimumSwarmSnodeCount && !isForcedReload { if let cachedSwarm = swarmCache[publicKey], cachedSwarm.count >= minimumSwarmSnodeCount && !isForcedReload {
return Promise<Set<Snode>> { $0.fulfill(cachedSwarm) } return Promise<Set<Snode>> { $0.fulfill(cachedSwarm) }
} else { } else {
SNLog("Getting swarm for: \((publicKey == Configuration.shared.storage.getUserPublicKey()) ? "self" : publicKey).") SNLog("Getting swarm for: \((publicKey == SNSnodeKitConfiguration.shared.storage.getUserPublicKey()) ? "self" : publicKey).")
let parameters: [String:Any] = [ "pubKey" : publicKey ] let parameters: [String:Any] = [ "pubKey" : publicKey ]
return getRandomSnode().then2 { snode in return getRandomSnode().then2 { snode in
attempt(maxRetryCount: 4, recoveringOn: Threading.workQueue) { attempt(maxRetryCount: 4, recoveringOn: Threading.workQueue) {
@ -163,8 +163,8 @@ public final class SnodeAPI : NSObject {
}.map2 { rawSnodes in }.map2 { rawSnodes in
let swarm = parseSnodes(from: rawSnodes) let swarm = parseSnodes(from: rawSnodes)
swarmCache[publicKey] = swarm swarmCache[publicKey] = swarm
Configuration.shared.storage.with { transaction in SNSnodeKitConfiguration.shared.storage.with { transaction in
Configuration.shared.storage.setSwarm(to: swarm, for: publicKey, using: transaction) SNSnodeKitConfiguration.shared.storage.setSwarm(to: swarm, for: publicKey, using: transaction)
} }
return swarm return swarm
} }
@ -172,7 +172,7 @@ public final class SnodeAPI : NSObject {
} }
public static func getRawMessages(from snode: Snode, associatedWith publicKey: String) -> RawResponsePromise { public static func getRawMessages(from snode: Snode, associatedWith publicKey: String) -> RawResponsePromise {
let storage = Configuration.shared.storage let storage = SNSnodeKitConfiguration.shared.storage
storage.with { transaction in storage.with { transaction in
storage.pruneLastMessageHashInfoIfExpired(for: snode, associatedWith: publicKey, using: transaction) storage.pruneLastMessageHashInfoIfExpired(for: snode, associatedWith: publicKey, using: transaction)
} }
@ -183,7 +183,7 @@ public final class SnodeAPI : NSObject {
public static func getMessages(for publicKey: String) -> Promise<Set<MessageListPromise>> { public static func getMessages(for publicKey: String) -> Promise<Set<MessageListPromise>> {
let (promise, seal) = Promise<Set<MessageListPromise>>.pending() let (promise, seal) = Promise<Set<MessageListPromise>>.pending()
let storage = Configuration.shared.storage let storage = SNSnodeKitConfiguration.shared.storage
Threading.workQueue.async { Threading.workQueue.async {
attempt(maxRetryCount: maxRetryCount, recoveringOn: Threading.workQueue) { attempt(maxRetryCount: maxRetryCount, recoveringOn: Threading.workQueue) {
getTargetSnodes(for: publicKey).mapValues2 { targetSnode in getTargetSnodes(for: publicKey).mapValues2 { targetSnode in
@ -253,8 +253,8 @@ public final class SnodeAPI : NSObject {
private static func updateLastMessageHashValueIfPossible(for snode: Snode, associatedWith publicKey: String, from rawMessages: [JSON]) { private static func updateLastMessageHashValueIfPossible(for snode: Snode, associatedWith publicKey: String, from rawMessages: [JSON]) {
if let lastMessage = rawMessages.last, let lastHash = lastMessage["hash"] as? String, let expirationDate = lastMessage["expiration"] as? UInt64 { if let lastMessage = rawMessages.last, let lastHash = lastMessage["hash"] as? String, let expirationDate = lastMessage["expiration"] as? UInt64 {
Configuration.shared.storage.with { transaction in SNSnodeKitConfiguration.shared.storage.with { transaction in
Configuration.shared.storage.setLastMessageHashInfo(for: snode, associatedWith: publicKey, SNSnodeKitConfiguration.shared.storage.setLastMessageHashInfo(for: snode, associatedWith: publicKey,
to: [ "hash" : lastHash, "expirationDate" : NSNumber(value: expirationDate) ], using: transaction) to: [ "hash" : lastHash, "expirationDate" : NSNumber(value: expirationDate) ], using: transaction)
} }
} else if (!rawMessages.isEmpty) { } else if (!rawMessages.isEmpty) {
@ -263,7 +263,7 @@ public final class SnodeAPI : NSObject {
} }
private static func removeDuplicates(from rawMessages: [JSON], associatedWith publicKey: String) -> [JSON] { private static func removeDuplicates(from rawMessages: [JSON], associatedWith publicKey: String) -> [JSON] {
var receivedMessages = Configuration.shared.storage.getReceivedMessages(for: publicKey) var receivedMessages = SNSnodeKitConfiguration.shared.storage.getReceivedMessages(for: publicKey)
return rawMessages.filter { rawMessage in return rawMessages.filter { rawMessage in
guard let hash = rawMessage["hash"] as? String else { guard let hash = rawMessage["hash"] as? String else {
SNLog("Missing hash value for message: \(rawMessage).") SNLog("Missing hash value for message: \(rawMessage).")
@ -271,8 +271,8 @@ public final class SnodeAPI : NSObject {
} }
let isDuplicate = receivedMessages.contains(hash) let isDuplicate = receivedMessages.contains(hash)
receivedMessages.insert(hash) receivedMessages.insert(hash)
Configuration.shared.storage.with { transaction in SNSnodeKitConfiguration.shared.storage.with { transaction in
Configuration.shared.storage.setReceivedMessages(to: receivedMessages, for: publicKey, using: transaction) SNSnodeKitConfiguration.shared.storage.setReceivedMessages(to: receivedMessages, for: publicKey, using: transaction)
} }
return !isDuplicate return !isDuplicate
} }

View File

@ -1,10 +1,10 @@
@objc(SNUtilitiesKitConfiguration) @objc
public final class Configuration : NSObject { public final class SNUtilitiesKitConfiguration : NSObject {
@objc public let owsPrimaryStorage: OWSPrimaryStorageProtocol @objc public let owsPrimaryStorage: OWSPrimaryStorageProtocol
public let maxFileSize: UInt public let maxFileSize: UInt
@objc public static var shared: Configuration! @objc public static var shared: SNUtilitiesKitConfiguration!
fileprivate init(owsPrimaryStorage: OWSPrimaryStorageProtocol, maxFileSize: UInt) { fileprivate init(owsPrimaryStorage: OWSPrimaryStorageProtocol, maxFileSize: UInt) {
self.owsPrimaryStorage = owsPrimaryStorage self.owsPrimaryStorage = owsPrimaryStorage
@ -12,9 +12,9 @@ public final class Configuration : NSObject {
} }
} }
public enum SessionUtilitiesKit { // Just to make the external API nice public enum SNUtilitiesKit { // Just to make the external API nice
public static func configure(owsPrimaryStorage: OWSPrimaryStorageProtocol, maxFileSize: UInt) { public static func configure(owsPrimaryStorage: OWSPrimaryStorageProtocol, maxFileSize: UInt) {
Configuration.shared = Configuration(owsPrimaryStorage: owsPrimaryStorage, maxFileSize: maxFileSize) SNUtilitiesKitConfiguration.shared = SNUtilitiesKitConfiguration(owsPrimaryStorage: owsPrimaryStorage, maxFileSize: maxFileSize)
} }
} }

View File

@ -111,15 +111,15 @@ public enum OWSMediaError: Error {
* https://github.com/signalapp/Signal-Android/blob/master/src/org/thoughtcrime/securesms/mms/PushMediaConstraints.java * https://github.com/signalapp/Signal-Android/blob/master/src/org/thoughtcrime/securesms/mms/PushMediaConstraints.java
*/ */
@objc @objc
public static var kMaxFileSizeAnimatedImage: UInt { Configuration.shared.maxFileSize } public static var kMaxFileSizeAnimatedImage: UInt { SNUtilitiesKitConfiguration.shared.maxFileSize }
@objc @objc
public static var kMaxFileSizeImage: UInt { Configuration.shared.maxFileSize } public static var kMaxFileSizeImage: UInt { SNUtilitiesKitConfiguration.shared.maxFileSize }
@objc @objc
public static var kMaxFileSizeVideo: UInt { Configuration.shared.maxFileSize } public static var kMaxFileSizeVideo: UInt { SNUtilitiesKitConfiguration.shared.maxFileSize }
@objc @objc
public static var kMaxFileSizeAudio: UInt { Configuration.shared.maxFileSize } public static var kMaxFileSizeAudio: UInt { SNUtilitiesKitConfiguration.shared.maxFileSize }
@objc @objc
public static var kMaxFileSizeGeneric: UInt { Configuration.shared.maxFileSize } public static var kMaxFileSizeGeneric: UInt { SNUtilitiesKitConfiguration.shared.maxFileSize }
@objc @objc
public static let kMaxVideoDimensions: CGFloat = 3 * 1024 public static let kMaxVideoDimensions: CGFloat = 3 * 1024

View File

@ -10,7 +10,7 @@ import YapDatabase
public final class Storage : NSObject { public final class Storage : NSObject {
public static let serialQueue = DispatchQueue(label: "Storage.serialQueue", qos: .userInitiated) public static let serialQueue = DispatchQueue(label: "Storage.serialQueue", qos: .userInitiated)
private static var owsStorage: OWSPrimaryStorageProtocol { Configuration.shared.owsPrimaryStorage } private static var owsStorage: OWSPrimaryStorageProtocol { SNUtilitiesKitConfiguration.shared.owsPrimaryStorage }
@objc public static let shared = Storage() @objc public static let shared = Storage()

View File

@ -4740,10 +4740,10 @@
"${BUILT_PRODUCTS_DIR}/ZXingObjC/ZXingObjC.framework", "${BUILT_PRODUCTS_DIR}/ZXingObjC/ZXingObjC.framework",
"${BUILT_PRODUCTS_DIR}/Curve25519Kit/Curve25519Kit.framework", "${BUILT_PRODUCTS_DIR}/Curve25519Kit/Curve25519Kit.framework",
"${PODS_ROOT}/GRKOpenSSLFramework/OpenSSL-iOS/bin/openssl.framework", "${PODS_ROOT}/GRKOpenSSLFramework/OpenSSL-iOS/bin/openssl.framework",
"${BUILT_PRODUCTS_DIR}/SAMKeychain/SAMKeychain.framework",
"${BUILT_PRODUCTS_DIR}/SignalCoreKit/SignalCoreKit.framework", "${BUILT_PRODUCTS_DIR}/SignalCoreKit/SignalCoreKit.framework",
"${BUILT_PRODUCTS_DIR}/SwiftProtobuf/SwiftProtobuf.framework",
"${BUILT_PRODUCTS_DIR}/HKDFKit/HKDFKit.framework", "${BUILT_PRODUCTS_DIR}/HKDFKit/HKDFKit.framework",
"${BUILT_PRODUCTS_DIR}/SAMKeychain/SAMKeychain.framework",
"${BUILT_PRODUCTS_DIR}/SwiftProtobuf/SwiftProtobuf.framework",
"${BUILT_PRODUCTS_DIR}/libPhoneNumber-iOS/libPhoneNumber_iOS.framework", "${BUILT_PRODUCTS_DIR}/libPhoneNumber-iOS/libPhoneNumber_iOS.framework",
); );
name = "[CP] Embed Pods Frameworks"; name = "[CP] Embed Pods Frameworks";
@ -4766,10 +4766,10 @@
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/ZXingObjC.framework", "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/ZXingObjC.framework",
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/Curve25519Kit.framework", "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/Curve25519Kit.framework",
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/openssl.framework", "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/openssl.framework",
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/SAMKeychain.framework",
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/SignalCoreKit.framework", "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/SignalCoreKit.framework",
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/SwiftProtobuf.framework",
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/HKDFKit.framework", "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/HKDFKit.framework",
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/SAMKeychain.framework",
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/SwiftProtobuf.framework",
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/libPhoneNumber_iOS.framework", "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/libPhoneNumber_iOS.framework",
); );
runOnlyForDeploymentPostprocessing = 0; runOnlyForDeploymentPostprocessing = 0;

View File

@ -15,8 +15,8 @@ public final class Configuration : NSObject {
sessionRestorationImplementation: SessionRestorationImplementation(), sessionRestorationImplementation: SessionRestorationImplementation(),
certificateValidator: SMKCertificateDefaultValidator(trustRoot: OWSUDManagerImpl.trustRoot()) certificateValidator: SMKCertificateDefaultValidator(trustRoot: OWSUDManagerImpl.trustRoot())
) )
SessionProtocolKit.configure(storage: Storage.shared, sharedSenderKeysDelegate: MessageSender.shared) SNProtocolKit.configure(storage: Storage.shared, sharedSenderKeysDelegate: MessageSender.shared)
SessionSnodeKit.configure(storage: Storage.shared) SNSnodeKit.configure(storage: Storage.shared)
SessionUtilitiesKit.configure(owsPrimaryStorage: OWSPrimaryStorage.shared(), maxFileSize: UInt(Double(FileServerAPI.maxFileSize) / FileServerAPI.fileSizeORMultiplier)) SNUtilitiesKit.configure(owsPrimaryStorage: OWSPrimaryStorage.shared(), maxFileSize: UInt(Double(FileServerAPI.maxFileSize) / FileServerAPI.fileSizeORMultiplier))
} }
} }

View File

@ -54,7 +54,7 @@ NS_ASSUME_NONNULL_BEGIN
[knownMigrationIds addObject:migration.uniqueId]; [knownMigrationIds addObject:migration.uniqueId];
} }
[LKStorage writeSyncWithBlock:^(YapDatabaseReadWriteTransaction *transaction) { [OWSPrimaryStorage.sharedManager.dbReadWriteConnection readWriteWithBlock:^(YapDatabaseReadWriteTransaction *transaction) {
NSArray<NSString *> *savedMigrationIds = [transaction allKeysInCollection:OWSDatabaseMigration.collection]; NSArray<NSString *> *savedMigrationIds = [transaction allKeysInCollection:OWSDatabaseMigration.collection];
NSMutableSet<NSString *> *unknownMigrationIds = [NSMutableSet new]; NSMutableSet<NSString *> *unknownMigrationIds = [NSMutableSet new];