CCNetworking.m 66 KB

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