CCNetworking.m 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087
  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. if ([CCUtility removeForbiddenCharactersFileSystem:[fields objectForKey:@"OC-ETag"]] != nil) {
  228. etag = [CCUtility removeForbiddenCharactersFileSystem:[fields objectForKey:@"OC-ETag"]];
  229. } else if ([CCUtility removeForbiddenCharactersFileSystem:[fields objectForKey:@"ETag"]] != nil) {
  230. etag = [CCUtility removeForbiddenCharactersFileSystem:[fields objectForKey:@"ETag"]];
  231. }
  232. NSString *dateString = [fields objectForKey:@"Date"];
  233. if (dateString) {
  234. if (![dateFormatter getObjectValue:&date forString:dateString range:nil error:&error]) {
  235. date = [NSDate date];
  236. }
  237. } else {
  238. date = [NSDate date];
  239. }
  240. }
  241. if (fileName.length > 0 && serverUrl.length > 0) {
  242. dispatch_async(dispatch_get_main_queue(), ^{
  243. [self downloadFileSuccessFailure:fileName ocId:metadata.ocId etag:etag date:date serverUrl:serverUrl selector:metadata.sessionSelector errorCode:errorCode];
  244. });
  245. }
  246. }
  247. }
  248. // ------------------------ UPLOAD -----------------------
  249. if ([task isKindOfClass:[NSURLSessionUploadTask class]]) {
  250. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataInSessionFromFileName:fileName serverUrl:serverUrl taskIdentifier:task.taskIdentifier];
  251. if (metadata) {
  252. NSDictionary *fields = [httpResponse allHeaderFields];
  253. NSString *ocId = metadata.ocId;
  254. NSString *etag = metadata.etag;
  255. if (errorCode == 0) {
  256. if ([CCUtility removeForbiddenCharactersFileSystem:[fields objectForKey:@"OC-FileId"]] != nil) {
  257. ocId = [CCUtility removeForbiddenCharactersFileSystem:[fields objectForKey:@"OC-FileId"]];
  258. } else if ([CCUtility removeForbiddenCharactersFileSystem:[fields objectForKey:@"FileId"]] != nil) {
  259. ocId = [CCUtility removeForbiddenCharactersFileSystem:[fields objectForKey:@"FileId"]];
  260. }
  261. if ([CCUtility removeForbiddenCharactersFileSystem:[fields objectForKey:@"OC-ETag"]] != nil) {
  262. etag = [CCUtility removeForbiddenCharactersFileSystem:[fields objectForKey:@"OC-ETag"]];
  263. } else if ([CCUtility removeForbiddenCharactersFileSystem:[fields objectForKey:@"ETag"]] != nil) {
  264. etag = [CCUtility removeForbiddenCharactersFileSystem:[fields objectForKey:@"ETag"]];
  265. }
  266. NSString *dateString = [fields objectForKey:@"Date"];
  267. if (dateString) {
  268. if (![dateFormatter getObjectValue:&date forString:dateString range:nil error:&error]) {
  269. NSLog(@"[LOG] Date '%@' could not be parsed: %@", dateString, error);
  270. date = [NSDate date];
  271. }
  272. } else {
  273. date = [NSDate date];
  274. }
  275. }
  276. if (fileName.length > 0 && ocId.length > 0 && serverUrl.length > 0) {
  277. dispatch_async(dispatch_get_main_queue(), ^{
  278. [self uploadFileSuccessFailure:metadata fileName:fileName ocId:ocId etag:etag date:date serverUrl:serverUrl errorCode:errorCode];
  279. });
  280. }
  281. }
  282. }
  283. }
  284. #pragma --------------------------------------------------------------------------------------------
  285. #pragma mark ===== Download =====
  286. #pragma --------------------------------------------------------------------------------------------
  287. - (void)downloadFile:(tableMetadata *)metadata taskStatus:(NSInteger)taskStatus
  288. {
  289. // No Password
  290. if ([CCUtility getPassword:metadata.account].length == 0) {
  291. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_downloadedFile object:nil userInfo:@{@"metadata": metadata, @"selector": metadata.sessionSelector, @"errorCode": @(kOCErrorServerUnauthorized), @"errorDescription": @"_bad_username_password_"}];
  292. return;
  293. } else if ([CCUtility getCertificateError:metadata.account]) {
  294. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_downloadedFile object:nil userInfo:@{@"metadata": metadata, @"selector": metadata.sessionSelector, @"errorCode": @(NSURLErrorServerCertificateUntrusted), @"errorDescription": @"_ssl_certificate_untrusted_"}];
  295. return;
  296. }
  297. // File exists ?
  298. tableLocalFile *localfile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadata.ocId]];
  299. if (localfile != nil && [CCUtility fileProviderStorageExists:metadata.ocId fileNameView:metadata.fileNameView]) {
  300. [[NCManageDatabase sharedInstance] setMetadataSession:@"" sessionError:@"" sessionSelector:@"" sessionTaskIdentifier:k_taskIdentifierDone status:k_metadataStatusNormal predicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadata.ocId]];
  301. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_downloadedFile object:nil userInfo:@{@"metadata": metadata, @"selector": metadata.sessionSelector, @"errorCode": @(0), @"errorDescription": @""}];
  302. return;
  303. }
  304. [self downloaURLSession:metadata taskStatus:taskStatus];
  305. }
  306. - (void)downloaURLSession:(tableMetadata *)metadata taskStatus:(NSInteger)taskStatus
  307. {
  308. NSURLSession *sessionDownload;
  309. NSURL *url;
  310. NSMutableURLRequest *request;
  311. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", metadata.account]];
  312. if (tableAccount == nil) {
  313. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadata.ocId]];
  314. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_downloadedFile object:nil userInfo:@{@"metadata": metadata, @"selector": metadata.sessionSelector, @"errorCode": @(k_CCErrorInternalError), @"errorDescription": @"Download error, account not found"}];
  315. return;
  316. }
  317. NSString *serverFileUrl = [[NSString stringWithFormat:@"%@/%@", metadata.serverUrl, metadata.fileName] encodeString:NSUTF8StringEncoding];
  318. url = [NSURL URLWithString:serverFileUrl];
  319. request = [NSMutableURLRequest requestWithURL:url];
  320. NSData *authData = [[NSString stringWithFormat:@"%@:%@", tableAccount.user, [CCUtility getPassword:tableAccount.account]] dataUsingEncoding:NSUTF8StringEncoding];
  321. NSString *authValue = [NSString stringWithFormat: @"Basic %@",[authData base64EncodedStringWithOptions:0]];
  322. [request setValue:authValue forHTTPHeaderField:@"Authorization"];
  323. [request setValue:[CCUtility getUserAgent] forHTTPHeaderField:@"User-Agent"];
  324. if ([metadata.session isEqualToString:k_download_session]) sessionDownload = [self sessionDownload];
  325. else if ([metadata.session isEqualToString:k_download_session_foreground]) sessionDownload = [self sessionDownloadForeground];
  326. else if ([metadata.session isEqualToString:k_download_session_wwan]) sessionDownload = [self sessionWWanDownload];
  327. NSURLSessionDownloadTask *downloadTask = [sessionDownload downloadTaskWithRequest:request];
  328. if (downloadTask == nil) {
  329. [[NCManageDatabase sharedInstance] setMetadataSession:nil sessionError:NSLocalizedString(@"_not_possible_download_", nil) sessionSelector:nil sessionTaskIdentifier:k_taskIdentifierDone status:k_metadataStatusDownloadError predicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadata.ocId]];
  330. NSString *errorDescription = [NSString stringWithFormat:@"%@ %@", NSLocalizedString(@"_not_possible_download_", nil), metadata.fileNameView];
  331. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_downloadedFile object:nil userInfo:@{@"metadata": metadata, @"selector": metadata.sessionSelector, @"errorCode": @(k_CCErrorInternalError), @"errorDescription": errorDescription}];
  332. } else {
  333. // Manage uploadTask cancel,suspend,resume
  334. if (taskStatus == k_taskStatusCancel) [downloadTask cancel];
  335. else if (taskStatus == k_taskStatusSuspend) [downloadTask suspend];
  336. else if (taskStatus == k_taskStatusResume) [downloadTask resume];
  337. [[NCManageDatabase sharedInstance] setMetadataSession:nil sessionError:nil sessionSelector:nil sessionTaskIdentifier:downloadTask.taskIdentifier status:k_metadataStatusDownloading predicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadata.ocId]];
  338. NSLog(@"[LOG] downloadFileSession %@ Task [%lu]", metadata.ocId, (unsigned long)downloadTask.taskIdentifier);
  339. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_downloadFileStart object:nil userInfo:@{@"ocId": metadata.ocId, @"task": downloadTask, @"serverUrl": metadata.serverUrl, @"account": metadata.account}];
  340. }
  341. }
  342. - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
  343. {
  344. NSString *url = [[[downloadTask currentRequest].URL absoluteString] stringByRemovingPercentEncoding];
  345. NSString *fileName = [url lastPathComponent];
  346. NSString *serverUrl = [self getServerUrlFromUrl:url];
  347. if (!serverUrl) return;
  348. if (totalBytesExpectedToWrite < 1) {
  349. totalBytesExpectedToWrite = totalBytesWritten;
  350. }
  351. float progress = (float) totalBytesWritten / (float)totalBytesExpectedToWrite;
  352. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataInSessionFromFileName:fileName serverUrl:serverUrl taskIdentifier:downloadTask.taskIdentifier];
  353. if (metadata) {
  354. 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])};
  355. if (userInfo)
  356. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_progressTask object:nil userInfo:userInfo];
  357. } else {
  358. NSLog(@"[LOG] metadata not found");
  359. }
  360. }
  361. - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
  362. {
  363. NSString *url = [[[downloadTask currentRequest].URL absoluteString] stringByRemovingPercentEncoding];
  364. if (!url)
  365. return;
  366. NSString *fileName = [url lastPathComponent];
  367. NSString *serverUrl = [self getServerUrlFromUrl:url];
  368. if (!serverUrl) return;
  369. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataInSessionFromFileName:fileName serverUrl:serverUrl taskIdentifier:downloadTask.taskIdentifier];
  370. if (!metadata) {
  371. NSLog(@"[LOG] Serious error internal download : metadata not found %@ ", url);
  372. return;
  373. }
  374. NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)downloadTask.response;
  375. if (httpResponse.statusCode >= 200 && httpResponse.statusCode < 300) {
  376. NSString *destinationFilePath = [CCUtility getDirectoryProviderStorageOcId:metadata.ocId fileNameView:metadata.fileName];
  377. NSURL *destinationURL = [NSURL fileURLWithPath:destinationFilePath];
  378. [[NSFileManager defaultManager] removeItemAtURL:destinationURL error:NULL];
  379. [[NSFileManager defaultManager] copyItemAtURL:location toURL:destinationURL error:nil];
  380. }
  381. }
  382. - (void)downloadFileSuccessFailure:(NSString *)fileName ocId:(NSString *)ocId etag:(NSString *)etag date:(NSDate *)date serverUrl:(NSString *)serverUrl selector:(NSString *)selector errorCode:(NSInteger)errorCode
  383. {
  384. #ifndef EXTENSION
  385. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  386. [appDelegate.listProgressMetadata removeObjectForKey:ocId];
  387. #endif
  388. NSString *errorMessage = [CCError manageErrorKCF:errorCode withNumberError:YES];
  389. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", ocId]];
  390. if (errorCode != 0) {
  391. if (errorCode == kCFURLErrorCancelled) {
  392. [[NCManageDatabase sharedInstance] setMetadataSession:@"" sessionError:@"" sessionSelector:@"" sessionTaskIdentifier:k_taskIdentifierDone status:k_metadataStatusNormal predicate:[NSPredicate predicateWithFormat:@"ocId == %@", ocId]];
  393. } else {
  394. if (metadata && (errorCode == kOCErrorServerUnauthorized || errorCode == kOCErrorServerForbidden)) {
  395. #ifndef EXTENSION
  396. [[NCNetworkingCheckRemoteUser shared] checkRemoteUserWithAccount:metadata.account];
  397. #endif
  398. } else if (metadata && errorCode == NSURLErrorServerCertificateUntrusted) {
  399. [CCUtility setCertificateError:metadata.account error:YES];
  400. }
  401. [[NCManageDatabase sharedInstance] setMetadataSession:nil sessionError:[CCError manageErrorKCF:errorCode withNumberError:NO] sessionSelector:nil sessionTaskIdentifier:k_taskIdentifierDone status:k_metadataStatusDownloadError predicate:[NSPredicate predicateWithFormat:@"ocId == %@", ocId]];
  402. }
  403. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_downloadedFile object:nil userInfo:@{@"metadata": metadata, @"selector": selector, @"errorCode": @(errorCode), @"errorDescription": errorMessage}];
  404. } else {
  405. if (!metadata) {
  406. NSLog(@"[LOG] Serious error internal download : metadata not found %@ ", fileName);
  407. return;
  408. }
  409. metadata.session = @"";
  410. metadata.sessionError = @"";
  411. metadata.sessionSelector = @"";
  412. metadata.sessionTaskIdentifier = k_taskIdentifierDone;
  413. metadata.status = k_metadataStatusNormal;
  414. metadata = [[NCManageDatabase sharedInstance] updateMetadata:metadata];
  415. (void)[[NCManageDatabase sharedInstance] addLocalFileWithMetadata:metadata];
  416. // E2EE Decrypted
  417. tableE2eEncryption *object = [[NCManageDatabase sharedInstance] getE2eEncryptionWithPredicate:[NSPredicate predicateWithFormat:@"fileNameIdentifier == %@ AND serverUrl == %@", fileName, serverUrl]];
  418. if (object) {
  419. BOOL result = [[NCEndToEndEncryption sharedManager] decryptFileName:metadata.fileName fileNameView:metadata.fileNameView ocId:metadata.ocId key:object.key initializationVector:object.initializationVector authenticationTag:object.authenticationTag];
  420. if (!result) {
  421. [[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]}];
  422. return;
  423. }
  424. }
  425. // Exif
  426. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image])
  427. [[CCExifGeo sharedInstance] setExifLocalTableEtag:metadata];
  428. // Icon
  429. if ([[NSFileManager defaultManager] fileExistsAtPath:[CCUtility getDirectoryProviderStorageIconOcId:metadata.ocId fileNameView:metadata.fileNameView]] == NO) {
  430. [CCGraphics createNewImageFrom:metadata.fileNameView ocId:metadata.ocId filterGrayScale:NO typeFile:metadata.typeFile writeImage:YES];
  431. }
  432. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_downloadedFile object:nil userInfo:@{@"metadata": metadata, @"selector": selector, @"errorCode": @(0), @"errorDescription": @""}];
  433. }
  434. // NSNotificationCenter
  435. NSDictionary* userInfo = @{@"metadata": metadata, @"errorCode": @(errorCode), @"errorDescription": errorMessage};
  436. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_downloadedFile object:nil userInfo:userInfo];
  437. }
  438. #pragma --------------------------------------------------------------------------------------------
  439. #pragma mark ===== Upload =====
  440. #pragma --------------------------------------------------------------------------------------------
  441. - (void)uploadFile:(tableMetadata *)metadata taskStatus:(NSInteger)taskStatus
  442. {
  443. // Password nil
  444. if ([CCUtility getPassword:metadata.account].length == 0) {
  445. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_uploadedFile object:nil userInfo:@{@"metadata": metadata, @"errorCode": @(kOCErrorServerUnauthorized), @"errorDescription": @"_bad_username_password_"}];
  446. return;
  447. } else if ([CCUtility getCertificateError:metadata.account]) {
  448. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_uploadedFile object:nil userInfo:@{@"metadata": metadata, @"errorCode": @(NSURLErrorServerCertificateUntrusted), @"errorDescription": @"_ssl_certificate_untrusted_"}];
  449. return;
  450. }
  451. if ([CCUtility fileProviderStorageExists:metadata.ocId fileNameView:metadata.fileNameView] == NO) {
  452. [CCUtility extractImageVideoFromAssetLocalIdentifierForUpload:metadata notification:true completion:^(tableMetadata *newMetadata, NSString *fileNamePath) {
  453. if (newMetadata == nil) {
  454. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadata.ocId]];
  455. } else {
  456. NSString *toPath = [CCUtility getDirectoryProviderStorageOcId:newMetadata.ocId fileNameView:newMetadata.fileNameView];
  457. [CCUtility moveFileAtPath:fileNamePath toPath:toPath];
  458. tableMetadata *metadataForUpload = [[NCManageDatabase sharedInstance] addMetadata:newMetadata];
  459. if ([CCUtility isFolderEncrypted:metadataForUpload.serverUrl e2eEncrypted:metadataForUpload.e2eEncrypted account:metadataForUpload.account] && [CCUtility isEndToEndEnabled:metadataForUpload.account]) {
  460. [self e2eEncryptedFile:metadataForUpload taskStatus:taskStatus];
  461. } else {
  462. [self uploadURLSessionMetadata:metadataForUpload taskStatus:taskStatus];
  463. }
  464. }
  465. }];
  466. } else {
  467. NSDictionary *results = [[NCCommunicationCommon shared] objcGetInternalContenTypeWithFileName:metadata.fileNameView contentType:metadata.contentType directory:metadata.directory];
  468. metadata.contentType = results[@"contentType"];
  469. metadata.iconName = results[@"iconName"];
  470. metadata.typeFile = results[@"typeFile"];
  471. NSDictionary *attributes = [[NSFileManager defaultManager] attributesOfItemAtPath:[CCUtility getDirectoryProviderStorageOcId:metadata.ocId fileNameView:metadata.fileName] error:nil];
  472. if (attributes[NSFileModificationDate]) {
  473. metadata.date = attributes[NSFileModificationDate];
  474. } else {
  475. metadata.date = [NSDate date];
  476. }
  477. metadata.size = [attributes[NSFileSize] longValue];
  478. tableMetadata *metadataForUpload = [[NCManageDatabase sharedInstance] addMetadata:metadata];
  479. if ([CCUtility isFolderEncrypted:metadataForUpload.serverUrl e2eEncrypted:metadataForUpload.e2eEncrypted account:metadataForUpload.account] && [CCUtility isEndToEndEnabled:metadataForUpload.account]) {
  480. [self e2eEncryptedFile:metadataForUpload taskStatus:taskStatus];
  481. } else {
  482. [self uploadURLSessionMetadata:metadataForUpload taskStatus:taskStatus];
  483. }
  484. }
  485. }
  486. - (void)e2eEncryptedFile:(tableMetadata *)metadata taskStatus:(NSInteger)taskStatus
  487. {
  488. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", metadata.account]];
  489. if (tableAccount == nil) {
  490. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadata.ocId]];
  491. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_uploadedFile object:nil userInfo:@{@"metadata": metadata, @"errorCode": @(k_CCErrorInternalError), @"errorDescription": @"Upload error, account not found"}];
  492. return;
  493. }
  494. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  495. NSError *error;
  496. NSString *fileNameIdentifier;
  497. NSString *key;
  498. NSString *initializationVector;
  499. NSString *authenticationTag;
  500. NSString *metadataKey;
  501. NSInteger metadataKeyIndex;
  502. NSString *e2eeMetadata;
  503. // Verify File Size
  504. NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:[CCUtility getDirectoryProviderStorageOcId:metadata.ocId fileNameView:metadata.fileNameView] error:&error];
  505. NSNumber *fileSizeNumber = [fileAttributes objectForKey:NSFileSize];
  506. long long fileSize = [fileSizeNumber longLongValue];
  507. if (fileSize > k_max_filesize_E2EE) {
  508. // Error for uploadFileFailure
  509. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_uploadedFile object:nil userInfo:@{@"metadata": metadata, @"errorCode": @(k_CCErrorInternalError), @"errorDescription": @"E2E Error file too big"}];
  510. return;
  511. }
  512. // if new file upload create a new encrypted filename
  513. fileNameIdentifier = [CCUtility generateRandomIdentifier];
  514. /*
  515. if ([metadata.ocId isEqualToString:[CCUtility createMetadataIDFromAccount:metadata.account serverUrl:metadata.serverUrl fileNameView:metadata.fileNameView directory:false]]) {
  516. fileNameIdentifier = [CCUtility generateRandomIdentifier];
  517. } else {
  518. fileNameIdentifier = metadata.fileName;
  519. }
  520. */
  521. if ([[NCEndToEndEncryption sharedManager] encryptFileName:metadata.fileNameView fileNameIdentifier:fileNameIdentifier directory:[CCUtility getDirectoryProviderStorageOcId:metadata.ocId] key:&key initializationVector:&initializationVector authenticationTag:&authenticationTag]) {
  522. tableE2eEncryption *object = [[NCManageDatabase sharedInstance] getE2eEncryptionWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", tableAccount.account, metadata.serverUrl]];
  523. if (object) {
  524. metadataKey = object.metadataKey;
  525. metadataKeyIndex = object.metadataKeyIndex;
  526. } else {
  527. metadataKey = [[[NCEndToEndEncryption sharedManager] generateKey:16] base64EncodedStringWithOptions:0]; // AES_KEY_128_LENGTH
  528. metadataKeyIndex = 0;
  529. }
  530. tableE2eEncryption *addObject = [tableE2eEncryption new];
  531. addObject.account = tableAccount.account;
  532. addObject.authenticationTag = authenticationTag;
  533. addObject.fileName = metadata.fileNameView;
  534. addObject.fileNameIdentifier = fileNameIdentifier;
  535. addObject.fileNamePath = [CCUtility returnFileNamePathFromFileName:metadata.fileNameView serverUrl:metadata.serverUrl activeUrl:tableAccount.url];
  536. addObject.key = key;
  537. addObject.initializationVector = initializationVector;
  538. addObject.metadataKey = metadataKey;
  539. addObject.metadataKeyIndex = metadataKeyIndex;
  540. CFStringRef UTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef)[metadata.fileNameView pathExtension], NULL);
  541. CFStringRef mimeTypeRef = UTTypeCopyPreferredTagWithClass (UTI, kUTTagClassMIMEType);
  542. if (mimeTypeRef) {
  543. addObject.mimeType = (__bridge NSString *)mimeTypeRef;
  544. } else {
  545. addObject.mimeType = @"application/octet-stream";
  546. }
  547. addObject.serverUrl = metadata.serverUrl;
  548. NSString *e2eeApiVersion = [[NCManageDatabase sharedInstance] getCapabilitiesServerStringWithAccount:tableAccount.account elements:NCElementsJSON.shared.capabilitiesE2EEApiVersion];
  549. addObject.version = [e2eeApiVersion intValue];
  550. // Get the last metadata
  551. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", tableAccount.account, metadata.serverUrl]];
  552. error = [[NCNetworkingEndToEnd sharedManager] getEndToEndMetadata:&e2eeMetadata fileId:directory.fileId user:tableAccount.user userID:tableAccount.userID password: [CCUtility getPassword:tableAccount.account] url:tableAccount.url];
  553. if (error == nil) {
  554. if ([[NCEndToEndMetadata sharedInstance] decoderMetadata:e2eeMetadata privateKey:[CCUtility getEndToEndPrivateKey:tableAccount.account] serverUrl:metadata.serverUrl account:tableAccount.account url:tableAccount.url] == false) {
  555. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_uploadedFile object:nil userInfo:@{@"metadata": metadata, @"errorCode": @(k_CCErrorInternalError), @"errorDescription": @"_e2e_error_decode_metadata_"}];
  556. return;
  557. }
  558. }
  559. // write new record e2ee
  560. if([[NCManageDatabase sharedInstance] addE2eEncryption:addObject] == NO) {
  561. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_uploadedFile object:nil userInfo:@{@"metadata": metadata, @"errorCode": @(k_CCErrorInternalError), @"errorDescription": @"_e2e_error_create_encrypted_"}];
  562. return;
  563. }
  564. } else {
  565. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_uploadedFile object:nil userInfo:@{@"metadata": metadata, @"errorCode": @(k_CCErrorInternalError), @"errorDescription": @"_e2e_error_create_encrypted_"}];
  566. return;
  567. }
  568. dispatch_async(dispatch_get_main_queue(), ^{
  569. // Now the fileName is fileNameIdentifier && flag e2eEncrypted
  570. metadata.fileName = fileNameIdentifier;
  571. metadata.e2eEncrypted = YES;
  572. // Update Metadata
  573. tableMetadata *metadataEncrypted = [[NCManageDatabase sharedInstance] addMetadata:metadata];
  574. [self uploadURLSessionMetadata:metadataEncrypted taskStatus:taskStatus];
  575. });
  576. });
  577. }
  578. - (void)uploadURLSessionMetadata:(tableMetadata *)metadata taskStatus:(NSInteger)taskStatus
  579. {
  580. NSURL *url;
  581. NSMutableURLRequest *request;
  582. PHAsset *asset;
  583. NSError *error;
  584. NSString *serverUrl = metadata.serverUrl;
  585. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", metadata.account]];
  586. if (tableAccount == nil) {
  587. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadata.ocId]];
  588. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_uploadedFile object:nil userInfo:@{@"metadata": metadata, @"errorCode": @(k_CCErrorInternalError), @"errorDescription": @"Upload error, account not found"}];
  589. return;
  590. }
  591. // calculate and store file size
  592. NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:[CCUtility getDirectoryProviderStorageOcId:metadata.ocId fileNameView:metadata.fileName] error:&error];
  593. long long fileSize = [[fileAttributes objectForKey:NSFileSize] longLongValue];
  594. metadata.size = fileSize;
  595. [[NCManageDatabase sharedInstance] addMetadata:metadata];
  596. url = [NSURL URLWithString:[[NSString stringWithFormat:@"%@/%@", metadata.serverUrl, metadata.fileName] encodeString:NSUTF8StringEncoding]];
  597. request = [NSMutableURLRequest requestWithURL:url];
  598. NSData *authData = [[NSString stringWithFormat:@"%@:%@", tableAccount.user, [CCUtility getPassword:tableAccount.account]] dataUsingEncoding:NSUTF8StringEncoding];
  599. NSString *authValue = [NSString stringWithFormat: @"Basic %@",[authData base64EncodedStringWithOptions:0]];
  600. [request setHTTPMethod:@"PUT"];
  601. [request setValue:authValue forHTTPHeaderField:@"Authorization"];
  602. [request setValue:[CCUtility getUserAgent] forHTTPHeaderField:@"User-Agent"];
  603. // Create Image for Upload (gray scale)
  604. #ifndef EXTENSION
  605. [CCGraphics createNewImageFrom:metadata.fileNameView ocId:metadata.ocId filterGrayScale:YES typeFile:metadata.typeFile writeImage:YES];
  606. #endif
  607. // Change date file upload with header : X-OC-Mtime (ctime assetLocalIdentifier) image/video
  608. if (metadata.assetLocalIdentifier) {
  609. PHFetchResult *result = [PHAsset fetchAssetsWithLocalIdentifiers:@[metadata.assetLocalIdentifier] options:nil];
  610. if (result.count) {
  611. asset = result[0];
  612. long dateFileCreation = [asset.creationDate timeIntervalSince1970];
  613. [request setValue:[NSString stringWithFormat:@"%ld", dateFileCreation] forHTTPHeaderField:@"X-OC-Mtime"];
  614. }
  615. }
  616. // E2EE : CREATE AND SEND METADATA
  617. if ([CCUtility isFolderEncrypted:metadata.serverUrl e2eEncrypted:metadata.e2eEncrypted account:tableAccount.account] && [CCUtility isEndToEndEnabled:tableAccount.account]) {
  618. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  619. // Send Metadata
  620. NSError *error = [[NCNetworkingEndToEnd sharedManager] sendEndToEndMetadataOnServerUrl:serverUrl fileNameRename:nil fileNameNewRename:nil unlock:false account:tableAccount.account user:tableAccount.user userID:tableAccount.userID password:[CCUtility getPassword:tableAccount.account] url:tableAccount.url];
  621. dispatch_async(dispatch_get_main_queue(), ^{
  622. if (error) {
  623. NSString *messageError = [NSString stringWithFormat:@"%@ (%d)", error.localizedDescription, (int)error.code];
  624. [[NCManageDatabase sharedInstance] setMetadataSession:metadata.session sessionError:messageError sessionSelector:nil sessionTaskIdentifier:k_taskIdentifierDone status:k_metadataStatusUploadError predicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadata.ocId]];
  625. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_uploadedFile object:nil userInfo:@{@"metadata": metadata, @"errorCode": @(k_CCErrorInternalError), @"errorDescription": messageError}];
  626. } else {
  627. // Add Header e2e-token
  628. tableE2eEncryptionLock *tableLock = [[NCManageDatabase sharedInstance] getE2ETokenLockWithServerUrl:metadata.serverUrl];
  629. [request setValue:tableLock.e2eToken forHTTPHeaderField:@"e2e-token"];
  630. // NSURLSession
  631. NSURLSession *sessionUpload;
  632. if ([metadata.session isEqualToString:k_upload_session]) sessionUpload = [self sessionUpload];
  633. else if ([metadata.session isEqualToString:k_upload_session_wwan]) sessionUpload = [self sessionWWanUpload];
  634. else if ([metadata.session isEqualToString:k_upload_session_foreground]) sessionUpload = [self sessionUploadForeground];
  635. else if ([metadata.session isEqualToString:k_upload_session_extension]) sessionUpload = [self sessionUploadExtension];
  636. NSURLSessionUploadTask *uploadTask = [sessionUpload uploadTaskWithRequest:request fromFile:[NSURL fileURLWithPath:[CCUtility getDirectoryProviderStorageOcId:metadata.ocId fileNameView:metadata.fileName]]];
  637. // Manage uploadTask cancel,suspend,resume
  638. if (taskStatus == k_taskStatusCancel) [uploadTask cancel];
  639. else if (taskStatus == k_taskStatusSuspend) [uploadTask suspend];
  640. else if (taskStatus == k_taskStatusResume) [uploadTask resume];
  641. // *** E2EE ***
  642. [[NCManageDatabase sharedInstance] setMetadataSession:metadata.session sessionError:@"" sessionSelector:nil sessionTaskIdentifier:uploadTask.taskIdentifier status:k_metadataStatusUploading predicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadata.ocId]];
  643. NSLog(@"[LOG] Upload file %@ TaskIdentifier %lu", metadata.fileName, (unsigned long)uploadTask.taskIdentifier);
  644. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_uploadFileStart object:nil userInfo:@{@"ocId": metadata.ocId, @"task": uploadTask, @"serverUrl": metadata.serverUrl, @"account": metadata.account}];
  645. }
  646. });
  647. });
  648. } else {
  649. // NSURLSession
  650. NSURLSession *sessionUpload;
  651. if ([metadata.session isEqualToString:k_upload_session]) sessionUpload = [self sessionUpload];
  652. else if ([metadata.session isEqualToString:k_upload_session_wwan]) sessionUpload = [self sessionWWanUpload];
  653. else if ([metadata.session isEqualToString:k_upload_session_foreground]) sessionUpload = [self sessionUploadForeground];
  654. else if ([metadata.session isEqualToString:k_upload_session_extension]) sessionUpload = [self sessionUploadExtension];
  655. NSURLSessionUploadTask *uploadTask = [sessionUpload uploadTaskWithRequest:request fromFile:[NSURL fileURLWithPath:[CCUtility getDirectoryProviderStorageOcId:metadata.ocId fileNameView:metadata.fileName]]];
  656. // Manage uploadTask cancel,suspend,resume
  657. if (taskStatus == k_taskStatusCancel) [uploadTask cancel];
  658. else if (taskStatus == k_taskStatusSuspend) [uploadTask suspend];
  659. else if (taskStatus == k_taskStatusResume) [uploadTask resume];
  660. // *** PLAIN ***
  661. [[NCManageDatabase sharedInstance] setMetadataSession:metadata.session sessionError:@"" sessionSelector:nil sessionTaskIdentifier:uploadTask.taskIdentifier status:k_metadataStatusUploading predicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadata.ocId]];
  662. NSLog(@"[LOG] Upload file %@ TaskIdentifier %lu", metadata.fileName, (unsigned long)uploadTask.taskIdentifier);
  663. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_uploadFileStart object:nil userInfo:@{@"ocId": metadata.ocId, @"task": uploadTask, @"serverUrl": metadata.serverUrl, @"account": metadata.account}];
  664. }
  665. }
  666. - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
  667. {
  668. }
  669. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend
  670. {
  671. NSString *url = [[[task currentRequest].URL absoluteString] stringByRemovingPercentEncoding];
  672. NSString *fileName = [url lastPathComponent];
  673. NSString *serverUrl = [self getServerUrlFromUrl:url];
  674. if (!serverUrl) return;
  675. if (totalBytesExpectedToSend < 1) {
  676. totalBytesExpectedToSend = totalBytesSent;
  677. }
  678. float progress = (float) totalBytesSent / (float)totalBytesExpectedToSend;
  679. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataInSessionFromFileName:fileName serverUrl:serverUrl taskIdentifier:task.taskIdentifier];
  680. if (metadata) {
  681. 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])};
  682. if (userInfo)
  683. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_progressTask object:nil userInfo:userInfo];
  684. }
  685. }
  686. - (void)uploadFileSuccessFailure:(tableMetadata *)metadata fileName:(NSString *)fileName ocId:(NSString *)ocId etag:(NSString *)etag date:(NSDate *)date serverUrl:(NSString *)serverUrl errorCode:(NSInteger)errorCode
  687. {
  688. NSString *tempocId = metadata.ocId;
  689. NSString *errorMessage = @"";
  690. BOOL isE2EEDirectory = false;
  691. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", metadata.account]];
  692. if (tableAccount == nil) {
  693. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", tempocId]];
  694. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_uploadedFile object:nil userInfo:@{@"metadata": metadata, @"errorCode": @(errorCode), @"errorDescription": errorMessage}];
  695. return;
  696. }
  697. // is this a E2EE Directory ?
  698. if ([CCUtility isFolderEncrypted:serverUrl e2eEncrypted:false account:tableAccount.account] && [CCUtility isEndToEndEnabled:tableAccount.account]) {
  699. isE2EEDirectory = true;
  700. }
  701. // ERRORE
  702. if (errorCode != 0) {
  703. #ifndef EXTENSION
  704. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  705. [appDelegate.listProgressMetadata removeObjectForKey:metadata.ocId];
  706. #endif
  707. // Mark error only if not Cancelled Task
  708. if (errorCode == kCFURLErrorCancelled) {
  709. if (metadata.status == k_metadataStatusUploadForcedStart) {
  710. errorCode = 0;
  711. metadata.session = k_upload_session;
  712. metadata.sessionError = @"";
  713. metadata.sessionTaskIdentifier = 0;
  714. metadata.status = k_metadataStatusInUpload;
  715. metadata = [[NCManageDatabase sharedInstance] addMetadata:metadata];
  716. [[CCNetworking sharedNetworking] uploadFile:metadata taskStatus:k_taskStatusResume];
  717. } else {
  718. [[NSFileManager defaultManager] removeItemAtPath:[CCUtility getDirectoryProviderStorageOcId:tempocId] error:nil];
  719. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", tempocId]];
  720. errorMessage = [CCError manageErrorKCF:errorCode withNumberError:YES];
  721. }
  722. } else {
  723. if (metadata && (errorCode == kOCErrorServerUnauthorized || errorCode == kOCErrorServerForbidden)) {
  724. #ifndef EXTENSION
  725. [[NCNetworkingCheckRemoteUser shared] checkRemoteUserWithAccount:metadata.account];
  726. #endif
  727. } else if (metadata && errorCode == NSURLErrorServerCertificateUntrusted) {
  728. [CCUtility setCertificateError:metadata.account error:YES];
  729. }
  730. [[NCManageDatabase sharedInstance] setMetadataSession:nil sessionError:[CCError manageErrorKCF:errorCode withNumberError:NO] sessionSelector:nil sessionTaskIdentifier:k_taskIdentifierDone status:k_metadataStatusUploadError predicate:[NSPredicate predicateWithFormat:@"ocId == %@", tempocId]];
  731. errorMessage = [CCError manageErrorKCF:errorCode withNumberError:YES];
  732. }
  733. } else {
  734. // Delete Asset
  735. if (tableAccount.autoUploadDeleteAssetLocalIdentifier && ![metadata.assetLocalIdentifier isEqualToString:@""] && [metadata.sessionSelector isEqualToString:selectorUploadAutoUpload]) {
  736. metadata.deleteAssetLocalIdentifier = true;
  737. }
  738. // Edited file, remove tempocId and adjust the directory provider storage
  739. if (metadata.edited) {
  740. // Update metadata tempocId
  741. [[NCManageDatabase sharedInstance] setMetadataSession:@"" sessionError:@"" sessionSelector:@"" sessionTaskIdentifier:k_taskIdentifierDone status:k_metadataStatusNormal predicate:[NSPredicate predicateWithFormat:@"ocId == %@", tempocId]];
  742. // Add metadata ocId
  743. metadata.date = date;
  744. if (isE2EEDirectory) {
  745. metadata.e2eEncrypted = true;
  746. } else {
  747. metadata.e2eEncrypted = false;
  748. }
  749. metadata.etag = etag;
  750. metadata.ocId = ocId;
  751. metadata.session = @"";
  752. metadata.sessionError = @"";
  753. metadata.sessionTaskIdentifier = k_taskIdentifierDone;
  754. metadata.status = k_metadataStatusNormal;
  755. metadata = [[NCManageDatabase sharedInstance] addMetadata:metadata];
  756. // Copy new version on old version
  757. if (![tempocId isEqualToString:metadata.ocId]) {
  758. [CCUtility copyFileAtPath:[NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryProviderStorage], tempocId] toPath:[NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryProviderStorage], metadata.ocId]];
  759. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", tempocId]];
  760. // IMI -> Unzip
  761. #if HC
  762. if ([metadata.typeFile isEqualToString:k_metadataTypeFile_imagemeter]) {
  763. (void)[[IMUtility shared] IMUnzipWithMetadata:metadata];
  764. }
  765. #endif
  766. }
  767. } else {
  768. // Replace Metadata
  769. metadata.date = date;
  770. if (isE2EEDirectory) {
  771. metadata.e2eEncrypted = true;
  772. } else {
  773. metadata.e2eEncrypted = false;
  774. }
  775. metadata.etag = etag;
  776. metadata.ocId = ocId;
  777. metadata.session = @"";
  778. metadata.sessionError = @"";
  779. metadata.sessionTaskIdentifier = k_taskIdentifierDone;
  780. metadata.status = k_metadataStatusNormal;
  781. [CCUtility moveFileAtPath:[NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryProviderStorage], tempocId] toPath:[NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryProviderStorage], metadata.ocId]];
  782. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@ AND fileName == %@", metadata.account, metadata.serverUrl, metadata.fileName]];
  783. metadata = [[NCManageDatabase sharedInstance] addMetadata:metadata];
  784. NSLog(@"[LOG] Insert new upload : %@ - ocId : %@", metadata.fileName, ocId);
  785. }
  786. #ifndef EXTENSION
  787. // EXIF
  788. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image])
  789. [[CCExifGeo sharedInstance] setExifLocalTableEtag:metadata];
  790. // Create preview
  791. [CCGraphics createNewImageFrom:metadata.fileNameView ocId:metadata.ocId filterGrayScale:NO typeFile:metadata.typeFile writeImage:YES];
  792. // Copy photo or video in the photo album for auto upload
  793. if ([metadata.assetLocalIdentifier length] > 0 && ([metadata.sessionSelector isEqualToString:selectorUploadAutoUpload] || [metadata.sessionSelector isEqualToString:selectorUploadFile])) {
  794. PHAsset *asset;
  795. PHFetchResult *result = [PHAsset fetchAssetsWithLocalIdentifiers:@[metadata.assetLocalIdentifier] options:nil];
  796. if(result.count){
  797. asset = result[0];
  798. [asset saveToAlbum:[NCBrandOptions sharedInstance].brand completionBlock:^(BOOL success) {
  799. if (success) NSLog(@"[LOG] Insert file %@ in %@", metadata.fileName, [NCBrandOptions sharedInstance].brand);
  800. else NSLog(@"[LOG] File %@ do not insert in %@", metadata.fileName, [NCBrandOptions sharedInstance].brand);
  801. }];
  802. }
  803. }
  804. #endif
  805. // Add Local or Remove from cache
  806. if ([CCUtility getDisableLocalCacheAfterUpload] && !metadata.edited) {
  807. [[NSFileManager defaultManager] removeItemAtPath:[CCUtility getDirectoryProviderStorageOcId:metadata.ocId] error:nil];
  808. } else {
  809. // Add Local
  810. (void)[[NCManageDatabase sharedInstance] addLocalFileWithMetadata:metadata];
  811. }
  812. }
  813. // Detect E2EE
  814. 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]];
  815. // E2EE : UNLOCK
  816. if (isE2EEDirectory && e2eeMetadataInSession == nil) {
  817. [[NCNetworkingE2EE sharedInstance] unlockWithAccount:tableAccount.account serverUrl:serverUrl completion:^(NSInteger errorCode, NSString *errorDescription) { }];
  818. }
  819. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_uploadedFile object:nil userInfo:@{@"metadata": metadata, @"errorCode": @(errorCode), @"errorDescription": errorMessage}];
  820. }
  821. #pragma --------------------------------------------------------------------------------------------
  822. #pragma mark ===== Utility =====
  823. #pragma --------------------------------------------------------------------------------------------
  824. - (NSString *)getServerUrlFromUrl:(NSString *)url
  825. {
  826. NSString *fileName = [url lastPathComponent];
  827. url = [url stringByReplacingOccurrencesOfString:[@"/" stringByAppendingString:fileName] withString:@""];
  828. return url;
  829. }
  830. @end