12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235 |
- //
- // CCNetworking.m
- // Nextcloud iOS
- //
- // Created by Marino Faggiana on 01/06/15.
- // Copyright (c) 2017 Marino Faggiana. All rights reserved.
- //
- // Author Marino Faggiana <marino.faggiana@nextcloud.com>
- //
- // This program is free software: you can redistribute it and/or modify
- // it under the terms of the GNU General Public License as published by
- // the Free Software Foundation, either version 3 of the License, or
- // (at your option) any later version.
- //
- // This program is distributed in the hope that it will be useful,
- // but WITHOUT ANY WARRANTY; without even the implied warranty of
- // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- // GNU General Public License for more details.
- //
- // You should have received a copy of the GNU General Public License
- // along with this program. If not, see <http://www.gnu.org/licenses/>.
- //
- #import "CCNetworking.h"
- #import "NCEndToEndEncryption.h"
- #import "NCNetworkingEndToEnd.h"
- #import "AppDelegate.h"
- #import "CCCertificate.h"
- #import "NSDate+ISO8601.h"
- #import "NSString+Encode.h"
- #import "NCBridgeSwift.h"
- @interface CCNetworking ()
- {
-
- }
- @end
- @implementation CCNetworking
- + (CCNetworking *)sharedNetworking {
- static CCNetworking *sharedNetworking;
- @synchronized(self)
- {
- if (!sharedNetworking) {
- sharedNetworking = [[CCNetworking alloc] init];
- }
- return sharedNetworking;
- }
- }
- - (id)init
- {
- self = [super init];
-
- // Initialization Sessions
- [self sessionDownload];
- [self sessionDownloadForeground];
- [self sessionWWanDownload];
- [self sessionUpload];
- [self sessionWWanUpload];
- [self sessionUploadForeground];
-
- // *** NOT Initialize ONLY for EXTENSION !!!!! ***
- // [self sessionUploadExtension];
-
- return self;
- }
- #pragma --------------------------------------------------------------------------------------------
- #pragma mark ===== Session =====
- #pragma --------------------------------------------------------------------------------------------
- - (NSURLSession *)sessionDownload
- {
- static NSURLSession *sessionDownload = nil;
-
- if (sessionDownload == nil) {
-
- NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:k_download_session];
-
- configuration.allowsCellularAccess = YES;
- configuration.sessionSendsLaunchEvents = YES;
- configuration.discretionary = NO;
- configuration.HTTPMaximumConnectionsPerHost = k_maxHTTPConnectionsPerHost;
- configuration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
-
- sessionDownload = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
- sessionDownload.sessionDescription = k_download_session;
- }
- return sessionDownload;
- }
- - (NSURLSession *)sessionDownloadForeground
- {
- static NSURLSession *sessionDownloadForeground = nil;
-
- if (sessionDownloadForeground == nil) {
-
- NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
-
- configuration.allowsCellularAccess = YES;
- configuration.discretionary = NO;
- configuration.HTTPMaximumConnectionsPerHost = k_maxHTTPConnectionsPerHost;
- configuration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
-
- sessionDownloadForeground = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
- sessionDownloadForeground.sessionDescription = k_download_session_foreground;
- }
- return sessionDownloadForeground;
- }
- - (NSURLSession *)sessionWWanDownload
- {
- static NSURLSession *sessionWWanDownload = nil;
-
- if (sessionWWanDownload == nil) {
-
- NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:k_download_session_wwan];
-
- configuration.allowsCellularAccess = NO;
- configuration.sessionSendsLaunchEvents = YES;
- configuration.discretionary = NO;
- configuration.HTTPMaximumConnectionsPerHost = k_maxHTTPConnectionsPerHost;
- configuration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
-
- sessionWWanDownload = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
- sessionWWanDownload.sessionDescription = k_download_session_wwan;
- }
- return sessionWWanDownload;
- }
- - (NSURLSession *)sessionUpload
- {
- static NSURLSession *sessionUpload = nil;
-
- if (sessionUpload == nil) {
-
- NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:k_upload_session];
-
- configuration.allowsCellularAccess = YES;
- configuration.sessionSendsLaunchEvents = YES;
- configuration.discretionary = NO;
- configuration.HTTPMaximumConnectionsPerHost = k_maxHTTPConnectionsPerHost;
- configuration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
- sessionUpload = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
- sessionUpload.sessionDescription = k_upload_session;
- }
- return sessionUpload;
- }
- - (NSURLSession *)sessionWWanUpload
- {
- static NSURLSession *sessionWWanUpload = nil;
-
- if (sessionWWanUpload == nil) {
-
- NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:k_upload_session_wwan];
-
- configuration.allowsCellularAccess = NO;
- configuration.sessionSendsLaunchEvents = YES;
- configuration.discretionary = NO;
- configuration.HTTPMaximumConnectionsPerHost = k_maxHTTPConnectionsPerHost;
- configuration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
-
- sessionWWanUpload = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
- sessionWWanUpload.sessionDescription = k_upload_session_wwan;
- }
- return sessionWWanUpload;
- }
- - (NSURLSession *)sessionUploadForeground
- {
- static NSURLSession *sessionUploadForeground;
-
- if (sessionUploadForeground == nil) {
-
- NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
-
- configuration.allowsCellularAccess = YES;
- configuration.discretionary = NO;
- configuration.HTTPMaximumConnectionsPerHost = k_maxHTTPConnectionsPerHost;
- configuration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
-
- sessionUploadForeground = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
- sessionUploadForeground.sessionDescription = k_upload_session_foreground;
- }
- return sessionUploadForeground;
- }
- - (NSURLSession *)sessionUploadExtension
- {
- static NSURLSession *sessionUpload = nil;
-
- if (sessionUpload == nil) {
-
- NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:k_upload_session_extension];
-
- configuration.allowsCellularAccess = YES;
- configuration.sessionSendsLaunchEvents = YES;
- configuration.discretionary = NO;
- configuration.HTTPMaximumConnectionsPerHost = 1;
- configuration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
- configuration.sharedContainerIdentifier = [NCBrandOptions sharedInstance].capabilitiesGroups;
-
- sessionUpload = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
- sessionUpload.sessionDescription = k_upload_session_extension;
- }
- return sessionUpload;
- }
- - (NSURLSession *)getSessionfromSessionDescription:(NSString *)sessionDescription
- {
- if ([sessionDescription isEqualToString:k_download_session]) return [self sessionDownload];
- if ([sessionDescription isEqualToString:k_download_session_foreground]) return [self sessionDownloadForeground];
- if ([sessionDescription isEqualToString:k_download_session_wwan]) return [self sessionWWanDownload];
- if ([sessionDescription isEqualToString:k_upload_session]) return [self sessionUpload];
- if ([sessionDescription isEqualToString:k_upload_session_wwan]) return [self sessionWWanUpload];
- if ([sessionDescription isEqualToString:k_upload_session_foreground]) return [self sessionUploadForeground];
-
- if ([sessionDescription isEqualToString:k_upload_session_extension]) return [self sessionUploadExtension];
- return nil;
- }
- - (void)invalidateAndCancelAllSession
- {
- [[self sessionDownload] invalidateAndCancel];
- [[self sessionDownloadForeground] invalidateAndCancel];
- [[self sessionWWanDownload] invalidateAndCancel];
-
- [[self sessionUpload] invalidateAndCancel];
- [[self sessionWWanUpload] invalidateAndCancel];
- [[self sessionUploadForeground] invalidateAndCancel];
- }
- - (NSArray *)getUploadTasksExtensionSession
- {
- __block NSArray *tasks = [NSArray new];
- [[self sessionUploadExtension] getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
- tasks = uploadTasks;
- }];
-
- return tasks;
- }
- #pragma --------------------------------------------------------------------------------------------
- #pragma mark ===== URLSession download/upload =====
- #pragma --------------------------------------------------------------------------------------------
- - (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler
- {
- // The pinnning check
-
- if ([[CCCertificate sharedManager] checkTrustedChallenge:challenge]) {
- completionHandler(NSURLSessionAuthChallengeUseCredential, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]);
- } else {
- completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
- }
- }
- - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
- {
- NSString *url = [[[task currentRequest].URL absoluteString] stringByRemovingPercentEncoding];
-
- if (!url)
- return;
-
- NSString *fileName = [url lastPathComponent];
- NSString *serverUrl = [self getServerUrlFromUrl:url];
- if (!serverUrl) return;
-
- NSInteger errorCode;
- NSDate *date = [NSDate date];
- NSDateFormatter *dateFormatter = [NSDateFormatter new];
- NSLocale *enUSPOSIXLocale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
- [dateFormatter setLocale:enUSPOSIXLocale];
- [dateFormatter setDateFormat:@"EEE, dd MMM y HH:mm:ss zzz"];
-
- NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)task.response;
-
- if (httpResponse.statusCode >= 200 && httpResponse.statusCode < 300) {
-
- errorCode = error.code;
-
- } else {
-
- if (httpResponse.statusCode > 0)
- errorCode = httpResponse.statusCode;
- else
- errorCode = error.code;
- }
- // ----------------------- DOWNLOAD -----------------------
-
- if ([task isKindOfClass:[NSURLSessionDownloadTask class]]) {
-
- tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataInSessionFromFileName:fileName serverUrl:serverUrl taskIdentifier:task.taskIdentifier];
- if (metadata) {
-
- NSString *etag = metadata.etag;
- //NSString *fileID = metadata.fileID;
- NSDictionary *fields = [httpResponse allHeaderFields];
-
- if (errorCode == 0) {
-
- etag = [CCUtility removeForbiddenCharactersFileSystem:[fields objectForKey:@"OC-ETag"]];
-
- NSString *dateString = [fields objectForKey:@"Date"];
- if (dateString) {
- if (![dateFormatter getObjectValue:&date forString:dateString range:nil error:&error]) {
- date = [NSDate date];
- }
- } else {
- date = [NSDate date];
- }
- }
-
- if (fileName.length > 0 && serverUrl.length > 0) {
- dispatch_async(dispatch_get_main_queue(), ^{
- [self downloadFileSuccessFailure:fileName fileID:metadata.fileID etag:etag date:date serverUrl:serverUrl selector:metadata.sessionSelector errorCode:errorCode];
- });
- }
-
- } else {
-
- NSLog(@"[LOG] Remove record ? : metadata not found %@", url);
- dispatch_async(dispatch_get_main_queue(), ^{
-
- if ([self.delegate respondsToSelector:@selector(downloadFileSuccessFailure:fileID:serverUrl:selector:errorMessage:errorCode:)]) {
- [self.delegate downloadFileSuccessFailure:fileName fileID:@"" serverUrl:serverUrl selector:@"" errorMessage:@"" errorCode:k_CCErrorInternalError];
- }
- });
- }
- }
-
- // ------------------------ UPLOAD -----------------------
-
- if ([task isKindOfClass:[NSURLSessionUploadTask class]]) {
-
- tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataInSessionFromFileName:fileName serverUrl:serverUrl taskIdentifier:task.taskIdentifier];
- if (metadata) {
-
- NSDictionary *fields = [httpResponse allHeaderFields];
- NSString *fileID = metadata.fileID;
- NSString *etag = metadata.etag;
-
- if (errorCode == 0) {
-
- fileID = [CCUtility removeForbiddenCharactersFileSystem:[fields objectForKey:@"OC-FileId"]];
- etag = [CCUtility removeForbiddenCharactersFileSystem:[fields objectForKey:@"OC-ETag"]];
-
- NSString *dateString = [fields objectForKey:@"Date"];
- if (dateString) {
- if (![dateFormatter getObjectValue:&date forString:dateString range:nil error:&error]) {
- NSLog(@"[LOG] Date '%@' could not be parsed: %@", dateString, error);
- date = [NSDate date];
- }
- } else {
- date = [NSDate date];
- }
- }
-
- if (fileName.length > 0 && fileID.length > 0 && serverUrl.length > 0) {
- dispatch_async(dispatch_get_main_queue(), ^{
- [self uploadFileSuccessFailure:metadata fileName:fileName fileID:fileID etag:etag date:date serverUrl:serverUrl errorCode:errorCode];
- });
- }
-
- } else {
- NSLog(@"[LOG] Remove record ? : metadata not found %@", url);
- dispatch_async(dispatch_get_main_queue(), ^{
- if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:fileID:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
- [self.delegate uploadFileSuccessFailure:fileName fileID:@"" assetLocalIdentifier:@"" serverUrl:serverUrl selector:@"" errorMessage:@"" errorCode:k_CCErrorInternalError];
- }
- });
- }
- }
- }
- #pragma --------------------------------------------------------------------------------------------
- #pragma mark ===== Download =====
- #pragma --------------------------------------------------------------------------------------------
- - (void)downloadFile:(tableMetadata *)metadata taskStatus:(NSInteger)taskStatus
- {
- // No Password
- if ([CCUtility getPassword:metadata.account].length == 0) {
- [self.delegate downloadFileSuccessFailure:metadata.fileName fileID:metadata.fileID serverUrl:metadata.serverUrl selector:metadata.sessionSelector errorMessage:NSLocalizedString(@"_bad_username_password_", nil) errorCode:kOCErrorServerUnauthorized];
- return;
- } else if ([CCUtility getCertificateError:metadata.account]) {
- [self.delegate downloadFileSuccessFailure:metadata.fileName fileID:metadata.fileID serverUrl:metadata.serverUrl selector:metadata.sessionSelector errorMessage:NSLocalizedString(@"_ssl_certificate_untrusted_", nil) errorCode:NSURLErrorServerCertificateUntrusted];
- return;
- }
-
- // File exists ?
- tableLocalFile *localfile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID]];
-
- if (localfile != nil && [CCUtility fileProviderStorageExists:metadata.fileID fileNameView:metadata.fileNameView]) {
-
- [[NCManageDatabase sharedInstance] setMetadataSession:@"" sessionError:@"" sessionSelector:@"" sessionTaskIdentifier:k_taskIdentifierDone status:k_metadataStatusNormal predicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID]];
-
- if ([self.delegate respondsToSelector:@selector(downloadFileSuccessFailure:fileID:serverUrl:selector:errorMessage:errorCode:)]) {
- [self.delegate downloadFileSuccessFailure:metadata.fileName fileID:metadata.fileID serverUrl:metadata.serverUrl selector:metadata.sessionSelector errorMessage:@"" errorCode:0];
- }
- return;
- }
-
- [self downloaURLSession:metadata taskStatus:taskStatus];
- }
- - (void)downloaURLSession:(tableMetadata *)metadata taskStatus:(NSInteger)taskStatus
- {
- NSURLSession *sessionDownload;
- NSURL *url;
- NSMutableURLRequest *request;
-
- tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", metadata.account]];
- if (tableAccount == nil) {
- [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID]];
- if ([self.delegate respondsToSelector:@selector(downloadFileSuccessFailure:fileID:serverUrl:selector:errorMessage:errorCode:)]) {
- [self.delegate downloadFileSuccessFailure:metadata.fileName fileID:metadata.fileID serverUrl:metadata.serverUrl selector:metadata.sessionSelector errorMessage:@"Download error, account not found" errorCode:k_CCErrorInternalError];
- }
- return;
- }
-
- NSString *serverFileUrl = [[NSString stringWithFormat:@"%@/%@", metadata.serverUrl, metadata.fileName] encodeString:NSUTF8StringEncoding];
-
- url = [NSURL URLWithString:serverFileUrl];
- request = [NSMutableURLRequest requestWithURL:url];
-
- NSData *authData = [[NSString stringWithFormat:@"%@:%@", tableAccount.user, [CCUtility getPassword:tableAccount.account]] dataUsingEncoding:NSUTF8StringEncoding];
- NSString *authValue = [NSString stringWithFormat: @"Basic %@",[authData base64EncodedStringWithOptions:0]];
- [request setValue:authValue forHTTPHeaderField:@"Authorization"];
- [request setValue:[CCUtility getUserAgent] forHTTPHeaderField:@"User-Agent"];
-
- if ([metadata.session isEqualToString:k_download_session]) sessionDownload = [self sessionDownload];
- else if ([metadata.session isEqualToString:k_download_session_foreground]) sessionDownload = [self sessionDownloadForeground];
- else if ([metadata.session isEqualToString:k_download_session_wwan]) sessionDownload = [self sessionWWanDownload];
-
- NSURLSessionDownloadTask *downloadTask = [sessionDownload downloadTaskWithRequest:request];
-
- if (downloadTask == nil) {
-
- [[NCManageDatabase sharedInstance] setMetadataSession:nil sessionError:@"Serious internal error downloadTask not available" sessionSelector:nil sessionTaskIdentifier:k_taskIdentifierDone status:k_metadataStatusDownloadError predicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID]];
-
- if ([self.delegate respondsToSelector:@selector(downloadFileSuccessFailure:fileID:serverUrl:selector:errorMessage:errorCode:)]) {
- [self.delegate downloadFileSuccessFailure:metadata.fileName fileID:metadata.fileID serverUrl:metadata.serverUrl selector:metadata.sessionSelector errorMessage:@"Serious internal error downloadTask not available" errorCode:k_CCErrorInternalError];
- }
-
- } else {
-
- // Manage uploadTask cancel,suspend,resume
- if (taskStatus == k_taskStatusCancel) [downloadTask cancel];
- else if (taskStatus == k_taskStatusSuspend) [downloadTask suspend];
- else if (taskStatus == k_taskStatusResume) [downloadTask resume];
-
- [[NCManageDatabase sharedInstance] setMetadataSession:nil sessionError:nil sessionSelector:nil sessionTaskIdentifier:downloadTask.taskIdentifier status:k_metadataStatusDownloading predicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID]];
-
- NSLog(@"[LOG] downloadFileSession %@ Task [%lu]", metadata.fileID, (unsigned long)downloadTask.taskIdentifier);
-
- dispatch_async(dispatch_get_main_queue(), ^{
- if ([self.delegate respondsToSelector:@selector(downloadStart:account:task:serverUrl:)]) {
- [self.delegate downloadStart:metadata.fileID account:metadata.account task:downloadTask serverUrl:metadata.serverUrl];
- }
- });
- }
- }
- - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
- {
- NSString *url = [[[downloadTask currentRequest].URL absoluteString] stringByRemovingPercentEncoding];
- NSString *fileName = [url lastPathComponent];
- NSString *serverUrl = [self getServerUrlFromUrl:url];
- if (!serverUrl) return;
-
- if (totalBytesExpectedToWrite < 1) {
- totalBytesExpectedToWrite = totalBytesWritten;
- }
-
- float progress = (float) totalBytesWritten / (float)totalBytesExpectedToWrite;
-
- tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataInSessionFromFileName:fileName serverUrl:serverUrl taskIdentifier:downloadTask.taskIdentifier];
- if (metadata) {
- NSDictionary *userInfo = @{@"account": (metadata.account), @"fileID": (metadata.fileID), @"serverUrl": (serverUrl), @"status": ([NSNumber numberWithLong:k_metadataStatusInDownload]), @"progress": ([NSNumber numberWithFloat:progress]), @"totalBytes": ([NSNumber numberWithLongLong:totalBytesWritten]), @"totalBytesExpected": ([NSNumber numberWithLongLong:totalBytesExpectedToWrite])};
- if (userInfo)
- [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"NotificationProgressTask" object:nil userInfo:userInfo];
- } else {
- NSLog(@"[LOG] metadata not found");
- }
- }
- - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
- {
- NSString *url = [[[downloadTask currentRequest].URL absoluteString] stringByRemovingPercentEncoding];
- if (!url)
- return;
- NSString *fileName = [url lastPathComponent];
- NSString *serverUrl = [self getServerUrlFromUrl:url];
- if (!serverUrl) return;
-
- tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataInSessionFromFileName:fileName serverUrl:serverUrl taskIdentifier:downloadTask.taskIdentifier];
- if (!metadata) {
-
- NSLog(@"[LOG] Serious error internal download : metadata not found %@ ", url);
- dispatch_async(dispatch_get_main_queue(), ^{
- if ([self.delegate respondsToSelector:@selector(downloadFileSuccessFailure:fileID:serverUrl:selector:errorMessage:errorCode:)]) {
- [self.delegate downloadFileSuccessFailure:@"" fileID:@"" serverUrl:serverUrl selector:@"" errorMessage:@"Serious error internal download : metadata not found" errorCode:k_CCErrorInternalError];
- }
- });
-
- return;
- }
-
- NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)downloadTask.response;
-
- if (httpResponse.statusCode >= 200 && httpResponse.statusCode < 300) {
-
- NSString *destinationFilePath = [CCUtility getDirectoryProviderStorageFileID:metadata.fileID fileNameView:metadata.fileName];
- NSURL *destinationURL = [NSURL fileURLWithPath:destinationFilePath];
-
- [[NSFileManager defaultManager] removeItemAtURL:destinationURL error:NULL];
- [[NSFileManager defaultManager] copyItemAtURL:location toURL:destinationURL error:nil];
- }
- }
- - (void)downloadFileSuccessFailure:(NSString *)fileName fileID:(NSString *)fileID etag:(NSString *)etag date:(NSDate *)date serverUrl:(NSString *)serverUrl selector:(NSString *)selector errorCode:(NSInteger)errorCode
- {
- #ifndef EXTENSION
- AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
- [appDelegate.listProgressMetadata removeObjectForKey:fileID];
- #endif
-
- tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", fileID]];
-
- if (errorCode != 0) {
-
- if (errorCode == kCFURLErrorCancelled) {
-
- [[NCManageDatabase sharedInstance] setMetadataSession:@"" sessionError:@"" sessionSelector:@"" sessionTaskIdentifier:k_taskIdentifierDone status:k_metadataStatusNormal predicate:[NSPredicate predicateWithFormat:@"fileID == %@", fileID]];
-
- } else {
-
- if (metadata && errorCode == kOCErrorServerUnauthorized)
- [CCUtility setPassword:metadata.account password:nil];
- else if (metadata && errorCode == NSURLErrorServerCertificateUntrusted)
- [CCUtility setCertificateError:metadata.account error:YES];
- [[NCManageDatabase sharedInstance] setMetadataSession:nil sessionError:[CCError manageErrorKCF:errorCode withNumberError:NO] sessionSelector:nil sessionTaskIdentifier:k_taskIdentifierDone status:k_metadataStatusDownloadError predicate:[NSPredicate predicateWithFormat:@"fileID == %@", fileID]];
- }
-
- if ([self.delegate respondsToSelector:@selector(downloadFileSuccessFailure:fileID:serverUrl:selector:errorMessage:errorCode:)]) {
- [self.delegate downloadFileSuccessFailure:fileName fileID:fileID serverUrl:serverUrl selector:selector errorMessage:[CCError manageErrorKCF:errorCode withNumberError:YES] errorCode:errorCode];
- }
-
- } else {
-
- if (!metadata) {
-
- NSLog(@"[LOG] Serious error internal download : metadata not found %@ ", fileName);
-
- if ([self.delegate respondsToSelector:@selector(downloadFileSuccessFailure:fileID:serverUrl:selector:errorMessage:errorCode:)]) {
- [self.delegate downloadFileSuccessFailure:fileName fileID:fileID serverUrl:serverUrl selector:selector errorMessage:[NSString stringWithFormat:@"Serious error internal download : metadata not found %@", fileName] errorCode:k_CCErrorInternalError];
- }
- return;
- }
-
- metadata.session = @"";
- metadata.sessionError = @"";
- metadata.sessionSelector = @"";
- metadata.sessionTaskIdentifier = k_taskIdentifierDone;
- metadata.status = k_metadataStatusNormal;
-
- metadata = [[NCManageDatabase sharedInstance] updateMetadata:metadata];
- [[NCManageDatabase sharedInstance] addLocalFileWithMetadata:metadata];
-
- // E2EE Decrypted
- tableE2eEncryption *object = [[NCManageDatabase sharedInstance] getE2eEncryptionWithPredicate:[NSPredicate predicateWithFormat:@"fileNameIdentifier == %@ AND serverUrl == %@", fileName, serverUrl]];
- if (object) {
- BOOL result = [[NCEndToEndEncryption sharedManager] decryptFileName:metadata.fileName fileNameView:metadata.fileNameView fileID:metadata.fileID key:object.key initializationVector:object.initializationVector authenticationTag:object.authenticationTag];
- if (!result) {
-
- if ([self.delegate respondsToSelector:@selector(downloadFileSuccessFailure:fileID:serverUrl:selector:errorMessage:errorCode:)]) {
- [self.delegate downloadFileSuccessFailure:fileName fileID:fileID serverUrl:serverUrl selector:selector errorMessage:[NSString stringWithFormat:@"Serious error internal download : decrypt error %@", fileName] errorCode:k_CCErrorInternalError];
- }
-
- return;
- }
- }
-
- // Exif
- if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image])
- [[CCExifGeo sharedInstance] setExifLocalTableEtag:metadata];
-
- // Icon
- if ([[NSFileManager defaultManager] fileExistsAtPath:[CCUtility getDirectoryProviderStorageIconFileID:metadata.fileID fileNameView:metadata.fileNameView]] == NO) {
- [CCGraphics createNewImageFrom:metadata.fileNameView fileID:metadata.fileID extension:[metadata.fileNameView pathExtension] filterGrayScale:NO typeFile:metadata.typeFile writeImage:YES];
- }
-
- if ([self.delegate respondsToSelector:@selector(downloadFileSuccessFailure:fileID:serverUrl:selector:errorMessage:errorCode:)]) {
- [self.delegate downloadFileSuccessFailure:fileName fileID:fileID serverUrl:serverUrl selector:selector errorMessage:@"" errorCode:0];
- }
- }
- }
- #pragma --------------------------------------------------------------------------------------------
- #pragma mark ===== Upload =====
- #pragma --------------------------------------------------------------------------------------------
- - (void)uploadFile:(tableMetadata *)metadata taskStatus:(NSInteger)taskStatus
- {
- // Password nil
- if ([CCUtility getPassword:metadata.account].length == 0) {
- [self.delegate uploadFileSuccessFailure:metadata.fileName fileID:metadata.fileID assetLocalIdentifier:metadata.assetLocalIdentifier serverUrl:metadata.serverUrl selector:metadata.sessionSelector errorMessage:NSLocalizedString(@"_bad_username_password_", nil) errorCode:kOCErrorServerUnauthorized];
- return;
- } else if ([CCUtility getCertificateError:metadata.account]) {
- [self.delegate uploadFileSuccessFailure:metadata.fileName fileID:metadata.fileID assetLocalIdentifier:metadata.assetLocalIdentifier serverUrl:metadata.serverUrl selector:metadata.sessionSelector errorMessage:NSLocalizedString(@"_ssl_certificate_untrusted_", nil) errorCode:NSURLErrorServerCertificateUntrusted];
- return;
- }
-
- tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", metadata.account]];
- if (tableAccount == nil) {
- [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID]];
-
- if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:fileID:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
- [self.delegate uploadFileSuccessFailure:metadata.fileName fileID:metadata.fileID assetLocalIdentifier:metadata.assetLocalIdentifier serverUrl:metadata.serverUrl selector:metadata.sessionSelector errorMessage:@"Upload error, account not found" errorCode:k_CCErrorInternalError];
- }
- return;
- }
-
- if ([CCUtility fileProviderStorageExists:metadata.fileID fileNameView:metadata.fileNameView] == NO) {
-
- PHFetchResult *result = [PHAsset fetchAssetsWithLocalIdentifiers:@[metadata.assetLocalIdentifier] options:nil];
-
- if (!result.count) {
- [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID]];
-
- if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:fileID:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
- [self.delegate uploadFileSuccessFailure:metadata.fileName fileID:metadata.fileID assetLocalIdentifier:metadata.assetLocalIdentifier serverUrl:metadata.serverUrl selector:metadata.sessionSelector errorMessage:@"Error photo/video not found, remove from upload" errorCode:k_CCErrorInternalError];
- }
-
- return;
- }
-
- PHAsset *asset= result[0];
-
- // IMAGE
- if (asset.mediaType == PHAssetMediaTypeImage) {
-
- PHImageRequestOptions *options = [PHImageRequestOptions new];
- options.networkAccessAllowed = YES; // iCloud
- options.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
- options.synchronous = YES;
- options.progressHandler = ^(double progress, NSError *error, BOOL *stop, NSDictionary *info) {
-
- NSLog(@"cacheAsset: %f", progress);
-
- if (error) {
- [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID]];
-
- if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:fileID:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
- [self.delegate uploadFileSuccessFailure:metadata.fileName fileID:metadata.fileID assetLocalIdentifier:metadata.assetLocalIdentifier serverUrl:metadata.serverUrl selector:metadata.sessionSelector errorMessage:[NSString stringWithFormat:@"Image request iCloud failed [%@]", error.description] errorCode:error.code];
- }
- }
- };
-
- [[PHImageManager defaultManager] requestImageDataForAsset:asset options:options resultHandler:^(NSData *imageData, NSString *dataUTI, UIImageOrientation orientation, NSDictionary *info) {
-
- NSError *error = nil;
- NSString *extensionAsset = [[[asset valueForKey:@"filename"] pathExtension] uppercaseString];
-
- if ([extensionAsset isEqualToString:@"HEIC"] && [CCUtility getFormatCompatibility]) {
-
- CIImage *ciImage = [CIImage imageWithData:imageData];
- CIContext *context = [CIContext context];
- imageData = [context JPEGRepresentationOfImage:ciImage colorSpace:ciImage.colorSpace options:@{}];
- NSString *fileNameJPEG = [[metadata.fileName lastPathComponent] stringByDeletingPathExtension];
- metadata.fileName = [fileNameJPEG stringByAppendingString:@".jpg"];
- metadata.fileNameView = metadata.fileName;
-
- // Change Metadata with new fileID, fileName, fileNameView
- [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID]];
- metadata.fileID = [CCUtility createMetadataIDFromAccount:metadata.account serverUrl:metadata.serverUrl fileNameView:metadata.fileNameView directory:false];
- }
-
- tableMetadata *metadataForUpload = [[NCManageDatabase sharedInstance] addMetadata:[CCUtility insertFileSystemInMetadata:metadata]];
- [imageData writeToFile:[CCUtility getDirectoryProviderStorageFileID:metadataForUpload.fileID fileNameView:metadataForUpload.fileNameView] options:NSDataWritingAtomic error:&error];
- if (error) {
- [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadataForUpload.fileID]];
-
- if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:fileID:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
- [self.delegate uploadFileSuccessFailure:metadataForUpload.fileName fileID:metadataForUpload.fileID assetLocalIdentifier:metadataForUpload.assetLocalIdentifier serverUrl:metadataForUpload.serverUrl selector:metadataForUpload.sessionSelector errorMessage:[NSString stringWithFormat:@"Image request failed [%@]", error.description] errorCode:error.code];
- }
-
- } else {
-
- // OOOOOK
- if ([CCUtility isFolderEncrypted:metadataForUpload.serverUrl account:tableAccount.account] && [CCUtility isEndToEndEnabled:tableAccount.account]) {
- [self e2eEncryptedFile:metadataForUpload tableAccount:tableAccount taskStatus:taskStatus];
- } else {
- [self uploadURLSessionMetadata:metadataForUpload tableAccount:tableAccount taskStatus:taskStatus];
- }
- }
- }];
- }
-
- // VIDEO
- if (asset.mediaType == PHAssetMediaTypeVideo) {
-
- PHVideoRequestOptions *options = [PHVideoRequestOptions new];
- options.networkAccessAllowed = YES;
- options.version = PHVideoRequestOptionsVersionOriginal;
- options.progressHandler = ^(double progress, NSError *error, BOOL *stop, NSDictionary *info) {
-
- NSLog(@"cacheAsset: %f", progress);
-
- if (error) {
- [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID]];
-
- if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:fileID:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
- [self.delegate uploadFileSuccessFailure:metadata.fileName fileID:metadata.fileID assetLocalIdentifier:metadata.assetLocalIdentifier serverUrl:metadata.serverUrl selector:metadata.sessionSelector errorMessage:[NSString stringWithFormat:@"Video request iCloud failed [%@]", error.description] errorCode:error.code];
- }
- }
- };
-
- [[PHImageManager defaultManager] requestAVAssetForVideo:asset options:options resultHandler:^(AVAsset *asset, AVAudioMix *audioMix, NSDictionary *info) {
-
- if ([asset isKindOfClass:[AVURLAsset class]]) {
-
- NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:[CCUtility getDirectoryProviderStorageFileID:metadata.fileID fileNameView:metadata.fileNameView]];
- NSError *error = nil;
-
- [[NSFileManager defaultManager] removeItemAtURL:fileURL error:nil];
- [[NSFileManager defaultManager] copyItemAtURL:[(AVURLAsset *)asset URL] toURL:fileURL error:&error];
-
- if (error) {
- dispatch_async(dispatch_get_main_queue(), ^{
- [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID]];
-
- if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:fileID:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
- [self.delegate uploadFileSuccessFailure:metadata.fileName fileID:metadata.fileID assetLocalIdentifier:metadata.assetLocalIdentifier serverUrl:metadata.serverUrl selector:metadata.sessionSelector errorMessage:[NSString stringWithFormat:@"Video request failed [%@]", error.description] errorCode:error.code];
- }
- });
- } else {
- dispatch_async(dispatch_get_main_queue(), ^{
-
- // create Metadata for Upload
- tableMetadata *metadataForUpload = [[NCManageDatabase sharedInstance] addMetadata:[CCUtility insertFileSystemInMetadata:metadata]];
-
- // OOOOOK
- if ([CCUtility isFolderEncrypted:metadataForUpload.serverUrl account:tableAccount.account] && [CCUtility isEndToEndEnabled:tableAccount.account]) {
- [self e2eEncryptedFile:metadataForUpload tableAccount:tableAccount taskStatus:taskStatus];
- } else {
- [self uploadURLSessionMetadata:metadataForUpload tableAccount:tableAccount taskStatus:taskStatus];
- }
- });
- }
- }
- }];
- }
-
- } else {
-
- // create Metadata for Upload
- tableMetadata *metadataForUpload = [[NCManageDatabase sharedInstance] addMetadata:[CCUtility insertFileSystemInMetadata:metadata]];
-
- // OOOOOK
- if ([CCUtility isFolderEncrypted:metadataForUpload.serverUrl account:tableAccount.account] && [CCUtility isEndToEndEnabled:tableAccount.account]) {
- [self e2eEncryptedFile:metadataForUpload tableAccount:tableAccount taskStatus:taskStatus];
- } else {
- [self uploadURLSessionMetadata:metadataForUpload tableAccount:tableAccount taskStatus:taskStatus];
- }
- }
- }
- - (void)e2eEncryptedFile:(tableMetadata *)metadata tableAccount:(tableAccount *)tableAccount taskStatus:(NSInteger)taskStatus
- {
- dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
-
- NSError *error;
- NSString *fileNameIdentifier;
- NSString *key;
- NSString *initializationVector;
- NSString *authenticationTag;
- NSString *metadataKey;
- NSInteger metadataKeyIndex;
- NSString *e2eeMetadata;
- // Verify File Size
- NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:[CCUtility getDirectoryProviderStorageFileID:metadata.fileID fileNameView:metadata.fileNameView] error:&error];
- NSNumber *fileSizeNumber = [fileAttributes objectForKey:NSFileSize];
- long long fileSize = [fileSizeNumber longLongValue];
- if (fileSize > k_max_filesize_E2EE) {
- // Error for uploadFileFailure
- if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:fileID:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
- [self.delegate uploadFileSuccessFailure:metadata.fileName fileID:metadata.fileID assetLocalIdentifier:metadata.assetLocalIdentifier serverUrl:metadata.serverUrl selector:metadata.sessionSelector errorMessage:@"E2E Error file too big" errorCode:k_CCErrorInternalError];
- }
- return;
- }
-
- // if new file upload create a new encrypted filename
- if ([metadata.fileID isEqualToString:[CCUtility createMetadataIDFromAccount:metadata.account serverUrl:metadata.serverUrl fileNameView:metadata.fileNameView directory:false]]) {
- fileNameIdentifier = [CCUtility generateRandomIdentifier];
- } else {
- fileNameIdentifier = metadata.fileName;
- }
-
- if ([[NCEndToEndEncryption sharedManager] encryptFileName:metadata.fileNameView fileNameIdentifier:fileNameIdentifier directory:[CCUtility getDirectoryProviderStorageFileID:metadata.fileID] key:&key initializationVector:&initializationVector authenticationTag:&authenticationTag]) {
-
- tableE2eEncryption *object = [[NCManageDatabase sharedInstance] getE2eEncryptionWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", tableAccount.account, metadata.serverUrl]];
- if (object) {
- metadataKey = object.metadataKey;
- metadataKeyIndex = object.metadataKeyIndex;
- } else {
- metadataKey = [[[NCEndToEndEncryption sharedManager] generateKey:16] base64EncodedStringWithOptions:0]; // AES_KEY_128_LENGTH
- metadataKeyIndex = 0;
- }
-
- tableE2eEncryption *addObject = [tableE2eEncryption new];
-
- addObject.account = tableAccount.account;
- addObject.authenticationTag = authenticationTag;
- addObject.fileName = metadata.fileNameView;
- addObject.fileNameIdentifier = fileNameIdentifier;
- addObject.fileNamePath = [CCUtility returnFileNamePathFromFileName:metadata.fileNameView serverUrl:metadata.serverUrl activeUrl:tableAccount.url];
- addObject.key = key;
- addObject.initializationVector = initializationVector;
- addObject.metadataKey = metadataKey;
- addObject.metadataKeyIndex = metadataKeyIndex;
-
- CFStringRef UTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef)[metadata.fileNameView pathExtension], NULL);
- CFStringRef mimeTypeRef = UTTypeCopyPreferredTagWithClass (UTI, kUTTagClassMIMEType);
- if (mimeTypeRef) {
- addObject.mimeType = (__bridge NSString *)mimeTypeRef;
- } else {
- addObject.mimeType = @"application/octet-stream";
- }
-
- addObject.serverUrl = metadata.serverUrl;
- addObject.version = [[NCManageDatabase sharedInstance] getEndToEndEncryptionVersionWithAccount:tableAccount.account];
-
- // Get the last metadata
- tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", tableAccount.account, metadata.serverUrl]];
-
- error = [[NCNetworkingEndToEnd sharedManager] getEndToEndMetadata:&e2eeMetadata fileID:directory.fileID user:tableAccount.user userID:tableAccount.userID password: [CCUtility getPassword:tableAccount.account] url:tableAccount.url];
- if (error == nil) {
- if ([[NCEndToEndMetadata sharedInstance] decoderMetadata:e2eeMetadata privateKey:[CCUtility getEndToEndPrivateKey:tableAccount.account] serverUrl:metadata.serverUrl account:tableAccount.account url:tableAccount.url] == false) {
-
- if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:fileID:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
- [self.delegate uploadFileSuccessFailure:metadata.fileName fileID:metadata.fileID assetLocalIdentifier:metadata.assetLocalIdentifier serverUrl:metadata.serverUrl selector:metadata.sessionSelector errorMessage:NSLocalizedString(@"_e2e_error_decode_metadata_", nil) errorCode:k_CCErrorInternalError];
- }
- return;
- }
- }
-
- // write new record e2ee
- if([[NCManageDatabase sharedInstance] addE2eEncryption:addObject] == NO) {
-
- if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:fileID:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
- [self.delegate uploadFileSuccessFailure:metadata.fileName fileID:metadata.fileID assetLocalIdentifier:metadata.assetLocalIdentifier serverUrl:metadata.serverUrl selector:metadata.sessionSelector errorMessage:NSLocalizedString(@"_e2e_error_create_encrypted_", nil) errorCode:k_CCErrorInternalError];
- }
- return;
- }
-
- } else {
-
- if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:fileID:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
- [self.delegate uploadFileSuccessFailure:metadata.fileName fileID:metadata.fileID assetLocalIdentifier:metadata.assetLocalIdentifier serverUrl:metadata.serverUrl selector:metadata.sessionSelector errorMessage:NSLocalizedString(@"_e2e_error_create_encrypted_", nil) errorCode:k_CCErrorInternalError];
- }
- return;
- }
- dispatch_async(dispatch_get_main_queue(), ^{
-
- // Now the fileName is fileNameIdentifier && flag e2eEncrypted
- metadata.fileName = fileNameIdentifier;
- metadata.e2eEncrypted = YES;
-
- // Update Metadata
- tableMetadata *metadataEncrypted = [[NCManageDatabase sharedInstance] addMetadata:metadata];
-
- [self uploadURLSessionMetadata:metadataEncrypted tableAccount:tableAccount taskStatus:taskStatus];
- });
- });
- }
- - (void)uploadURLSessionMetadata:(tableMetadata *)metadata tableAccount:(tableAccount *)tableAccount taskStatus:(NSInteger)taskStatus
- {
- NSURL *url;
- NSMutableURLRequest *request;
- PHAsset *asset;
- NSError *error;
-
- // calculate and store file size
- NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:[CCUtility getDirectoryProviderStorageFileID:metadata.fileID fileNameView:metadata.fileName] error:&error];
- long long fileSize = [[fileAttributes objectForKey:NSFileSize] longLongValue];
- metadata.size = fileSize;
- (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
-
- url = [NSURL URLWithString:[[NSString stringWithFormat:@"%@/%@", metadata.serverUrl, metadata.fileName] encodeString:NSUTF8StringEncoding]];
- request = [NSMutableURLRequest requestWithURL:url];
-
- NSData *authData = [[NSString stringWithFormat:@"%@:%@", tableAccount.user, [CCUtility getPassword:tableAccount.account]] dataUsingEncoding:NSUTF8StringEncoding];
- NSString *authValue = [NSString stringWithFormat: @"Basic %@",[authData base64EncodedStringWithOptions:0]];
- [request setHTTPMethod:@"PUT"];
- [request setValue:authValue forHTTPHeaderField:@"Authorization"];
- [request setValue:[CCUtility getUserAgent] forHTTPHeaderField:@"User-Agent"];
- // Create Image for Upload (gray scale)
- #ifndef EXTENSION
- [CCGraphics createNewImageFrom:metadata.fileNameView fileID:metadata.fileID extension:[metadata.fileNameView pathExtension] filterGrayScale:YES typeFile:metadata.typeFile writeImage:YES];
- #endif
-
- // Change date file upload with header : X-OC-Mtime (ctime assetLocalIdentifier) image/video
- if (metadata.assetLocalIdentifier) {
- PHFetchResult *result = [PHAsset fetchAssetsWithLocalIdentifiers:@[metadata.assetLocalIdentifier] options:nil];
- if (result.count) {
- asset = result[0];
- long dateFileCreation = [asset.creationDate timeIntervalSince1970];
- [request setValue:[NSString stringWithFormat:@"%ld", dateFileCreation] forHTTPHeaderField:@"X-OC-Mtime"];
- }
- }
-
- NSURLSession *sessionUpload;
-
- // NSURLSession
- if ([metadata.session isEqualToString:k_upload_session]) sessionUpload = [self sessionUpload];
- else if ([metadata.session isEqualToString:k_upload_session_wwan]) sessionUpload = [self sessionWWanUpload];
- else if ([metadata.session isEqualToString:k_upload_session_foreground]) sessionUpload = [self sessionUploadForeground];
- else if ([metadata.session isEqualToString:k_upload_session_extension]) sessionUpload = [self sessionUploadExtension];
- NSURLSessionUploadTask *uploadTask = [sessionUpload uploadTaskWithRequest:request fromFile:[NSURL fileURLWithPath:[CCUtility getDirectoryProviderStorageFileID:metadata.fileID fileNameView:metadata.fileName]]];
-
- // Error
- if (uploadTask == nil) {
-
- NSString *messageError = @"Serious internal error uploadTask not available";
- [[NCManageDatabase sharedInstance] setMetadataSession:metadata.session sessionError:messageError sessionSelector:nil sessionTaskIdentifier:k_taskIdentifierDone status:k_metadataStatusUploadError predicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID]];
-
- if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:fileID:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
- [self.delegate uploadFileSuccessFailure:metadata.fileNameView fileID:metadata.fileID assetLocalIdentifier:metadata.assetLocalIdentifier serverUrl:metadata.serverUrl selector:metadata.sessionSelector errorMessage:messageError errorCode:k_CCErrorInternalError];
- }
-
- } else {
-
- // E2EE : CREATE AND SEND METADATA
- if ([CCUtility isFolderEncrypted:metadata.serverUrl account:tableAccount.account] && [CCUtility isEndToEndEnabled:tableAccount.account]) {
-
- NSString *serverUrl = metadata.serverUrl;
-
- dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
-
- // Send Metadata
- NSError *error = [[NCNetworkingEndToEnd sharedManager] sendEndToEndMetadataOnServerUrl:serverUrl fileNameRename:nil fileNameNewRename:nil account:tableAccount.account user:tableAccount.user userID:tableAccount.userID password:[CCUtility getPassword:tableAccount.account] url:tableAccount.url];
-
- dispatch_async(dispatch_get_main_queue(), ^{
- if (error) {
-
- [uploadTask cancel];
- NSString *messageError = [NSString stringWithFormat:@"%@ (%d)", error.localizedDescription, (int)error.code];
- [[NCManageDatabase sharedInstance] setMetadataSession:metadata.session sessionError:messageError sessionSelector:nil sessionTaskIdentifier:k_taskIdentifierDone status:k_metadataStatusUploadError predicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID]];
-
- if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:fileID:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
- [self.delegate uploadFileSuccessFailure:metadata.fileNameView fileID:metadata.fileID assetLocalIdentifier:metadata.assetLocalIdentifier serverUrl:metadata.serverUrl selector:metadata.sessionSelector errorMessage:messageError errorCode:k_CCErrorInternalError];
- }
-
- } else {
-
- // Manage uploadTask cancel,suspend,resume
- if (taskStatus == k_taskStatusCancel) [uploadTask cancel];
- else if (taskStatus == k_taskStatusSuspend) [uploadTask suspend];
- else if (taskStatus == k_taskStatusResume) [uploadTask resume];
-
- // *** E2EE ***
- [[NCManageDatabase sharedInstance] setMetadataSession:metadata.session sessionError:@"" sessionSelector:nil sessionTaskIdentifier:uploadTask.taskIdentifier status:k_metadataStatusUploading predicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID]];
-
- NSLog(@"[LOG] Upload file %@ TaskIdentifier %lu", metadata.fileName, (unsigned long)uploadTask.taskIdentifier);
-
- NSString *fileID = metadata.fileID;
- NSString *account = metadata.account;
-
- dispatch_async(dispatch_get_main_queue(), ^{
- if ([self.delegate respondsToSelector:@selector(uploadStart:account:task:serverUrl:)]) {
- [self.delegate uploadStart:fileID account:account task:uploadTask serverUrl:metadata.serverUrl];
- }
- });
- }
- });
- });
-
- } else {
-
- // Manage uploadTask cancel,suspend,resume
- if (taskStatus == k_taskStatusCancel) [uploadTask cancel];
- else if (taskStatus == k_taskStatusSuspend) [uploadTask suspend];
- else if (taskStatus == k_taskStatusResume) [uploadTask resume];
-
- // *** PLAIN ***
- [[NCManageDatabase sharedInstance] setMetadataSession:metadata.session sessionError:@"" sessionSelector:nil sessionTaskIdentifier:uploadTask.taskIdentifier status:k_metadataStatusUploading predicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID]];
-
- NSLog(@"[LOG] Upload file %@ TaskIdentifier %lu", metadata.fileName, (unsigned long)uploadTask.taskIdentifier);
-
- NSString *fileID = metadata.fileID;
- NSString *account = metadata.account;
- NSString *serverUrl = metadata.serverUrl;
-
- dispatch_async(dispatch_get_main_queue(), ^{
- if ([self.delegate respondsToSelector:@selector(uploadStart:account:task:serverUrl:)]) {
- [self.delegate uploadStart:fileID account:account task:uploadTask serverUrl:serverUrl];
- }
- });
- }
- }
- }
- - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
- {
- }
- - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend
- {
- NSString *url = [[[task currentRequest].URL absoluteString] stringByRemovingPercentEncoding];
- NSString *fileName = [url lastPathComponent];
- NSString *serverUrl = [self getServerUrlFromUrl:url];
- if (!serverUrl) return;
-
- if (totalBytesExpectedToSend < 1) {
- totalBytesExpectedToSend = totalBytesSent;
- }
-
- float progress = (float) totalBytesSent / (float)totalBytesExpectedToSend;
- tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataInSessionFromFileName:fileName serverUrl:serverUrl taskIdentifier:task.taskIdentifier];
-
- if (metadata) {
- NSDictionary *userInfo = @{@"account": (metadata.account), @"fileID": (metadata.fileID), @"serverUrl": (serverUrl), @"status": ([NSNumber numberWithLong:k_metadataStatusInUpload]), @"progress": ([NSNumber numberWithFloat:progress]), @"totalBytes": ([NSNumber numberWithLongLong:totalBytesSent]), @"totalBytesExpected": ([NSNumber numberWithLongLong:totalBytesExpectedToSend])};
- if (userInfo)
- [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"NotificationProgressTask" object:nil userInfo:userInfo];
- }
- }
- - (void)uploadFileSuccessFailure:(tableMetadata *)metadata fileName:(NSString *)fileName fileID:(NSString *)fileID etag:(NSString *)etag date:(NSDate *)date serverUrl:(NSString *)serverUrl errorCode:(NSInteger)errorCode
- {
- NSString *tempFileID = metadata.fileID;
- NSString *tempSession = metadata.session;
- NSString *errorMessage = @"";
- BOOL isE2EEDirectory = false;
-
- tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", metadata.account]];
- if (tableAccount == nil) {
- [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", tempFileID]];
- if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:fileID:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
- [self.delegate uploadFileSuccessFailure:metadata.fileName fileID:metadata.fileID assetLocalIdentifier:metadata.assetLocalIdentifier serverUrl:serverUrl selector:metadata.sessionSelector errorMessage:errorMessage errorCode:errorCode];
- }
- return;
- }
-
- // is this a E2EE Directory ?
- if ([CCUtility isFolderEncrypted:serverUrl account:tableAccount.account] && [CCUtility isEndToEndEnabled:tableAccount.account]) {
- isE2EEDirectory = true;
- }
-
- // ERRORE
- if (errorCode != 0) {
-
- #ifndef EXTENSION
- AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
- [appDelegate.listProgressMetadata removeObjectForKey:metadata.fileID];
- #endif
-
- // Mark error only if not Cancelled Task
- if (errorCode == kCFURLErrorCancelled) {
-
- if (metadata.status == k_metadataStatusUploadForcedStart) {
-
- errorCode = 0;
-
- metadata.session = k_upload_session;
- metadata.sessionError = @"";
- metadata.sessionTaskIdentifier = 0;
- metadata.status = k_metadataStatusInUpload;
- metadata = [[NCManageDatabase sharedInstance] addMetadata:metadata];
- [[CCNetworking sharedNetworking] uploadFile:metadata taskStatus:k_taskStatusResume];
-
- } else {
-
- [[NSFileManager defaultManager] removeItemAtPath:[CCUtility getDirectoryProviderStorageFileID:tempFileID] error:nil];
- [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", tempFileID]];
-
- errorMessage = [CCError manageErrorKCF:errorCode withNumberError:YES];
- }
-
- } else {
- if (metadata && errorCode == kOCErrorServerUnauthorized)
- [CCUtility setPassword:metadata.account password:nil];
- else if (metadata && errorCode == NSURLErrorServerCertificateUntrusted)
- [CCUtility setCertificateError:metadata.account error:YES];
-
- [[NCManageDatabase sharedInstance] setMetadataSession:nil sessionError:[CCError manageErrorKCF:errorCode withNumberError:NO] sessionSelector:nil sessionTaskIdentifier:k_taskIdentifierDone status:k_metadataStatusUploadError predicate:[NSPredicate predicateWithFormat:@"fileID == %@", tempFileID]];
-
- errorMessage = [CCError manageErrorKCF:errorCode withNumberError:YES];
- }
-
- } else {
-
- // Replace Metadata
- metadata.date = date;
- if (isE2EEDirectory) {
- metadata.e2eEncrypted = true;
- } else {
- metadata.e2eEncrypted = false;
- }
- metadata.etag = etag;
- metadata.fileID = fileID;
- metadata.session = @"";
- metadata.sessionError = @"";
- metadata.sessionTaskIdentifier = k_taskIdentifierDone;
- metadata.status = k_metadataStatusNormal;
-
- [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@ AND fileName == %@", metadata.account, metadata.serverUrl, metadata.fileName]];
- metadata = [[NCManageDatabase sharedInstance] addMetadata:metadata];
-
- NSLog(@"[LOG] Insert new upload : %@ - fileID : %@", metadata.fileName, fileID);
- // remove tempFileID and adjust the directory provider storage
- if ([tempFileID isEqualToString:[CCUtility createMetadataIDFromAccount:metadata.account serverUrl:metadata.serverUrl fileNameView:metadata.fileNameView directory:metadata.directory]]) {
-
- [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", tempFileID]];
-
- // adjust file system Directory Provider Storage
- if ([tempSession isEqualToString:k_upload_session_extension]) {
- // this is for File Provider Extension [Apple Works and ... ?]
- [CCUtility copyFileAtPath:[NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryProviderStorage], tempFileID] toPath:[NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryProviderStorage], metadata.fileID]];
- } else {
- [CCUtility moveFileAtPath:[NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryProviderStorage], tempFileID] toPath:[NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryProviderStorage], metadata.fileID]];
- }
- }
-
- // Add Local
- [[NCManageDatabase sharedInstance] addLocalFileWithMetadata:metadata];
-
- #ifndef EXTENSION
-
- // EXIF
- if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image])
- [[CCExifGeo sharedInstance] setExifLocalTableEtag:metadata];
-
- // Create preview
- [CCGraphics createNewImageFrom:metadata.fileNameView fileID:metadata.fileID extension:[metadata.fileNameView pathExtension] filterGrayScale:NO typeFile:metadata.typeFile writeImage:YES];
- // Copy photo or video in the photo album for auto upload
- if ([metadata.assetLocalIdentifier length] > 0 && ([metadata.sessionSelector isEqualToString:selectorUploadAutoUpload] || [metadata.sessionSelector isEqualToString:selectorUploadFile])) {
-
- PHAsset *asset;
- PHFetchResult *result = [PHAsset fetchAssetsWithLocalIdentifiers:@[metadata.assetLocalIdentifier] options:nil];
-
- if(result.count){
- asset = result[0];
-
- [asset saveToAlbum:[NCBrandOptions sharedInstance].brand completionBlock:^(BOOL success) {
- if (success) NSLog(@"[LOG] Insert file %@ in %@", metadata.fileName, [NCBrandOptions sharedInstance].brand);
- else NSLog(@"[LOG] File %@ do not insert in %@", metadata.fileName, [NCBrandOptions sharedInstance].brand);
- }];
- }
- }
- #endif
- }
-
- // Detect E2EE
- tableMetadata *e2eeMetadataInSession = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@ AND e2eEncrypted == 1 AND (status == %d OR status == %d)", metadata.account, metadata.serverUrl, k_metadataStatusInUpload, k_metadataStatusUploading]];
-
- // E2EE : UNLOCK
- if (isE2EEDirectory && e2eeMetadataInSession == nil) {
-
- tableE2eEncryptionLock *tableLock = [[NCManageDatabase sharedInstance] getE2ETokenLockWithServerUrl:serverUrl];
- dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
-
- if (tableLock) {
-
- NSError *error = [[NCNetworkingEndToEnd sharedManager] unlockEndToEndFolderEncryptedOnServerUrl:serverUrl fileID:tableLock.fileID token:tableLock.token user:tableAccount.user userID:tableAccount.userID password:[CCUtility getPassword:tableAccount.account] url:tableAccount.url];
- if (error) {
- #ifndef EXTENSION
- dispatch_async(dispatch_get_main_queue(), ^{
- [(AppDelegate *)[[UIApplication sharedApplication] delegate] messageNotification:@"_e2e_error_unlock_" description:error.localizedDescription visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
- });
- #endif
- }
- } else {
- NSLog(@"Error unlock not found");
- }
-
- dispatch_async(dispatch_get_main_queue(), ^{
- if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:fileID:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
- [self.delegate uploadFileSuccessFailure:metadata.fileName fileID:metadata.fileID assetLocalIdentifier:metadata.assetLocalIdentifier serverUrl:serverUrl selector:metadata.sessionSelector errorMessage:errorMessage errorCode:errorCode];
- }
- });
- });
- } else {
-
- if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:fileID:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
- [self.delegate uploadFileSuccessFailure:metadata.fileName fileID:metadata.fileID assetLocalIdentifier:metadata.assetLocalIdentifier serverUrl:serverUrl selector:metadata.sessionSelector errorMessage:errorMessage errorCode:errorCode];
- }
- }
- }
- #pragma --------------------------------------------------------------------------------------------
- #pragma mark ===== Utility =====
- #pragma --------------------------------------------------------------------------------------------
- - (NSString *)getServerUrlFromUrl:(NSString *)url
- {
- NSString *fileName = [url lastPathComponent];
-
- url = [url stringByReplacingOccurrencesOfString:[@"/" stringByAppendingString:fileName] withString:@""];
- return url;
- }
- @end
|