CCNetworking.m 56 KB

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