CCNetworking.m 69 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267
  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. NSString *errorMessage = [CCError manageErrorKCF:errorCode withNumberError:YES];
  405. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", ocId]];
  406. if (errorCode != 0) {
  407. if (errorCode == kCFURLErrorCancelled) {
  408. [[NCManageDatabase sharedInstance] setMetadataSession:@"" sessionError:@"" sessionSelector:@"" sessionTaskIdentifier:k_taskIdentifierDone status:k_metadataStatusNormal predicate:[NSPredicate predicateWithFormat:@"ocId == %@", ocId]];
  409. } else {
  410. if (metadata && (errorCode == kOCErrorServerUnauthorized || errorCode == kOCErrorServerForbidden))
  411. [[OCNetworking sharedManager] checkRemoteUser:metadata.account function:@"download" errorCode:errorCode];
  412. else if (metadata && errorCode == NSURLErrorServerCertificateUntrusted)
  413. [CCUtility setCertificateError:metadata.account error:YES];
  414. [[NCManageDatabase sharedInstance] setMetadataSession:nil sessionError:[CCError manageErrorKCF:errorCode withNumberError:NO] sessionSelector:nil sessionTaskIdentifier:k_taskIdentifierDone status:k_metadataStatusDownloadError predicate:[NSPredicate predicateWithFormat:@"ocId == %@", ocId]];
  415. }
  416. if ([self.delegate respondsToSelector:@selector(downloadFileSuccessFailure:ocId:serverUrl:selector:errorMessage:errorCode:)]) {
  417. [self.delegate downloadFileSuccessFailure:fileName ocId:ocId serverUrl:serverUrl selector:selector errorMessage:errorMessage errorCode:errorCode];
  418. }
  419. } else {
  420. if (!metadata) {
  421. NSLog(@"[LOG] Serious error internal download : metadata not found %@ ", fileName);
  422. if ([self.delegate respondsToSelector:@selector(downloadFileSuccessFailure:ocId:serverUrl:selector:errorMessage:errorCode:)]) {
  423. [self.delegate downloadFileSuccessFailure:fileName ocId:ocId serverUrl:serverUrl selector:selector errorMessage:[NSString stringWithFormat:@"Serious error internal download : metadata not found %@", fileName] errorCode:k_CCErrorInternalError];
  424. }
  425. return;
  426. }
  427. metadata.session = @"";
  428. metadata.sessionError = @"";
  429. metadata.sessionSelector = @"";
  430. metadata.sessionTaskIdentifier = k_taskIdentifierDone;
  431. metadata.status = k_metadataStatusNormal;
  432. metadata = [[NCManageDatabase sharedInstance] updateMetadata:metadata];
  433. (void)[[NCManageDatabase sharedInstance] addLocalFileWithMetadata:metadata];
  434. // E2EE Decrypted
  435. tableE2eEncryption *object = [[NCManageDatabase sharedInstance] getE2eEncryptionWithPredicate:[NSPredicate predicateWithFormat:@"fileNameIdentifier == %@ AND serverUrl == %@", fileName, serverUrl]];
  436. if (object) {
  437. BOOL result = [[NCEndToEndEncryption sharedManager] decryptFileName:metadata.fileName fileNameView:metadata.fileNameView ocId:metadata.ocId key:object.key initializationVector:object.initializationVector authenticationTag:object.authenticationTag];
  438. if (!result) {
  439. if ([self.delegate respondsToSelector:@selector(downloadFileSuccessFailure:ocId:serverUrl:selector:errorMessage:errorCode:)]) {
  440. [self.delegate downloadFileSuccessFailure:fileName ocId:ocId serverUrl:serverUrl selector:selector errorMessage:[NSString stringWithFormat:@"Serious error internal download : decrypt error %@", fileName] errorCode:k_CCErrorInternalError];
  441. }
  442. return;
  443. }
  444. }
  445. // Exif
  446. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image])
  447. [[CCExifGeo sharedInstance] setExifLocalTableEtag:metadata];
  448. // Icon
  449. if ([[NSFileManager defaultManager] fileExistsAtPath:[CCUtility getDirectoryProviderStorageIconOcId:metadata.ocId fileNameView:metadata.fileNameView]] == NO) {
  450. [CCGraphics createNewImageFrom:metadata.fileNameView ocId:metadata.ocId extension:[metadata.fileNameView pathExtension] filterGrayScale:NO typeFile:metadata.typeFile writeImage:YES];
  451. }
  452. if ([self.delegate respondsToSelector:@selector(downloadFileSuccessFailure:ocId:serverUrl:selector:errorMessage:errorCode:)]) {
  453. [self.delegate downloadFileSuccessFailure:fileName ocId:ocId serverUrl:serverUrl selector:selector errorMessage:@"" errorCode:0];
  454. }
  455. }
  456. // NSNotificationCenter
  457. NSDictionary* userInfo = @{@"metadata": metadata, @"errorCode": @(errorCode)};
  458. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_downloadFile object:nil userInfo:userInfo];
  459. }
  460. #pragma --------------------------------------------------------------------------------------------
  461. #pragma mark ===== Upload =====
  462. #pragma --------------------------------------------------------------------------------------------
  463. - (void)uploadFile:(tableMetadata *)metadata taskStatus:(NSInteger)taskStatus
  464. {
  465. // Password nil
  466. if ([CCUtility getPassword:metadata.account].length == 0) {
  467. [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];
  468. return;
  469. } else if ([CCUtility getCertificateError:metadata.account]) {
  470. [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];
  471. return;
  472. }
  473. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", metadata.account]];
  474. if (tableAccount == nil) {
  475. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadata.ocId]];
  476. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:ocId:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  477. [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];
  478. }
  479. return;
  480. }
  481. if ([CCUtility fileProviderStorageExists:metadata.ocId fileNameView:metadata.fileNameView] == NO) {
  482. PHFetchResult *result = [PHAsset fetchAssetsWithLocalIdentifiers:@[metadata.assetLocalIdentifier] options:nil];
  483. if (!result.count) {
  484. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadata.ocId]];
  485. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:ocId:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  486. [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];
  487. }
  488. return;
  489. }
  490. PHAsset *asset= result[0];
  491. // IMAGE
  492. if (asset.mediaType == PHAssetMediaTypeImage) {
  493. PHImageRequestOptions *options = [PHImageRequestOptions new];
  494. options.networkAccessAllowed = YES; // iCloud
  495. options.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
  496. options.synchronous = YES;
  497. options.progressHandler = ^(double progress, NSError *error, BOOL *stop, NSDictionary *info) {
  498. NSLog(@"cacheAsset: %f", progress);
  499. if (error) {
  500. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadata.ocId]];
  501. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:ocId:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  502. [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];
  503. }
  504. }
  505. };
  506. [[PHImageManager defaultManager] requestImageDataForAsset:asset options:options resultHandler:^(NSData *imageData, NSString *dataUTI, UIImageOrientation orientation, NSDictionary *info) {
  507. NSError *error = nil;
  508. NSString *extensionAsset = [[[asset valueForKey:@"filename"] pathExtension] uppercaseString];
  509. if ([extensionAsset isEqualToString:@"HEIC"] && [CCUtility getFormatCompatibility]) {
  510. CIImage *ciImage = [CIImage imageWithData:imageData];
  511. CIContext *context = [CIContext context];
  512. imageData = [context JPEGRepresentationOfImage:ciImage colorSpace:ciImage.colorSpace options:@{}];
  513. NSString *fileNameJPEG = [[metadata.fileName lastPathComponent] stringByDeletingPathExtension];
  514. metadata.fileName = [fileNameJPEG stringByAppendingString:@".jpg"];
  515. metadata.fileNameView = metadata.fileName;
  516. // Change Metadata with new ocId, fileName, fileNameView
  517. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadata.ocId]];
  518. metadata.ocId = [CCUtility createMetadataIDFromAccount:metadata.account serverUrl:metadata.serverUrl fileNameView:metadata.fileNameView directory:false];
  519. }
  520. tableMetadata *metadataForUpload = [[NCManageDatabase sharedInstance] addMetadata:[CCUtility insertFileSystemInMetadata:metadata]];
  521. [imageData writeToFile:[CCUtility getDirectoryProviderStorageOcId:metadataForUpload.ocId fileNameView:metadataForUpload.fileNameView] options:NSDataWritingAtomic error:&error];
  522. if (error) {
  523. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadataForUpload.ocId]];
  524. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:ocId:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  525. [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];
  526. }
  527. } else {
  528. // OOOOOK
  529. if ([CCUtility isFolderEncrypted:metadataForUpload.serverUrl account:tableAccount.account] && [CCUtility isEndToEndEnabled:tableAccount.account]) {
  530. [self e2eEncryptedFile:metadataForUpload tableAccount:tableAccount taskStatus:taskStatus];
  531. } else {
  532. [self uploadURLSessionMetadata:metadataForUpload tableAccount:tableAccount taskStatus:taskStatus];
  533. }
  534. }
  535. }];
  536. }
  537. // VIDEO
  538. if (asset.mediaType == PHAssetMediaTypeVideo) {
  539. PHVideoRequestOptions *options = [PHVideoRequestOptions new];
  540. options.networkAccessAllowed = YES;
  541. options.version = PHVideoRequestOptionsVersionOriginal;
  542. options.progressHandler = ^(double progress, NSError *error, BOOL *stop, NSDictionary *info) {
  543. NSLog(@"cacheAsset: %f", progress);
  544. if (error) {
  545. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadata.ocId]];
  546. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:ocId:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  547. [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];
  548. }
  549. }
  550. };
  551. [[PHImageManager defaultManager] requestAVAssetForVideo:asset options:options resultHandler:^(AVAsset *asset, AVAudioMix *audioMix, NSDictionary *info) {
  552. if ([asset isKindOfClass:[AVURLAsset class]]) {
  553. NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:[CCUtility getDirectoryProviderStorageOcId:metadata.ocId fileNameView:metadata.fileNameView]];
  554. NSError *error = nil;
  555. [[NSFileManager defaultManager] removeItemAtURL:fileURL error:nil];
  556. [[NSFileManager defaultManager] copyItemAtURL:[(AVURLAsset *)asset URL] toURL:fileURL error:&error];
  557. if (error) {
  558. dispatch_async(dispatch_get_main_queue(), ^{
  559. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadata.ocId]];
  560. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:ocId:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  561. [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];
  562. }
  563. });
  564. } else {
  565. dispatch_async(dispatch_get_main_queue(), ^{
  566. // create Metadata for Upload
  567. tableMetadata *metadataForUpload = [[NCManageDatabase sharedInstance] addMetadata:[CCUtility insertFileSystemInMetadata:metadata]];
  568. // OOOOOK
  569. if ([CCUtility isFolderEncrypted:metadataForUpload.serverUrl account:tableAccount.account] && [CCUtility isEndToEndEnabled:tableAccount.account]) {
  570. [self e2eEncryptedFile:metadataForUpload tableAccount:tableAccount taskStatus:taskStatus];
  571. } else {
  572. [self uploadURLSessionMetadata:metadataForUpload tableAccount:tableAccount taskStatus:taskStatus];
  573. }
  574. });
  575. }
  576. }
  577. }];
  578. }
  579. } else {
  580. // create Metadata for Upload
  581. tableMetadata *metadataForUpload = [[NCManageDatabase sharedInstance] addMetadata:[CCUtility insertFileSystemInMetadata:metadata]];
  582. // OOOOOK
  583. if ([CCUtility isFolderEncrypted:metadataForUpload.serverUrl account:tableAccount.account] && [CCUtility isEndToEndEnabled:tableAccount.account]) {
  584. [self e2eEncryptedFile:metadataForUpload tableAccount:tableAccount taskStatus:taskStatus];
  585. } else {
  586. [self uploadURLSessionMetadata:metadataForUpload tableAccount:tableAccount taskStatus:taskStatus];
  587. }
  588. }
  589. }
  590. - (void)e2eEncryptedFile:(tableMetadata *)metadata tableAccount:(tableAccount *)tableAccount taskStatus:(NSInteger)taskStatus
  591. {
  592. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  593. NSError *error;
  594. NSString *fileNameIdentifier;
  595. NSString *key;
  596. NSString *initializationVector;
  597. NSString *authenticationTag;
  598. NSString *metadataKey;
  599. NSInteger metadataKeyIndex;
  600. NSString *e2eeMetadata;
  601. // Verify File Size
  602. NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:[CCUtility getDirectoryProviderStorageOcId:metadata.ocId fileNameView:metadata.fileNameView] error:&error];
  603. NSNumber *fileSizeNumber = [fileAttributes objectForKey:NSFileSize];
  604. long long fileSize = [fileSizeNumber longLongValue];
  605. if (fileSize > k_max_filesize_E2EE) {
  606. // Error for uploadFileFailure
  607. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:ocId:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  608. [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];
  609. }
  610. return;
  611. }
  612. // if new file upload create a new encrypted filename
  613. if ([metadata.ocId isEqualToString:[CCUtility createMetadataIDFromAccount:metadata.account serverUrl:metadata.serverUrl fileNameView:metadata.fileNameView directory:false]]) {
  614. fileNameIdentifier = [CCUtility generateRandomIdentifier];
  615. } else {
  616. fileNameIdentifier = metadata.fileName;
  617. }
  618. if ([[NCEndToEndEncryption sharedManager] encryptFileName:metadata.fileNameView fileNameIdentifier:fileNameIdentifier directory:[CCUtility getDirectoryProviderStorageOcId:metadata.ocId] key:&key initializationVector:&initializationVector authenticationTag:&authenticationTag]) {
  619. tableE2eEncryption *object = [[NCManageDatabase sharedInstance] getE2eEncryptionWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", tableAccount.account, metadata.serverUrl]];
  620. if (object) {
  621. metadataKey = object.metadataKey;
  622. metadataKeyIndex = object.metadataKeyIndex;
  623. } else {
  624. metadataKey = [[[NCEndToEndEncryption sharedManager] generateKey:16] base64EncodedStringWithOptions:0]; // AES_KEY_128_LENGTH
  625. metadataKeyIndex = 0;
  626. }
  627. tableE2eEncryption *addObject = [tableE2eEncryption new];
  628. addObject.account = tableAccount.account;
  629. addObject.authenticationTag = authenticationTag;
  630. addObject.fileName = metadata.fileNameView;
  631. addObject.fileNameIdentifier = fileNameIdentifier;
  632. addObject.fileNamePath = [CCUtility returnFileNamePathFromFileName:metadata.fileNameView serverUrl:metadata.serverUrl activeUrl:tableAccount.url];
  633. addObject.key = key;
  634. addObject.initializationVector = initializationVector;
  635. addObject.metadataKey = metadataKey;
  636. addObject.metadataKeyIndex = metadataKeyIndex;
  637. CFStringRef UTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef)[metadata.fileNameView pathExtension], NULL);
  638. CFStringRef mimeTypeRef = UTTypeCopyPreferredTagWithClass (UTI, kUTTagClassMIMEType);
  639. if (mimeTypeRef) {
  640. addObject.mimeType = (__bridge NSString *)mimeTypeRef;
  641. } else {
  642. addObject.mimeType = @"application/octet-stream";
  643. }
  644. addObject.serverUrl = metadata.serverUrl;
  645. addObject.version = [[NCManageDatabase sharedInstance] getEndToEndEncryptionVersionWithAccount:tableAccount.account];
  646. // Get the last metadata
  647. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", tableAccount.account, metadata.serverUrl]];
  648. error = [[NCNetworkingEndToEnd sharedManager] getEndToEndMetadata:&e2eeMetadata ocId:directory.ocId user:tableAccount.user userID:tableAccount.userID password: [CCUtility getPassword:tableAccount.account] url:tableAccount.url];
  649. if (error == nil) {
  650. if ([[NCEndToEndMetadata sharedInstance] decoderMetadata:e2eeMetadata privateKey:[CCUtility getEndToEndPrivateKey:tableAccount.account] serverUrl:metadata.serverUrl account:tableAccount.account url:tableAccount.url] == false) {
  651. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:ocId:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  652. [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];
  653. }
  654. return;
  655. }
  656. }
  657. // write new record e2ee
  658. if([[NCManageDatabase sharedInstance] addE2eEncryption:addObject] == NO) {
  659. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:ocId:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  660. [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];
  661. }
  662. return;
  663. }
  664. } else {
  665. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:ocId:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  666. [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];
  667. }
  668. return;
  669. }
  670. dispatch_async(dispatch_get_main_queue(), ^{
  671. // Now the fileName is fileNameIdentifier && flag e2eEncrypted
  672. metadata.fileName = fileNameIdentifier;
  673. metadata.e2eEncrypted = YES;
  674. // Update Metadata
  675. tableMetadata *metadataEncrypted = [[NCManageDatabase sharedInstance] addMetadata:metadata];
  676. [self uploadURLSessionMetadata:metadataEncrypted tableAccount:tableAccount taskStatus:taskStatus];
  677. });
  678. });
  679. }
  680. - (void)uploadURLSessionMetadata:(tableMetadata *)metadata tableAccount:(tableAccount *)tableAccount taskStatus:(NSInteger)taskStatus
  681. {
  682. NSURL *url;
  683. NSMutableURLRequest *request;
  684. PHAsset *asset;
  685. NSError *error;
  686. // calculate and store file size
  687. NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:[CCUtility getDirectoryProviderStorageOcId:metadata.ocId fileNameView:metadata.fileName] error:&error];
  688. long long fileSize = [[fileAttributes objectForKey:NSFileSize] longLongValue];
  689. metadata.size = fileSize;
  690. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  691. url = [NSURL URLWithString:[[NSString stringWithFormat:@"%@/%@", metadata.serverUrl, metadata.fileName] encodeString:NSUTF8StringEncoding]];
  692. request = [NSMutableURLRequest requestWithURL:url];
  693. NSData *authData = [[NSString stringWithFormat:@"%@:%@", tableAccount.user, [CCUtility getPassword:tableAccount.account]] dataUsingEncoding:NSUTF8StringEncoding];
  694. NSString *authValue = [NSString stringWithFormat: @"Basic %@",[authData base64EncodedStringWithOptions:0]];
  695. [request setHTTPMethod:@"PUT"];
  696. [request setValue:authValue forHTTPHeaderField:@"Authorization"];
  697. [request setValue:[CCUtility getUserAgent] forHTTPHeaderField:@"User-Agent"];
  698. // Create Image for Upload (gray scale)
  699. #ifndef EXTENSION
  700. [CCGraphics createNewImageFrom:metadata.fileNameView ocId:metadata.ocId extension:[metadata.fileNameView pathExtension] filterGrayScale:YES typeFile:metadata.typeFile writeImage:YES];
  701. #endif
  702. // Change date file upload with header : X-OC-Mtime (ctime assetLocalIdentifier) image/video
  703. if (metadata.assetLocalIdentifier) {
  704. PHFetchResult *result = [PHAsset fetchAssetsWithLocalIdentifiers:@[metadata.assetLocalIdentifier] options:nil];
  705. if (result.count) {
  706. asset = result[0];
  707. long dateFileCreation = [asset.creationDate timeIntervalSince1970];
  708. [request setValue:[NSString stringWithFormat:@"%ld", dateFileCreation] forHTTPHeaderField:@"X-OC-Mtime"];
  709. }
  710. }
  711. NSURLSession *sessionUpload;
  712. // NSURLSession
  713. if ([metadata.session isEqualToString:k_upload_session]) sessionUpload = [self sessionUpload];
  714. else if ([metadata.session isEqualToString:k_upload_session_wwan]) sessionUpload = [self sessionWWanUpload];
  715. else if ([metadata.session isEqualToString:k_upload_session_foreground]) sessionUpload = [self sessionUploadForeground];
  716. else if ([metadata.session isEqualToString:k_upload_session_extension]) sessionUpload = [self sessionUploadExtension];
  717. NSURLSessionUploadTask *uploadTask = [sessionUpload uploadTaskWithRequest:request fromFile:[NSURL fileURLWithPath:[CCUtility getDirectoryProviderStorageOcId:metadata.ocId fileNameView:metadata.fileName]]];
  718. // Error
  719. if (uploadTask == nil) {
  720. NSString *messageError = @"Serious internal error uploadTask not available";
  721. [[NCManageDatabase sharedInstance] setMetadataSession:metadata.session sessionError:messageError sessionSelector:nil sessionTaskIdentifier:k_taskIdentifierDone status:k_metadataStatusUploadError predicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadata.ocId]];
  722. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:ocId:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  723. [self.delegate uploadFileSuccessFailure:metadata.fileNameView ocId:metadata.ocId assetLocalIdentifier:metadata.assetLocalIdentifier serverUrl:metadata.serverUrl selector:metadata.sessionSelector errorMessage:messageError errorCode:k_CCErrorInternalError];
  724. }
  725. } else {
  726. // E2EE : CREATE AND SEND METADATA
  727. if ([CCUtility isFolderEncrypted:metadata.serverUrl account:tableAccount.account] && [CCUtility isEndToEndEnabled:tableAccount.account]) {
  728. NSString *serverUrl = metadata.serverUrl;
  729. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  730. // Send Metadata
  731. 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];
  732. dispatch_async(dispatch_get_main_queue(), ^{
  733. if (error) {
  734. [uploadTask cancel];
  735. NSString *messageError = [NSString stringWithFormat:@"%@ (%d)", error.localizedDescription, (int)error.code];
  736. [[NCManageDatabase sharedInstance] setMetadataSession:metadata.session sessionError:messageError sessionSelector:nil sessionTaskIdentifier:k_taskIdentifierDone status:k_metadataStatusUploadError predicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadata.ocId]];
  737. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:ocId:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  738. [self.delegate uploadFileSuccessFailure:metadata.fileNameView ocId:metadata.ocId assetLocalIdentifier:metadata.assetLocalIdentifier serverUrl:metadata.serverUrl selector:metadata.sessionSelector errorMessage:messageError errorCode:k_CCErrorInternalError];
  739. }
  740. } else {
  741. // Manage uploadTask cancel,suspend,resume
  742. if (taskStatus == k_taskStatusCancel) [uploadTask cancel];
  743. else if (taskStatus == k_taskStatusSuspend) [uploadTask suspend];
  744. else if (taskStatus == k_taskStatusResume) [uploadTask resume];
  745. // *** E2EE ***
  746. [[NCManageDatabase sharedInstance] setMetadataSession:metadata.session sessionError:@"" sessionSelector:nil sessionTaskIdentifier:uploadTask.taskIdentifier status:k_metadataStatusUploading predicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadata.ocId]];
  747. NSLog(@"[LOG] Upload file %@ TaskIdentifier %lu", metadata.fileName, (unsigned long)uploadTask.taskIdentifier);
  748. NSString *ocId = metadata.ocId;
  749. NSString *account = metadata.account;
  750. dispatch_async(dispatch_get_main_queue(), ^{
  751. if ([self.delegate respondsToSelector:@selector(uploadStart:account:task:serverUrl:)]) {
  752. [self.delegate uploadStart:ocId account:account task:uploadTask serverUrl:metadata.serverUrl];
  753. }
  754. });
  755. }
  756. });
  757. });
  758. } else {
  759. // Manage uploadTask cancel,suspend,resume
  760. if (taskStatus == k_taskStatusCancel) [uploadTask cancel];
  761. else if (taskStatus == k_taskStatusSuspend) [uploadTask suspend];
  762. else if (taskStatus == k_taskStatusResume) [uploadTask resume];
  763. // *** PLAIN ***
  764. [[NCManageDatabase sharedInstance] setMetadataSession:metadata.session sessionError:@"" sessionSelector:nil sessionTaskIdentifier:uploadTask.taskIdentifier status:k_metadataStatusUploading predicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadata.ocId]];
  765. NSLog(@"[LOG] Upload file %@ TaskIdentifier %lu", metadata.fileName, (unsigned long)uploadTask.taskIdentifier);
  766. NSString *ocId = metadata.ocId;
  767. NSString *account = metadata.account;
  768. NSString *serverUrl = metadata.serverUrl;
  769. dispatch_async(dispatch_get_main_queue(), ^{
  770. if ([self.delegate respondsToSelector:@selector(uploadStart:account:task:serverUrl:)]) {
  771. [self.delegate uploadStart:ocId account:account task:uploadTask serverUrl:serverUrl];
  772. }
  773. });
  774. }
  775. }
  776. }
  777. - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
  778. {
  779. }
  780. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend
  781. {
  782. NSString *url = [[[task currentRequest].URL absoluteString] stringByRemovingPercentEncoding];
  783. NSString *fileName = [url lastPathComponent];
  784. NSString *serverUrl = [self getServerUrlFromUrl:url];
  785. if (!serverUrl) return;
  786. if (totalBytesExpectedToSend < 1) {
  787. totalBytesExpectedToSend = totalBytesSent;
  788. }
  789. float progress = (float) totalBytesSent / (float)totalBytesExpectedToSend;
  790. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataInSessionFromFileName:fileName serverUrl:serverUrl taskIdentifier:task.taskIdentifier];
  791. if (metadata) {
  792. 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])};
  793. if (userInfo)
  794. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"NotificationProgressTask" object:nil userInfo:userInfo];
  795. }
  796. }
  797. - (void)uploadFileSuccessFailure:(tableMetadata *)metadata fileName:(NSString *)fileName ocId:(NSString *)ocId etag:(NSString *)etag date:(NSDate *)date serverUrl:(NSString *)serverUrl errorCode:(NSInteger)errorCode
  798. {
  799. NSString *tempocId = metadata.ocId;
  800. NSString *tempSession = metadata.session;
  801. NSString *errorMessage = @"";
  802. BOOL isE2EEDirectory = false;
  803. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", metadata.account]];
  804. if (tableAccount == nil) {
  805. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", tempocId]];
  806. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:ocId:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  807. [self.delegate uploadFileSuccessFailure:metadata.fileName ocId:metadata.ocId assetLocalIdentifier:metadata.assetLocalIdentifier serverUrl:serverUrl selector:metadata.sessionSelector errorMessage:errorMessage errorCode:errorCode];
  808. }
  809. return;
  810. }
  811. // is this a E2EE Directory ?
  812. if ([CCUtility isFolderEncrypted:serverUrl account:tableAccount.account] && [CCUtility isEndToEndEnabled:tableAccount.account]) {
  813. isE2EEDirectory = true;
  814. }
  815. // ERRORE
  816. if (errorCode != 0) {
  817. #ifndef EXTENSION
  818. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  819. [appDelegate.listProgressMetadata removeObjectForKey:metadata.ocId];
  820. #endif
  821. // Mark error only if not Cancelled Task
  822. if (errorCode == kCFURLErrorCancelled) {
  823. if (metadata.status == k_metadataStatusUploadForcedStart) {
  824. errorCode = 0;
  825. metadata.session = k_upload_session;
  826. metadata.sessionError = @"";
  827. metadata.sessionTaskIdentifier = 0;
  828. metadata.status = k_metadataStatusInUpload;
  829. metadata = [[NCManageDatabase sharedInstance] addMetadata:metadata];
  830. [[CCNetworking sharedNetworking] uploadFile:metadata taskStatus:k_taskStatusResume];
  831. } else {
  832. [[NSFileManager defaultManager] removeItemAtPath:[CCUtility getDirectoryProviderStorageOcId:tempocId] error:nil];
  833. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", tempocId]];
  834. errorMessage = [CCError manageErrorKCF:errorCode withNumberError:YES];
  835. }
  836. } else {
  837. if (metadata && (errorCode == kOCErrorServerUnauthorized || errorCode == kOCErrorServerForbidden))
  838. [[OCNetworking sharedManager] checkRemoteUser:metadata.account function:@"upload" errorCode:errorCode];
  839. else if (metadata && errorCode == NSURLErrorServerCertificateUntrusted)
  840. [CCUtility setCertificateError:metadata.account error:YES];
  841. [[NCManageDatabase sharedInstance] setMetadataSession:nil sessionError:[CCError manageErrorKCF:errorCode withNumberError:NO] sessionSelector:nil sessionTaskIdentifier:k_taskIdentifierDone status:k_metadataStatusUploadError predicate:[NSPredicate predicateWithFormat:@"ocId == %@", tempocId]];
  842. errorMessage = [CCError manageErrorKCF:errorCode withNumberError:YES];
  843. }
  844. } else {
  845. // Edited file, remove tempocId and adjust the directory provider storage
  846. if (metadata.edited) {
  847. // Update metadata tempocId
  848. [[NCManageDatabase sharedInstance] setMetadataSession:@"" sessionError:@"" sessionSelector:@"" sessionTaskIdentifier:k_taskIdentifierDone status:k_metadataStatusNormal predicate:[NSPredicate predicateWithFormat:@"ocId == %@", tempocId]];
  849. // Add metadata ocId
  850. metadata.date = date;
  851. if (isE2EEDirectory) {
  852. metadata.e2eEncrypted = true;
  853. } else {
  854. metadata.e2eEncrypted = false;
  855. }
  856. metadata.etag = etag;
  857. metadata.ocId = ocId;
  858. metadata.session = @"";
  859. metadata.sessionError = @"";
  860. metadata.sessionTaskIdentifier = k_taskIdentifierDone;
  861. metadata.status = k_metadataStatusNormal;
  862. metadata = [[NCManageDatabase sharedInstance] addMetadata:metadata];
  863. // Copy new version on old version
  864. if (![tempocId isEqualToString:metadata.ocId]) {
  865. [CCUtility copyFileAtPath:[NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryProviderStorage], tempocId] toPath:[NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryProviderStorage], metadata.ocId]];
  866. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", tempocId]];
  867. // IMI -> Unzip
  868. #if HC
  869. if ([metadata.typeFile isEqualToString:k_metadataTypeFile_imagemeter]) {
  870. (void)[[IMUtility shared] IMUnzipWithMetadata:metadata];
  871. }
  872. #endif
  873. }
  874. } else {
  875. // Replace Metadata
  876. metadata.date = date;
  877. if (isE2EEDirectory) {
  878. metadata.e2eEncrypted = true;
  879. } else {
  880. metadata.e2eEncrypted = false;
  881. }
  882. metadata.etag = etag;
  883. metadata.ocId = ocId;
  884. metadata.session = @"";
  885. metadata.sessionError = @"";
  886. metadata.sessionTaskIdentifier = k_taskIdentifierDone;
  887. metadata.status = k_metadataStatusNormal;
  888. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@ AND fileName == %@", metadata.account, metadata.serverUrl, metadata.fileName]];
  889. metadata = [[NCManageDatabase sharedInstance] addMetadata:metadata];
  890. NSLog(@"[LOG] Insert new upload : %@ - ocId : %@", metadata.fileName, ocId);
  891. if ([tempocId isEqualToString:[CCUtility createMetadataIDFromAccount:metadata.account serverUrl:metadata.serverUrl fileNameView:metadata.fileNameView directory:metadata.directory]]) {
  892. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", tempocId]];
  893. // adjust file system Directory Provider Storage
  894. if ([tempSession isEqualToString:k_upload_session_extension]) {
  895. // this is for File Provider Extension [Apple Works and ... ?]
  896. [CCUtility copyFileAtPath:[NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryProviderStorage], tempocId] toPath:[NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryProviderStorage], metadata.ocId]];
  897. } else {
  898. [CCUtility moveFileAtPath:[NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryProviderStorage], tempocId] toPath:[NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryProviderStorage], metadata.ocId]];
  899. }
  900. }
  901. }
  902. #ifndef EXTENSION
  903. // EXIF
  904. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image])
  905. [[CCExifGeo sharedInstance] setExifLocalTableEtag:metadata];
  906. // Create preview
  907. [CCGraphics createNewImageFrom:metadata.fileNameView ocId:metadata.ocId extension:[metadata.fileNameView pathExtension] filterGrayScale:NO typeFile:metadata.typeFile writeImage:YES];
  908. // Copy photo or video in the photo album for auto upload
  909. if ([metadata.assetLocalIdentifier length] > 0 && ([metadata.sessionSelector isEqualToString:selectorUploadAutoUpload] || [metadata.sessionSelector isEqualToString:selectorUploadFile])) {
  910. PHAsset *asset;
  911. PHFetchResult *result = [PHAsset fetchAssetsWithLocalIdentifiers:@[metadata.assetLocalIdentifier] options:nil];
  912. if(result.count){
  913. asset = result[0];
  914. [asset saveToAlbum:[NCBrandOptions sharedInstance].brand completionBlock:^(BOOL success) {
  915. if (success) NSLog(@"[LOG] Insert file %@ in %@", metadata.fileName, [NCBrandOptions sharedInstance].brand);
  916. else NSLog(@"[LOG] File %@ do not insert in %@", metadata.fileName, [NCBrandOptions sharedInstance].brand);
  917. }];
  918. }
  919. }
  920. #endif
  921. // Add Local or Remove from cache
  922. if ([CCUtility getDisableLocalCacheAfterUpload] && !metadata.edited) {
  923. [[NSFileManager defaultManager] removeItemAtPath:[CCUtility getDirectoryProviderStorageOcId:metadata.ocId] error:nil];
  924. } else {
  925. // Add Local
  926. (void)[[NCManageDatabase sharedInstance] addLocalFileWithMetadata:metadata];
  927. }
  928. }
  929. // Detect E2EE
  930. 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]];
  931. // E2EE : UNLOCK
  932. if (isE2EEDirectory && e2eeMetadataInSession == nil) {
  933. tableE2eEncryptionLock *tableLock = [[NCManageDatabase sharedInstance] getE2ETokenLockWithServerUrl:serverUrl];
  934. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  935. if (tableLock) {
  936. 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];
  937. if (error) {
  938. [[NCContentPresenter shared] messageNotification:@"_e2e_error_unlock_" description:error.localizedDescription delay:k_dismissAfterSecond type:messageTypeError errorCode:error.code];
  939. }
  940. } else {
  941. NSLog(@"Error unlock not found");
  942. }
  943. dispatch_async(dispatch_get_main_queue(), ^{
  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. } else {
  950. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:ocId:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  951. [self.delegate uploadFileSuccessFailure:metadata.fileName ocId:metadata.ocId assetLocalIdentifier:metadata.assetLocalIdentifier serverUrl:serverUrl selector:metadata.sessionSelector errorMessage:errorMessage errorCode:errorCode];
  952. }
  953. }
  954. // NSNotificationCenter
  955. NSDictionary* userInfo = @{@"metadata": metadata, @"errorCode": @(errorCode)};
  956. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_uploadFile object:nil userInfo:userInfo];
  957. }
  958. #pragma --------------------------------------------------------------------------------------------
  959. #pragma mark ===== Utility =====
  960. #pragma --------------------------------------------------------------------------------------------
  961. - (NSString *)getServerUrlFromUrl:(NSString *)url
  962. {
  963. NSString *fileName = [url lastPathComponent];
  964. url = [url stringByReplacingOccurrencesOfString:[@"/" stringByAppendingString:fileName] withString:@""];
  965. return url;
  966. }
  967. @end