CCNetworking.m 69 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254
  1. //
  2. // CCNetworking.m
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 01/06/15.
  6. // Copyright (c) 2017 Marino Faggiana. All rights reserved.
  7. //
  8. // Author Marino Faggiana <marino.faggiana@nextcloud.com>
  9. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. //
  23. #import "CCNetworking.h"
  24. #import "NCEndToEndEncryption.h"
  25. #import "NCNetworkingEndToEnd.h"
  26. #import "AppDelegate.h"
  27. #import "NSDate+ISO8601.h"
  28. #import "NSString+Encode.h"
  29. #import "NCBridgeSwift.h"
  30. @interface CCNetworking ()
  31. {
  32. }
  33. @end
  34. @implementation CCNetworking
  35. + (CCNetworking *)sharedNetworking {
  36. static CCNetworking *sharedNetworking;
  37. @synchronized(self)
  38. {
  39. if (!sharedNetworking) {
  40. sharedNetworking = [[CCNetworking alloc] init];
  41. }
  42. return sharedNetworking;
  43. }
  44. }
  45. - (id)init
  46. {
  47. self = [super init];
  48. // Initialization Sessions
  49. [self sessionDownload];
  50. [self sessionDownloadForeground];
  51. [self sessionWWanDownload];
  52. [self sessionUpload];
  53. [self sessionWWanUpload];
  54. [self sessionUploadForeground];
  55. return self;
  56. }
  57. #pragma --------------------------------------------------------------------------------------------
  58. #pragma mark ===== Session =====
  59. #pragma --------------------------------------------------------------------------------------------
  60. - (NSURLSession *)sessionDownload
  61. {
  62. static NSURLSession *sessionDownload = nil;
  63. if (sessionDownload == nil) {
  64. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:k_download_session];
  65. configuration.allowsCellularAccess = YES;
  66. configuration.sessionSendsLaunchEvents = YES;
  67. configuration.discretionary = NO;
  68. configuration.HTTPMaximumConnectionsPerHost = k_maxHTTPConnectionsPerHost;
  69. configuration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  70. sessionDownload = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
  71. sessionDownload.sessionDescription = k_download_session;
  72. }
  73. return sessionDownload;
  74. }
  75. - (NSURLSession *)sessionDownloadForeground
  76. {
  77. static NSURLSession *sessionDownloadForeground = nil;
  78. if (sessionDownloadForeground == nil) {
  79. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
  80. configuration.allowsCellularAccess = YES;
  81. configuration.discretionary = NO;
  82. configuration.HTTPMaximumConnectionsPerHost = k_maxHTTPConnectionsPerHost;
  83. configuration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  84. sessionDownloadForeground = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
  85. sessionDownloadForeground.sessionDescription = k_download_session_foreground;
  86. }
  87. return sessionDownloadForeground;
  88. }
  89. - (NSURLSession *)sessionWWanDownload
  90. {
  91. static NSURLSession *sessionWWanDownload = nil;
  92. if (sessionWWanDownload == nil) {
  93. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:k_download_session_wwan];
  94. configuration.allowsCellularAccess = NO;
  95. configuration.sessionSendsLaunchEvents = YES;
  96. configuration.discretionary = NO;
  97. configuration.HTTPMaximumConnectionsPerHost = k_maxHTTPConnectionsPerHost;
  98. configuration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  99. sessionWWanDownload = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
  100. sessionWWanDownload.sessionDescription = k_download_session_wwan;
  101. }
  102. return sessionWWanDownload;
  103. }
  104. - (NSURLSession *)sessionUpload
  105. {
  106. static NSURLSession *sessionUpload = nil;
  107. if (sessionUpload == nil) {
  108. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:k_upload_session];
  109. configuration.allowsCellularAccess = YES;
  110. configuration.sessionSendsLaunchEvents = YES;
  111. configuration.discretionary = NO;
  112. configuration.HTTPMaximumConnectionsPerHost = k_maxHTTPConnectionsPerHost;
  113. configuration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  114. sessionUpload = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
  115. sessionUpload.sessionDescription = k_upload_session;
  116. }
  117. return sessionUpload;
  118. }
  119. - (NSURLSession *)sessionWWanUpload
  120. {
  121. static NSURLSession *sessionWWanUpload = nil;
  122. if (sessionWWanUpload == nil) {
  123. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:k_upload_session_wwan];
  124. configuration.allowsCellularAccess = NO;
  125. configuration.sessionSendsLaunchEvents = YES;
  126. configuration.discretionary = NO;
  127. configuration.HTTPMaximumConnectionsPerHost = k_maxHTTPConnectionsPerHost;
  128. configuration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  129. sessionWWanUpload = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
  130. sessionWWanUpload.sessionDescription = k_upload_session_wwan;
  131. }
  132. return sessionWWanUpload;
  133. }
  134. - (NSURLSession *)sessionUploadForeground
  135. {
  136. static NSURLSession *sessionUploadForeground;
  137. if (sessionUploadForeground == nil) {
  138. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
  139. configuration.allowsCellularAccess = YES;
  140. configuration.discretionary = NO;
  141. configuration.HTTPMaximumConnectionsPerHost = k_maxHTTPConnectionsPerHost;
  142. configuration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  143. sessionUploadForeground = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
  144. sessionUploadForeground.sessionDescription = k_upload_session_foreground;
  145. }
  146. return sessionUploadForeground;
  147. }
  148. - (NSURLSession *)sessionUploadExtension
  149. {
  150. static NSURLSession *sessionUpload = nil;
  151. if (sessionUpload == nil) {
  152. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:k_upload_session_extension];
  153. configuration.allowsCellularAccess = YES;
  154. configuration.sessionSendsLaunchEvents = YES;
  155. configuration.discretionary = NO;
  156. configuration.HTTPMaximumConnectionsPerHost = 1;
  157. configuration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  158. configuration.sharedContainerIdentifier = [NCBrandOptions sharedInstance].capabilitiesGroups;
  159. sessionUpload = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
  160. sessionUpload.sessionDescription = k_upload_session_extension;
  161. }
  162. return sessionUpload;
  163. }
  164. - (NSURLSession *)getSessionfromSessionDescription:(NSString *)sessionDescription
  165. {
  166. if ([sessionDescription isEqualToString:k_download_session]) return [self sessionDownload];
  167. if ([sessionDescription isEqualToString:k_download_session_foreground]) return [self sessionDownloadForeground];
  168. if ([sessionDescription isEqualToString:k_download_session_wwan]) return [self sessionWWanDownload];
  169. if ([sessionDescription isEqualToString:k_upload_session]) return [self sessionUpload];
  170. if ([sessionDescription isEqualToString:k_upload_session_wwan]) return [self sessionWWanUpload];
  171. if ([sessionDescription isEqualToString:k_upload_session_foreground]) return [self sessionUploadForeground];
  172. if ([sessionDescription isEqualToString:k_upload_session_extension]) return [self sessionUploadExtension];
  173. return nil;
  174. }
  175. - (void)invalidateAndCancelAllSession
  176. {
  177. [[self sessionDownload] invalidateAndCancel];
  178. [[self sessionDownloadForeground] invalidateAndCancel];
  179. [[self sessionWWanDownload] invalidateAndCancel];
  180. [[self sessionUpload] invalidateAndCancel];
  181. [[self sessionWWanUpload] invalidateAndCancel];
  182. [[self sessionUploadForeground] invalidateAndCancel];
  183. }
  184. #pragma --------------------------------------------------------------------------------------------
  185. #pragma mark ===== URLSession download/upload =====
  186. #pragma --------------------------------------------------------------------------------------------
  187. - (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler
  188. {
  189. // The pinnning check
  190. if ([[NCNetworking sharedInstance] checkTrustedChallengeWithChallenge:challenge directoryCertificate:[CCUtility getDirectoryCerificates]]) {
  191. completionHandler(NSURLSessionAuthChallengeUseCredential, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]);
  192. } else {
  193. completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
  194. }
  195. }
  196. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
  197. {
  198. NSString *url = [[[task currentRequest].URL absoluteString] stringByRemovingPercentEncoding];
  199. if (!url)
  200. return;
  201. NSString *fileName = [url lastPathComponent];
  202. NSString *serverUrl = [self getServerUrlFromUrl:url];
  203. if (!serverUrl) return;
  204. NSInteger errorCode;
  205. NSDate *date = [NSDate date];
  206. NSDateFormatter *dateFormatter = [NSDateFormatter new];
  207. NSLocale *enUSPOSIXLocale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
  208. [dateFormatter setLocale:enUSPOSIXLocale];
  209. [dateFormatter setDateFormat:@"EEE, dd MMM y HH:mm:ss zzz"];
  210. NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)task.response;
  211. if (httpResponse.statusCode >= 200 && httpResponse.statusCode < 300) {
  212. errorCode = error.code;
  213. } else {
  214. if (httpResponse.statusCode > 0)
  215. errorCode = httpResponse.statusCode;
  216. else
  217. errorCode = error.code;
  218. }
  219. // ----------------------- DOWNLOAD -----------------------
  220. if ([task isKindOfClass:[NSURLSessionDownloadTask class]]) {
  221. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataInSessionFromFileName:fileName serverUrl:serverUrl taskIdentifier:task.taskIdentifier];
  222. if (metadata) {
  223. NSString *etag = metadata.etag;
  224. //NSString *ocId = metadata.ocId;
  225. NSDictionary *fields = [httpResponse allHeaderFields];
  226. if (errorCode == 0) {
  227. etag = [CCUtility removeForbiddenCharactersFileSystem:[fields objectForKey:@"OC-ETag"]];
  228. NSString *dateString = [fields objectForKey:@"Date"];
  229. if (dateString) {
  230. if (![dateFormatter getObjectValue:&date forString:dateString range:nil error:&error]) {
  231. date = [NSDate date];
  232. }
  233. } else {
  234. date = [NSDate date];
  235. }
  236. }
  237. if (fileName.length > 0 && serverUrl.length > 0) {
  238. dispatch_async(dispatch_get_main_queue(), ^{
  239. [self downloadFileSuccessFailure:fileName ocId:metadata.ocId etag:etag date:date serverUrl:serverUrl selector:metadata.sessionSelector errorCode:errorCode];
  240. });
  241. }
  242. } else {
  243. NSLog(@"[LOG] Remove record ? : metadata not found %@", url);
  244. dispatch_async(dispatch_get_main_queue(), ^{
  245. if ([self.delegate respondsToSelector:@selector(downloadFileSuccessFailure:ocId:serverUrl:selector:errorMessage:errorCode:)]) {
  246. [self.delegate downloadFileSuccessFailure:fileName ocId:@"" serverUrl:serverUrl selector:@"" errorMessage:@"" errorCode:k_CCErrorInternalError];
  247. }
  248. });
  249. }
  250. }
  251. // ------------------------ UPLOAD -----------------------
  252. if ([task isKindOfClass:[NSURLSessionUploadTask class]]) {
  253. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataInSessionFromFileName:fileName serverUrl:serverUrl taskIdentifier:task.taskIdentifier];
  254. if (metadata) {
  255. NSDictionary *fields = [httpResponse allHeaderFields];
  256. NSString *ocId = metadata.ocId;
  257. NSString *etag = metadata.etag;
  258. if (errorCode == 0) {
  259. ocId = [CCUtility removeForbiddenCharactersFileSystem:[fields objectForKey:@"OC-FileId"]];
  260. etag = [CCUtility removeForbiddenCharactersFileSystem:[fields objectForKey:@"OC-ETag"]];
  261. NSString *dateString = [fields objectForKey:@"Date"];
  262. if (dateString) {
  263. if (![dateFormatter getObjectValue:&date forString:dateString range:nil error:&error]) {
  264. NSLog(@"[LOG] Date '%@' could not be parsed: %@", dateString, error);
  265. date = [NSDate date];
  266. }
  267. } else {
  268. date = [NSDate date];
  269. }
  270. }
  271. if (fileName.length > 0 && ocId.length > 0 && serverUrl.length > 0) {
  272. dispatch_async(dispatch_get_main_queue(), ^{
  273. [self uploadFileSuccessFailure:metadata fileName:fileName ocId:ocId etag:etag date:date serverUrl:serverUrl errorCode:errorCode];
  274. });
  275. }
  276. } else {
  277. NSLog(@"[LOG] Remove record ? : metadata not found %@", url);
  278. dispatch_async(dispatch_get_main_queue(), ^{
  279. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:ocId:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  280. [self.delegate uploadFileSuccessFailure:fileName ocId:@"" assetLocalIdentifier:@"" serverUrl:serverUrl selector:@"" errorMessage:@"" errorCode:k_CCErrorInternalError];
  281. }
  282. });
  283. }
  284. }
  285. }
  286. #pragma --------------------------------------------------------------------------------------------
  287. #pragma mark ===== Download =====
  288. #pragma --------------------------------------------------------------------------------------------
  289. - (void)downloadFile:(tableMetadata *)metadata taskStatus:(NSInteger)taskStatus
  290. {
  291. // No Password
  292. if ([CCUtility getPassword:metadata.account].length == 0) {
  293. [self.delegate downloadFileSuccessFailure:metadata.fileName ocId:metadata.ocId serverUrl:metadata.serverUrl selector:metadata.sessionSelector errorMessage:NSLocalizedString(@"_bad_username_password_", nil) errorCode:kOCErrorServerUnauthorized];
  294. return;
  295. } else if ([CCUtility getCertificateError:metadata.account]) {
  296. [self.delegate downloadFileSuccessFailure:metadata.fileName ocId:metadata.ocId serverUrl:metadata.serverUrl selector:metadata.sessionSelector errorMessage:NSLocalizedString(@"_ssl_certificate_untrusted_", nil) errorCode:NSURLErrorServerCertificateUntrusted];
  297. return;
  298. }
  299. // File exists ?
  300. tableLocalFile *localfile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadata.ocId]];
  301. if (localfile != nil && [CCUtility fileProviderStorageExists:metadata.ocId fileNameView:metadata.fileNameView]) {
  302. [[NCManageDatabase sharedInstance] setMetadataSession:@"" sessionError:@"" sessionSelector:@"" sessionTaskIdentifier:k_taskIdentifierDone status:k_metadataStatusNormal predicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadata.ocId]];
  303. if ([self.delegate respondsToSelector:@selector(downloadFileSuccessFailure:ocId:serverUrl:selector:errorMessage:errorCode:)]) {
  304. [self.delegate downloadFileSuccessFailure:metadata.fileName ocId:metadata.ocId serverUrl:metadata.serverUrl selector:metadata.sessionSelector errorMessage:@"" errorCode:0];
  305. }
  306. return;
  307. }
  308. [self downloaURLSession:metadata taskStatus:taskStatus];
  309. }
  310. - (void)downloaURLSession:(tableMetadata *)metadata taskStatus:(NSInteger)taskStatus
  311. {
  312. NSURLSession *sessionDownload;
  313. NSURL *url;
  314. NSMutableURLRequest *request;
  315. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", metadata.account]];
  316. if (tableAccount == nil) {
  317. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadata.ocId]];
  318. if ([self.delegate respondsToSelector:@selector(downloadFileSuccessFailure:ocId:serverUrl:selector:errorMessage:errorCode:)]) {
  319. [self.delegate downloadFileSuccessFailure:metadata.fileName ocId:metadata.ocId serverUrl:metadata.serverUrl selector:metadata.sessionSelector errorMessage:@"Download error, account not found" errorCode:k_CCErrorInternalError];
  320. }
  321. return;
  322. }
  323. NSString *serverFileUrl = [[NSString stringWithFormat:@"%@/%@", metadata.serverUrl, metadata.fileName] encodeString:NSUTF8StringEncoding];
  324. url = [NSURL URLWithString:serverFileUrl];
  325. request = [NSMutableURLRequest requestWithURL:url];
  326. NSData *authData = [[NSString stringWithFormat:@"%@:%@", tableAccount.user, [CCUtility getPassword:tableAccount.account]] dataUsingEncoding:NSUTF8StringEncoding];
  327. NSString *authValue = [NSString stringWithFormat: @"Basic %@",[authData base64EncodedStringWithOptions:0]];
  328. [request setValue:authValue forHTTPHeaderField:@"Authorization"];
  329. [request setValue:[CCUtility getUserAgent] forHTTPHeaderField:@"User-Agent"];
  330. if ([metadata.session isEqualToString:k_download_session]) sessionDownload = [self sessionDownload];
  331. else if ([metadata.session isEqualToString:k_download_session_foreground]) sessionDownload = [self sessionDownloadForeground];
  332. else if ([metadata.session isEqualToString:k_download_session_wwan]) sessionDownload = [self sessionWWanDownload];
  333. NSURLSessionDownloadTask *downloadTask = [sessionDownload downloadTaskWithRequest:request];
  334. if (downloadTask == nil) {
  335. [[NCManageDatabase sharedInstance] setMetadataSession:nil sessionError:@"Serious internal error downloadTask not available" sessionSelector:nil sessionTaskIdentifier:k_taskIdentifierDone status:k_metadataStatusDownloadError predicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadata.ocId]];
  336. if ([self.delegate respondsToSelector:@selector(downloadFileSuccessFailure:ocId:serverUrl:selector:errorMessage:errorCode:)]) {
  337. [self.delegate downloadFileSuccessFailure:metadata.fileName ocId:metadata.ocId serverUrl:metadata.serverUrl selector:metadata.sessionSelector errorMessage:@"Serious internal error downloadTask not available" errorCode:k_CCErrorInternalError];
  338. }
  339. } else {
  340. // Manage uploadTask cancel,suspend,resume
  341. if (taskStatus == k_taskStatusCancel) [downloadTask cancel];
  342. else if (taskStatus == k_taskStatusSuspend) [downloadTask suspend];
  343. else if (taskStatus == k_taskStatusResume) [downloadTask resume];
  344. [[NCManageDatabase sharedInstance] setMetadataSession:nil sessionError:nil sessionSelector:nil sessionTaskIdentifier:downloadTask.taskIdentifier status:k_metadataStatusDownloading predicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadata.ocId]];
  345. NSLog(@"[LOG] downloadFileSession %@ Task [%lu]", metadata.ocId, (unsigned long)downloadTask.taskIdentifier);
  346. dispatch_async(dispatch_get_main_queue(), ^{
  347. if ([self.delegate respondsToSelector:@selector(downloadStart:account:task:serverUrl:)]) {
  348. [self.delegate downloadStart:metadata.ocId account:metadata.account task:downloadTask serverUrl:metadata.serverUrl];
  349. }
  350. });
  351. }
  352. }
  353. - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
  354. {
  355. NSString *url = [[[downloadTask currentRequest].URL absoluteString] stringByRemovingPercentEncoding];
  356. NSString *fileName = [url lastPathComponent];
  357. NSString *serverUrl = [self getServerUrlFromUrl:url];
  358. if (!serverUrl) return;
  359. if (totalBytesExpectedToWrite < 1) {
  360. totalBytesExpectedToWrite = totalBytesWritten;
  361. }
  362. float progress = (float) totalBytesWritten / (float)totalBytesExpectedToWrite;
  363. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataInSessionFromFileName:fileName serverUrl:serverUrl taskIdentifier:downloadTask.taskIdentifier];
  364. if (metadata) {
  365. NSDictionary *userInfo = @{@"account": (metadata.account), @"ocId": (metadata.ocId), @"serverUrl": (serverUrl), @"status": ([NSNumber numberWithLong:k_metadataStatusInDownload]), @"progress": ([NSNumber numberWithFloat:progress]), @"totalBytes": ([NSNumber numberWithLongLong:totalBytesWritten]), @"totalBytesExpected": ([NSNumber numberWithLongLong:totalBytesExpectedToWrite])};
  366. if (userInfo)
  367. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"NotificationProgressTask" object:nil userInfo:userInfo];
  368. } else {
  369. NSLog(@"[LOG] metadata not found");
  370. }
  371. }
  372. - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
  373. {
  374. NSString *url = [[[downloadTask currentRequest].URL absoluteString] stringByRemovingPercentEncoding];
  375. if (!url)
  376. return;
  377. NSString *fileName = [url lastPathComponent];
  378. NSString *serverUrl = [self getServerUrlFromUrl:url];
  379. if (!serverUrl) return;
  380. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataInSessionFromFileName:fileName serverUrl:serverUrl taskIdentifier:downloadTask.taskIdentifier];
  381. if (!metadata) {
  382. NSLog(@"[LOG] Serious error internal download : metadata not found %@ ", url);
  383. dispatch_async(dispatch_get_main_queue(), ^{
  384. if ([self.delegate respondsToSelector:@selector(downloadFileSuccessFailure:ocId:serverUrl:selector:errorMessage:errorCode:)]) {
  385. [self.delegate downloadFileSuccessFailure:@"" ocId:@"" serverUrl:serverUrl selector:@"" errorMessage:@"Serious error internal download : metadata not found" errorCode:k_CCErrorInternalError];
  386. }
  387. });
  388. return;
  389. }
  390. NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)downloadTask.response;
  391. if (httpResponse.statusCode >= 200 && httpResponse.statusCode < 300) {
  392. NSString *destinationFilePath = [CCUtility getDirectoryProviderStorageOcId:metadata.ocId fileNameView:metadata.fileName];
  393. NSURL *destinationURL = [NSURL fileURLWithPath:destinationFilePath];
  394. [[NSFileManager defaultManager] removeItemAtURL:destinationURL error:NULL];
  395. [[NSFileManager defaultManager] copyItemAtURL:location toURL:destinationURL error:nil];
  396. }
  397. }
  398. - (void)downloadFileSuccessFailure:(NSString *)fileName ocId:(NSString *)ocId etag:(NSString *)etag date:(NSDate *)date serverUrl:(NSString *)serverUrl selector:(NSString *)selector errorCode:(NSInteger)errorCode
  399. {
  400. #ifndef EXTENSION
  401. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  402. [appDelegate.listProgressMetadata removeObjectForKey:ocId];
  403. #endif
  404. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", ocId]];
  405. if (errorCode != 0) {
  406. if (errorCode == kCFURLErrorCancelled) {
  407. [[NCManageDatabase sharedInstance] setMetadataSession:@"" sessionError:@"" sessionSelector:@"" sessionTaskIdentifier:k_taskIdentifierDone status:k_metadataStatusNormal predicate:[NSPredicate predicateWithFormat:@"ocId == %@", ocId]];
  408. } else {
  409. if (metadata && (errorCode == kOCErrorServerUnauthorized || errorCode == kOCErrorServerForbidden))
  410. [[OCNetworking sharedManager] checkRemoteUser:metadata.account function:@"download" errorCode:errorCode];
  411. else if (metadata && errorCode == NSURLErrorServerCertificateUntrusted)
  412. [CCUtility setCertificateError:metadata.account error:YES];
  413. [[NCManageDatabase sharedInstance] setMetadataSession:nil sessionError:[CCError manageErrorKCF:errorCode withNumberError:NO] sessionSelector:nil sessionTaskIdentifier:k_taskIdentifierDone status:k_metadataStatusDownloadError predicate:[NSPredicate predicateWithFormat:@"ocId == %@", ocId]];
  414. }
  415. if ([self.delegate respondsToSelector:@selector(downloadFileSuccessFailure:ocId:serverUrl:selector:errorMessage:errorCode:)]) {
  416. [self.delegate downloadFileSuccessFailure:fileName ocId:ocId serverUrl:serverUrl selector:selector errorMessage:[CCError manageErrorKCF:errorCode withNumberError:YES] errorCode:errorCode];
  417. }
  418. } else {
  419. if (!metadata) {
  420. NSLog(@"[LOG] Serious error internal download : metadata not found %@ ", fileName);
  421. if ([self.delegate respondsToSelector:@selector(downloadFileSuccessFailure:ocId:serverUrl:selector:errorMessage:errorCode:)]) {
  422. [self.delegate downloadFileSuccessFailure:fileName ocId:ocId serverUrl:serverUrl selector:selector errorMessage:[NSString stringWithFormat:@"Serious error internal download : metadata not found %@", fileName] errorCode:k_CCErrorInternalError];
  423. }
  424. return;
  425. }
  426. metadata.session = @"";
  427. metadata.sessionError = @"";
  428. metadata.sessionSelector = @"";
  429. metadata.sessionTaskIdentifier = k_taskIdentifierDone;
  430. metadata.status = k_metadataStatusNormal;
  431. metadata = [[NCManageDatabase sharedInstance] updateMetadata:metadata];
  432. [[NCManageDatabase sharedInstance] addLocalFileWithMetadata:metadata];
  433. // E2EE Decrypted
  434. tableE2eEncryption *object = [[NCManageDatabase sharedInstance] getE2eEncryptionWithPredicate:[NSPredicate predicateWithFormat:@"fileNameIdentifier == %@ AND serverUrl == %@", fileName, serverUrl]];
  435. if (object) {
  436. BOOL result = [[NCEndToEndEncryption sharedManager] decryptFileName:metadata.fileName fileNameView:metadata.fileNameView ocId:metadata.ocId key:object.key initializationVector:object.initializationVector authenticationTag:object.authenticationTag];
  437. if (!result) {
  438. if ([self.delegate respondsToSelector:@selector(downloadFileSuccessFailure:ocId:serverUrl:selector:errorMessage:errorCode:)]) {
  439. [self.delegate downloadFileSuccessFailure:fileName ocId:ocId serverUrl:serverUrl selector:selector errorMessage:[NSString stringWithFormat:@"Serious error internal download : decrypt error %@", fileName] errorCode:k_CCErrorInternalError];
  440. }
  441. return;
  442. }
  443. }
  444. // Exif
  445. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image])
  446. [[CCExifGeo sharedInstance] setExifLocalTableEtag:metadata];
  447. // Icon
  448. if ([[NSFileManager defaultManager] fileExistsAtPath:[CCUtility getDirectoryProviderStorageIconOcId:metadata.ocId fileNameView:metadata.fileNameView]] == NO) {
  449. [CCGraphics createNewImageFrom:metadata.fileNameView ocId:metadata.ocId extension:[metadata.fileNameView pathExtension] filterGrayScale:NO typeFile:metadata.typeFile writeImage:YES];
  450. }
  451. if ([self.delegate respondsToSelector:@selector(downloadFileSuccessFailure:ocId:serverUrl:selector:errorMessage:errorCode:)]) {
  452. [self.delegate downloadFileSuccessFailure:fileName ocId:ocId serverUrl:serverUrl selector:selector errorMessage:@"" errorCode:0];
  453. }
  454. }
  455. }
  456. #pragma --------------------------------------------------------------------------------------------
  457. #pragma mark ===== Upload =====
  458. #pragma --------------------------------------------------------------------------------------------
  459. - (void)uploadFile:(tableMetadata *)metadata taskStatus:(NSInteger)taskStatus
  460. {
  461. // Password nil
  462. if ([CCUtility getPassword:metadata.account].length == 0) {
  463. [self.delegate uploadFileSuccessFailure:metadata.fileName ocId:metadata.ocId assetLocalIdentifier:metadata.assetLocalIdentifier serverUrl:metadata.serverUrl selector:metadata.sessionSelector errorMessage:NSLocalizedString(@"_bad_username_password_", nil) errorCode:kOCErrorServerUnauthorized];
  464. return;
  465. } else if ([CCUtility getCertificateError:metadata.account]) {
  466. [self.delegate uploadFileSuccessFailure:metadata.fileName ocId:metadata.ocId assetLocalIdentifier:metadata.assetLocalIdentifier serverUrl:metadata.serverUrl selector:metadata.sessionSelector errorMessage:NSLocalizedString(@"_ssl_certificate_untrusted_", nil) errorCode:NSURLErrorServerCertificateUntrusted];
  467. return;
  468. }
  469. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", metadata.account]];
  470. if (tableAccount == nil) {
  471. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadata.ocId]];
  472. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:ocId:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  473. [self.delegate uploadFileSuccessFailure:metadata.fileName ocId:metadata.ocId assetLocalIdentifier:metadata.assetLocalIdentifier serverUrl:metadata.serverUrl selector:metadata.sessionSelector errorMessage:@"Upload error, account not found" errorCode:k_CCErrorInternalError];
  474. }
  475. return;
  476. }
  477. if ([CCUtility fileProviderStorageExists:metadata.ocId fileNameView:metadata.fileNameView] == NO) {
  478. PHFetchResult *result = [PHAsset fetchAssetsWithLocalIdentifiers:@[metadata.assetLocalIdentifier] options:nil];
  479. if (!result.count) {
  480. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadata.ocId]];
  481. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:ocId:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  482. [self.delegate uploadFileSuccessFailure:metadata.fileName ocId:metadata.ocId assetLocalIdentifier:metadata.assetLocalIdentifier serverUrl:metadata.serverUrl selector:metadata.sessionSelector errorMessage:@"Error photo/video not found, remove from upload" errorCode:k_CCErrorInternalError];
  483. }
  484. return;
  485. }
  486. PHAsset *asset= result[0];
  487. // IMAGE
  488. if (asset.mediaType == PHAssetMediaTypeImage) {
  489. PHImageRequestOptions *options = [PHImageRequestOptions new];
  490. options.networkAccessAllowed = YES; // iCloud
  491. options.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
  492. options.synchronous = YES;
  493. options.progressHandler = ^(double progress, NSError *error, BOOL *stop, NSDictionary *info) {
  494. NSLog(@"cacheAsset: %f", progress);
  495. if (error) {
  496. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadata.ocId]];
  497. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:ocId:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  498. [self.delegate uploadFileSuccessFailure:metadata.fileName ocId:metadata.ocId assetLocalIdentifier:metadata.assetLocalIdentifier serverUrl:metadata.serverUrl selector:metadata.sessionSelector errorMessage:[NSString stringWithFormat:@"Image request iCloud failed [%@]", error.description] errorCode:error.code];
  499. }
  500. }
  501. };
  502. [[PHImageManager defaultManager] requestImageDataForAsset:asset options:options resultHandler:^(NSData *imageData, NSString *dataUTI, UIImageOrientation orientation, NSDictionary *info) {
  503. NSError *error = nil;
  504. NSString *extensionAsset = [[[asset valueForKey:@"filename"] pathExtension] uppercaseString];
  505. if ([extensionAsset isEqualToString:@"HEIC"] && [CCUtility getFormatCompatibility]) {
  506. CIImage *ciImage = [CIImage imageWithData:imageData];
  507. CIContext *context = [CIContext context];
  508. imageData = [context JPEGRepresentationOfImage:ciImage colorSpace:ciImage.colorSpace options:@{}];
  509. NSString *fileNameJPEG = [[metadata.fileName lastPathComponent] stringByDeletingPathExtension];
  510. metadata.fileName = [fileNameJPEG stringByAppendingString:@".jpg"];
  511. metadata.fileNameView = metadata.fileName;
  512. // Change Metadata with new ocId, fileName, fileNameView
  513. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadata.ocId]];
  514. metadata.ocId = [CCUtility createMetadataIDFromAccount:metadata.account serverUrl:metadata.serverUrl fileNameView:metadata.fileNameView directory:false];
  515. }
  516. tableMetadata *metadataForUpload = [[NCManageDatabase sharedInstance] addMetadata:[CCUtility insertFileSystemInMetadata:metadata]];
  517. [imageData writeToFile:[CCUtility getDirectoryProviderStorageOcId:metadataForUpload.ocId fileNameView:metadataForUpload.fileNameView] options:NSDataWritingAtomic error:&error];
  518. if (error) {
  519. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadataForUpload.ocId]];
  520. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:ocId:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  521. [self.delegate uploadFileSuccessFailure:metadataForUpload.fileName ocId:metadataForUpload.ocId assetLocalIdentifier:metadataForUpload.assetLocalIdentifier serverUrl:metadataForUpload.serverUrl selector:metadataForUpload.sessionSelector errorMessage:[NSString stringWithFormat:@"Image request failed [%@]", error.description] errorCode:error.code];
  522. }
  523. } else {
  524. // OOOOOK
  525. if ([CCUtility isFolderEncrypted:metadataForUpload.serverUrl account:tableAccount.account] && [CCUtility isEndToEndEnabled:tableAccount.account]) {
  526. [self e2eEncryptedFile:metadataForUpload tableAccount:tableAccount taskStatus:taskStatus];
  527. } else {
  528. [self uploadURLSessionMetadata:metadataForUpload tableAccount:tableAccount taskStatus:taskStatus];
  529. }
  530. }
  531. }];
  532. }
  533. // VIDEO
  534. if (asset.mediaType == PHAssetMediaTypeVideo) {
  535. PHVideoRequestOptions *options = [PHVideoRequestOptions new];
  536. options.networkAccessAllowed = YES;
  537. options.version = PHVideoRequestOptionsVersionOriginal;
  538. options.progressHandler = ^(double progress, NSError *error, BOOL *stop, NSDictionary *info) {
  539. NSLog(@"cacheAsset: %f", progress);
  540. if (error) {
  541. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadata.ocId]];
  542. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:ocId:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  543. [self.delegate uploadFileSuccessFailure:metadata.fileName ocId:metadata.ocId assetLocalIdentifier:metadata.assetLocalIdentifier serverUrl:metadata.serverUrl selector:metadata.sessionSelector errorMessage:[NSString stringWithFormat:@"Video request iCloud failed [%@]", error.description] errorCode:error.code];
  544. }
  545. }
  546. };
  547. [[PHImageManager defaultManager] requestAVAssetForVideo:asset options:options resultHandler:^(AVAsset *asset, AVAudioMix *audioMix, NSDictionary *info) {
  548. if ([asset isKindOfClass:[AVURLAsset class]]) {
  549. NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:[CCUtility getDirectoryProviderStorageOcId:metadata.ocId fileNameView:metadata.fileNameView]];
  550. NSError *error = nil;
  551. [[NSFileManager defaultManager] removeItemAtURL:fileURL error:nil];
  552. [[NSFileManager defaultManager] copyItemAtURL:[(AVURLAsset *)asset URL] toURL:fileURL error:&error];
  553. if (error) {
  554. dispatch_async(dispatch_get_main_queue(), ^{
  555. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadata.ocId]];
  556. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:ocId:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  557. [self.delegate uploadFileSuccessFailure:metadata.fileName ocId:metadata.ocId assetLocalIdentifier:metadata.assetLocalIdentifier serverUrl:metadata.serverUrl selector:metadata.sessionSelector errorMessage:[NSString stringWithFormat:@"Video request failed [%@]", error.description] errorCode:error.code];
  558. }
  559. });
  560. } else {
  561. dispatch_async(dispatch_get_main_queue(), ^{
  562. // create Metadata for Upload
  563. tableMetadata *metadataForUpload = [[NCManageDatabase sharedInstance] addMetadata:[CCUtility insertFileSystemInMetadata:metadata]];
  564. // OOOOOK
  565. if ([CCUtility isFolderEncrypted:metadataForUpload.serverUrl account:tableAccount.account] && [CCUtility isEndToEndEnabled:tableAccount.account]) {
  566. [self e2eEncryptedFile:metadataForUpload tableAccount:tableAccount taskStatus:taskStatus];
  567. } else {
  568. [self uploadURLSessionMetadata:metadataForUpload tableAccount:tableAccount taskStatus:taskStatus];
  569. }
  570. });
  571. }
  572. }
  573. }];
  574. }
  575. } else {
  576. // create Metadata for Upload
  577. tableMetadata *metadataForUpload = [[NCManageDatabase sharedInstance] addMetadata:[CCUtility insertFileSystemInMetadata:metadata]];
  578. // OOOOOK
  579. if ([CCUtility isFolderEncrypted:metadataForUpload.serverUrl account:tableAccount.account] && [CCUtility isEndToEndEnabled:tableAccount.account]) {
  580. [self e2eEncryptedFile:metadataForUpload tableAccount:tableAccount taskStatus:taskStatus];
  581. } else {
  582. [self uploadURLSessionMetadata:metadataForUpload tableAccount:tableAccount taskStatus:taskStatus];
  583. }
  584. }
  585. }
  586. - (void)e2eEncryptedFile:(tableMetadata *)metadata tableAccount:(tableAccount *)tableAccount taskStatus:(NSInteger)taskStatus
  587. {
  588. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  589. NSError *error;
  590. NSString *fileNameIdentifier;
  591. NSString *key;
  592. NSString *initializationVector;
  593. NSString *authenticationTag;
  594. NSString *metadataKey;
  595. NSInteger metadataKeyIndex;
  596. NSString *e2eeMetadata;
  597. // Verify File Size
  598. NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:[CCUtility getDirectoryProviderStorageOcId:metadata.ocId fileNameView:metadata.fileNameView] error:&error];
  599. NSNumber *fileSizeNumber = [fileAttributes objectForKey:NSFileSize];
  600. long long fileSize = [fileSizeNumber longLongValue];
  601. if (fileSize > k_max_filesize_E2EE) {
  602. // Error for uploadFileFailure
  603. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:ocId:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  604. [self.delegate uploadFileSuccessFailure:metadata.fileName ocId:metadata.ocId assetLocalIdentifier:metadata.assetLocalIdentifier serverUrl:metadata.serverUrl selector:metadata.sessionSelector errorMessage:@"E2E Error file too big" errorCode:k_CCErrorInternalError];
  605. }
  606. return;
  607. }
  608. // if new file upload create a new encrypted filename
  609. if ([metadata.ocId isEqualToString:[CCUtility createMetadataIDFromAccount:metadata.account serverUrl:metadata.serverUrl fileNameView:metadata.fileNameView directory:false]]) {
  610. fileNameIdentifier = [CCUtility generateRandomIdentifier];
  611. } else {
  612. fileNameIdentifier = metadata.fileName;
  613. }
  614. if ([[NCEndToEndEncryption sharedManager] encryptFileName:metadata.fileNameView fileNameIdentifier:fileNameIdentifier directory:[CCUtility getDirectoryProviderStorageOcId:metadata.ocId] key:&key initializationVector:&initializationVector authenticationTag:&authenticationTag]) {
  615. tableE2eEncryption *object = [[NCManageDatabase sharedInstance] getE2eEncryptionWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", tableAccount.account, metadata.serverUrl]];
  616. if (object) {
  617. metadataKey = object.metadataKey;
  618. metadataKeyIndex = object.metadataKeyIndex;
  619. } else {
  620. metadataKey = [[[NCEndToEndEncryption sharedManager] generateKey:16] base64EncodedStringWithOptions:0]; // AES_KEY_128_LENGTH
  621. metadataKeyIndex = 0;
  622. }
  623. tableE2eEncryption *addObject = [tableE2eEncryption new];
  624. addObject.account = tableAccount.account;
  625. addObject.authenticationTag = authenticationTag;
  626. addObject.fileName = metadata.fileNameView;
  627. addObject.fileNameIdentifier = fileNameIdentifier;
  628. addObject.fileNamePath = [CCUtility returnFileNamePathFromFileName:metadata.fileNameView serverUrl:metadata.serverUrl activeUrl:tableAccount.url];
  629. addObject.key = key;
  630. addObject.initializationVector = initializationVector;
  631. addObject.metadataKey = metadataKey;
  632. addObject.metadataKeyIndex = metadataKeyIndex;
  633. CFStringRef UTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef)[metadata.fileNameView pathExtension], NULL);
  634. CFStringRef mimeTypeRef = UTTypeCopyPreferredTagWithClass (UTI, kUTTagClassMIMEType);
  635. if (mimeTypeRef) {
  636. addObject.mimeType = (__bridge NSString *)mimeTypeRef;
  637. } else {
  638. addObject.mimeType = @"application/octet-stream";
  639. }
  640. addObject.serverUrl = metadata.serverUrl;
  641. addObject.version = [[NCManageDatabase sharedInstance] getEndToEndEncryptionVersionWithAccount:tableAccount.account];
  642. // Get the last metadata
  643. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", tableAccount.account, metadata.serverUrl]];
  644. error = [[NCNetworkingEndToEnd sharedManager] getEndToEndMetadata:&e2eeMetadata ocId:directory.ocId user:tableAccount.user userID:tableAccount.userID password: [CCUtility getPassword:tableAccount.account] url:tableAccount.url];
  645. if (error == nil) {
  646. if ([[NCEndToEndMetadata sharedInstance] decoderMetadata:e2eeMetadata privateKey:[CCUtility getEndToEndPrivateKey:tableAccount.account] serverUrl:metadata.serverUrl account:tableAccount.account url:tableAccount.url] == false) {
  647. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:ocId:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  648. [self.delegate uploadFileSuccessFailure:metadata.fileName ocId:metadata.ocId assetLocalIdentifier:metadata.assetLocalIdentifier serverUrl:metadata.serverUrl selector:metadata.sessionSelector errorMessage:NSLocalizedString(@"_e2e_error_decode_metadata_", nil) errorCode:k_CCErrorInternalError];
  649. }
  650. return;
  651. }
  652. }
  653. // write new record e2ee
  654. if([[NCManageDatabase sharedInstance] addE2eEncryption:addObject] == NO) {
  655. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:ocId:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  656. [self.delegate uploadFileSuccessFailure:metadata.fileName ocId:metadata.ocId assetLocalIdentifier:metadata.assetLocalIdentifier serverUrl:metadata.serverUrl selector:metadata.sessionSelector errorMessage:NSLocalizedString(@"_e2e_error_create_encrypted_", nil) errorCode:k_CCErrorInternalError];
  657. }
  658. return;
  659. }
  660. } else {
  661. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:ocId:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  662. [self.delegate uploadFileSuccessFailure:metadata.fileName ocId:metadata.ocId assetLocalIdentifier:metadata.assetLocalIdentifier serverUrl:metadata.serverUrl selector:metadata.sessionSelector errorMessage:NSLocalizedString(@"_e2e_error_create_encrypted_", nil) errorCode:k_CCErrorInternalError];
  663. }
  664. return;
  665. }
  666. dispatch_async(dispatch_get_main_queue(), ^{
  667. // Now the fileName is fileNameIdentifier && flag e2eEncrypted
  668. metadata.fileName = fileNameIdentifier;
  669. metadata.e2eEncrypted = YES;
  670. // Update Metadata
  671. tableMetadata *metadataEncrypted = [[NCManageDatabase sharedInstance] addMetadata:metadata];
  672. [self uploadURLSessionMetadata:metadataEncrypted tableAccount:tableAccount taskStatus:taskStatus];
  673. });
  674. });
  675. }
  676. - (void)uploadURLSessionMetadata:(tableMetadata *)metadata tableAccount:(tableAccount *)tableAccount taskStatus:(NSInteger)taskStatus
  677. {
  678. NSURL *url;
  679. NSMutableURLRequest *request;
  680. PHAsset *asset;
  681. NSError *error;
  682. // calculate and store file size
  683. NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:[CCUtility getDirectoryProviderStorageOcId:metadata.ocId fileNameView:metadata.fileName] error:&error];
  684. long long fileSize = [[fileAttributes objectForKey:NSFileSize] longLongValue];
  685. metadata.size = fileSize;
  686. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  687. url = [NSURL URLWithString:[[NSString stringWithFormat:@"%@/%@", metadata.serverUrl, metadata.fileName] encodeString:NSUTF8StringEncoding]];
  688. request = [NSMutableURLRequest requestWithURL:url];
  689. NSData *authData = [[NSString stringWithFormat:@"%@:%@", tableAccount.user, [CCUtility getPassword:tableAccount.account]] dataUsingEncoding:NSUTF8StringEncoding];
  690. NSString *authValue = [NSString stringWithFormat: @"Basic %@",[authData base64EncodedStringWithOptions:0]];
  691. [request setHTTPMethod:@"PUT"];
  692. [request setValue:authValue forHTTPHeaderField:@"Authorization"];
  693. [request setValue:[CCUtility getUserAgent] forHTTPHeaderField:@"User-Agent"];
  694. // Create Image for Upload (gray scale)
  695. #ifndef EXTENSION
  696. [CCGraphics createNewImageFrom:metadata.fileNameView ocId:metadata.ocId extension:[metadata.fileNameView pathExtension] filterGrayScale:YES typeFile:metadata.typeFile writeImage:YES];
  697. #endif
  698. // Change date file upload with header : X-OC-Mtime (ctime assetLocalIdentifier) image/video
  699. if (metadata.assetLocalIdentifier) {
  700. PHFetchResult *result = [PHAsset fetchAssetsWithLocalIdentifiers:@[metadata.assetLocalIdentifier] options:nil];
  701. if (result.count) {
  702. asset = result[0];
  703. long dateFileCreation = [asset.creationDate timeIntervalSince1970];
  704. [request setValue:[NSString stringWithFormat:@"%ld", dateFileCreation] forHTTPHeaderField:@"X-OC-Mtime"];
  705. }
  706. }
  707. NSURLSession *sessionUpload;
  708. // NSURLSession
  709. if ([metadata.session isEqualToString:k_upload_session]) sessionUpload = [self sessionUpload];
  710. else if ([metadata.session isEqualToString:k_upload_session_wwan]) sessionUpload = [self sessionWWanUpload];
  711. else if ([metadata.session isEqualToString:k_upload_session_foreground]) sessionUpload = [self sessionUploadForeground];
  712. else if ([metadata.session isEqualToString:k_upload_session_extension]) sessionUpload = [self sessionUploadExtension];
  713. NSURLSessionUploadTask *uploadTask = [sessionUpload uploadTaskWithRequest:request fromFile:[NSURL fileURLWithPath:[CCUtility getDirectoryProviderStorageOcId:metadata.ocId fileNameView:metadata.fileName]]];
  714. // Error
  715. if (uploadTask == nil) {
  716. NSString *messageError = @"Serious internal error uploadTask not available";
  717. [[NCManageDatabase sharedInstance] setMetadataSession:metadata.session sessionError:messageError sessionSelector:nil sessionTaskIdentifier:k_taskIdentifierDone status:k_metadataStatusUploadError predicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadata.ocId]];
  718. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:ocId:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  719. [self.delegate uploadFileSuccessFailure:metadata.fileNameView ocId:metadata.ocId assetLocalIdentifier:metadata.assetLocalIdentifier serverUrl:metadata.serverUrl selector:metadata.sessionSelector errorMessage:messageError errorCode:k_CCErrorInternalError];
  720. }
  721. } else {
  722. // E2EE : CREATE AND SEND METADATA
  723. if ([CCUtility isFolderEncrypted:metadata.serverUrl account:tableAccount.account] && [CCUtility isEndToEndEnabled:tableAccount.account]) {
  724. NSString *serverUrl = metadata.serverUrl;
  725. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  726. // Send Metadata
  727. 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];
  728. dispatch_async(dispatch_get_main_queue(), ^{
  729. if (error) {
  730. [uploadTask cancel];
  731. NSString *messageError = [NSString stringWithFormat:@"%@ (%d)", error.localizedDescription, (int)error.code];
  732. [[NCManageDatabase sharedInstance] setMetadataSession:metadata.session sessionError:messageError sessionSelector:nil sessionTaskIdentifier:k_taskIdentifierDone status:k_metadataStatusUploadError predicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadata.ocId]];
  733. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:ocId:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  734. [self.delegate uploadFileSuccessFailure:metadata.fileNameView ocId:metadata.ocId assetLocalIdentifier:metadata.assetLocalIdentifier serverUrl:metadata.serverUrl selector:metadata.sessionSelector errorMessage:messageError errorCode:k_CCErrorInternalError];
  735. }
  736. } else {
  737. // Manage uploadTask cancel,suspend,resume
  738. if (taskStatus == k_taskStatusCancel) [uploadTask cancel];
  739. else if (taskStatus == k_taskStatusSuspend) [uploadTask suspend];
  740. else if (taskStatus == k_taskStatusResume) [uploadTask resume];
  741. // *** E2EE ***
  742. [[NCManageDatabase sharedInstance] setMetadataSession:metadata.session sessionError:@"" sessionSelector:nil sessionTaskIdentifier:uploadTask.taskIdentifier status:k_metadataStatusUploading predicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadata.ocId]];
  743. NSLog(@"[LOG] Upload file %@ TaskIdentifier %lu", metadata.fileName, (unsigned long)uploadTask.taskIdentifier);
  744. NSString *ocId = metadata.ocId;
  745. NSString *account = metadata.account;
  746. dispatch_async(dispatch_get_main_queue(), ^{
  747. if ([self.delegate respondsToSelector:@selector(uploadStart:account:task:serverUrl:)]) {
  748. [self.delegate uploadStart:ocId account:account task:uploadTask serverUrl:metadata.serverUrl];
  749. }
  750. });
  751. }
  752. });
  753. });
  754. } else {
  755. // Manage uploadTask cancel,suspend,resume
  756. if (taskStatus == k_taskStatusCancel) [uploadTask cancel];
  757. else if (taskStatus == k_taskStatusSuspend) [uploadTask suspend];
  758. else if (taskStatus == k_taskStatusResume) [uploadTask resume];
  759. // *** PLAIN ***
  760. [[NCManageDatabase sharedInstance] setMetadataSession:metadata.session sessionError:@"" sessionSelector:nil sessionTaskIdentifier:uploadTask.taskIdentifier status:k_metadataStatusUploading predicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadata.ocId]];
  761. NSLog(@"[LOG] Upload file %@ TaskIdentifier %lu", metadata.fileName, (unsigned long)uploadTask.taskIdentifier);
  762. NSString *ocId = metadata.ocId;
  763. NSString *account = metadata.account;
  764. NSString *serverUrl = metadata.serverUrl;
  765. dispatch_async(dispatch_get_main_queue(), ^{
  766. if ([self.delegate respondsToSelector:@selector(uploadStart:account:task:serverUrl:)]) {
  767. [self.delegate uploadStart:ocId account:account task:uploadTask serverUrl:serverUrl];
  768. }
  769. });
  770. }
  771. }
  772. }
  773. - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
  774. {
  775. }
  776. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend
  777. {
  778. NSString *url = [[[task currentRequest].URL absoluteString] stringByRemovingPercentEncoding];
  779. NSString *fileName = [url lastPathComponent];
  780. NSString *serverUrl = [self getServerUrlFromUrl:url];
  781. if (!serverUrl) return;
  782. if (totalBytesExpectedToSend < 1) {
  783. totalBytesExpectedToSend = totalBytesSent;
  784. }
  785. float progress = (float) totalBytesSent / (float)totalBytesExpectedToSend;
  786. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataInSessionFromFileName:fileName serverUrl:serverUrl taskIdentifier:task.taskIdentifier];
  787. if (metadata) {
  788. NSDictionary *userInfo = @{@"account": (metadata.account), @"ocId": (metadata.ocId), @"serverUrl": (serverUrl), @"status": ([NSNumber numberWithLong:k_metadataStatusInUpload]), @"progress": ([NSNumber numberWithFloat:progress]), @"totalBytes": ([NSNumber numberWithLongLong:totalBytesSent]), @"totalBytesExpected": ([NSNumber numberWithLongLong:totalBytesExpectedToSend])};
  789. if (userInfo)
  790. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"NotificationProgressTask" object:nil userInfo:userInfo];
  791. }
  792. }
  793. - (void)uploadFileSuccessFailure:(tableMetadata *)metadata fileName:(NSString *)fileName ocId:(NSString *)ocId etag:(NSString *)etag date:(NSDate *)date serverUrl:(NSString *)serverUrl errorCode:(NSInteger)errorCode
  794. {
  795. NSString *tempocId = metadata.ocId;
  796. NSString *tempSession = metadata.session;
  797. NSString *errorMessage = @"";
  798. BOOL isE2EEDirectory = false;
  799. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", metadata.account]];
  800. if (tableAccount == nil) {
  801. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", tempocId]];
  802. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:ocId:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  803. [self.delegate uploadFileSuccessFailure:metadata.fileName ocId:metadata.ocId assetLocalIdentifier:metadata.assetLocalIdentifier serverUrl:serverUrl selector:metadata.sessionSelector errorMessage:errorMessage errorCode:errorCode];
  804. }
  805. return;
  806. }
  807. // is this a E2EE Directory ?
  808. if ([CCUtility isFolderEncrypted:serverUrl account:tableAccount.account] && [CCUtility isEndToEndEnabled:tableAccount.account]) {
  809. isE2EEDirectory = true;
  810. }
  811. // ERRORE
  812. if (errorCode != 0) {
  813. #ifndef EXTENSION
  814. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  815. [appDelegate.listProgressMetadata removeObjectForKey:metadata.ocId];
  816. #endif
  817. // Mark error only if not Cancelled Task
  818. if (errorCode == kCFURLErrorCancelled) {
  819. if (metadata.status == k_metadataStatusUploadForcedStart) {
  820. errorCode = 0;
  821. metadata.session = k_upload_session;
  822. metadata.sessionError = @"";
  823. metadata.sessionTaskIdentifier = 0;
  824. metadata.status = k_metadataStatusInUpload;
  825. metadata = [[NCManageDatabase sharedInstance] addMetadata:metadata];
  826. [[CCNetworking sharedNetworking] uploadFile:metadata taskStatus:k_taskStatusResume];
  827. } else {
  828. [[NSFileManager defaultManager] removeItemAtPath:[CCUtility getDirectoryProviderStorageOcId:tempocId] error:nil];
  829. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", tempocId]];
  830. errorMessage = [CCError manageErrorKCF:errorCode withNumberError:YES];
  831. }
  832. } else {
  833. if (metadata && (errorCode == kOCErrorServerUnauthorized || errorCode == kOCErrorServerForbidden))
  834. [[OCNetworking sharedManager] checkRemoteUser:metadata.account function:@"upload" errorCode:errorCode];
  835. else if (metadata && errorCode == NSURLErrorServerCertificateUntrusted)
  836. [CCUtility setCertificateError:metadata.account error:YES];
  837. [[NCManageDatabase sharedInstance] setMetadataSession:nil sessionError:[CCError manageErrorKCF:errorCode withNumberError:NO] sessionSelector:nil sessionTaskIdentifier:k_taskIdentifierDone status:k_metadataStatusUploadError predicate:[NSPredicate predicateWithFormat:@"ocId == %@", tempocId]];
  838. errorMessage = [CCError manageErrorKCF:errorCode withNumberError:YES];
  839. }
  840. } else {
  841. // Edited file, remove tempocId and adjust the directory provider storage
  842. if (metadata.edited) {
  843. // Update metadata tempocId
  844. [[NCManageDatabase sharedInstance] setMetadataSession:@"" sessionError:@"" sessionSelector:@"" sessionTaskIdentifier:k_taskIdentifierDone status:k_metadataStatusNormal predicate:[NSPredicate predicateWithFormat:@"ocId == %@", tempocId]];
  845. // Add metadata ocId
  846. metadata.date = date;
  847. if (isE2EEDirectory) {
  848. metadata.e2eEncrypted = true;
  849. } else {
  850. metadata.e2eEncrypted = false;
  851. }
  852. metadata.etag = etag;
  853. metadata.ocId = ocId;
  854. metadata.session = @"";
  855. metadata.sessionError = @"";
  856. metadata.sessionTaskIdentifier = k_taskIdentifierDone;
  857. metadata.status = k_metadataStatusNormal;
  858. metadata = [[NCManageDatabase sharedInstance] addMetadata:metadata];
  859. // Copy new version on old version
  860. if (![tempocId isEqualToString:metadata.ocId]) {
  861. [CCUtility copyFileAtPath:[NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryProviderStorage], tempocId] toPath:[NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryProviderStorage], metadata.ocId]];
  862. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", tempocId]];
  863. // IMI -> Unzip
  864. if ([metadata.typeFile isEqualToString:k_metadataTypeFile_imagemeter] && NCBrandOptions.sharedInstance.use_imi_viewer) {
  865. (void)[[NCUtility sharedInstance] IMUnzipWithMetadata:metadata];
  866. }
  867. }
  868. } else {
  869. // Replace Metadata
  870. metadata.date = date;
  871. if (isE2EEDirectory) {
  872. metadata.e2eEncrypted = true;
  873. } else {
  874. metadata.e2eEncrypted = false;
  875. }
  876. metadata.etag = etag;
  877. metadata.ocId = ocId;
  878. metadata.session = @"";
  879. metadata.sessionError = @"";
  880. metadata.sessionTaskIdentifier = k_taskIdentifierDone;
  881. metadata.status = k_metadataStatusNormal;
  882. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@ AND fileName == %@", metadata.account, metadata.serverUrl, metadata.fileName]];
  883. metadata = [[NCManageDatabase sharedInstance] addMetadata:metadata];
  884. NSLog(@"[LOG] Insert new upload : %@ - ocId : %@", metadata.fileName, ocId);
  885. if ([tempocId isEqualToString:[CCUtility createMetadataIDFromAccount:metadata.account serverUrl:metadata.serverUrl fileNameView:metadata.fileNameView directory:metadata.directory]]) {
  886. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", tempocId]];
  887. // adjust file system Directory Provider Storage
  888. if ([tempSession isEqualToString:k_upload_session_extension]) {
  889. // this is for File Provider Extension [Apple Works and ... ?]
  890. [CCUtility copyFileAtPath:[NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryProviderStorage], tempocId] toPath:[NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryProviderStorage], metadata.ocId]];
  891. } else {
  892. [CCUtility moveFileAtPath:[NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryProviderStorage], tempocId] toPath:[NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryProviderStorage], metadata.ocId]];
  893. }
  894. }
  895. }
  896. #ifndef EXTENSION
  897. // EXIF
  898. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image])
  899. [[CCExifGeo sharedInstance] setExifLocalTableEtag:metadata];
  900. // Create preview
  901. [CCGraphics createNewImageFrom:metadata.fileNameView ocId:metadata.ocId extension:[metadata.fileNameView pathExtension] filterGrayScale:NO typeFile:metadata.typeFile writeImage:YES];
  902. // Copy photo or video in the photo album for auto upload
  903. if ([metadata.assetLocalIdentifier length] > 0 && ([metadata.sessionSelector isEqualToString:selectorUploadAutoUpload] || [metadata.sessionSelector isEqualToString:selectorUploadFile])) {
  904. PHAsset *asset;
  905. PHFetchResult *result = [PHAsset fetchAssetsWithLocalIdentifiers:@[metadata.assetLocalIdentifier] options:nil];
  906. if(result.count){
  907. asset = result[0];
  908. [asset saveToAlbum:[NCBrandOptions sharedInstance].brand completionBlock:^(BOOL success) {
  909. if (success) NSLog(@"[LOG] Insert file %@ in %@", metadata.fileName, [NCBrandOptions sharedInstance].brand);
  910. else NSLog(@"[LOG] File %@ do not insert in %@", metadata.fileName, [NCBrandOptions sharedInstance].brand);
  911. }];
  912. }
  913. }
  914. #endif
  915. // Add Local or Remove from cache
  916. if ([CCUtility getDisableLocalCacheAfterUpload] && !metadata.edited) {
  917. [[NSFileManager defaultManager] removeItemAtPath:[CCUtility getDirectoryProviderStorageOcId:metadata.ocId] error:nil];
  918. } else {
  919. // Add Local
  920. [[NCManageDatabase sharedInstance] addLocalFileWithMetadata:metadata];
  921. }
  922. }
  923. // Detect E2EE
  924. 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]];
  925. // E2EE : UNLOCK
  926. if (isE2EEDirectory && e2eeMetadataInSession == nil) {
  927. tableE2eEncryptionLock *tableLock = [[NCManageDatabase sharedInstance] getE2ETokenLockWithServerUrl:serverUrl];
  928. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  929. if (tableLock) {
  930. NSError *error = [[NCNetworkingEndToEnd sharedManager] unlockEndToEndFolderEncryptedOnServerUrl:serverUrl ocId:tableLock.ocId token:tableLock.token user:tableAccount.user userID:tableAccount.userID password:[CCUtility getPassword:tableAccount.account] url:tableAccount.url];
  931. if (error) {
  932. [[NCContentPresenter shared] messageNotification:@"_e2e_error_unlock_" description:error.localizedDescription delay:k_dismissAfterSecond type:messageTypeError errorCode:error.code];
  933. }
  934. } else {
  935. NSLog(@"Error unlock not found");
  936. }
  937. dispatch_async(dispatch_get_main_queue(), ^{
  938. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:ocId:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  939. [self.delegate uploadFileSuccessFailure:metadata.fileName ocId:metadata.ocId assetLocalIdentifier:metadata.assetLocalIdentifier serverUrl:serverUrl selector:metadata.sessionSelector errorMessage:errorMessage errorCode:errorCode];
  940. }
  941. });
  942. });
  943. } else {
  944. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:ocId:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  945. [self.delegate uploadFileSuccessFailure:metadata.fileName ocId:metadata.ocId assetLocalIdentifier:metadata.assetLocalIdentifier serverUrl:serverUrl selector:metadata.sessionSelector errorMessage:errorMessage errorCode:errorCode];
  946. }
  947. }
  948. }
  949. #pragma --------------------------------------------------------------------------------------------
  950. #pragma mark ===== Utility =====
  951. #pragma --------------------------------------------------------------------------------------------
  952. - (NSString *)getServerUrlFromUrl:(NSString *)url
  953. {
  954. NSString *fileName = [url lastPathComponent];
  955. url = [url stringByReplacingOccurrencesOfString:[@"/" stringByAppendingString:fileName] withString:@""];
  956. return url;
  957. }
  958. @end