CCNetworking.m 58 KB

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