2019-09-26 03:32:47 +02:00
|
|
|
import PromiseKit
|
|
|
|
|
2020-02-02 01:33:34 +01:00
|
|
|
/// Base class for `LokiStorageAPI` and `LokiPublicChatAPI`.
|
2019-09-26 03:32:47 +02:00
|
|
|
public class LokiDotNetAPI : NSObject {
|
|
|
|
|
|
|
|
// MARK: Convenience
|
|
|
|
internal static let storage = OWSPrimaryStorage.shared()
|
2019-10-02 05:34:34 +02:00
|
|
|
internal static let userKeyPair = OWSIdentityManager.shared().identityKeyPair()!
|
2019-09-26 03:32:47 +02:00
|
|
|
internal static let userHexEncodedPublicKey = userKeyPair.hexEncodedPublicKey
|
|
|
|
|
2019-10-18 00:46:44 +02:00
|
|
|
// MARK: Settings
|
|
|
|
private static let attachmentType = "network.loki"
|
|
|
|
|
2019-09-26 03:32:47 +02:00
|
|
|
// MARK: Error
|
|
|
|
public enum Error : Swift.Error {
|
2019-10-17 02:28:51 +02:00
|
|
|
case generic, parsingFailed, encryptionFailed, decryptionFailed, signingFailed
|
2019-09-26 03:32:47 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// MARK: Database
|
|
|
|
/// To be overridden by subclasses.
|
|
|
|
internal class var authTokenCollection: String { preconditionFailure("authTokenCollection is abstract and must be overridden.") }
|
|
|
|
|
|
|
|
private static func getAuthTokenFromDatabase(for server: String) -> String? {
|
|
|
|
var result: String? = nil
|
|
|
|
storage.dbReadConnection.read { transaction in
|
|
|
|
result = transaction.object(forKey: server, inCollection: authTokenCollection) as! String?
|
|
|
|
}
|
|
|
|
return result
|
|
|
|
}
|
|
|
|
|
|
|
|
private static func setAuthToken(for server: String, to newValue: String) {
|
|
|
|
storage.dbReadWriteConnection.readWrite { transaction in
|
|
|
|
transaction.setObject(newValue, forKey: server, inCollection: authTokenCollection)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// MARK: Lifecycle
|
|
|
|
override private init() { }
|
|
|
|
|
2019-10-18 00:46:44 +02:00
|
|
|
// MARK: Attachments (Public API)
|
|
|
|
public static func uploadAttachment(_ attachment: TSAttachmentStream, with attachmentID: String, to server: String) -> Promise<Void> {
|
2019-10-18 02:33:14 +02:00
|
|
|
let isEncryptionRequired = (server == LokiStorageAPI.server)
|
2019-10-18 00:46:44 +02:00
|
|
|
return Promise<Void>() { seal in
|
2019-11-13 03:12:25 +01:00
|
|
|
getAuthToken(for: server).done(on: DispatchQueue.global()) { token in
|
2019-10-18 02:33:14 +02:00
|
|
|
let data: Data
|
2019-10-18 00:46:44 +02:00
|
|
|
guard let unencryptedAttachmentData = try? attachment.readDataFromFile() else {
|
|
|
|
print("[Loki] Couldn't read attachment data from disk.")
|
|
|
|
return seal.reject(Error.generic)
|
|
|
|
}
|
2019-10-18 02:33:14 +02:00
|
|
|
// Encrypt the attachment if needed
|
|
|
|
if isEncryptionRequired {
|
|
|
|
var encryptionKey = NSData()
|
|
|
|
var digest = NSData()
|
|
|
|
guard let encryptedAttachmentData = Cryptography.encryptAttachmentData(unencryptedAttachmentData, outKey: &encryptionKey, outDigest: &digest) else {
|
|
|
|
print("[Loki] Couldn't encrypt attachment.")
|
|
|
|
return seal.reject(Error.encryptionFailed)
|
|
|
|
}
|
|
|
|
attachment.encryptionKey = encryptionKey as Data
|
|
|
|
attachment.digest = digest as Data
|
|
|
|
data = encryptedAttachmentData
|
|
|
|
} else {
|
|
|
|
data = unencryptedAttachmentData
|
2019-10-18 00:46:44 +02:00
|
|
|
}
|
|
|
|
// Create the request
|
|
|
|
let url = "\(server)/files"
|
|
|
|
let parameters: JSON = [ "type" : attachmentType, "Content-Type" : "application/binary" ]
|
|
|
|
var error: NSError?
|
|
|
|
var request = AFHTTPRequestSerializer().multipartFormRequest(withMethod: "POST", urlString: url, parameters: parameters, constructingBodyWith: { formData in
|
2019-10-18 02:33:14 +02:00
|
|
|
formData.appendPart(withFileData: data, name: "content", fileName: UUID().uuidString, mimeType: "application/binary")
|
2019-10-18 00:46:44 +02:00
|
|
|
}, error: &error)
|
|
|
|
request.addValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
|
|
|
|
if let error = error {
|
|
|
|
print("[Loki] Couldn't upload attachment due to error: \(error).")
|
|
|
|
throw error
|
|
|
|
}
|
|
|
|
// Send the request
|
2020-02-03 06:50:14 +01:00
|
|
|
let isLokiFileServer = server.contains("file.lokinet.org") || server.contains("file-dev.lokinet.org")
|
|
|
|
if isLokiFileServer {
|
|
|
|
LokiFileServerProxy(for: server).performLokiFileServerNSURLRequest(request as NSURLRequest).done { responseObject in
|
|
|
|
// Parse the server ID & download URL
|
|
|
|
guard let json = responseObject as? JSON, let data = json["data"] as? JSON, let serverID = data["id"] as? UInt64, let downloadURL = data["url"] as? String else {
|
|
|
|
print("[Loki] Couldn't parse attachment from: \(responseObject).")
|
|
|
|
return seal.reject(Error.parsingFailed)
|
|
|
|
}
|
|
|
|
// Update the attachment
|
|
|
|
attachment.serverId = serverID
|
|
|
|
attachment.isUploaded = true
|
|
|
|
attachment.downloadURL = downloadURL
|
|
|
|
attachment.save()
|
|
|
|
seal.fulfill(())
|
|
|
|
}.catch { error in
|
|
|
|
seal.reject(error)
|
2019-10-18 00:46:44 +02:00
|
|
|
}
|
2020-02-03 06:50:14 +01:00
|
|
|
} else {
|
|
|
|
let task = AFURLSessionManager(sessionConfiguration: .default).uploadTask(withStreamedRequest: request as URLRequest, progress: { rawProgress in
|
|
|
|
// Broadcast progress updates
|
|
|
|
let progress = max(0.1, rawProgress.fractionCompleted)
|
|
|
|
let userInfo: [String:Any] = [ kAttachmentUploadProgressKey : progress, kAttachmentUploadAttachmentIDKey : attachmentID ]
|
|
|
|
DispatchQueue.main.async {
|
|
|
|
NotificationCenter.default.post(name: .attachmentUploadProgress, object: nil, userInfo: userInfo)
|
|
|
|
}
|
|
|
|
}, completionHandler: { response, responseObject, error in
|
|
|
|
if let error = error {
|
|
|
|
print("[Loki] Couldn't upload attachment due to error: \(error).")
|
|
|
|
return seal.reject(error)
|
|
|
|
}
|
|
|
|
let statusCode = (response as! HTTPURLResponse).statusCode
|
|
|
|
let isSuccessful = (200...299) ~= statusCode
|
|
|
|
guard isSuccessful else {
|
|
|
|
print("[Loki] Couldn't upload attachment.")
|
|
|
|
return seal.reject(Error.generic)
|
|
|
|
}
|
|
|
|
// Parse the server ID & download URL
|
|
|
|
guard let json = responseObject as? JSON, let data = json["data"] as? JSON, let serverID = data["id"] as? UInt64, let downloadURL = data["url"] as? String else {
|
|
|
|
print("[Loki] Couldn't parse attachment from: \(responseObject).")
|
|
|
|
return seal.reject(Error.parsingFailed)
|
|
|
|
}
|
|
|
|
// Update the attachment
|
|
|
|
attachment.serverId = serverID
|
|
|
|
attachment.isUploaded = true
|
|
|
|
attachment.downloadURL = downloadURL
|
|
|
|
attachment.save()
|
|
|
|
return seal.fulfill(())
|
|
|
|
})
|
|
|
|
task.resume()
|
|
|
|
}
|
2019-11-13 03:12:25 +01:00
|
|
|
}.catch(on: DispatchQueue.global()) { error in
|
2019-10-18 00:46:44 +02:00
|
|
|
print("[Loki] Couldn't upload attachment.")
|
|
|
|
seal.reject(error)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-09-26 03:32:47 +02:00
|
|
|
// MARK: Internal API
|
|
|
|
internal static func getAuthToken(for server: String) -> Promise<String> {
|
|
|
|
if let token = getAuthTokenFromDatabase(for: server) {
|
|
|
|
return Promise.value(token)
|
|
|
|
} else {
|
2019-11-13 03:12:25 +01:00
|
|
|
return requestNewAuthToken(for: server).then(on: DispatchQueue.global()) { submitAuthToken($0, for: server) }.map { token -> String in
|
2019-09-26 03:32:47 +02:00
|
|
|
setAuthToken(for: server, to: token)
|
|
|
|
return token
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// MARK: Private API
|
|
|
|
private static func requestNewAuthToken(for server: String) -> Promise<String> {
|
|
|
|
print("[Loki] Requesting auth token for server: \(server).")
|
|
|
|
let queryParameters = "pubKey=\(userHexEncodedPublicKey)"
|
|
|
|
let url = URL(string: "\(server)/loki/v1/get_challenge?\(queryParameters)")!
|
|
|
|
let request = TSRequest(url: url)
|
2020-02-02 01:33:34 +01:00
|
|
|
return LokiFileServerProxy(for: server).perform(request, withCompletionQueue: DispatchQueue.global()).map { rawResponse in
|
2019-09-26 03:32:47 +02:00
|
|
|
guard let json = rawResponse as? JSON, let base64EncodedChallenge = json["cipherText64"] as? String, let base64EncodedServerPublicKey = json["serverPubKey64"] as? String,
|
|
|
|
let challenge = Data(base64Encoded: base64EncodedChallenge), var serverPublicKey = Data(base64Encoded: base64EncodedServerPublicKey) else {
|
|
|
|
throw Error.parsingFailed
|
|
|
|
}
|
|
|
|
// Discard the "05" prefix if needed
|
|
|
|
if (serverPublicKey.count == 33) {
|
2019-10-02 05:34:34 +02:00
|
|
|
let hexEncodedServerPublicKey = serverPublicKey.toHexString()
|
2019-09-26 03:32:47 +02:00
|
|
|
serverPublicKey = Data.data(fromHex: hexEncodedServerPublicKey.substring(from: 2))!
|
|
|
|
}
|
|
|
|
// The challenge is prefixed by the 16 bit IV
|
|
|
|
guard let tokenAsData = try? DiffieHellman.decrypt(challenge, publicKey: serverPublicKey, privateKey: userKeyPair.privateKey),
|
|
|
|
let token = String(bytes: tokenAsData, encoding: .utf8) else {
|
|
|
|
throw Error.decryptionFailed
|
|
|
|
}
|
|
|
|
return token
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
private static func submitAuthToken(_ token: String, for server: String) -> Promise<String> {
|
|
|
|
print("[Loki] Submitting auth token for server: \(server).")
|
|
|
|
let url = URL(string: "\(server)/loki/v1/submit_challenge")!
|
|
|
|
let parameters = [ "pubKey" : userHexEncodedPublicKey, "token" : token ]
|
|
|
|
let request = TSRequest(url: url, method: "POST", parameters: parameters)
|
2020-02-02 01:33:34 +01:00
|
|
|
return LokiFileServerProxy(for: server).perform(request, withCompletionQueue: DispatchQueue.global()).map { _ in token }
|
2019-09-26 03:32:47 +02:00
|
|
|
}
|
2019-10-18 00:46:44 +02:00
|
|
|
|
|
|
|
// MARK: Attachments (Public Obj-C API)
|
|
|
|
@objc(uploadAttachment:withID:toServer:)
|
|
|
|
public static func objc_uploadAttachment(_ attachment: TSAttachmentStream, with attachmentID: String, to server: String) -> AnyPromise {
|
|
|
|
return AnyPromise.from(uploadAttachment(attachment, with: attachmentID, to: server))
|
|
|
|
}
|
2019-09-26 03:32:47 +02:00
|
|
|
}
|