CCNetworking.m 65 KB

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