CCNetworking.m 66 KB

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