Convert remaining file server usages

pull/394/head
Niels Andriesse 4 years ago
parent 0ceb434215
commit f7613e09bf

@ -4,9 +4,9 @@ import SessionSnodeKit
@objc(SNFileServerAPIV2) @objc(SNFileServerAPIV2)
public final class FileServerAPIV2 : NSObject { public final class FileServerAPIV2 : NSObject {
public static let server = "http://88.99.175.227" @objc public static let server = "http://88.99.175.227"
public static let serverPublicKey = "7cb31905b55cd5580c686911debf672577b3fb0bff81df4ce2d5c4cb3a7aaa69" public static let serverPublicKey = "7cb31905b55cd5580c686911debf672577b3fb0bff81df4ce2d5c4cb3a7aaa69"
public static let useV2FileServer = true @objc public static let useV2FileServer = false
private override init() { } private override init() { }
@ -71,6 +71,11 @@ public final class FileServerAPIV2 : NSObject {
} }
// MARK: File Storage // MARK: File Storage
@objc(upload:)
public static func objc_upload(file: Data) -> AnyPromise {
return AnyPromise.from(upload(file))
}
public static func upload(_ file: Data) -> Promise<UInt64> { public static func upload(_ file: Data) -> Promise<UInt64> {
let base64EncodedFile = file.base64EncodedString() let base64EncodedFile = file.base64EncodedString()
let parameters = [ "file" : base64EncodedFile ] let parameters = [ "file" : base64EncodedFile ]
@ -81,6 +86,11 @@ public final class FileServerAPIV2 : NSObject {
} }
} }
@objc(download:)
public static func objc_download(file: UInt64) -> AnyPromise {
return AnyPromise.from(download(file))
}
public static func download(_ file: UInt64) -> Promise<Data> { public static func download(_ file: UInt64) -> Promise<Data> {
let request = Request(verb: .get, endpoint: "files/\(file)") let request = Request(verb: .get, endpoint: "files/\(file)")
return send(request).map(on: DispatchQueue.global(qos: .userInitiated)) { json in return send(request).map(on: DispatchQueue.global(qos: .userInitiated)) { json in

@ -66,9 +66,9 @@ public final class AttachmentUploadJob : NSObject, Job, NSCoding { // NSObject/N
guard !stream.isUploaded else { return handleSuccess() } // Should never occur guard !stream.isUploaded else { return handleSuccess() } // Should never occur
let storage = SNMessagingKitConfiguration.shared.storage let storage = SNMessagingKitConfiguration.shared.storage
if let v2OpenGroup = storage.getV2OpenGroup(for: threadID) { if let v2OpenGroup = storage.getV2OpenGroup(for: threadID) {
upload(stream, using: { data in return OpenGroupAPIV2.upload(data, to: v2OpenGroup.room, on: v2OpenGroup.server) }, encrypt: false) AttachmentUploadJob.upload(stream, using: { data in return OpenGroupAPIV2.upload(data, to: v2OpenGroup.room, on: v2OpenGroup.server) }, encrypt: false, onSuccess: handleSuccess, onFailure: handleFailure)
} else if FileServerAPIV2.useV2FileServer && storage.getOpenGroup(for: threadID) == nil { } else if FileServerAPIV2.useV2FileServer && storage.getOpenGroup(for: threadID) == nil {
upload(stream, using: FileServerAPIV2.upload, encrypt: true) AttachmentUploadJob.upload(stream, using: FileServerAPIV2.upload, encrypt: true, onSuccess: handleSuccess, onFailure: handleFailure)
} else { // Legacy } else { // Legacy
let openGroup = storage.getOpenGroup(for: threadID) let openGroup = storage.getOpenGroup(for: threadID)
let server = openGroup?.server ?? FileServerAPI.server let server = openGroup?.server ?? FileServerAPI.server
@ -87,11 +87,11 @@ public final class AttachmentUploadJob : NSObject, Job, NSCoding { // NSObject/N
} }
} }
private func upload(_ stream: TSAttachmentStream, using upload: (Data) -> Promise<UInt64>, encrypt: Bool) { public static func upload(_ stream: TSAttachmentStream, using upload: (Data) -> Promise<UInt64>, encrypt: Bool, onSuccess: (() -> Void)?, onFailure: ((Swift.Error) -> Void)?) {
// Get the attachment // Get the attachment
guard var data = try? stream.readDataFromFile() else { guard var data = try? stream.readDataFromFile() else {
SNLog("Couldn't read attachment from disk.") SNLog("Couldn't read attachment from disk.")
return handleFailure(error: Error.noAttachment) onFailure?(Error.noAttachment); return
} }
// Encrypt the attachment if needed // Encrypt the attachment if needed
if encrypt { if encrypt {
@ -99,7 +99,7 @@ public final class AttachmentUploadJob : NSObject, Job, NSCoding { // NSObject/N
var digest = NSData() var digest = NSData()
guard let ciphertext = Cryptography.encryptAttachmentData(data, shouldPad: false, outKey: &encryptionKey, outDigest: &digest) else { guard let ciphertext = Cryptography.encryptAttachmentData(data, shouldPad: false, outKey: &encryptionKey, outDigest: &digest) else {
SNLog("Couldn't encrypt attachment.") SNLog("Couldn't encrypt attachment.")
return handleFailure(error: Error.encryptionFailed) onFailure?(Error.encryptionFailed); return
} }
stream.encryptionKey = encryptionKey as Data stream.encryptionKey = encryptionKey as Data
stream.digest = digest as Data stream.digest = digest as Data
@ -108,7 +108,7 @@ public final class AttachmentUploadJob : NSObject, Job, NSCoding { // NSObject/N
// Check the file size // Check the file size
SNLog("File size: \(data.count) bytes.") SNLog("File size: \(data.count) bytes.")
if Double(data.count) > Double(FileServerAPI.maxFileSize) / FileServerAPI.fileSizeORMultiplier { if Double(data.count) > Double(FileServerAPI.maxFileSize) / FileServerAPI.fileSizeORMultiplier {
return handleFailure(error: FileServerAPI.Error.maxFileSizeExceeded) onFailure?(FileServerAPI.Error.maxFileSizeExceeded); return
} }
// Send the request // Send the request
stream.isUploaded = false stream.isUploaded = false
@ -119,9 +119,9 @@ public final class AttachmentUploadJob : NSObject, Job, NSCoding { // NSObject/N
stream.isUploaded = true stream.isUploaded = true
stream.downloadURL = downloadURL stream.downloadURL = downloadURL
stream.save() stream.save()
self.handleSuccess() onSuccess?()
}.catch { error in }.catch { error in
self.handleFailure(error: error) onFailure?(error)
} }
} }

@ -42,13 +42,22 @@ extension MessageSender {
let attachments = attachmentIDs.compactMap { TSAttachment.fetch(uniqueId: $0, transaction: transaction) as? TSAttachmentStream } let attachments = attachmentIDs.compactMap { TSAttachment.fetch(uniqueId: $0, transaction: transaction) as? TSAttachmentStream }
let attachmentsToUpload = attachments.filter { !$0.isUploaded } let attachmentsToUpload = attachments.filter { !$0.isUploaded }
let attachmentUploadPromises: [Promise<Void>] = attachmentsToUpload.map { stream in let attachmentUploadPromises: [Promise<Void>] = attachmentsToUpload.map { stream in
let openGroup = SNMessagingKitConfiguration.shared.storage.getOpenGroup(for: thread.uniqueId!) let storage = SNMessagingKitConfiguration.shared.storage
let openGroupV2 = SNMessagingKitConfiguration.shared.storage.getV2OpenGroup(for: thread.uniqueId!) if let v2OpenGroup = storage.getV2OpenGroup(for: thread.uniqueId!) {
let server = openGroupV2?.server ?? openGroup?.server ?? FileServerAPI.server let (promise, seal) = Promise<Void>.pending()
// FIXME: This is largely a duplication of the code in AttachmentUploadJob AttachmentUploadJob.upload(stream, using: { data in return OpenGroupAPIV2.upload(data, to: v2OpenGroup.room, on: v2OpenGroup.server) }, encrypt: false, onSuccess: { seal.fulfill(()) }, onFailure: { seal.reject($0) })
let maxRetryCount: UInt = (openGroup != nil) ? 24 : 8 return promise
return attempt(maxRetryCount: maxRetryCount, recoveringOn: DispatchQueue.global(qos: .userInitiated)) { } else if FileServerAPIV2.useV2FileServer && storage.getOpenGroup(for: thread.uniqueId!) == nil {
FileServerAPI.uploadAttachment(stream, with: stream.uniqueId!, to: server) let (promise, seal) = Promise<Void>.pending()
AttachmentUploadJob.upload(stream, using: FileServerAPIV2.upload, encrypt: true, onSuccess: { seal.fulfill(()) }, onFailure: { seal.reject($0) })
return promise
} else { // Legacy
let openGroup = storage.getOpenGroup(for: thread.uniqueId!)
let server = openGroup?.server ?? FileServerAPI.server
let maxRetryCount: UInt = (openGroup != nil) ? 24 : 8
return attempt(maxRetryCount: maxRetryCount, recoveringOn: DispatchQueue.global(qos: .userInitiated)) {
FileServerAPI.uploadAttachment(stream, with: stream.uniqueId!, to: server)
}
} }
} }
return when(resolved: attachmentUploadPromises).then(on: DispatchQueue.global(qos: .userInitiated)) { results -> Promise<Void> in return when(resolved: attachmentUploadPromises).then(on: DispatchQueue.global(qos: .userInitiated)) { results -> Promise<Void> in

@ -362,8 +362,14 @@ typedef void (^ProfileManagerFailureBlock)(NSError *error);
NSData *encryptedAvatarData = [self encryptProfileData:avatarData profileKey:newProfileKey]; NSData *encryptedAvatarData = [self encryptProfileData:avatarData profileKey:newProfileKey];
OWSAssertDebug(encryptedAvatarData.length > 0); OWSAssertDebug(encryptedAvatarData.length > 0);
[[SNFileServerAPI uploadProfilePicture:encryptedAvatarData] AnyPromise *promise;
.thenOn(dispatch_get_main_queue(), ^(NSString *downloadURL) { if (SNFileServerAPIV2.useV2FileServer) {
promise = [SNFileServerAPIV2 upload:encryptedAvatarData];
} else {
promise = [SNFileServerAPI uploadProfilePicture:encryptedAvatarData];
}
[promise.thenOn(dispatch_get_main_queue(), ^(NSString *downloadURL) {
[self.localUserProfile updateWithProfileKey:newProfileKey dbConnection:self.dbConnection completion:^{ [self.localUserProfile updateWithProfileKey:newProfileKey dbConnection:self.dbConnection completion:^{
successBlock(downloadURL); successBlock(downloadURL);
}]; }];
@ -801,7 +807,16 @@ typedef void (^ProfileManagerFailureBlock)(NSError *error);
OWSLogVerbose(@"downloading profile avatar: %@", userProfile.uniqueId); OWSLogVerbose(@"downloading profile avatar: %@", userProfile.uniqueId);
NSString *profilePictureURL = userProfile.avatarUrlPath; NSString *profilePictureURL = userProfile.avatarUrlPath;
[[SNFileServerAPI downloadAttachmentFrom:profilePictureURL].then(^(NSData *data) {
AnyPromise *promise;
if ([profilePictureURL containsString:SNFileServerAPIV2.server]) {
uint64_t *file = (uint64_t)[[profilePictureURL lastPathComponent] intValue];
promise = [SNFileServerAPIV2 download:file];
} else {
promise = [SNFileServerAPI downloadAttachmentFrom:profilePictureURL];
}
[promise.then(^(NSData *data) {
@synchronized(self.currentAvatarDownloads) @synchronized(self.currentAvatarDownloads)
{ {
[self.currentAvatarDownloads removeObject:userProfile.recipientId]; [self.currentAvatarDownloads removeObject:userProfile.recipientId];

Loading…
Cancel
Save