CCNetworking.m 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060
  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 "AppDelegate.h"
  26. #import "NSDate+ISO8601.h"
  27. #import "NSString+Encode.h"
  28. #import "NCBridgeSwift.h"
  29. @interface CCNetworking ()
  30. {
  31. }
  32. @end
  33. @implementation CCNetworking
  34. + (CCNetworking *)sharedNetworking {
  35. static CCNetworking *sharedNetworking;
  36. @synchronized(self)
  37. {
  38. if (!sharedNetworking) {
  39. sharedNetworking = [[CCNetworking alloc] init];
  40. }
  41. return sharedNetworking;
  42. }
  43. }
  44. - (id)init
  45. {
  46. self = [super init];
  47. // Initialization Sessions
  48. [self sessionDownload];
  49. [self sessionDownloadForeground];
  50. [self sessionWWanDownload];
  51. [self sessionUpload];
  52. [self sessionWWanUpload];
  53. [self sessionUploadForeground];
  54. return self;
  55. }
  56. #pragma --------------------------------------------------------------------------------------------
  57. #pragma mark ===== Session =====
  58. #pragma --------------------------------------------------------------------------------------------
  59. - (NSURLSession *)sessionDownload
  60. {
  61. static NSURLSession *sessionDownload = nil;
  62. if (sessionDownload == nil) {
  63. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:k_download_session];
  64. configuration.allowsCellularAccess = YES;
  65. configuration.sessionSendsLaunchEvents = YES;
  66. configuration.discretionary = NO;
  67. configuration.HTTPMaximumConnectionsPerHost = k_maxHTTPConnectionsPerHost;
  68. configuration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  69. sessionDownload = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
  70. sessionDownload.sessionDescription = k_download_session;
  71. }
  72. return sessionDownload;
  73. }
  74. - (NSURLSession *)sessionDownloadForeground
  75. {
  76. static NSURLSession *sessionDownloadForeground = nil;
  77. if (sessionDownloadForeground == nil) {
  78. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
  79. configuration.allowsCellularAccess = YES;
  80. configuration.discretionary = NO;
  81. configuration.HTTPMaximumConnectionsPerHost = k_maxHTTPConnectionsPerHost;
  82. configuration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  83. sessionDownloadForeground = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
  84. sessionDownloadForeground.sessionDescription = k_download_session_foreground;
  85. }
  86. return sessionDownloadForeground;
  87. }
  88. - (NSURLSession *)sessionWWanDownload
  89. {
  90. static NSURLSession *sessionWWanDownload = nil;
  91. if (sessionWWanDownload == nil) {
  92. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:k_download_session_wwan];
  93. configuration.allowsCellularAccess = NO;
  94. configuration.sessionSendsLaunchEvents = YES;
  95. configuration.discretionary = NO;
  96. configuration.HTTPMaximumConnectionsPerHost = k_maxHTTPConnectionsPerHost;
  97. configuration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  98. sessionWWanDownload = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
  99. sessionWWanDownload.sessionDescription = k_download_session_wwan;
  100. }
  101. return sessionWWanDownload;
  102. }
  103. - (NSURLSession *)sessionUpload
  104. {
  105. static NSURLSession *sessionUpload = nil;
  106. if (sessionUpload == nil) {
  107. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:k_upload_session];
  108. configuration.allowsCellularAccess = YES;
  109. configuration.sessionSendsLaunchEvents = YES;
  110. configuration.discretionary = NO;
  111. configuration.HTTPMaximumConnectionsPerHost = k_maxHTTPConnectionsPerHost;
  112. configuration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  113. sessionUpload = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
  114. sessionUpload.sessionDescription = k_upload_session;
  115. }
  116. return sessionUpload;
  117. }
  118. - (NSURLSession *)sessionWWanUpload
  119. {
  120. static NSURLSession *sessionWWanUpload = nil;
  121. if (sessionWWanUpload == nil) {
  122. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:k_upload_session_wwan];
  123. configuration.allowsCellularAccess = NO;
  124. configuration.sessionSendsLaunchEvents = YES;
  125. configuration.discretionary = NO;
  126. configuration.HTTPMaximumConnectionsPerHost = k_maxHTTPConnectionsPerHost;
  127. configuration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  128. sessionWWanUpload = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
  129. sessionWWanUpload.sessionDescription = k_upload_session_wwan;
  130. }
  131. return sessionWWanUpload;
  132. }
  133. - (NSURLSession *)sessionUploadForeground
  134. {
  135. static NSURLSession *sessionUploadForeground;
  136. if (sessionUploadForeground == nil) {
  137. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
  138. configuration.allowsCellularAccess = YES;
  139. configuration.discretionary = NO;
  140. configuration.HTTPMaximumConnectionsPerHost = k_maxHTTPConnectionsPerHost;
  141. configuration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  142. sessionUploadForeground = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
  143. sessionUploadForeground.sessionDescription = k_upload_session_foreground;
  144. }
  145. return sessionUploadForeground;
  146. }
  147. - (NSURLSession *)sessionUploadExtension
  148. {
  149. static NSURLSession *sessionUpload = nil;
  150. if (sessionUpload == nil) {
  151. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:k_upload_session_extension];
  152. configuration.allowsCellularAccess = YES;
  153. configuration.sessionSendsLaunchEvents = YES;
  154. configuration.discretionary = NO;
  155. configuration.HTTPMaximumConnectionsPerHost = 1;
  156. configuration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  157. configuration.sharedContainerIdentifier = [NCBrandOptions sharedInstance].capabilitiesGroups;
  158. sessionUpload = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
  159. sessionUpload.sessionDescription = k_upload_session_extension;
  160. }
  161. return sessionUpload;
  162. }
  163. - (NSURLSession *)getSessionfromSessionDescription:(NSString *)sessionDescription
  164. {
  165. if ([sessionDescription isEqualToString:k_download_session]) return [self sessionDownload];
  166. if ([sessionDescription isEqualToString:k_download_session_foreground]) return [self sessionDownloadForeground];
  167. if ([sessionDescription isEqualToString:k_download_session_wwan]) return [self sessionWWanDownload];
  168. if ([sessionDescription isEqualToString:k_upload_session]) return [self sessionUpload];
  169. if ([sessionDescription isEqualToString:k_upload_session_wwan]) return [self sessionWWanUpload];
  170. if ([sessionDescription isEqualToString:k_upload_session_foreground]) return [self sessionUploadForeground];
  171. if ([sessionDescription isEqualToString:k_upload_session_extension]) return [self sessionUploadExtension];
  172. return nil;
  173. }
  174. - (void)invalidateAndCancelAllSession
  175. {
  176. [[self sessionDownload] invalidateAndCancel];
  177. [[self sessionDownloadForeground] invalidateAndCancel];
  178. [[self sessionWWanDownload] invalidateAndCancel];
  179. [[self sessionUpload] invalidateAndCancel];
  180. [[self sessionWWanUpload] invalidateAndCancel];
  181. [[self sessionUploadForeground] invalidateAndCancel];
  182. }
  183. #pragma --------------------------------------------------------------------------------------------
  184. #pragma mark ===== URLSession download/upload =====
  185. #pragma --------------------------------------------------------------------------------------------
  186. - (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler
  187. {
  188. // The pinnning check
  189. if ([[NCNetworking shared] checkTrustedChallengeWithChallenge:challenge directoryCertificate:[CCUtility getDirectoryCerificates]]) {
  190. completionHandler(NSURLSessionAuthChallengeUseCredential, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]);
  191. } else {
  192. completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
  193. }
  194. }
  195. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
  196. {
  197. NSString *url = [[[task currentRequest].URL absoluteString] stringByRemovingPercentEncoding];
  198. if (!url)
  199. return;
  200. NSString *fileName = [url lastPathComponent];
  201. NSString *serverUrl = [self getServerUrlFromUrl:url];
  202. if (!serverUrl) return;
  203. NSInteger errorCode;
  204. NSDate *date = [NSDate date];
  205. NSDateFormatter *dateFormatter = [NSDateFormatter new];
  206. NSLocale *enUSPOSIXLocale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
  207. [dateFormatter setLocale:enUSPOSIXLocale];
  208. [dateFormatter setDateFormat:@"EEE, dd MMM y HH:mm:ss zzz"];
  209. NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)task.response;
  210. if (httpResponse.statusCode >= 200 && httpResponse.statusCode < 300) {
  211. errorCode = error.code;
  212. } else {
  213. if (httpResponse.statusCode > 0)
  214. errorCode = httpResponse.statusCode;
  215. else
  216. errorCode = error.code;
  217. }
  218. // ----------------------- DOWNLOAD -----------------------
  219. if ([task isKindOfClass:[NSURLSessionDownloadTask class]]) {
  220. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataInSessionFromFileName:fileName serverUrl:serverUrl taskIdentifier:task.taskIdentifier];
  221. if (metadata) {
  222. NSString *etag = metadata.etag;
  223. //NSString *ocId = metadata.ocId;
  224. NSDictionary *fields = [httpResponse allHeaderFields];
  225. if (errorCode == 0) {
  226. if ([CCUtility removeForbiddenCharactersFileSystem:[fields objectForKey:@"OC-ETag"]] != nil) {
  227. etag = [CCUtility removeForbiddenCharactersFileSystem:[fields objectForKey:@"OC-ETag"]];
  228. } else if ([CCUtility removeForbiddenCharactersFileSystem:[fields objectForKey:@"ETag"]] != nil) {
  229. etag = [CCUtility removeForbiddenCharactersFileSystem:[fields objectForKey:@"ETag"]];
  230. }
  231. NSString *dateString = [fields objectForKey:@"Date"];
  232. if (dateString) {
  233. if (![dateFormatter getObjectValue:&date forString:dateString range:nil error:&error]) {
  234. date = [NSDate date];
  235. }
  236. } else {
  237. date = [NSDate date];
  238. }
  239. }
  240. if (fileName.length > 0 && serverUrl.length > 0) {
  241. dispatch_async(dispatch_get_main_queue(), ^{
  242. [self downloadFileSuccessFailure:fileName ocId:metadata.ocId etag:etag date:date serverUrl:serverUrl selector:metadata.sessionSelector errorCode:errorCode];
  243. });
  244. }
  245. }
  246. }
  247. // ------------------------ UPLOAD -----------------------
  248. if ([task isKindOfClass:[NSURLSessionUploadTask class]]) {
  249. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataInSessionFromFileName:fileName serverUrl:serverUrl taskIdentifier:task.taskIdentifier];
  250. if (metadata) {
  251. NSDictionary *fields = [httpResponse allHeaderFields];
  252. NSString *ocId = metadata.ocId;
  253. NSString *etag = metadata.etag;
  254. if (errorCode == 0) {
  255. if ([CCUtility removeForbiddenCharactersFileSystem:[fields objectForKey:@"OC-FileId"]] != nil) {
  256. ocId = [CCUtility removeForbiddenCharactersFileSystem:[fields objectForKey:@"OC-FileId"]];
  257. } else if ([CCUtility removeForbiddenCharactersFileSystem:[fields objectForKey:@"FileId"]] != nil) {
  258. ocId = [CCUtility removeForbiddenCharactersFileSystem:[fields objectForKey:@"FileId"]];
  259. }
  260. if ([CCUtility removeForbiddenCharactersFileSystem:[fields objectForKey:@"OC-ETag"]] != nil) {
  261. etag = [CCUtility removeForbiddenCharactersFileSystem:[fields objectForKey:@"OC-ETag"]];
  262. } else if ([CCUtility removeForbiddenCharactersFileSystem:[fields objectForKey:@"ETag"]] != nil) {
  263. etag = [CCUtility removeForbiddenCharactersFileSystem:[fields objectForKey:@"ETag"]];
  264. }
  265. NSString *dateString = [fields objectForKey:@"Date"];
  266. if (dateString) {
  267. if (![dateFormatter getObjectValue:&date forString:dateString range:nil error:&error]) {
  268. NSLog(@"[LOG] Date '%@' could not be parsed: %@", dateString, error);
  269. date = [NSDate date];
  270. }
  271. } else {
  272. date = [NSDate date];
  273. }
  274. }
  275. if (fileName.length > 0 && ocId.length > 0 && serverUrl.length > 0) {
  276. dispatch_async(dispatch_get_main_queue(), ^{
  277. [self uploadFileSuccessFailure:metadata fileName:fileName ocId:ocId etag:etag date:date serverUrl:serverUrl errorCode:errorCode];
  278. });
  279. }
  280. }
  281. }
  282. }
  283. #pragma --------------------------------------------------------------------------------------------
  284. #pragma mark ===== Download =====
  285. #pragma --------------------------------------------------------------------------------------------
  286. - (void)downloadFile:(tableMetadata *)metadata taskStatus:(NSInteger)taskStatus
  287. {
  288. // No Password
  289. if ([CCUtility getPassword:metadata.account].length == 0) {
  290. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_downloadedFile object:nil userInfo:@{@"metadata": metadata, @"selector": metadata.sessionSelector, @"errorCode": @(kOCErrorServerUnauthorized), @"errorDescription": @"_bad_username_password_"}];
  291. return;
  292. } else if ([CCUtility getCertificateError:metadata.account]) {
  293. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_downloadedFile object:nil userInfo:@{@"metadata": metadata, @"selector": metadata.sessionSelector, @"errorCode": @(NSURLErrorServerCertificateUntrusted), @"errorDescription": @"_ssl_certificate_untrusted_"}];
  294. return;
  295. }
  296. // File exists ?
  297. tableLocalFile *localfile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadata.ocId]];
  298. if (localfile != nil && [CCUtility fileProviderStorageExists:metadata.ocId fileNameView:metadata.fileNameView]) {
  299. [[NCManageDatabase sharedInstance] setMetadataSession:@"" sessionError:@"" sessionSelector:@"" sessionTaskIdentifier:k_taskIdentifierDone status:k_metadataStatusNormal predicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadata.ocId]];
  300. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_downloadedFile object:nil userInfo:@{@"metadata": metadata, @"selector": metadata.sessionSelector, @"errorCode": @(0), @"errorDescription": @""}];
  301. return;
  302. }
  303. [self downloaURLSession:metadata taskStatus:taskStatus];
  304. }
  305. - (void)downloaURLSession:(tableMetadata *)metadata taskStatus:(NSInteger)taskStatus
  306. {
  307. NSURLSession *sessionDownload;
  308. NSURL *url;
  309. NSMutableURLRequest *request;
  310. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", metadata.account]];
  311. if (tableAccount == nil) {
  312. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadata.ocId]];
  313. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_downloadedFile object:nil userInfo:@{@"metadata": metadata, @"selector": metadata.sessionSelector, @"errorCode": @(k_CCErrorInternalError), @"errorDescription": @"Download error, account not found"}];
  314. return;
  315. }
  316. NSString *serverFileUrl = [[NSString stringWithFormat:@"%@/%@", metadata.serverUrl, metadata.fileName] encodeString:NSUTF8StringEncoding];
  317. url = [NSURL URLWithString:serverFileUrl];
  318. request = [NSMutableURLRequest requestWithURL:url];
  319. NSData *authData = [[NSString stringWithFormat:@"%@:%@", tableAccount.user, [CCUtility getPassword:tableAccount.account]] dataUsingEncoding:NSUTF8StringEncoding];
  320. NSString *authValue = [NSString stringWithFormat: @"Basic %@",[authData base64EncodedStringWithOptions:0]];
  321. [request setValue:authValue forHTTPHeaderField:@"Authorization"];
  322. [request setValue:[CCUtility getUserAgent] forHTTPHeaderField:@"User-Agent"];
  323. if ([metadata.session isEqualToString:k_download_session]) sessionDownload = [self sessionDownload];
  324. else if ([metadata.session isEqualToString:k_download_session_foreground]) sessionDownload = [self sessionDownloadForeground];
  325. else if ([metadata.session isEqualToString:k_download_session_wwan]) sessionDownload = [self sessionWWanDownload];
  326. NSURLSessionDownloadTask *downloadTask = [sessionDownload downloadTaskWithRequest:request];
  327. if (downloadTask == nil) {
  328. [[NCManageDatabase sharedInstance] setMetadataSession:nil sessionError:NSLocalizedString(@"_not_possible_download_", nil) sessionSelector:nil sessionTaskIdentifier:k_taskIdentifierDone status:k_metadataStatusDownloadError predicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadata.ocId]];
  329. NSString *errorDescription = [NSString stringWithFormat:@"%@ %@", NSLocalizedString(@"_not_possible_download_", nil), metadata.fileNameView];
  330. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_downloadedFile object:nil userInfo:@{@"metadata": metadata, @"selector": metadata.sessionSelector, @"errorCode": @(k_CCErrorInternalError), @"errorDescription": errorDescription}];
  331. } else {
  332. // Manage uploadTask cancel,suspend,resume
  333. if (taskStatus == k_taskStatusCancel) [downloadTask cancel];
  334. else if (taskStatus == k_taskStatusSuspend) [downloadTask suspend];
  335. else if (taskStatus == k_taskStatusResume) [downloadTask resume];
  336. [[NCManageDatabase sharedInstance] setMetadataSession:nil sessionError:nil sessionSelector:nil sessionTaskIdentifier:downloadTask.taskIdentifier status:k_metadataStatusDownloading predicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadata.ocId]];
  337. NSLog(@"[LOG] downloadFileSession %@ Task [%lu]", metadata.ocId, (unsigned long)downloadTask.taskIdentifier);
  338. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_downloadFileStart object:nil userInfo:@{@"ocId": metadata.ocId, @"task": downloadTask, @"serverUrl": metadata.serverUrl, @"account": metadata.account}];
  339. }
  340. }
  341. - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
  342. {
  343. NSString *url = [[[downloadTask currentRequest].URL absoluteString] stringByRemovingPercentEncoding];
  344. NSString *fileName = [url lastPathComponent];
  345. NSString *serverUrl = [self getServerUrlFromUrl:url];
  346. if (!serverUrl) return;
  347. if (totalBytesExpectedToWrite < 1) {
  348. totalBytesExpectedToWrite = totalBytesWritten;
  349. }
  350. float progress = (float) totalBytesWritten / (float)totalBytesExpectedToWrite;
  351. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataInSessionFromFileName:fileName serverUrl:serverUrl taskIdentifier:downloadTask.taskIdentifier];
  352. if (metadata) {
  353. 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])};
  354. if (userInfo)
  355. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_progressTask object:nil userInfo:userInfo];
  356. } else {
  357. NSLog(@"[LOG] metadata not found");
  358. }
  359. }
  360. - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
  361. {
  362. NSString *url = [[[downloadTask currentRequest].URL absoluteString] stringByRemovingPercentEncoding];
  363. if (!url)
  364. return;
  365. NSString *fileName = [url lastPathComponent];
  366. NSString *serverUrl = [self getServerUrlFromUrl:url];
  367. if (!serverUrl) return;
  368. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataInSessionFromFileName:fileName serverUrl:serverUrl taskIdentifier:downloadTask.taskIdentifier];
  369. if (!metadata) {
  370. NSLog(@"[LOG] Serious error internal download : metadata not found %@ ", url);
  371. return;
  372. }
  373. NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)downloadTask.response;
  374. if (httpResponse.statusCode >= 200 && httpResponse.statusCode < 300) {
  375. NSString *destinationFilePath = [CCUtility getDirectoryProviderStorageOcId:metadata.ocId fileNameView:metadata.fileName];
  376. NSURL *destinationURL = [NSURL fileURLWithPath:destinationFilePath];
  377. [[NSFileManager defaultManager] removeItemAtURL:destinationURL error:NULL];
  378. [[NSFileManager defaultManager] copyItemAtURL:location toURL:destinationURL error:nil];
  379. }
  380. }
  381. - (void)downloadFileSuccessFailure:(NSString *)fileName ocId:(NSString *)ocId etag:(NSString *)etag date:(NSDate *)date serverUrl:(NSString *)serverUrl selector:(NSString *)selector errorCode:(NSInteger)errorCode
  382. {
  383. #ifndef EXTENSION
  384. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  385. [appDelegate.listProgressMetadata removeObjectForKey:ocId];
  386. #endif
  387. NSString *errorMessage = [CCError manageErrorKCF:errorCode withNumberError:YES];
  388. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", ocId]];
  389. if (errorCode != 0) {
  390. if (errorCode == kCFURLErrorCancelled) {
  391. [[NCManageDatabase sharedInstance] setMetadataSession:@"" sessionError:@"" sessionSelector:@"" sessionTaskIdentifier:k_taskIdentifierDone status:k_metadataStatusNormal predicate:[NSPredicate predicateWithFormat:@"ocId == %@", ocId]];
  392. } else {
  393. if (metadata && (errorCode == kOCErrorServerUnauthorized || errorCode == kOCErrorServerForbidden)) {
  394. #ifndef EXTENSION
  395. [[NCNetworkingCheckRemoteUser shared] checkRemoteUserWithAccount:metadata.account];
  396. #endif
  397. } else if (metadata && errorCode == NSURLErrorServerCertificateUntrusted) {
  398. [CCUtility setCertificateError:metadata.account error:YES];
  399. }
  400. [[NCManageDatabase sharedInstance] setMetadataSession:nil sessionError:[CCError manageErrorKCF:errorCode withNumberError:NO] sessionSelector:nil sessionTaskIdentifier:k_taskIdentifierDone status:k_metadataStatusDownloadError predicate:[NSPredicate predicateWithFormat:@"ocId == %@", ocId]];
  401. }
  402. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_downloadedFile object:nil userInfo:@{@"metadata": metadata, @"selector": selector, @"errorCode": @(errorCode), @"errorDescription": errorMessage}];
  403. } else {
  404. if (!metadata) {
  405. NSLog(@"[LOG] Serious error internal download : metadata not found %@ ", fileName);
  406. return;
  407. }
  408. metadata.session = @"";
  409. metadata.sessionError = @"";
  410. metadata.sessionSelector = @"";
  411. metadata.sessionTaskIdentifier = k_taskIdentifierDone;
  412. metadata.status = k_metadataStatusNormal;
  413. metadata = [[NCManageDatabase sharedInstance] updateMetadata:metadata];
  414. (void)[[NCManageDatabase sharedInstance] addLocalFileWithMetadata:metadata];
  415. // E2EE Decrypted
  416. tableE2eEncryption *object = [[NCManageDatabase sharedInstance] getE2eEncryptionWithPredicate:[NSPredicate predicateWithFormat:@"fileNameIdentifier == %@ AND serverUrl == %@", fileName, serverUrl]];
  417. if (object) {
  418. BOOL result = [[NCEndToEndEncryption sharedManager] decryptFileName:metadata.fileName fileNameView:metadata.fileNameView ocId:metadata.ocId key:object.key initializationVector:object.initializationVector authenticationTag:object.authenticationTag];
  419. if (!result) {
  420. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_downloadedFile object:nil userInfo:@{@"metadata": metadata, @"selector": selector, @"errorCode": @(k_CCErrorInternalError), @"errorDescription": [NSString stringWithFormat:@"Serious error internal download : decrypt error %@", fileName]}];
  421. return;
  422. }
  423. }
  424. // Exif
  425. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image])
  426. [[CCExifGeo sharedInstance] setExifLocalTableEtag:metadata];
  427. // Icon
  428. if ([[NSFileManager defaultManager] fileExistsAtPath:[CCUtility getDirectoryProviderStorageIconOcId:metadata.ocId fileNameView:metadata.fileNameView]] == NO) {
  429. [CCGraphics createNewImageFrom:metadata.fileNameView ocId:metadata.ocId filterGrayScale:NO typeFile:metadata.typeFile writeImage:YES];
  430. }
  431. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_downloadedFile object:nil userInfo:@{@"metadata": metadata, @"selector": selector, @"errorCode": @(0), @"errorDescription": @""}];
  432. }
  433. // NSNotificationCenter
  434. NSDictionary* userInfo = @{@"metadata": metadata, @"errorCode": @(errorCode), @"errorDescription": errorMessage};
  435. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_downloadedFile object:nil userInfo:userInfo];
  436. }
  437. #pragma --------------------------------------------------------------------------------------------
  438. #pragma mark ===== Upload =====
  439. #pragma --------------------------------------------------------------------------------------------
  440. - (void)uploadFile:(tableMetadata *)metadata taskStatus:(NSInteger)taskStatus
  441. {
  442. // Password nil
  443. if ([CCUtility getPassword:metadata.account].length == 0) {
  444. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_uploadedFile object:nil userInfo:@{@"metadata": metadata, @"errorCode": @(kOCErrorServerUnauthorized), @"errorDescription": @"_bad_username_password_"}];
  445. return;
  446. } else if ([CCUtility getCertificateError:metadata.account]) {
  447. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_uploadedFile object:nil userInfo:@{@"metadata": metadata, @"errorCode": @(NSURLErrorServerCertificateUntrusted), @"errorDescription": @"_ssl_certificate_untrusted_"}];
  448. return;
  449. }
  450. if ([CCUtility fileProviderStorageExists:metadata.ocId fileNameView:metadata.fileNameView] == NO) {
  451. [CCUtility extractImageVideoFromAssetLocalIdentifierForUpload:metadata notification:true completion:^(tableMetadata *newMetadata, NSString *fileNamePath) {
  452. if (newMetadata == nil) {
  453. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadata.ocId]];
  454. } else {
  455. NSString *toPath = [CCUtility getDirectoryProviderStorageOcId:newMetadata.ocId fileNameView:newMetadata.fileNameView];
  456. [CCUtility moveFileAtPath:fileNamePath toPath:toPath];
  457. tableMetadata *metadataForUpload = [[NCManageDatabase sharedInstance] addMetadata:newMetadata];
  458. if ([CCUtility isFolderEncrypted:metadataForUpload.serverUrl e2eEncrypted:metadataForUpload.e2eEncrypted account:metadataForUpload.account] && [CCUtility isEndToEndEnabled:metadataForUpload.account]) {
  459. [self e2eEncryptedFile:metadataForUpload taskStatus:taskStatus];
  460. } else {
  461. [self uploadURLSessionMetadata:metadataForUpload taskStatus:taskStatus];
  462. }
  463. }
  464. }];
  465. } else {
  466. NSDictionary *results = [[NCCommunicationCommon shared] objcGetInternalContenTypeWithFileName:metadata.fileNameView contentType:metadata.contentType directory:metadata.directory];
  467. metadata.contentType = results[@"contentType"];
  468. metadata.iconName = results[@"iconName"];
  469. metadata.typeFile = results[@"typeFile"];
  470. NSDictionary *attributes = [[NSFileManager defaultManager] attributesOfItemAtPath:[CCUtility getDirectoryProviderStorageOcId:metadata.ocId fileNameView:metadata.fileName] error:nil];
  471. if (attributes[NSFileModificationDate]) {
  472. metadata.date = attributes[NSFileModificationDate];
  473. } else {
  474. metadata.date = [NSDate date];
  475. }
  476. metadata.size = [attributes[NSFileSize] longValue];
  477. tableMetadata *metadataForUpload = [[NCManageDatabase sharedInstance] addMetadata:metadata];
  478. if ([CCUtility isFolderEncrypted:metadataForUpload.serverUrl e2eEncrypted:metadataForUpload.e2eEncrypted account:metadataForUpload.account] && [CCUtility isEndToEndEnabled:metadataForUpload.account]) {
  479. [self e2eEncryptedFile:metadataForUpload taskStatus:taskStatus];
  480. } else {
  481. [self uploadURLSessionMetadata:metadataForUpload taskStatus:taskStatus];
  482. }
  483. }
  484. }
  485. - (void)e2eEncryptedFile:(tableMetadata *)metadata taskStatus:(NSInteger)taskStatus
  486. {
  487. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", metadata.account]];
  488. if (tableAccount == nil) {
  489. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadata.ocId]];
  490. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_uploadedFile object:nil userInfo:@{@"metadata": metadata, @"errorCode": @(k_CCErrorInternalError), @"errorDescription": @"Upload error, account not found"}];
  491. return;
  492. }
  493. NSString *fileNameIdentifier;
  494. NSString *key;
  495. NSString *initializationVector;
  496. NSString *authenticationTag;
  497. NSString *metadataKey;
  498. NSInteger metadataKeyIndex;
  499. // Verify File Size
  500. NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:[CCUtility getDirectoryProviderStorageOcId:metadata.ocId fileNameView:metadata.fileNameView] error:nil];
  501. NSNumber *fileSizeNumber = [fileAttributes objectForKey:NSFileSize];
  502. long long fileSize = [fileSizeNumber longLongValue];
  503. if (fileSize > k_max_filesize_E2EE) {
  504. // Error for uploadFileFailure
  505. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_uploadedFile object:nil userInfo:@{@"metadata": metadata, @"errorCode": @(k_CCErrorInternalError), @"errorDescription": @"E2E Error file too big"}];
  506. return;
  507. }
  508. // if new file upload create a new encrypted filename
  509. fileNameIdentifier = [CCUtility generateRandomIdentifier];
  510. /*
  511. if ([metadata.ocId isEqualToString:[CCUtility createMetadataIDFromAccount:metadata.account serverUrl:metadata.serverUrl fileNameView:metadata.fileNameView directory:false]]) {
  512. fileNameIdentifier = [CCUtility generateRandomIdentifier];
  513. } else {
  514. fileNameIdentifier = metadata.fileName;
  515. }
  516. */
  517. [[NCEndToEndEncryption sharedManager] encryptFileName:metadata.fileNameView fileNameIdentifier:fileNameIdentifier directory:[CCUtility getDirectoryProviderStorageOcId:metadata.ocId] key:&key initializationVector:&initializationVector authenticationTag:&authenticationTag];
  518. tableE2eEncryption *object = [[NCManageDatabase sharedInstance] getE2eEncryptionWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", tableAccount.account, metadata.serverUrl]];
  519. if (object) {
  520. metadataKey = object.metadataKey;
  521. metadataKeyIndex = object.metadataKeyIndex;
  522. } else {
  523. metadataKey = [[[NCEndToEndEncryption sharedManager] generateKey:16] base64EncodedStringWithOptions:0]; // AES_KEY_128_LENGTH
  524. metadataKeyIndex = 0;
  525. }
  526. tableE2eEncryption *addObject = [tableE2eEncryption new];
  527. addObject.account = tableAccount.account;
  528. addObject.authenticationTag = authenticationTag;
  529. addObject.fileName = metadata.fileNameView;
  530. addObject.fileNameIdentifier = fileNameIdentifier;
  531. addObject.fileNamePath = [CCUtility returnFileNamePathFromFileName:metadata.fileNameView serverUrl:metadata.serverUrl activeUrl:tableAccount.url];
  532. addObject.key = key;
  533. addObject.initializationVector = initializationVector;
  534. addObject.metadataKey = metadataKey;
  535. addObject.metadataKeyIndex = metadataKeyIndex;
  536. CFStringRef UTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef)[metadata.fileNameView pathExtension], NULL);
  537. CFStringRef mimeTypeRef = UTTypeCopyPreferredTagWithClass (UTI, kUTTagClassMIMEType);
  538. if (mimeTypeRef) {
  539. addObject.mimeType = (__bridge NSString *)mimeTypeRef;
  540. } else {
  541. addObject.mimeType = @"application/octet-stream";
  542. }
  543. addObject.serverUrl = metadata.serverUrl;
  544. NSString *e2eeApiVersion = [[NCManageDatabase sharedInstance] getCapabilitiesServerStringWithAccount:tableAccount.account elements:NCElementsJSON.shared.capabilitiesE2EEApiVersion];
  545. addObject.version = [e2eeApiVersion intValue];
  546. // Get the last metadata
  547. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", tableAccount.account, metadata.serverUrl]];
  548. [[NCCommunication shared] getE2EEMetadataWithFileId:directory.fileId e2eToken:nil customUserAgent:nil addCustomHeaders:nil completionHandler:^(NSString *account, NSString *e2eMetadata, NSInteger errorCode, NSString *errorDescription) {
  549. if (errorCode == 0 && e2eMetadata != nil) {
  550. if ([[NCEndToEndMetadata sharedInstance] decoderMetadata:e2eMetadata privateKey:[CCUtility getEndToEndPrivateKey:tableAccount.account] serverUrl:directory.serverUrl account:tableAccount.account url:tableAccount.url] == false) {
  551. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_uploadedFile object:nil userInfo:@{@"metadata": metadata, @"errorCode": @(k_CCErrorInternalError), @"errorDescription": @"_e2e_error_decode_metadata_"}];
  552. return;
  553. }
  554. }
  555. if([[NCManageDatabase sharedInstance] addE2eEncryption:addObject] == NO) {
  556. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_uploadedFile object:nil userInfo:@{@"metadata": metadata, @"errorCode": @(k_CCErrorInternalError), @"errorDescription": @"_e2e_error_create_encrypted_"}];
  557. return;
  558. }
  559. // Now the fileName is fileNameIdentifier && flag e2eEncrypted
  560. metadata.fileName = fileNameIdentifier;
  561. metadata.e2eEncrypted = YES;
  562. // Update Metadata
  563. tableMetadata *metadataEncrypted = [[NCManageDatabase sharedInstance] addMetadata:metadata];
  564. [self uploadURLSessionMetadata:metadataEncrypted taskStatus:taskStatus];
  565. }];
  566. }
  567. - (void)uploadURLSessionMetadata:(tableMetadata *)metadata taskStatus:(NSInteger)taskStatus
  568. {
  569. NSURL *url;
  570. NSMutableURLRequest *request;
  571. PHAsset *asset;
  572. NSError *error;
  573. NSString *serverUrl = metadata.serverUrl;
  574. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", metadata.account]];
  575. if (tableAccount == nil) {
  576. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadata.ocId]];
  577. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_uploadedFile object:nil userInfo:@{@"metadata": metadata, @"errorCode": @(k_CCErrorInternalError), @"errorDescription": @"Upload error, account not found"}];
  578. return;
  579. }
  580. // calculate and store file size
  581. NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:[CCUtility getDirectoryProviderStorageOcId:metadata.ocId fileNameView:metadata.fileName] error:&error];
  582. long long fileSize = [[fileAttributes objectForKey:NSFileSize] longLongValue];
  583. metadata.size = fileSize;
  584. [[NCManageDatabase sharedInstance] addMetadata:metadata];
  585. url = [NSURL URLWithString:[[NSString stringWithFormat:@"%@/%@", metadata.serverUrl, metadata.fileName] encodeString:NSUTF8StringEncoding]];
  586. request = [NSMutableURLRequest requestWithURL:url];
  587. NSData *authData = [[NSString stringWithFormat:@"%@:%@", tableAccount.user, [CCUtility getPassword:tableAccount.account]] dataUsingEncoding:NSUTF8StringEncoding];
  588. NSString *authValue = [NSString stringWithFormat: @"Basic %@",[authData base64EncodedStringWithOptions:0]];
  589. [request setHTTPMethod:@"PUT"];
  590. [request setValue:authValue forHTTPHeaderField:@"Authorization"];
  591. [request setValue:[CCUtility getUserAgent] forHTTPHeaderField:@"User-Agent"];
  592. // Create Image for Upload (gray scale)
  593. #ifndef EXTENSION
  594. [CCGraphics createNewImageFrom:metadata.fileNameView ocId:metadata.ocId filterGrayScale:YES typeFile:metadata.typeFile writeImage:YES];
  595. #endif
  596. // Change date file upload with header : X-OC-Mtime (ctime assetLocalIdentifier) image/video
  597. if (metadata.assetLocalIdentifier) {
  598. PHFetchResult *result = [PHAsset fetchAssetsWithLocalIdentifiers:@[metadata.assetLocalIdentifier] options:nil];
  599. if (result.count) {
  600. asset = result[0];
  601. long dateFileCreation = [asset.creationDate timeIntervalSince1970];
  602. [request setValue:[NSString stringWithFormat:@"%ld", dateFileCreation] forHTTPHeaderField:@"X-OC-Mtime"];
  603. }
  604. }
  605. // E2EE : CREATE AND SEND METADATA
  606. if ([CCUtility isFolderEncrypted:metadata.serverUrl e2eEncrypted:metadata.e2eEncrypted account:tableAccount.account] && [CCUtility isEndToEndEnabled:tableAccount.account]) {
  607. [[NCNetworkingE2EE shared] sendE2EMetadataWithAccount:tableAccount.account serverUrl:serverUrl fileNameRename:nil fileNameNewRename:nil deleteE2eEncryption:nil url:tableAccount.url upload:true completion:^(NSString *e2eToken, NSInteger errorCode, NSString *errorDescription) {
  608. if (errorCode == 0) {
  609. // NSURLSession
  610. NSURLSession *sessionUpload;
  611. if ([metadata.session isEqualToString:k_upload_session]) sessionUpload = [self sessionUpload];
  612. else if ([metadata.session isEqualToString:k_upload_session_wwan]) sessionUpload = [self sessionWWanUpload];
  613. else if ([metadata.session isEqualToString:k_upload_session_foreground]) sessionUpload = [self sessionUploadForeground];
  614. else if ([metadata.session isEqualToString:k_upload_session_extension]) sessionUpload = [self sessionUploadExtension];
  615. [request setValue:e2eToken forHTTPHeaderField:@"e2e-token"];
  616. NSURLSessionUploadTask *uploadTask = [sessionUpload uploadTaskWithRequest:request fromFile:[NSURL fileURLWithPath:[CCUtility getDirectoryProviderStorageOcId:metadata.ocId fileNameView:metadata.fileName]]];
  617. // Manage uploadTask cancel,suspend,resume
  618. if (taskStatus == k_taskStatusCancel) [uploadTask cancel];
  619. else if (taskStatus == k_taskStatusSuspend) [uploadTask suspend];
  620. else if (taskStatus == k_taskStatusResume) [uploadTask resume];
  621. // *** E2EE ***
  622. [[NCManageDatabase sharedInstance] setMetadataSession:metadata.session sessionError:@"" sessionSelector:nil sessionTaskIdentifier:uploadTask.taskIdentifier status:k_metadataStatusUploading predicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadata.ocId]];
  623. NSLog(@"[LOG] Upload file %@ TaskIdentifier %lu", metadata.fileName, (unsigned long)uploadTask.taskIdentifier);
  624. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_uploadFileStart object:nil userInfo:@{@"ocId": metadata.ocId, @"task": uploadTask, @"serverUrl": metadata.serverUrl, @"account": metadata.account}];
  625. } else {
  626. [[NCManageDatabase sharedInstance] setMetadataSession:metadata.session sessionError:errorDescription sessionSelector:nil sessionTaskIdentifier:k_taskIdentifierDone status:k_metadataStatusUploadError predicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadata.ocId]];
  627. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_uploadedFile object:nil userInfo:@{@"metadata": metadata, @"errorCode": @(errorCode), @"errorDescription": errorDescription}];
  628. }
  629. }];
  630. } else {
  631. // NSURLSession
  632. NSURLSession *sessionUpload;
  633. if ([metadata.session isEqualToString:k_upload_session]) sessionUpload = [self sessionUpload];
  634. else if ([metadata.session isEqualToString:k_upload_session_wwan]) sessionUpload = [self sessionWWanUpload];
  635. else if ([metadata.session isEqualToString:k_upload_session_foreground]) sessionUpload = [self sessionUploadForeground];
  636. else if ([metadata.session isEqualToString:k_upload_session_extension]) sessionUpload = [self sessionUploadExtension];
  637. NSURLSessionUploadTask *uploadTask = [sessionUpload uploadTaskWithRequest:request fromFile:[NSURL fileURLWithPath:[CCUtility getDirectoryProviderStorageOcId:metadata.ocId fileNameView:metadata.fileName]]];
  638. // Manage uploadTask cancel,suspend,resume
  639. if (taskStatus == k_taskStatusCancel) [uploadTask cancel];
  640. else if (taskStatus == k_taskStatusSuspend) [uploadTask suspend];
  641. else if (taskStatus == k_taskStatusResume) [uploadTask resume];
  642. // *** PLAIN ***
  643. [[NCManageDatabase sharedInstance] setMetadataSession:metadata.session sessionError:@"" sessionSelector:nil sessionTaskIdentifier:uploadTask.taskIdentifier status:k_metadataStatusUploading predicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadata.ocId]];
  644. NSLog(@"[LOG] Upload file %@ TaskIdentifier %lu", metadata.fileName, (unsigned long)uploadTask.taskIdentifier);
  645. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_uploadFileStart object:nil userInfo:@{@"ocId": metadata.ocId, @"task": uploadTask, @"serverUrl": metadata.serverUrl, @"account": metadata.account}];
  646. }
  647. }
  648. - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
  649. {
  650. }
  651. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend
  652. {
  653. NSString *url = [[[task currentRequest].URL absoluteString] stringByRemovingPercentEncoding];
  654. NSString *fileName = [url lastPathComponent];
  655. NSString *serverUrl = [self getServerUrlFromUrl:url];
  656. if (!serverUrl) return;
  657. if (totalBytesExpectedToSend < 1) {
  658. totalBytesExpectedToSend = totalBytesSent;
  659. }
  660. float progress = (float) totalBytesSent / (float)totalBytesExpectedToSend;
  661. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataInSessionFromFileName:fileName serverUrl:serverUrl taskIdentifier:task.taskIdentifier];
  662. if (metadata) {
  663. 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])};
  664. if (userInfo)
  665. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_progressTask object:nil userInfo:userInfo];
  666. }
  667. }
  668. - (void)uploadFileSuccessFailure:(tableMetadata *)metadata fileName:(NSString *)fileName ocId:(NSString *)ocId etag:(NSString *)etag date:(NSDate *)date serverUrl:(NSString *)serverUrl errorCode:(NSInteger)errorCode
  669. {
  670. NSString *tempocId = metadata.ocId;
  671. NSString *errorMessage = @"";
  672. BOOL isE2EEDirectory = false;
  673. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", metadata.account]];
  674. if (tableAccount == nil) {
  675. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", tempocId]];
  676. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_uploadedFile object:nil userInfo:@{@"metadata": metadata, @"errorCode": @(errorCode), @"errorDescription": errorMessage}];
  677. return;
  678. }
  679. // is this a E2EE Directory ?
  680. if ([CCUtility isFolderEncrypted:serverUrl e2eEncrypted:false account:tableAccount.account] && [CCUtility isEndToEndEnabled:tableAccount.account]) {
  681. isE2EEDirectory = true;
  682. }
  683. // ERRORE
  684. if (errorCode != 0) {
  685. #ifndef EXTENSION
  686. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  687. [appDelegate.listProgressMetadata removeObjectForKey:metadata.ocId];
  688. #endif
  689. // Mark error only if not Cancelled Task
  690. if (errorCode == kCFURLErrorCancelled) {
  691. if (metadata.status == k_metadataStatusUploadForcedStart) {
  692. errorCode = 0;
  693. metadata.session = k_upload_session;
  694. metadata.sessionError = @"";
  695. metadata.sessionTaskIdentifier = 0;
  696. metadata.status = k_metadataStatusInUpload;
  697. metadata = [[NCManageDatabase sharedInstance] addMetadata:metadata];
  698. [[CCNetworking sharedNetworking] uploadFile:metadata taskStatus:k_taskStatusResume];
  699. } else {
  700. [[NSFileManager defaultManager] removeItemAtPath:[CCUtility getDirectoryProviderStorageOcId:tempocId] error:nil];
  701. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", tempocId]];
  702. errorMessage = [CCError manageErrorKCF:errorCode withNumberError:YES];
  703. }
  704. } else {
  705. if (metadata && (errorCode == kOCErrorServerUnauthorized || errorCode == kOCErrorServerForbidden)) {
  706. #ifndef EXTENSION
  707. [[NCNetworkingCheckRemoteUser shared] checkRemoteUserWithAccount:metadata.account];
  708. #endif
  709. } else if (metadata && errorCode == NSURLErrorServerCertificateUntrusted) {
  710. [CCUtility setCertificateError:metadata.account error:YES];
  711. }
  712. [[NCManageDatabase sharedInstance] setMetadataSession:nil sessionError:[CCError manageErrorKCF:errorCode withNumberError:NO] sessionSelector:nil sessionTaskIdentifier:k_taskIdentifierDone status:k_metadataStatusUploadError predicate:[NSPredicate predicateWithFormat:@"ocId == %@", tempocId]];
  713. errorMessage = [CCError manageErrorKCF:errorCode withNumberError:YES];
  714. }
  715. } else {
  716. // Delete Asset
  717. if (tableAccount.autoUploadDeleteAssetLocalIdentifier && ![metadata.assetLocalIdentifier isEqualToString:@""] && [metadata.sessionSelector isEqualToString:selectorUploadAutoUpload]) {
  718. metadata.deleteAssetLocalIdentifier = true;
  719. }
  720. // Edited file, remove tempocId and adjust the directory provider storage
  721. if (metadata.edited) {
  722. // Update metadata tempocId
  723. [[NCManageDatabase sharedInstance] setMetadataSession:@"" sessionError:@"" sessionSelector:@"" sessionTaskIdentifier:k_taskIdentifierDone status:k_metadataStatusNormal predicate:[NSPredicate predicateWithFormat:@"ocId == %@", tempocId]];
  724. // Add metadata ocId
  725. metadata.date = date;
  726. if (isE2EEDirectory) {
  727. metadata.e2eEncrypted = true;
  728. } else {
  729. metadata.e2eEncrypted = false;
  730. }
  731. metadata.etag = etag;
  732. metadata.ocId = ocId;
  733. metadata.session = @"";
  734. metadata.sessionError = @"";
  735. metadata.sessionTaskIdentifier = k_taskIdentifierDone;
  736. metadata.status = k_metadataStatusNormal;
  737. metadata = [[NCManageDatabase sharedInstance] addMetadata:metadata];
  738. // Copy new version on old version
  739. if (![tempocId isEqualToString:metadata.ocId]) {
  740. [CCUtility copyFileAtPath:[NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryProviderStorage], tempocId] toPath:[NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryProviderStorage], metadata.ocId]];
  741. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", tempocId]];
  742. // IMI -> Unzip
  743. #if HC
  744. if ([metadata.typeFile isEqualToString:k_metadataTypeFile_imagemeter]) {
  745. (void)[[IMUtility shared] IMUnzipWithMetadata:metadata];
  746. }
  747. #endif
  748. }
  749. } else {
  750. // Replace Metadata
  751. metadata.date = date;
  752. if (isE2EEDirectory) {
  753. metadata.e2eEncrypted = true;
  754. } else {
  755. metadata.e2eEncrypted = false;
  756. }
  757. metadata.etag = etag;
  758. metadata.ocId = ocId;
  759. metadata.session = @"";
  760. metadata.sessionError = @"";
  761. metadata.sessionTaskIdentifier = k_taskIdentifierDone;
  762. metadata.status = k_metadataStatusNormal;
  763. [CCUtility moveFileAtPath:[NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryProviderStorage], tempocId] toPath:[NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryProviderStorage], metadata.ocId]];
  764. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@ AND fileName == %@", metadata.account, metadata.serverUrl, metadata.fileName]];
  765. metadata = [[NCManageDatabase sharedInstance] addMetadata:metadata];
  766. NSLog(@"[LOG] Insert new upload : %@ - ocId : %@", metadata.fileName, ocId);
  767. }
  768. #ifndef EXTENSION
  769. // EXIF
  770. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image])
  771. [[CCExifGeo sharedInstance] setExifLocalTableEtag:metadata];
  772. // Create preview
  773. [CCGraphics createNewImageFrom:metadata.fileNameView ocId:metadata.ocId filterGrayScale:NO typeFile:metadata.typeFile writeImage:YES];
  774. // Copy photo or video in the photo album for auto upload
  775. if ([metadata.assetLocalIdentifier length] > 0 && ([metadata.sessionSelector isEqualToString:selectorUploadAutoUpload] || [metadata.sessionSelector isEqualToString:selectorUploadFile])) {
  776. PHAsset *asset;
  777. PHFetchResult *result = [PHAsset fetchAssetsWithLocalIdentifiers:@[metadata.assetLocalIdentifier] options:nil];
  778. if(result.count){
  779. asset = result[0];
  780. [asset saveToAlbum:[NCBrandOptions sharedInstance].brand completionBlock:^(BOOL success) {
  781. if (success) NSLog(@"[LOG] Insert file %@ in %@", metadata.fileName, [NCBrandOptions sharedInstance].brand);
  782. else NSLog(@"[LOG] File %@ do not insert in %@", metadata.fileName, [NCBrandOptions sharedInstance].brand);
  783. }];
  784. }
  785. }
  786. #endif
  787. // Add Local or Remove from cache
  788. if ([CCUtility getDisableLocalCacheAfterUpload] && !metadata.edited) {
  789. [[NSFileManager defaultManager] removeItemAtPath:[CCUtility getDirectoryProviderStorageOcId:metadata.ocId] error:nil];
  790. } else {
  791. // Add Local
  792. (void)[[NCManageDatabase sharedInstance] addLocalFileWithMetadata:metadata];
  793. }
  794. }
  795. // Detect E2EE
  796. 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]];
  797. // E2EE : UNLOCK
  798. if (isE2EEDirectory && e2eeMetadataInSession == nil) {
  799. [[NCNetworkingE2EE shared] unlockWithAccount:tableAccount.account serverUrl:serverUrl completion:^(tableDirectory *directory, NSString *e2eToken, NSInteger errorCode, NSString *errorDescription) { }];
  800. }
  801. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_uploadedFile object:nil userInfo:@{@"metadata": metadata, @"errorCode": @(errorCode), @"errorDescription": errorMessage}];
  802. }
  803. #pragma --------------------------------------------------------------------------------------------
  804. #pragma mark ===== Utility =====
  805. #pragma --------------------------------------------------------------------------------------------
  806. - (NSString *)getServerUrlFromUrl:(NSString *)url
  807. {
  808. NSString *fileName = [url lastPathComponent];
  809. url = [url stringByReplacingOccurrencesOfString:[@"/" stringByAppendingString:fileName] withString:@""];
  810. return url;
  811. }
  812. @end