use onion routing for individual avatar downloads

This commit is contained in:
Ryan ZHAO 2020-10-08 16:20:42 +11:00
parent 43724d6578
commit e262013147
2 changed files with 31 additions and 43 deletions

View File

@ -1157,43 +1157,14 @@ typedef void (^ProfileManagerFailureBlock)(NSError *error);
OWSLogVerbose(@"downloading profile avatar: %@", userProfile.uniqueId);
NSString *tempDirectory = OWSTemporaryDirectory();
NSString *tempFilePath = [tempDirectory stringByAppendingPathComponent:fileName];
NSString *profilePictureURL = userProfile.avatarUrlPath;
NSError *serializationError;
NSMutableURLRequest *request =
[self.avatarHTTPManager.requestSerializer requestWithMethod:@"GET"
URLString:profilePictureURL
parameters:nil
error:&serializationError];
if (serializationError) {
OWSFailDebug(@"serializationError: %@", serializationError);
return;
}
NSURLSession* session = [NSURLSession sharedSession];
NSURLSessionTask* downloadTask = [session downloadTaskWithRequest:request completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
AnyPromise *promise = [LKFileServerAPI downloadProfilePicture:profilePictureURL];
[promise.then(^(NSData *data) {
@synchronized(self.currentAvatarDownloads)
{
[self.currentAvatarDownloads removeObject:userProfile.recipientId];
}
if (error) {
OWSLogError(@"Dowload failed: %@", error);
return;
}
NSFileManager *fileManager = [NSFileManager defaultManager];
NSURL *tempFileUrl = [NSURL fileURLWithPath:tempFilePath];
NSError *moveError;
if (![fileManager moveItemAtURL:location toURL:tempFileUrl error:&moveError]) {
OWSLogError(@"MoveItemAtURL for avatar failed: %@", moveError);
return;
}
NSData *_Nullable encryptedData = (error ? nil : [NSData dataWithContentsOfFile:tempFilePath]);
NSData *_Nullable encryptedData = data;
NSData *_Nullable decryptedData = [self decryptProfileData:encryptedData profileKey:profileKeyAtStart];
UIImage *_Nullable image = nil;
if (decryptedData) {
@ -1213,19 +1184,12 @@ typedef void (^ProfileManagerFailureBlock)(NSError *error);
if (latestUserProfile.avatarUrlPath.length > 0) {
[self downloadAvatarForUserProfile:latestUserProfile];
}
} else if (error) {
if ([response isKindOfClass:NSHTTPURLResponse.class]
&& ((NSHTTPURLResponse *)response).statusCode == 403) {
OWSLogInfo(@"no avatar for: %@", userProfile.recipientId);
} else {
OWSLogError(@"avatar download for %@ failed with error: %@", userProfile.recipientId, error);
}
} else if (!encryptedData) {
OWSLogError(@"avatar encrypted data for %@ could not be read.", userProfile.recipientId);
} else if (!decryptedData) {
OWSLogError(@"avatar data for %@ could not be decrypted.", userProfile.recipientId);
} else if (!image) {
OWSLogError(@"avatar image for %@ could not be loaded with error: %@", userProfile.recipientId, error);
OWSLogError(@"avatar image for %@ could not be loaded.", userProfile.recipientId);
} else {
[self updateProfileAvatarCache:image filename:fileName];
@ -1248,9 +1212,7 @@ typedef void (^ProfileManagerFailureBlock)(NSError *error);
OWSAssertDebug(backgroundTask);
backgroundTask = nil;
}];
[downloadTask resume];
}) retainUntilComplete];
});
}

View File

@ -18,6 +18,7 @@ public final class FileServerAPI : DotNetAPI {
public static let fileSizeORMultiplier: Double = 6
@objc public static let server = "https://file.getsession.org"
@objc public static let fileStaticServer = "https://file-static.lokinet.org"
// MARK: Storage
override internal class var authTokenCollection: String { return "LokiStorageAuthTokenCollection" }
@ -52,6 +53,31 @@ public final class FileServerAPI : DotNetAPI {
}
}
@objc(downloadProfilePicture:)
public static func objc_downloadProfilePicture(_ downloadURL: String) -> AnyPromise {
return AnyPromise.from(downloadProfilePicture(downloadURL))
}
public static func downloadProfilePicture(_ downloadURL: String) -> Promise<Data> {
var error: NSError?
var url = downloadURL
if downloadURL.contains(fileStaticServer) {
url = downloadURL.replacingOccurrences(of: fileStaticServer, with: "\(server)/loki/v1")
}
let request = AFHTTPRequestSerializer().request(withMethod: "GET", urlString: url, parameters: nil, error: &error)
if let error = error {
print("[Loki] Couldn't download profile picture due to error: \(error).")
return Promise(error: error)
}
return OnionRequestAPI.sendOnionRequest(request, to: server, using: fileServerPublicKey, isJSONRequired: false).map2 { json in
guard let body = json["body"] as? JSON, let dataArray = body["data"] as? [UInt8] else {
print("[Loki] Couldn't download profile picture.")
return Data()
}
return Data(dataArray)
}
}
// MARK: Open Group Server Public Key
public static func getPublicKey(for openGroupServer: String) -> Promise<String> {
let url = URL(string: "\(server)/loki/v1/getOpenGroupKey/\(URL(string: openGroupServer)!.host!)")!