CCNetworking.m 69 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265
  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. } else {
  277. NSLog(@"[LOG] Remove record ? : metadata not found %@", url);
  278. dispatch_async(dispatch_get_main_queue(), ^{
  279. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:ocId:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  280. [self.delegate uploadFileSuccessFailure:fileName ocId:@"" assetLocalIdentifier:@"" serverUrl:serverUrl selector:@"" errorMessage:@"" errorCode:k_CCErrorInternalError];
  281. }
  282. });
  283. }
  284. }
  285. }
  286. #pragma --------------------------------------------------------------------------------------------
  287. #pragma mark ===== Download =====
  288. #pragma --------------------------------------------------------------------------------------------
  289. - (void)downloadFile:(tableMetadata *)metadata taskStatus:(NSInteger)taskStatus
  290. {
  291. // No Password
  292. if ([CCUtility getPassword:metadata.account].length == 0) {
  293. [self.delegate downloadFileSuccessFailure:metadata.fileName ocId:metadata.ocId serverUrl:metadata.serverUrl selector:metadata.sessionSelector errorMessage:NSLocalizedString(@"_bad_username_password_", nil) errorCode:kOCErrorServerUnauthorized];
  294. return;
  295. } else if ([CCUtility getCertificateError:metadata.account]) {
  296. [self.delegate downloadFileSuccessFailure:metadata.fileName ocId:metadata.ocId serverUrl:metadata.serverUrl selector:metadata.sessionSelector errorMessage:NSLocalizedString(@"_ssl_certificate_untrusted_", nil) errorCode:NSURLErrorServerCertificateUntrusted];
  297. return;
  298. }
  299. // File exists ?
  300. tableLocalFile *localfile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadata.ocId]];
  301. if (localfile != nil && [CCUtility fileProviderStorageExists:metadata.ocId fileNameView:metadata.fileNameView]) {
  302. [[NCManageDatabase sharedInstance] setMetadataSession:@"" sessionError:@"" sessionSelector:@"" sessionTaskIdentifier:k_taskIdentifierDone status:k_metadataStatusNormal predicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadata.ocId]];
  303. if ([self.delegate respondsToSelector:@selector(downloadFileSuccessFailure:ocId:serverUrl:selector:errorMessage:errorCode:)]) {
  304. [self.delegate downloadFileSuccessFailure:metadata.fileName ocId:metadata.ocId serverUrl:metadata.serverUrl selector:metadata.sessionSelector errorMessage:@"" errorCode:0];
  305. }
  306. return;
  307. }
  308. [self downloaURLSession:metadata taskStatus:taskStatus];
  309. }
  310. - (void)downloaURLSession:(tableMetadata *)metadata taskStatus:(NSInteger)taskStatus
  311. {
  312. NSURLSession *sessionDownload;
  313. NSURL *url;
  314. NSMutableURLRequest *request;
  315. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", metadata.account]];
  316. if (tableAccount == nil) {
  317. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadata.ocId]];
  318. if ([self.delegate respondsToSelector:@selector(downloadFileSuccessFailure:ocId:serverUrl:selector:errorMessage:errorCode:)]) {
  319. [self.delegate downloadFileSuccessFailure:metadata.fileName ocId:metadata.ocId serverUrl:metadata.serverUrl selector:metadata.sessionSelector errorMessage:@"Download error, account not found" errorCode:k_CCErrorInternalError];
  320. }
  321. return;
  322. }
  323. NSString *serverFileUrl = [[NSString stringWithFormat:@"%@/%@", metadata.serverUrl, metadata.fileName] encodeString:NSUTF8StringEncoding];
  324. url = [NSURL URLWithString:serverFileUrl];
  325. request = [NSMutableURLRequest requestWithURL:url];
  326. NSData *authData = [[NSString stringWithFormat:@"%@:%@", tableAccount.user, [CCUtility getPassword:tableAccount.account]] dataUsingEncoding:NSUTF8StringEncoding];
  327. NSString *authValue = [NSString stringWithFormat: @"Basic %@",[authData base64EncodedStringWithOptions:0]];
  328. [request setValue:authValue forHTTPHeaderField:@"Authorization"];
  329. [request setValue:[CCUtility getUserAgent] forHTTPHeaderField:@"User-Agent"];
  330. if ([metadata.session isEqualToString:k_download_session]) sessionDownload = [self sessionDownload];
  331. else if ([metadata.session isEqualToString:k_download_session_foreground]) sessionDownload = [self sessionDownloadForeground];
  332. else if ([metadata.session isEqualToString:k_download_session_wwan]) sessionDownload = [self sessionWWanDownload];
  333. NSURLSessionDownloadTask *downloadTask = [sessionDownload downloadTaskWithRequest:request];
  334. if (downloadTask == nil) {
  335. [[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]];
  336. if ([self.delegate respondsToSelector:@selector(downloadFileSuccessFailure:ocId:serverUrl:selector:errorMessage:errorCode:)]) {
  337. [self.delegate downloadFileSuccessFailure:metadata.fileName ocId:metadata.ocId serverUrl:metadata.serverUrl selector:metadata.sessionSelector errorMessage:@"Serious internal error downloadTask not available" errorCode:k_CCErrorInternalError];
  338. }
  339. } else {
  340. // Manage uploadTask cancel,suspend,resume
  341. if (taskStatus == k_taskStatusCancel) [downloadTask cancel];
  342. else if (taskStatus == k_taskStatusSuspend) [downloadTask suspend];
  343. else if (taskStatus == k_taskStatusResume) [downloadTask resume];
  344. [[NCManageDatabase sharedInstance] setMetadataSession:nil sessionError:nil sessionSelector:nil sessionTaskIdentifier:downloadTask.taskIdentifier status:k_metadataStatusDownloading predicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadata.ocId]];
  345. NSLog(@"[LOG] downloadFileSession %@ Task [%lu]", metadata.ocId, (unsigned long)downloadTask.taskIdentifier);
  346. dispatch_async(dispatch_get_main_queue(), ^{
  347. if ([self.delegate respondsToSelector:@selector(downloadStart:account:task:serverUrl:)]) {
  348. [self.delegate downloadStart:metadata.ocId account:metadata.account task:downloadTask serverUrl:metadata.serverUrl];
  349. }
  350. });
  351. }
  352. }
  353. - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
  354. {
  355. NSString *url = [[[downloadTask currentRequest].URL absoluteString] stringByRemovingPercentEncoding];
  356. NSString *fileName = [url lastPathComponent];
  357. NSString *serverUrl = [self getServerUrlFromUrl:url];
  358. if (!serverUrl) return;
  359. if (totalBytesExpectedToWrite < 1) {
  360. totalBytesExpectedToWrite = totalBytesWritten;
  361. }
  362. float progress = (float) totalBytesWritten / (float)totalBytesExpectedToWrite;
  363. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataInSessionFromFileName:fileName serverUrl:serverUrl taskIdentifier:downloadTask.taskIdentifier];
  364. if (metadata) {
  365. 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])};
  366. if (userInfo)
  367. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"NotificationProgressTask" object:nil userInfo:userInfo];
  368. } else {
  369. NSLog(@"[LOG] metadata not found");
  370. }
  371. }
  372. - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
  373. {
  374. NSString *url = [[[downloadTask currentRequest].URL absoluteString] stringByRemovingPercentEncoding];
  375. if (!url)
  376. return;
  377. NSString *fileName = [url lastPathComponent];
  378. NSString *serverUrl = [self getServerUrlFromUrl:url];
  379. if (!serverUrl) return;
  380. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataInSessionFromFileName:fileName serverUrl:serverUrl taskIdentifier:downloadTask.taskIdentifier];
  381. if (!metadata) {
  382. NSLog(@"[LOG] Serious error internal download : metadata not found %@ ", url);
  383. dispatch_async(dispatch_get_main_queue(), ^{
  384. if ([self.delegate respondsToSelector:@selector(downloadFileSuccessFailure:ocId:serverUrl:selector:errorMessage:errorCode:)]) {
  385. [self.delegate downloadFileSuccessFailure:@"" ocId:@"" serverUrl:serverUrl selector:@"" errorMessage:@"Serious error internal download : metadata not found" errorCode:k_CCErrorInternalError];
  386. }
  387. });
  388. return;
  389. }
  390. NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)downloadTask.response;
  391. if (httpResponse.statusCode >= 200 && httpResponse.statusCode < 300) {
  392. NSString *destinationFilePath = [CCUtility getDirectoryProviderStorageOcId:metadata.ocId fileNameView:metadata.fileName];
  393. NSURL *destinationURL = [NSURL fileURLWithPath:destinationFilePath];
  394. [[NSFileManager defaultManager] removeItemAtURL:destinationURL error:NULL];
  395. [[NSFileManager defaultManager] copyItemAtURL:location toURL:destinationURL error:nil];
  396. }
  397. }
  398. - (void)downloadFileSuccessFailure:(NSString *)fileName ocId:(NSString *)ocId etag:(NSString *)etag date:(NSDate *)date serverUrl:(NSString *)serverUrl selector:(NSString *)selector errorCode:(NSInteger)errorCode
  399. {
  400. #ifndef EXTENSION
  401. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  402. [appDelegate.listProgressMetadata removeObjectForKey:ocId];
  403. #endif
  404. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", ocId]];
  405. if (errorCode != 0) {
  406. if (errorCode == kCFURLErrorCancelled) {
  407. [[NCManageDatabase sharedInstance] setMetadataSession:@"" sessionError:@"" sessionSelector:@"" sessionTaskIdentifier:k_taskIdentifierDone status:k_metadataStatusNormal predicate:[NSPredicate predicateWithFormat:@"ocId == %@", ocId]];
  408. } else {
  409. if (metadata && (errorCode == kOCErrorServerUnauthorized || errorCode == kOCErrorServerForbidden))
  410. [[OCNetworking sharedManager] checkRemoteUser:metadata.account function:@"download" errorCode:errorCode];
  411. else if (metadata && errorCode == NSURLErrorServerCertificateUntrusted)
  412. [CCUtility setCertificateError:metadata.account error:YES];
  413. [[NCManageDatabase sharedInstance] setMetadataSession:nil sessionError:[CCError manageErrorKCF:errorCode withNumberError:NO] sessionSelector:nil sessionTaskIdentifier:k_taskIdentifierDone status:k_metadataStatusDownloadError predicate:[NSPredicate predicateWithFormat:@"ocId == %@", ocId]];
  414. }
  415. if ([self.delegate respondsToSelector:@selector(downloadFileSuccessFailure:ocId:serverUrl:selector:errorMessage:errorCode:)]) {
  416. [self.delegate downloadFileSuccessFailure:fileName ocId:ocId serverUrl:serverUrl selector:selector errorMessage:[CCError manageErrorKCF:errorCode withNumberError:YES] errorCode:errorCode];
  417. }
  418. } else {
  419. if (!metadata) {
  420. NSLog(@"[LOG] Serious error internal download : metadata not found %@ ", fileName);
  421. if ([self.delegate respondsToSelector:@selector(downloadFileSuccessFailure:ocId:serverUrl:selector:errorMessage:errorCode:)]) {
  422. [self.delegate downloadFileSuccessFailure:fileName ocId:ocId serverUrl:serverUrl selector:selector errorMessage:[NSString stringWithFormat:@"Serious error internal download : metadata not found %@", fileName] errorCode:k_CCErrorInternalError];
  423. }
  424. return;
  425. }
  426. metadata.session = @"";
  427. metadata.sessionError = @"";
  428. metadata.sessionSelector = @"";
  429. metadata.sessionTaskIdentifier = k_taskIdentifierDone;
  430. metadata.status = k_metadataStatusNormal;
  431. metadata = [[NCManageDatabase sharedInstance] updateMetadata:metadata];
  432. (void)[[NCManageDatabase sharedInstance] addLocalFileWithMetadata:metadata];
  433. // E2EE Decrypted
  434. tableE2eEncryption *object = [[NCManageDatabase sharedInstance] getE2eEncryptionWithPredicate:[NSPredicate predicateWithFormat:@"fileNameIdentifier == %@ AND serverUrl == %@", fileName, serverUrl]];
  435. if (object) {
  436. BOOL result = [[NCEndToEndEncryption sharedManager] decryptFileName:metadata.fileName fileNameView:metadata.fileNameView ocId:metadata.ocId key:object.key initializationVector:object.initializationVector authenticationTag:object.authenticationTag];
  437. if (!result) {
  438. if ([self.delegate respondsToSelector:@selector(downloadFileSuccessFailure:ocId:serverUrl:selector:errorMessage:errorCode:)]) {
  439. [self.delegate downloadFileSuccessFailure:fileName ocId:ocId serverUrl:serverUrl selector:selector errorMessage:[NSString stringWithFormat:@"Serious error internal download : decrypt error %@", fileName] errorCode:k_CCErrorInternalError];
  440. }
  441. return;
  442. }
  443. }
  444. // NSNotificationCenter
  445. NSDictionary* userInfo = @{@"metadata": metadata};
  446. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_downloadFile object:nil userInfo:userInfo];
  447. // Exif
  448. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image])
  449. [[CCExifGeo sharedInstance] setExifLocalTableEtag:metadata];
  450. // Icon
  451. if ([[NSFileManager defaultManager] fileExistsAtPath:[CCUtility getDirectoryProviderStorageIconOcId:metadata.ocId fileNameView:metadata.fileNameView]] == NO) {
  452. [CCGraphics createNewImageFrom:metadata.fileNameView ocId:metadata.ocId extension:[metadata.fileNameView pathExtension] filterGrayScale:NO typeFile:metadata.typeFile writeImage:YES];
  453. }
  454. if ([self.delegate respondsToSelector:@selector(downloadFileSuccessFailure:ocId:serverUrl:selector:errorMessage:errorCode:)]) {
  455. [self.delegate downloadFileSuccessFailure:fileName ocId:ocId serverUrl:serverUrl selector:selector errorMessage:@"" errorCode:0];
  456. }
  457. }
  458. }
  459. #pragma --------------------------------------------------------------------------------------------
  460. #pragma mark ===== Upload =====
  461. #pragma --------------------------------------------------------------------------------------------
  462. - (void)uploadFile:(tableMetadata *)metadata taskStatus:(NSInteger)taskStatus
  463. {
  464. // Password nil
  465. if ([CCUtility getPassword:metadata.account].length == 0) {
  466. [self.delegate uploadFileSuccessFailure:metadata.fileName ocId:metadata.ocId assetLocalIdentifier:metadata.assetLocalIdentifier serverUrl:metadata.serverUrl selector:metadata.sessionSelector errorMessage:NSLocalizedString(@"_bad_username_password_", nil) errorCode:kOCErrorServerUnauthorized];
  467. return;
  468. } else if ([CCUtility getCertificateError:metadata.account]) {
  469. [self.delegate uploadFileSuccessFailure:metadata.fileName ocId:metadata.ocId assetLocalIdentifier:metadata.assetLocalIdentifier serverUrl:metadata.serverUrl selector:metadata.sessionSelector errorMessage:NSLocalizedString(@"_ssl_certificate_untrusted_", nil) errorCode:NSURLErrorServerCertificateUntrusted];
  470. return;
  471. }
  472. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", metadata.account]];
  473. if (tableAccount == nil) {
  474. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadata.ocId]];
  475. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:ocId:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  476. [self.delegate uploadFileSuccessFailure:metadata.fileName ocId:metadata.ocId assetLocalIdentifier:metadata.assetLocalIdentifier serverUrl:metadata.serverUrl selector:metadata.sessionSelector errorMessage:@"Upload error, account not found" errorCode:k_CCErrorInternalError];
  477. }
  478. return;
  479. }
  480. if ([CCUtility fileProviderStorageExists:metadata.ocId fileNameView:metadata.fileNameView] == NO) {
  481. PHFetchResult *result = [PHAsset fetchAssetsWithLocalIdentifiers:@[metadata.assetLocalIdentifier] options:nil];
  482. if (!result.count) {
  483. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadata.ocId]];
  484. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:ocId:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  485. [self.delegate uploadFileSuccessFailure:metadata.fileName ocId:metadata.ocId assetLocalIdentifier:metadata.assetLocalIdentifier serverUrl:metadata.serverUrl selector:metadata.sessionSelector errorMessage:@"Error photo/video not found, remove from upload" errorCode:k_CCErrorInternalError];
  486. }
  487. return;
  488. }
  489. PHAsset *asset= result[0];
  490. // IMAGE
  491. if (asset.mediaType == PHAssetMediaTypeImage) {
  492. PHImageRequestOptions *options = [PHImageRequestOptions new];
  493. options.networkAccessAllowed = YES; // iCloud
  494. options.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
  495. options.synchronous = YES;
  496. options.progressHandler = ^(double progress, NSError *error, BOOL *stop, NSDictionary *info) {
  497. NSLog(@"cacheAsset: %f", progress);
  498. if (error) {
  499. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadata.ocId]];
  500. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:ocId:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  501. [self.delegate uploadFileSuccessFailure:metadata.fileName ocId:metadata.ocId assetLocalIdentifier:metadata.assetLocalIdentifier serverUrl:metadata.serverUrl selector:metadata.sessionSelector errorMessage:[NSString stringWithFormat:@"Image request iCloud failed [%@]", error.description] errorCode:error.code];
  502. }
  503. }
  504. };
  505. [[PHImageManager defaultManager] requestImageDataForAsset:asset options:options resultHandler:^(NSData *imageData, NSString *dataUTI, UIImageOrientation orientation, NSDictionary *info) {
  506. NSError *error = nil;
  507. NSString *extensionAsset = [[[asset valueForKey:@"filename"] pathExtension] uppercaseString];
  508. if ([extensionAsset isEqualToString:@"HEIC"] && [CCUtility getFormatCompatibility]) {
  509. CIImage *ciImage = [CIImage imageWithData:imageData];
  510. CIContext *context = [CIContext context];
  511. imageData = [context JPEGRepresentationOfImage:ciImage colorSpace:ciImage.colorSpace options:@{}];
  512. NSString *fileNameJPEG = [[metadata.fileName lastPathComponent] stringByDeletingPathExtension];
  513. metadata.fileName = [fileNameJPEG stringByAppendingString:@".jpg"];
  514. metadata.fileNameView = metadata.fileName;
  515. // Change Metadata with new ocId, fileName, fileNameView
  516. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadata.ocId]];
  517. metadata.ocId = [CCUtility createMetadataIDFromAccount:metadata.account serverUrl:metadata.serverUrl fileNameView:metadata.fileNameView directory:false];
  518. }
  519. tableMetadata *metadataForUpload = [[NCManageDatabase sharedInstance] addMetadata:[CCUtility insertFileSystemInMetadata:metadata]];
  520. [imageData writeToFile:[CCUtility getDirectoryProviderStorageOcId:metadataForUpload.ocId fileNameView:metadataForUpload.fileNameView] options:NSDataWritingAtomic error:&error];
  521. if (error) {
  522. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadataForUpload.ocId]];
  523. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:ocId:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  524. [self.delegate uploadFileSuccessFailure:metadataForUpload.fileName ocId:metadataForUpload.ocId assetLocalIdentifier:metadataForUpload.assetLocalIdentifier serverUrl:metadataForUpload.serverUrl selector:metadataForUpload.sessionSelector errorMessage:[NSString stringWithFormat:@"Image request failed [%@]", error.description] errorCode:error.code];
  525. }
  526. } else {
  527. // OOOOOK
  528. if ([CCUtility isFolderEncrypted:metadataForUpload.serverUrl account:tableAccount.account] && [CCUtility isEndToEndEnabled:tableAccount.account]) {
  529. [self e2eEncryptedFile:metadataForUpload tableAccount:tableAccount taskStatus:taskStatus];
  530. } else {
  531. [self uploadURLSessionMetadata:metadataForUpload tableAccount:tableAccount taskStatus:taskStatus];
  532. }
  533. }
  534. }];
  535. }
  536. // VIDEO
  537. if (asset.mediaType == PHAssetMediaTypeVideo) {
  538. PHVideoRequestOptions *options = [PHVideoRequestOptions new];
  539. options.networkAccessAllowed = YES;
  540. options.version = PHVideoRequestOptionsVersionOriginal;
  541. options.progressHandler = ^(double progress, NSError *error, BOOL *stop, NSDictionary *info) {
  542. NSLog(@"cacheAsset: %f", progress);
  543. if (error) {
  544. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadata.ocId]];
  545. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:ocId:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  546. [self.delegate uploadFileSuccessFailure:metadata.fileName ocId:metadata.ocId assetLocalIdentifier:metadata.assetLocalIdentifier serverUrl:metadata.serverUrl selector:metadata.sessionSelector errorMessage:[NSString stringWithFormat:@"Video request iCloud failed [%@]", error.description] errorCode:error.code];
  547. }
  548. }
  549. };
  550. [[PHImageManager defaultManager] requestAVAssetForVideo:asset options:options resultHandler:^(AVAsset *asset, AVAudioMix *audioMix, NSDictionary *info) {
  551. if ([asset isKindOfClass:[AVURLAsset class]]) {
  552. NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:[CCUtility getDirectoryProviderStorageOcId:metadata.ocId fileNameView:metadata.fileNameView]];
  553. NSError *error = nil;
  554. [[NSFileManager defaultManager] removeItemAtURL:fileURL error:nil];
  555. [[NSFileManager defaultManager] copyItemAtURL:[(AVURLAsset *)asset URL] toURL:fileURL error:&error];
  556. if (error) {
  557. dispatch_async(dispatch_get_main_queue(), ^{
  558. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadata.ocId]];
  559. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:ocId:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  560. [self.delegate uploadFileSuccessFailure:metadata.fileName ocId:metadata.ocId assetLocalIdentifier:metadata.assetLocalIdentifier serverUrl:metadata.serverUrl selector:metadata.sessionSelector errorMessage:[NSString stringWithFormat:@"Video request failed [%@]", error.description] errorCode:error.code];
  561. }
  562. });
  563. } else {
  564. dispatch_async(dispatch_get_main_queue(), ^{
  565. // create Metadata for Upload
  566. tableMetadata *metadataForUpload = [[NCManageDatabase sharedInstance] addMetadata:[CCUtility insertFileSystemInMetadata:metadata]];
  567. // OOOOOK
  568. if ([CCUtility isFolderEncrypted:metadataForUpload.serverUrl account:tableAccount.account] && [CCUtility isEndToEndEnabled:tableAccount.account]) {
  569. [self e2eEncryptedFile:metadataForUpload tableAccount:tableAccount taskStatus:taskStatus];
  570. } else {
  571. [self uploadURLSessionMetadata:metadataForUpload tableAccount:tableAccount taskStatus:taskStatus];
  572. }
  573. });
  574. }
  575. }
  576. }];
  577. }
  578. } else {
  579. // create Metadata for Upload
  580. tableMetadata *metadataForUpload = [[NCManageDatabase sharedInstance] addMetadata:[CCUtility insertFileSystemInMetadata:metadata]];
  581. // OOOOOK
  582. if ([CCUtility isFolderEncrypted:metadataForUpload.serverUrl account:tableAccount.account] && [CCUtility isEndToEndEnabled:tableAccount.account]) {
  583. [self e2eEncryptedFile:metadataForUpload tableAccount:tableAccount taskStatus:taskStatus];
  584. } else {
  585. [self uploadURLSessionMetadata:metadataForUpload tableAccount:tableAccount taskStatus:taskStatus];
  586. }
  587. }
  588. }
  589. - (void)e2eEncryptedFile:(tableMetadata *)metadata tableAccount:(tableAccount *)tableAccount taskStatus:(NSInteger)taskStatus
  590. {
  591. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  592. NSError *error;
  593. NSString *fileNameIdentifier;
  594. NSString *key;
  595. NSString *initializationVector;
  596. NSString *authenticationTag;
  597. NSString *metadataKey;
  598. NSInteger metadataKeyIndex;
  599. NSString *e2eeMetadata;
  600. // Verify File Size
  601. NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:[CCUtility getDirectoryProviderStorageOcId:metadata.ocId fileNameView:metadata.fileNameView] error:&error];
  602. NSNumber *fileSizeNumber = [fileAttributes objectForKey:NSFileSize];
  603. long long fileSize = [fileSizeNumber longLongValue];
  604. if (fileSize > k_max_filesize_E2EE) {
  605. // Error for uploadFileFailure
  606. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:ocId:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  607. [self.delegate uploadFileSuccessFailure:metadata.fileName ocId:metadata.ocId assetLocalIdentifier:metadata.assetLocalIdentifier serverUrl:metadata.serverUrl selector:metadata.sessionSelector errorMessage:@"E2E Error file too big" errorCode:k_CCErrorInternalError];
  608. }
  609. return;
  610. }
  611. // if new file upload create a new encrypted filename
  612. if ([metadata.ocId isEqualToString:[CCUtility createMetadataIDFromAccount:metadata.account serverUrl:metadata.serverUrl fileNameView:metadata.fileNameView directory:false]]) {
  613. fileNameIdentifier = [CCUtility generateRandomIdentifier];
  614. } else {
  615. fileNameIdentifier = metadata.fileName;
  616. }
  617. if ([[NCEndToEndEncryption sharedManager] encryptFileName:metadata.fileNameView fileNameIdentifier:fileNameIdentifier directory:[CCUtility getDirectoryProviderStorageOcId:metadata.ocId] key:&key initializationVector:&initializationVector authenticationTag:&authenticationTag]) {
  618. tableE2eEncryption *object = [[NCManageDatabase sharedInstance] getE2eEncryptionWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", tableAccount.account, metadata.serverUrl]];
  619. if (object) {
  620. metadataKey = object.metadataKey;
  621. metadataKeyIndex = object.metadataKeyIndex;
  622. } else {
  623. metadataKey = [[[NCEndToEndEncryption sharedManager] generateKey:16] base64EncodedStringWithOptions:0]; // AES_KEY_128_LENGTH
  624. metadataKeyIndex = 0;
  625. }
  626. tableE2eEncryption *addObject = [tableE2eEncryption new];
  627. addObject.account = tableAccount.account;
  628. addObject.authenticationTag = authenticationTag;
  629. addObject.fileName = metadata.fileNameView;
  630. addObject.fileNameIdentifier = fileNameIdentifier;
  631. addObject.fileNamePath = [CCUtility returnFileNamePathFromFileName:metadata.fileNameView serverUrl:metadata.serverUrl activeUrl:tableAccount.url];
  632. addObject.key = key;
  633. addObject.initializationVector = initializationVector;
  634. addObject.metadataKey = metadataKey;
  635. addObject.metadataKeyIndex = metadataKeyIndex;
  636. CFStringRef UTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef)[metadata.fileNameView pathExtension], NULL);
  637. CFStringRef mimeTypeRef = UTTypeCopyPreferredTagWithClass (UTI, kUTTagClassMIMEType);
  638. if (mimeTypeRef) {
  639. addObject.mimeType = (__bridge NSString *)mimeTypeRef;
  640. } else {
  641. addObject.mimeType = @"application/octet-stream";
  642. }
  643. addObject.serverUrl = metadata.serverUrl;
  644. addObject.version = [[NCManageDatabase sharedInstance] getEndToEndEncryptionVersionWithAccount:tableAccount.account];
  645. // Get the last metadata
  646. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", tableAccount.account, metadata.serverUrl]];
  647. error = [[NCNetworkingEndToEnd sharedManager] getEndToEndMetadata:&e2eeMetadata ocId:directory.ocId user:tableAccount.user userID:tableAccount.userID password: [CCUtility getPassword:tableAccount.account] url:tableAccount.url];
  648. if (error == nil) {
  649. if ([[NCEndToEndMetadata sharedInstance] decoderMetadata:e2eeMetadata privateKey:[CCUtility getEndToEndPrivateKey:tableAccount.account] serverUrl:metadata.serverUrl account:tableAccount.account url:tableAccount.url] == false) {
  650. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:ocId:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  651. [self.delegate uploadFileSuccessFailure:metadata.fileName ocId:metadata.ocId assetLocalIdentifier:metadata.assetLocalIdentifier serverUrl:metadata.serverUrl selector:metadata.sessionSelector errorMessage:NSLocalizedString(@"_e2e_error_decode_metadata_", nil) errorCode:k_CCErrorInternalError];
  652. }
  653. return;
  654. }
  655. }
  656. // write new record e2ee
  657. if([[NCManageDatabase sharedInstance] addE2eEncryption:addObject] == NO) {
  658. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:ocId:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  659. [self.delegate uploadFileSuccessFailure:metadata.fileName ocId:metadata.ocId assetLocalIdentifier:metadata.assetLocalIdentifier serverUrl:metadata.serverUrl selector:metadata.sessionSelector errorMessage:NSLocalizedString(@"_e2e_error_create_encrypted_", nil) errorCode:k_CCErrorInternalError];
  660. }
  661. return;
  662. }
  663. } else {
  664. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:ocId:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  665. [self.delegate uploadFileSuccessFailure:metadata.fileName ocId:metadata.ocId assetLocalIdentifier:metadata.assetLocalIdentifier serverUrl:metadata.serverUrl selector:metadata.sessionSelector errorMessage:NSLocalizedString(@"_e2e_error_create_encrypted_", nil) errorCode:k_CCErrorInternalError];
  666. }
  667. return;
  668. }
  669. dispatch_async(dispatch_get_main_queue(), ^{
  670. // Now the fileName is fileNameIdentifier && flag e2eEncrypted
  671. metadata.fileName = fileNameIdentifier;
  672. metadata.e2eEncrypted = YES;
  673. // Update Metadata
  674. tableMetadata *metadataEncrypted = [[NCManageDatabase sharedInstance] addMetadata:metadata];
  675. [self uploadURLSessionMetadata:metadataEncrypted tableAccount:tableAccount taskStatus:taskStatus];
  676. });
  677. });
  678. }
  679. - (void)uploadURLSessionMetadata:(tableMetadata *)metadata tableAccount:(tableAccount *)tableAccount taskStatus:(NSInteger)taskStatus
  680. {
  681. NSURL *url;
  682. NSMutableURLRequest *request;
  683. PHAsset *asset;
  684. NSError *error;
  685. // calculate and store file size
  686. NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:[CCUtility getDirectoryProviderStorageOcId:metadata.ocId fileNameView:metadata.fileName] error:&error];
  687. long long fileSize = [[fileAttributes objectForKey:NSFileSize] longLongValue];
  688. metadata.size = fileSize;
  689. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  690. url = [NSURL URLWithString:[[NSString stringWithFormat:@"%@/%@", metadata.serverUrl, metadata.fileName] encodeString:NSUTF8StringEncoding]];
  691. request = [NSMutableURLRequest requestWithURL:url];
  692. NSData *authData = [[NSString stringWithFormat:@"%@:%@", tableAccount.user, [CCUtility getPassword:tableAccount.account]] dataUsingEncoding:NSUTF8StringEncoding];
  693. NSString *authValue = [NSString stringWithFormat: @"Basic %@",[authData base64EncodedStringWithOptions:0]];
  694. [request setHTTPMethod:@"PUT"];
  695. [request setValue:authValue forHTTPHeaderField:@"Authorization"];
  696. [request setValue:[CCUtility getUserAgent] forHTTPHeaderField:@"User-Agent"];
  697. // Create Image for Upload (gray scale)
  698. #ifndef EXTENSION
  699. [CCGraphics createNewImageFrom:metadata.fileNameView ocId:metadata.ocId extension:[metadata.fileNameView pathExtension] filterGrayScale:YES typeFile:metadata.typeFile writeImage:YES];
  700. #endif
  701. // Change date file upload with header : X-OC-Mtime (ctime assetLocalIdentifier) image/video
  702. if (metadata.assetLocalIdentifier) {
  703. PHFetchResult *result = [PHAsset fetchAssetsWithLocalIdentifiers:@[metadata.assetLocalIdentifier] options:nil];
  704. if (result.count) {
  705. asset = result[0];
  706. long dateFileCreation = [asset.creationDate timeIntervalSince1970];
  707. [request setValue:[NSString stringWithFormat:@"%ld", dateFileCreation] forHTTPHeaderField:@"X-OC-Mtime"];
  708. }
  709. }
  710. NSURLSession *sessionUpload;
  711. // NSURLSession
  712. if ([metadata.session isEqualToString:k_upload_session]) sessionUpload = [self sessionUpload];
  713. else if ([metadata.session isEqualToString:k_upload_session_wwan]) sessionUpload = [self sessionWWanUpload];
  714. else if ([metadata.session isEqualToString:k_upload_session_foreground]) sessionUpload = [self sessionUploadForeground];
  715. else if ([metadata.session isEqualToString:k_upload_session_extension]) sessionUpload = [self sessionUploadExtension];
  716. NSURLSessionUploadTask *uploadTask = [sessionUpload uploadTaskWithRequest:request fromFile:[NSURL fileURLWithPath:[CCUtility getDirectoryProviderStorageOcId:metadata.ocId fileNameView:metadata.fileName]]];
  717. // Error
  718. if (uploadTask == nil) {
  719. NSString *messageError = @"Serious internal error uploadTask not available";
  720. [[NCManageDatabase sharedInstance] setMetadataSession:metadata.session sessionError:messageError sessionSelector:nil sessionTaskIdentifier:k_taskIdentifierDone status:k_metadataStatusUploadError predicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadata.ocId]];
  721. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:ocId:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  722. [self.delegate uploadFileSuccessFailure:metadata.fileNameView ocId:metadata.ocId assetLocalIdentifier:metadata.assetLocalIdentifier serverUrl:metadata.serverUrl selector:metadata.sessionSelector errorMessage:messageError errorCode:k_CCErrorInternalError];
  723. }
  724. } else {
  725. // E2EE : CREATE AND SEND METADATA
  726. if ([CCUtility isFolderEncrypted:metadata.serverUrl account:tableAccount.account] && [CCUtility isEndToEndEnabled:tableAccount.account]) {
  727. NSString *serverUrl = metadata.serverUrl;
  728. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  729. // Send Metadata
  730. NSError *error = [[NCNetworkingEndToEnd sharedManager] sendEndToEndMetadataOnServerUrl:serverUrl fileNameRename:nil fileNameNewRename:nil account:tableAccount.account user:tableAccount.user userID:tableAccount.userID password:[CCUtility getPassword:tableAccount.account] url:tableAccount.url];
  731. dispatch_async(dispatch_get_main_queue(), ^{
  732. if (error) {
  733. [uploadTask cancel];
  734. NSString *messageError = [NSString stringWithFormat:@"%@ (%d)", error.localizedDescription, (int)error.code];
  735. [[NCManageDatabase sharedInstance] setMetadataSession:metadata.session sessionError:messageError sessionSelector:nil sessionTaskIdentifier:k_taskIdentifierDone status:k_metadataStatusUploadError predicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadata.ocId]];
  736. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:ocId:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  737. [self.delegate uploadFileSuccessFailure:metadata.fileNameView ocId:metadata.ocId assetLocalIdentifier:metadata.assetLocalIdentifier serverUrl:metadata.serverUrl selector:metadata.sessionSelector errorMessage:messageError errorCode:k_CCErrorInternalError];
  738. }
  739. } else {
  740. // Manage uploadTask cancel,suspend,resume
  741. if (taskStatus == k_taskStatusCancel) [uploadTask cancel];
  742. else if (taskStatus == k_taskStatusSuspend) [uploadTask suspend];
  743. else if (taskStatus == k_taskStatusResume) [uploadTask resume];
  744. // *** E2EE ***
  745. [[NCManageDatabase sharedInstance] setMetadataSession:metadata.session sessionError:@"" sessionSelector:nil sessionTaskIdentifier:uploadTask.taskIdentifier status:k_metadataStatusUploading predicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadata.ocId]];
  746. NSLog(@"[LOG] Upload file %@ TaskIdentifier %lu", metadata.fileName, (unsigned long)uploadTask.taskIdentifier);
  747. NSString *ocId = metadata.ocId;
  748. NSString *account = metadata.account;
  749. dispatch_async(dispatch_get_main_queue(), ^{
  750. if ([self.delegate respondsToSelector:@selector(uploadStart:account:task:serverUrl:)]) {
  751. [self.delegate uploadStart:ocId account:account task:uploadTask serverUrl:metadata.serverUrl];
  752. }
  753. });
  754. }
  755. });
  756. });
  757. } else {
  758. // Manage uploadTask cancel,suspend,resume
  759. if (taskStatus == k_taskStatusCancel) [uploadTask cancel];
  760. else if (taskStatus == k_taskStatusSuspend) [uploadTask suspend];
  761. else if (taskStatus == k_taskStatusResume) [uploadTask resume];
  762. // *** PLAIN ***
  763. [[NCManageDatabase sharedInstance] setMetadataSession:metadata.session sessionError:@"" sessionSelector:nil sessionTaskIdentifier:uploadTask.taskIdentifier status:k_metadataStatusUploading predicate:[NSPredicate predicateWithFormat:@"ocId == %@", metadata.ocId]];
  764. NSLog(@"[LOG] Upload file %@ TaskIdentifier %lu", metadata.fileName, (unsigned long)uploadTask.taskIdentifier);
  765. NSString *ocId = metadata.ocId;
  766. NSString *account = metadata.account;
  767. NSString *serverUrl = metadata.serverUrl;
  768. dispatch_async(dispatch_get_main_queue(), ^{
  769. if ([self.delegate respondsToSelector:@selector(uploadStart:account:task:serverUrl:)]) {
  770. [self.delegate uploadStart:ocId account:account task:uploadTask serverUrl:serverUrl];
  771. }
  772. });
  773. }
  774. }
  775. }
  776. - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
  777. {
  778. }
  779. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend
  780. {
  781. NSString *url = [[[task currentRequest].URL absoluteString] stringByRemovingPercentEncoding];
  782. NSString *fileName = [url lastPathComponent];
  783. NSString *serverUrl = [self getServerUrlFromUrl:url];
  784. if (!serverUrl) return;
  785. if (totalBytesExpectedToSend < 1) {
  786. totalBytesExpectedToSend = totalBytesSent;
  787. }
  788. float progress = (float) totalBytesSent / (float)totalBytesExpectedToSend;
  789. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataInSessionFromFileName:fileName serverUrl:serverUrl taskIdentifier:task.taskIdentifier];
  790. if (metadata) {
  791. NSDictionary *userInfo = @{@"account": (metadata.account), @"ocId": (metadata.ocId), @"serverUrl": (serverUrl), @"status": ([NSNumber numberWithLong:k_metadataStatusInUpload]), @"progress": ([NSNumber numberWithFloat:progress]), @"totalBytes": ([NSNumber numberWithLongLong:totalBytesSent]), @"totalBytesExpected": ([NSNumber numberWithLongLong:totalBytesExpectedToSend])};
  792. if (userInfo)
  793. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"NotificationProgressTask" object:nil userInfo:userInfo];
  794. }
  795. }
  796. - (void)uploadFileSuccessFailure:(tableMetadata *)metadata fileName:(NSString *)fileName ocId:(NSString *)ocId etag:(NSString *)etag date:(NSDate *)date serverUrl:(NSString *)serverUrl errorCode:(NSInteger)errorCode
  797. {
  798. NSString *tempocId = metadata.ocId;
  799. NSString *tempSession = metadata.session;
  800. NSString *errorMessage = @"";
  801. BOOL isE2EEDirectory = false;
  802. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", metadata.account]];
  803. if (tableAccount == nil) {
  804. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", tempocId]];
  805. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:ocId:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  806. [self.delegate uploadFileSuccessFailure:metadata.fileName ocId:metadata.ocId assetLocalIdentifier:metadata.assetLocalIdentifier serverUrl:serverUrl selector:metadata.sessionSelector errorMessage:errorMessage errorCode:errorCode];
  807. }
  808. return;
  809. }
  810. // is this a E2EE Directory ?
  811. if ([CCUtility isFolderEncrypted:serverUrl account:tableAccount.account] && [CCUtility isEndToEndEnabled:tableAccount.account]) {
  812. isE2EEDirectory = true;
  813. }
  814. // ERRORE
  815. if (errorCode != 0) {
  816. #ifndef EXTENSION
  817. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  818. [appDelegate.listProgressMetadata removeObjectForKey:metadata.ocId];
  819. #endif
  820. // Mark error only if not Cancelled Task
  821. if (errorCode == kCFURLErrorCancelled) {
  822. if (metadata.status == k_metadataStatusUploadForcedStart) {
  823. errorCode = 0;
  824. metadata.session = k_upload_session;
  825. metadata.sessionError = @"";
  826. metadata.sessionTaskIdentifier = 0;
  827. metadata.status = k_metadataStatusInUpload;
  828. metadata = [[NCManageDatabase sharedInstance] addMetadata:metadata];
  829. [[CCNetworking sharedNetworking] uploadFile:metadata taskStatus:k_taskStatusResume];
  830. } else {
  831. [[NSFileManager defaultManager] removeItemAtPath:[CCUtility getDirectoryProviderStorageOcId:tempocId] error:nil];
  832. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", tempocId]];
  833. errorMessage = [CCError manageErrorKCF:errorCode withNumberError:YES];
  834. }
  835. } else {
  836. if (metadata && (errorCode == kOCErrorServerUnauthorized || errorCode == kOCErrorServerForbidden))
  837. [[OCNetworking sharedManager] checkRemoteUser:metadata.account function:@"upload" errorCode:errorCode];
  838. else if (metadata && errorCode == NSURLErrorServerCertificateUntrusted)
  839. [CCUtility setCertificateError:metadata.account error:YES];
  840. [[NCManageDatabase sharedInstance] setMetadataSession:nil sessionError:[CCError manageErrorKCF:errorCode withNumberError:NO] sessionSelector:nil sessionTaskIdentifier:k_taskIdentifierDone status:k_metadataStatusUploadError predicate:[NSPredicate predicateWithFormat:@"ocId == %@", tempocId]];
  841. errorMessage = [CCError manageErrorKCF:errorCode withNumberError:YES];
  842. }
  843. } else {
  844. // Edited file, remove tempocId and adjust the directory provider storage
  845. if (metadata.edited) {
  846. // Update metadata tempocId
  847. [[NCManageDatabase sharedInstance] setMetadataSession:@"" sessionError:@"" sessionSelector:@"" sessionTaskIdentifier:k_taskIdentifierDone status:k_metadataStatusNormal predicate:[NSPredicate predicateWithFormat:@"ocId == %@", tempocId]];
  848. // Add metadata ocId
  849. metadata.date = date;
  850. if (isE2EEDirectory) {
  851. metadata.e2eEncrypted = true;
  852. } else {
  853. metadata.e2eEncrypted = false;
  854. }
  855. metadata.etag = etag;
  856. metadata.ocId = ocId;
  857. metadata.session = @"";
  858. metadata.sessionError = @"";
  859. metadata.sessionTaskIdentifier = k_taskIdentifierDone;
  860. metadata.status = k_metadataStatusNormal;
  861. metadata = [[NCManageDatabase sharedInstance] addMetadata:metadata];
  862. // Copy new version on old version
  863. if (![tempocId isEqualToString:metadata.ocId]) {
  864. [CCUtility copyFileAtPath:[NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryProviderStorage], tempocId] toPath:[NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryProviderStorage], metadata.ocId]];
  865. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", tempocId]];
  866. // IMI -> Unzip
  867. #if HC
  868. if ([metadata.typeFile isEqualToString:k_metadataTypeFile_imagemeter]) {
  869. (void)[[IMUtility shared] IMUnzipWithMetadata:metadata];
  870. }
  871. #endif
  872. }
  873. } else {
  874. // Replace Metadata
  875. metadata.date = date;
  876. if (isE2EEDirectory) {
  877. metadata.e2eEncrypted = true;
  878. } else {
  879. metadata.e2eEncrypted = false;
  880. }
  881. metadata.etag = etag;
  882. metadata.ocId = ocId;
  883. metadata.session = @"";
  884. metadata.sessionError = @"";
  885. metadata.sessionTaskIdentifier = k_taskIdentifierDone;
  886. metadata.status = k_metadataStatusNormal;
  887. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@ AND fileName == %@", metadata.account, metadata.serverUrl, metadata.fileName]];
  888. metadata = [[NCManageDatabase sharedInstance] addMetadata:metadata];
  889. NSLog(@"[LOG] Insert new upload : %@ - ocId : %@", metadata.fileName, ocId);
  890. if ([tempocId isEqualToString:[CCUtility createMetadataIDFromAccount:metadata.account serverUrl:metadata.serverUrl fileNameView:metadata.fileNameView directory:metadata.directory]]) {
  891. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"ocId == %@", tempocId]];
  892. // adjust file system Directory Provider Storage
  893. if ([tempSession isEqualToString:k_upload_session_extension]) {
  894. // this is for File Provider Extension [Apple Works and ... ?]
  895. [CCUtility copyFileAtPath:[NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryProviderStorage], tempocId] toPath:[NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryProviderStorage], metadata.ocId]];
  896. } else {
  897. [CCUtility moveFileAtPath:[NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryProviderStorage], tempocId] toPath:[NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryProviderStorage], metadata.ocId]];
  898. }
  899. }
  900. }
  901. #ifndef EXTENSION
  902. // NSNotificationCenter
  903. NSDictionary* userInfo = @{@"metadata": metadata};
  904. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_uploadFile object:nil userInfo:userInfo];
  905. // EXIF
  906. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image])
  907. [[CCExifGeo sharedInstance] setExifLocalTableEtag:metadata];
  908. // Create preview
  909. [CCGraphics createNewImageFrom:metadata.fileNameView ocId:metadata.ocId extension:[metadata.fileNameView pathExtension] filterGrayScale:NO typeFile:metadata.typeFile writeImage:YES];
  910. // Copy photo or video in the photo album for auto upload
  911. if ([metadata.assetLocalIdentifier length] > 0 && ([metadata.sessionSelector isEqualToString:selectorUploadAutoUpload] || [metadata.sessionSelector isEqualToString:selectorUploadFile])) {
  912. PHAsset *asset;
  913. PHFetchResult *result = [PHAsset fetchAssetsWithLocalIdentifiers:@[metadata.assetLocalIdentifier] options:nil];
  914. if(result.count){
  915. asset = result[0];
  916. [asset saveToAlbum:[NCBrandOptions sharedInstance].brand completionBlock:^(BOOL success) {
  917. if (success) NSLog(@"[LOG] Insert file %@ in %@", metadata.fileName, [NCBrandOptions sharedInstance].brand);
  918. else NSLog(@"[LOG] File %@ do not insert in %@", metadata.fileName, [NCBrandOptions sharedInstance].brand);
  919. }];
  920. }
  921. }
  922. #endif
  923. // Add Local or Remove from cache
  924. if ([CCUtility getDisableLocalCacheAfterUpload] && !metadata.edited) {
  925. [[NSFileManager defaultManager] removeItemAtPath:[CCUtility getDirectoryProviderStorageOcId:metadata.ocId] error:nil];
  926. } else {
  927. // Add Local
  928. (void)[[NCManageDatabase sharedInstance] addLocalFileWithMetadata:metadata];
  929. }
  930. }
  931. // Detect E2EE
  932. 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]];
  933. // E2EE : UNLOCK
  934. if (isE2EEDirectory && e2eeMetadataInSession == nil) {
  935. tableE2eEncryptionLock *tableLock = [[NCManageDatabase sharedInstance] getE2ETokenLockWithServerUrl:serverUrl];
  936. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  937. if (tableLock) {
  938. NSError *error = [[NCNetworkingEndToEnd sharedManager] unlockEndToEndFolderEncryptedOnServerUrl:serverUrl ocId:tableLock.ocId token:tableLock.token user:tableAccount.user userID:tableAccount.userID password:[CCUtility getPassword:tableAccount.account] url:tableAccount.url];
  939. if (error) {
  940. [[NCContentPresenter shared] messageNotification:@"_e2e_error_unlock_" description:error.localizedDescription delay:k_dismissAfterSecond type:messageTypeError errorCode:error.code];
  941. }
  942. } else {
  943. NSLog(@"Error unlock not found");
  944. }
  945. dispatch_async(dispatch_get_main_queue(), ^{
  946. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:ocId:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  947. [self.delegate uploadFileSuccessFailure:metadata.fileName ocId:metadata.ocId assetLocalIdentifier:metadata.assetLocalIdentifier serverUrl:serverUrl selector:metadata.sessionSelector errorMessage:errorMessage errorCode:errorCode];
  948. }
  949. });
  950. });
  951. } else {
  952. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:ocId:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  953. [self.delegate uploadFileSuccessFailure:metadata.fileName ocId:metadata.ocId assetLocalIdentifier:metadata.assetLocalIdentifier serverUrl:serverUrl selector:metadata.sessionSelector errorMessage:errorMessage errorCode:errorCode];
  954. }
  955. }
  956. }
  957. #pragma --------------------------------------------------------------------------------------------
  958. #pragma mark ===== Utility =====
  959. #pragma --------------------------------------------------------------------------------------------
  960. - (NSString *)getServerUrlFromUrl:(NSString *)url
  961. {
  962. NSString *fileName = [url lastPathComponent];
  963. url = [url stringByReplacingOccurrencesOfString:[@"/" stringByAppendingString:fileName] withString:@""];
  964. return url;
  965. }
  966. @end