CCNetworking.m 67 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209
  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. return nil;
  176. }
  177. - (void)invalidateAndCancelAllSession
  178. {
  179. [[self sessionDownload] invalidateAndCancel];
  180. [[self sessionDownloadForeground] invalidateAndCancel];
  181. [[self sessionWWanDownload] invalidateAndCancel];
  182. [[self sessionUpload] invalidateAndCancel];
  183. [[self sessionWWanUpload] invalidateAndCancel];
  184. [[self sessionUploadForeground] invalidateAndCancel];
  185. }
  186. - (NSArray *)getUploadTasksExtensionSession
  187. {
  188. __block NSArray *tasks = [NSArray new];
  189. [[self sessionUploadExtension] getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  190. tasks = uploadTasks;
  191. }];
  192. return tasks;
  193. }
  194. #pragma --------------------------------------------------------------------------------------------
  195. #pragma mark ===== URLSession download/upload =====
  196. #pragma --------------------------------------------------------------------------------------------
  197. - (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler
  198. {
  199. // The pinnning check
  200. if ([[CCCertificate sharedManager] checkTrustedChallenge:challenge]) {
  201. completionHandler(NSURLSessionAuthChallengeUseCredential, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]);
  202. } else {
  203. completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
  204. }
  205. }
  206. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
  207. {
  208. NSString *url = [[[task currentRequest].URL absoluteString] stringByRemovingPercentEncoding];
  209. if (!url)
  210. return;
  211. NSString *fileName = [url lastPathComponent];
  212. NSString *serverUrl = [self getServerUrlFromUrl:url];
  213. if (!serverUrl) return;
  214. NSInteger errorCode;
  215. NSDate *date = [NSDate date];
  216. NSDateFormatter *dateFormatter = [NSDateFormatter new];
  217. NSLocale *enUSPOSIXLocale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
  218. [dateFormatter setLocale:enUSPOSIXLocale];
  219. [dateFormatter setDateFormat:@"EEE, dd MMM y HH:mm:ss zzz"];
  220. NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)task.response;
  221. if (httpResponse.statusCode >= 200 && httpResponse.statusCode < 300) {
  222. errorCode = error.code;
  223. } else {
  224. if (httpResponse.statusCode > 0)
  225. errorCode = httpResponse.statusCode;
  226. else
  227. errorCode = error.code;
  228. }
  229. // ----------------------- DOWNLOAD -----------------------
  230. if ([task isKindOfClass:[NSURLSessionDownloadTask class]]) {
  231. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataInSessionFromFileName:fileName serverUrl:serverUrl taskIdentifier:task.taskIdentifier];
  232. if (metadata) {
  233. NSString *etag = metadata.etag;
  234. //NSString *fileID = metadata.fileID;
  235. NSDictionary *fields = [httpResponse allHeaderFields];
  236. if (errorCode == 0) {
  237. etag = [CCUtility removeForbiddenCharactersFileSystem:[fields objectForKey:@"OC-ETag"]];
  238. NSString *dateString = [fields objectForKey:@"Date"];
  239. if (dateString) {
  240. if (![dateFormatter getObjectValue:&date forString:dateString range:nil error:&error]) {
  241. date = [NSDate date];
  242. }
  243. } else {
  244. date = [NSDate date];
  245. }
  246. }
  247. if (fileName.length > 0 && serverUrl.length > 0) {
  248. dispatch_async(dispatch_get_main_queue(), ^{
  249. [self downloadFileSuccessFailure:fileName fileID:metadata.fileID etag:etag date:date serverUrl:serverUrl selector:metadata.sessionSelector errorCode:errorCode];
  250. });
  251. }
  252. } else {
  253. NSLog(@"[LOG] Remove record ? : metadata not found %@", url);
  254. dispatch_async(dispatch_get_main_queue(), ^{
  255. if ([self.delegate respondsToSelector:@selector(downloadFileSuccessFailure:fileID:serverUrl:selector:errorMessage:errorCode:)]) {
  256. [self.delegate downloadFileSuccessFailure:fileName fileID:@"" serverUrl:serverUrl selector:@"" errorMessage:@"" errorCode:k_CCErrorInternalError];
  257. }
  258. });
  259. }
  260. }
  261. // ------------------------ UPLOAD -----------------------
  262. if ([task isKindOfClass:[NSURLSessionUploadTask class]]) {
  263. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataInSessionFromFileName:fileName serverUrl:serverUrl taskIdentifier:task.taskIdentifier];
  264. if (metadata) {
  265. NSDictionary *fields = [httpResponse allHeaderFields];
  266. NSString *fileID = metadata.fileID;
  267. NSString *etag = metadata.etag;
  268. if (errorCode == 0) {
  269. fileID = [CCUtility removeForbiddenCharactersFileSystem:[fields objectForKey:@"OC-FileId"]];
  270. etag = [CCUtility removeForbiddenCharactersFileSystem:[fields objectForKey:@"OC-ETag"]];
  271. NSString *dateString = [fields objectForKey:@"Date"];
  272. if (dateString) {
  273. if (![dateFormatter getObjectValue:&date forString:dateString range:nil error:&error]) {
  274. NSLog(@"[LOG] Date '%@' could not be parsed: %@", dateString, error);
  275. date = [NSDate date];
  276. }
  277. } else {
  278. date = [NSDate date];
  279. }
  280. }
  281. if (fileName.length > 0 && fileID.length > 0 && serverUrl.length > 0) {
  282. dispatch_async(dispatch_get_main_queue(), ^{
  283. [self uploadFileSuccessFailure:metadata fileName:fileName fileID:fileID etag:etag date:date serverUrl:serverUrl errorCode:errorCode];
  284. });
  285. }
  286. } else {
  287. NSLog(@"[LOG] Remove record ? : metadata not found %@", url);
  288. dispatch_async(dispatch_get_main_queue(), ^{
  289. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:fileID:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  290. [self.delegate uploadFileSuccessFailure:fileName fileID:@"" assetLocalIdentifier:@"" serverUrl:serverUrl selector:@"" errorMessage:@"" errorCode:k_CCErrorInternalError];
  291. }
  292. });
  293. }
  294. }
  295. }
  296. #pragma --------------------------------------------------------------------------------------------
  297. #pragma mark ===== Download =====
  298. #pragma --------------------------------------------------------------------------------------------
  299. - (void)downloadFile:(tableMetadata *)metadata taskStatus:(NSInteger)taskStatus
  300. {
  301. // File exists ?
  302. tableLocalFile *localfile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID]];
  303. if (localfile != nil && [CCUtility fileProviderStorageExists:metadata.fileID fileNameView:metadata.fileNameView]) {
  304. [[NCManageDatabase sharedInstance] setMetadataSession:@"" sessionError:@"" sessionSelector:@"" sessionTaskIdentifier:k_taskIdentifierDone status:k_metadataStatusNormal predicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID]];
  305. if ([self.delegate respondsToSelector:@selector(downloadFileSuccessFailure:fileID:serverUrl:selector:errorMessage:errorCode:)]) {
  306. [self.delegate downloadFileSuccessFailure:metadata.fileName fileID:metadata.fileID serverUrl:metadata.serverUrl selector:metadata.sessionSelector errorMessage:@"" errorCode:0];
  307. }
  308. return;
  309. }
  310. [self downloaURLSession:metadata taskStatus:taskStatus];
  311. }
  312. - (void)downloaURLSession:(tableMetadata *)metadata taskStatus:(NSInteger)taskStatus
  313. {
  314. NSURLSession *sessionDownload;
  315. NSURL *url;
  316. NSMutableURLRequest *request;
  317. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", metadata.account]];
  318. if (tableAccount == nil) {
  319. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID]];
  320. if ([self.delegate respondsToSelector:@selector(downloadFileSuccessFailure:fileID:serverUrl:selector:errorMessage:errorCode:)]) {
  321. [self.delegate downloadFileSuccessFailure:metadata.fileName fileID:metadata.fileID serverUrl:metadata.serverUrl selector:metadata.sessionSelector errorMessage:@"Download error, account not found" errorCode:k_CCErrorInternalError];
  322. }
  323. return;
  324. }
  325. NSString *serverFileUrl = [[NSString stringWithFormat:@"%@/%@", metadata.serverUrl, metadata.fileName] encodeString:NSUTF8StringEncoding];
  326. url = [NSURL URLWithString:serverFileUrl];
  327. request = [NSMutableURLRequest requestWithURL:url];
  328. NSData *authData = [[NSString stringWithFormat:@"%@:%@", tableAccount.user, tableAccount.password] dataUsingEncoding:NSUTF8StringEncoding];
  329. NSString *authValue = [NSString stringWithFormat: @"Basic %@",[authData base64EncodedStringWithOptions:0]];
  330. [request setValue:authValue forHTTPHeaderField:@"Authorization"];
  331. [request setValue:[CCUtility getUserAgent] forHTTPHeaderField:@"User-Agent"];
  332. if ([metadata.session isEqualToString:k_download_session]) sessionDownload = [self sessionDownload];
  333. else if ([metadata.session isEqualToString:k_download_session_foreground]) sessionDownload = [self sessionDownloadForeground];
  334. else if ([metadata.session isEqualToString:k_download_session_wwan]) sessionDownload = [self sessionWWanDownload];
  335. NSURLSessionDownloadTask *downloadTask = [sessionDownload downloadTaskWithRequest:request];
  336. if (downloadTask == nil) {
  337. [[NCManageDatabase sharedInstance] addActivityClient:metadata.fileName fileID:metadata.fileID action:k_activityDebugActionUpload selector:metadata.sessionSelector note:@"Serious internal error downloadTask not available" type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:tableAccount.url];
  338. [[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]];
  339. if ([self.delegate respondsToSelector:@selector(downloadFileSuccessFailure:fileID:serverUrl:selector:errorMessage:errorCode:)]) {
  340. [self.delegate downloadFileSuccessFailure:metadata.fileName fileID:metadata.fileID serverUrl:metadata.serverUrl selector:metadata.sessionSelector errorMessage:@"Serious internal error downloadTask not available" errorCode:k_CCErrorInternalError];
  341. }
  342. } else {
  343. // Manage uploadTask cancel,suspend,resume
  344. if (taskStatus == k_taskStatusCancel) [downloadTask cancel];
  345. else if (taskStatus == k_taskStatusSuspend) [downloadTask suspend];
  346. else if (taskStatus == k_taskStatusResume) [downloadTask resume];
  347. [[NCManageDatabase sharedInstance] setMetadataSession:nil sessionError:nil sessionSelector:nil sessionTaskIdentifier:downloadTask.taskIdentifier status:k_metadataStatusDownloading predicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID]];
  348. NSLog(@"[LOG] downloadFileSession %@ Task [%lu]", metadata.fileID, (unsigned long)downloadTask.taskIdentifier);
  349. dispatch_async(dispatch_get_main_queue(), ^{
  350. if ([self.delegate respondsToSelector:@selector(downloadStart:account:task:serverUrl:)]) {
  351. [self.delegate downloadStart:metadata.fileID account:metadata.account task:downloadTask serverUrl:metadata.serverUrl];
  352. }
  353. });
  354. }
  355. }
  356. - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
  357. {
  358. NSString *url = [[[downloadTask currentRequest].URL absoluteString] stringByRemovingPercentEncoding];
  359. NSString *fileName = [url lastPathComponent];
  360. NSString *serverUrl = [self getServerUrlFromUrl:url];
  361. if (!serverUrl) return;
  362. if (totalBytesExpectedToWrite < 1) {
  363. totalBytesExpectedToWrite = totalBytesWritten;
  364. }
  365. float progress = (float) totalBytesWritten / (float)totalBytesExpectedToWrite;
  366. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataInSessionFromFileName:fileName serverUrl:serverUrl taskIdentifier:downloadTask.taskIdentifier];
  367. if (metadata) {
  368. 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])};
  369. if (userInfo)
  370. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"NotificationProgressTask" object:nil userInfo:userInfo];
  371. } else {
  372. NSLog(@"[LOG] metadata not found");
  373. }
  374. }
  375. - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
  376. {
  377. NSString *url = [[[downloadTask currentRequest].URL absoluteString] stringByRemovingPercentEncoding];
  378. if (!url)
  379. return;
  380. NSString *fileName = [url lastPathComponent];
  381. NSString *serverUrl = [self getServerUrlFromUrl:url];
  382. if (!serverUrl) return;
  383. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataInSessionFromFileName:fileName serverUrl:serverUrl taskIdentifier:downloadTask.taskIdentifier];
  384. if (!metadata) {
  385. [[NCManageDatabase sharedInstance] addActivityClient:fileName fileID:@"" action:k_activityDebugActionUpload selector:@"" note:[NSString stringWithFormat:@"Serious error internal download : metadata not found %@", url] type:k_activityTypeFailure verbose:k_activityVerboseDefault activeUrl:@""];
  386. NSLog(@"[LOG] Serious error internal download : metadata not found %@ ", url);
  387. dispatch_async(dispatch_get_main_queue(), ^{
  388. if ([self.delegate respondsToSelector:@selector(downloadFileSuccessFailure:fileID:serverUrl:selector:errorMessage:errorCode:)]) {
  389. [self.delegate downloadFileSuccessFailure:@"" fileID:@"" serverUrl:serverUrl selector:@"" errorMessage:@"Serious error internal download : metadata not found" errorCode:k_CCErrorInternalError];
  390. }
  391. });
  392. return;
  393. }
  394. NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)downloadTask.response;
  395. if (httpResponse.statusCode >= 200 && httpResponse.statusCode < 300) {
  396. NSString *destinationFilePath = [CCUtility getDirectoryProviderStorageFileID:metadata.fileID fileNameView:metadata.fileName];
  397. NSURL *destinationURL = [NSURL fileURLWithPath:destinationFilePath];
  398. [[NSFileManager defaultManager] removeItemAtURL:destinationURL error:NULL];
  399. [[NSFileManager defaultManager] copyItemAtURL:location toURL:destinationURL error:nil];
  400. }
  401. }
  402. - (void)downloadFileSuccessFailure:(NSString *)fileName fileID:(NSString *)fileID etag:(NSString *)etag date:(NSDate *)date serverUrl:(NSString *)serverUrl selector:(NSString *)selector errorCode:(NSInteger)errorCode
  403. {
  404. #ifndef EXTENSION
  405. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  406. [appDelegate.listProgressMetadata removeObjectForKey:fileID];
  407. #endif
  408. if (errorCode != 0) {
  409. if (errorCode == kCFURLErrorCancelled) {
  410. [[NCManageDatabase sharedInstance] setMetadataSession:@"" sessionError:@"" sessionSelector:@"" sessionTaskIdentifier:k_taskIdentifierDone status:k_metadataStatusNormal predicate:[NSPredicate predicateWithFormat:@"fileID == %@", fileID]];
  411. } else {
  412. [[NCManageDatabase sharedInstance] setMetadataSession:nil sessionError:[CCError manageErrorKCF:errorCode withNumberError:NO] sessionSelector:nil sessionTaskIdentifier:k_taskIdentifierDone status:k_metadataStatusDownloadError predicate:[NSPredicate predicateWithFormat:@"fileID == %@", fileID]];
  413. }
  414. if ([self.delegate respondsToSelector:@selector(downloadFileSuccessFailure:fileID:serverUrl:selector:errorMessage:errorCode:)]) {
  415. [self.delegate downloadFileSuccessFailure:fileName fileID:fileID serverUrl:serverUrl selector:selector errorMessage:[CCError manageErrorKCF:errorCode withNumberError:YES] errorCode:errorCode];
  416. }
  417. } else {
  418. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", fileID]];
  419. if (!metadata) {
  420. [[NCManageDatabase sharedInstance] addActivityClient:fileName fileID:fileID action:k_activityDebugActionUpload selector:@"" note:[NSString stringWithFormat:@"Serious error internal download : metadata not found %@", fileName] type:k_activityTypeFailure verbose:k_activityVerboseDefault activeUrl:@""];
  421. NSLog(@"[LOG] Serious error internal download : metadata not found %@ ", fileName);
  422. if ([self.delegate respondsToSelector:@selector(downloadFileSuccessFailure:fileID:serverUrl:selector:errorMessage:errorCode:)]) {
  423. [self.delegate downloadFileSuccessFailure:fileName fileID:fileID serverUrl:serverUrl selector:selector errorMessage:[NSString stringWithFormat:@"Serious error internal download : metadata not found %@", fileName] errorCode:k_CCErrorInternalError];
  424. }
  425. return;
  426. }
  427. metadata.session = @"";
  428. metadata.sessionError = @"";
  429. metadata.sessionSelector = @"";
  430. metadata.sessionTaskIdentifier = k_taskIdentifierDone;
  431. metadata.status = k_metadataStatusNormal;
  432. metadata = [[NCManageDatabase sharedInstance] updateMetadata:metadata];
  433. [[NCManageDatabase sharedInstance] addLocalFileWithMetadata:metadata];
  434. // E2EE Decrypted
  435. tableE2eEncryption *object = [[NCManageDatabase sharedInstance] getE2eEncryptionWithPredicate:[NSPredicate predicateWithFormat:@"fileNameIdentifier == %@ AND serverUrl == %@", fileName, serverUrl]];
  436. if (object) {
  437. BOOL result = [[NCEndToEndEncryption sharedManager] decryptFileName:metadata.fileName fileNameView:metadata.fileNameView fileID:metadata.fileID key:object.key initializationVector:object.initializationVector authenticationTag:object.authenticationTag];
  438. if (!result) {
  439. [[NCManageDatabase sharedInstance] addActivityClient:metadata.fileNameView fileID:fileID action:k_activityDebugActionUpload selector:@"" note:[NSString stringWithFormat:@"Serious error internal download : decrypt error %@", fileName] type:k_activityTypeFailure verbose:k_activityVerboseDefault activeUrl:@""];
  440. if ([self.delegate respondsToSelector:@selector(downloadFileSuccessFailure:fileID:serverUrl:selector:errorMessage:errorCode:)]) {
  441. [self.delegate downloadFileSuccessFailure:fileName fileID:fileID serverUrl:serverUrl selector:selector errorMessage:[NSString stringWithFormat:@"Serious error internal download : decrypt error %@", fileName] errorCode:k_CCErrorInternalError];
  442. }
  443. return;
  444. }
  445. }
  446. // Exif
  447. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image])
  448. [[CCExifGeo sharedInstance] setExifLocalTableEtag:metadata];
  449. // Icon
  450. if ([[NSFileManager defaultManager] fileExistsAtPath:[CCUtility getDirectoryProviderStorageIconFileID:metadata.fileID fileNameView:metadata.fileNameView]] == NO) {
  451. [CCGraphics createNewImageFrom:metadata.fileNameView fileID:metadata.fileID extension:[metadata.fileNameView pathExtension] filterGrayScale:NO typeFile:metadata.typeFile writeImage:YES];
  452. }
  453. // Activity
  454. [[NCManageDatabase sharedInstance] addActivityClient:metadata.fileNameView fileID:metadata.fileID action:k_activityDebugActionDownload selector:metadata.sessionSelector note:serverUrl type:k_activityTypeSuccess verbose:k_activityVerboseDefault activeUrl:@""];
  455. if ([self.delegate respondsToSelector:@selector(downloadFileSuccessFailure:fileID:serverUrl:selector:errorMessage:errorCode:)]) {
  456. [self.delegate downloadFileSuccessFailure:fileName fileID:fileID serverUrl:serverUrl selector:selector errorMessage:@"" errorCode:0];
  457. }
  458. }
  459. }
  460. #pragma --------------------------------------------------------------------------------------------
  461. #pragma mark ===== Upload =====
  462. #pragma --------------------------------------------------------------------------------------------
  463. - (void)uploadFile:(tableMetadata *)metadata taskStatus:(NSInteger)taskStatus
  464. {
  465. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", metadata.account]];
  466. if (tableAccount == nil) {
  467. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID]];
  468. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:fileID:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  469. [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];
  470. }
  471. return;
  472. }
  473. if ([CCUtility fileProviderStorageExists:metadata.fileID fileNameView:metadata.fileNameView] == NO) {
  474. PHFetchResult *result = [PHAsset fetchAssetsWithLocalIdentifiers:@[metadata.assetLocalIdentifier] options:nil];
  475. if (!result.count) {
  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:@"Error photo/video not found, remove from upload" errorCode:k_CCErrorInternalError];
  479. }
  480. return;
  481. }
  482. PHAsset *asset= result[0];
  483. // IMAGE
  484. if (asset.mediaType == PHAssetMediaTypeImage) {
  485. PHImageRequestOptions *options = [PHImageRequestOptions new];
  486. options.networkAccessAllowed = YES; // iCloud
  487. options.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
  488. options.synchronous = YES;
  489. options.progressHandler = ^(double progress, NSError *error, BOOL *stop, NSDictionary *info) {
  490. NSLog(@"cacheAsset: %f", progress);
  491. if (error) {
  492. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID]];
  493. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:fileID:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  494. [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];
  495. }
  496. }
  497. };
  498. [[PHImageManager defaultManager] requestImageDataForAsset:asset options:options resultHandler:^(NSData *imageData, NSString *dataUTI, UIImageOrientation orientation, NSDictionary *info) {
  499. NSError *error = nil;
  500. NSString *extensionAsset = [[[asset valueForKey:@"filename"] pathExtension] uppercaseString];
  501. if ([extensionAsset isEqualToString:@"HEIC"] && [CCUtility getFormatCompatibility]) {
  502. UIImage *image = [UIImage imageWithData:imageData];
  503. imageData = UIImageJPEGRepresentation(image, 1.0);
  504. NSString *fileNameJPEG = [[metadata.fileName lastPathComponent] stringByDeletingPathExtension];
  505. metadata.fileName = [fileNameJPEG stringByAppendingString:@".jpg"];
  506. metadata.fileNameView = metadata.fileName;
  507. // Change Metadata with new fileID, fileName, fileNameView
  508. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID]];
  509. metadata.fileID = [CCUtility createMetadataIDFromAccount:metadata.account serverUrl:metadata.serverUrl fileNameView:metadata.fileNameView directory:false];
  510. }
  511. tableMetadata *metadataForUpload = [[NCManageDatabase sharedInstance] addMetadata:[CCUtility insertFileSystemInMetadata:metadata]];
  512. [imageData writeToFile:[CCUtility getDirectoryProviderStorageFileID:metadataForUpload.fileID fileNameView:metadataForUpload.fileNameView] options:NSDataWritingAtomic error:&error];
  513. if (error) {
  514. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadataForUpload.fileID]];
  515. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:fileID:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  516. [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];
  517. }
  518. } else {
  519. // OOOOOK
  520. if ([CCUtility isFolderEncrypted:metadataForUpload.serverUrl account:tableAccount.account] && [CCUtility isEndToEndEnabled:tableAccount.account]) {
  521. [self e2eEncryptedFile:metadataForUpload tableAccount:tableAccount taskStatus:taskStatus];
  522. } else {
  523. [self uploadURLSessionMetadata:metadataForUpload tableAccount:tableAccount taskStatus:taskStatus];
  524. }
  525. }
  526. }];
  527. }
  528. // VIDEO
  529. if (asset.mediaType == PHAssetMediaTypeVideo) {
  530. PHVideoRequestOptions *options = [PHVideoRequestOptions new];
  531. options.networkAccessAllowed = YES;
  532. options.version = PHVideoRequestOptionsVersionOriginal;
  533. options.progressHandler = ^(double progress, NSError *error, BOOL *stop, NSDictionary *info) {
  534. NSLog(@"cacheAsset: %f", progress);
  535. if (error) {
  536. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID]];
  537. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:fileID:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  538. [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];
  539. }
  540. }
  541. };
  542. [[PHImageManager defaultManager] requestAVAssetForVideo:asset options:options resultHandler:^(AVAsset *asset, AVAudioMix *audioMix, NSDictionary *info) {
  543. if ([asset isKindOfClass:[AVURLAsset class]]) {
  544. NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:[CCUtility getDirectoryProviderStorageFileID:metadata.fileID fileNameView:metadata.fileNameView]];
  545. NSError *error = nil;
  546. [[NSFileManager defaultManager] removeItemAtURL:fileURL error:nil];
  547. [[NSFileManager defaultManager] copyItemAtURL:[(AVURLAsset *)asset URL] toURL:fileURL error:&error];
  548. if (error) {
  549. dispatch_async(dispatch_get_main_queue(), ^{
  550. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID]];
  551. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:fileID:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  552. [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];
  553. }
  554. });
  555. } else {
  556. dispatch_async(dispatch_get_main_queue(), ^{
  557. // create Metadata for Upload
  558. tableMetadata *metadataForUpload = [[NCManageDatabase sharedInstance] addMetadata:[CCUtility insertFileSystemInMetadata:metadata]];
  559. // OOOOOK
  560. if ([CCUtility isFolderEncrypted:metadataForUpload.serverUrl account:tableAccount.account] && [CCUtility isEndToEndEnabled:tableAccount.account]) {
  561. [self e2eEncryptedFile:metadataForUpload tableAccount:tableAccount taskStatus:taskStatus];
  562. } else {
  563. [self uploadURLSessionMetadata:metadataForUpload tableAccount:tableAccount taskStatus:taskStatus];
  564. }
  565. });
  566. }
  567. }
  568. }];
  569. }
  570. } else {
  571. // create Metadata for Upload
  572. tableMetadata *metadataForUpload = [[NCManageDatabase sharedInstance] addMetadata:[CCUtility insertFileSystemInMetadata:metadata]];
  573. // OOOOOK
  574. if ([CCUtility isFolderEncrypted:metadataForUpload.serverUrl account:tableAccount.account] && [CCUtility isEndToEndEnabled:tableAccount.account]) {
  575. [self e2eEncryptedFile:metadataForUpload tableAccount:tableAccount taskStatus:taskStatus];
  576. } else {
  577. [self uploadURLSessionMetadata:metadataForUpload tableAccount:tableAccount taskStatus:taskStatus];
  578. }
  579. }
  580. }
  581. - (void)e2eEncryptedFile:(tableMetadata *)metadata tableAccount:(tableAccount *)tableAccount taskStatus:(NSInteger)taskStatus
  582. {
  583. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  584. NSError *error;
  585. NSString *fileNameIdentifier;
  586. NSString *key;
  587. NSString *initializationVector;
  588. NSString *authenticationTag;
  589. NSString *metadataKey;
  590. NSInteger metadataKeyIndex;
  591. NSString *e2eeMetadata;
  592. // Verify File Size
  593. NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:[CCUtility getDirectoryProviderStorageFileID:metadata.fileID fileNameView:metadata.fileNameView] error:&error];
  594. NSNumber *fileSizeNumber = [fileAttributes objectForKey:NSFileSize];
  595. long long fileSize = [fileSizeNumber longLongValue];
  596. if (fileSize > k_max_filesize_E2EE) {
  597. // Error for uploadFileFailure
  598. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:fileID:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  599. [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];
  600. }
  601. return;
  602. }
  603. // if new file upload create a new encrypted filename
  604. if ([metadata.fileID isEqualToString:[CCUtility createMetadataIDFromAccount:metadata.account serverUrl:metadata.serverUrl fileNameView:metadata.fileNameView directory:false]]) {
  605. fileNameIdentifier = [CCUtility generateRandomIdentifier];
  606. } else {
  607. fileNameIdentifier = metadata.fileName;
  608. }
  609. if ([[NCEndToEndEncryption sharedManager] encryptFileName:metadata.fileNameView fileNameIdentifier:fileNameIdentifier directory:[CCUtility getDirectoryProviderStorageFileID:metadata.fileID] key:&key initializationVector:&initializationVector authenticationTag:&authenticationTag]) {
  610. tableE2eEncryption *object = [[NCManageDatabase sharedInstance] getE2eEncryptionWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", tableAccount.account, metadata.serverUrl]];
  611. if (object) {
  612. metadataKey = object.metadataKey;
  613. metadataKeyIndex = object.metadataKeyIndex;
  614. } else {
  615. metadataKey = [[[NCEndToEndEncryption sharedManager] generateKey:16] base64EncodedStringWithOptions:0]; // AES_KEY_128_LENGTH
  616. metadataKeyIndex = 0;
  617. }
  618. tableE2eEncryption *addObject = [tableE2eEncryption new];
  619. addObject.account = tableAccount.account;
  620. addObject.authenticationTag = authenticationTag;
  621. addObject.fileName = metadata.fileNameView;
  622. addObject.fileNameIdentifier = fileNameIdentifier;
  623. addObject.fileNamePath = [CCUtility returnFileNamePathFromFileName:metadata.fileNameView serverUrl:metadata.serverUrl activeUrl:tableAccount.url];
  624. addObject.key = key;
  625. addObject.initializationVector = initializationVector;
  626. addObject.metadataKey = metadataKey;
  627. addObject.metadataKeyIndex = metadataKeyIndex;
  628. CFStringRef UTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef)[metadata.fileNameView pathExtension], NULL);
  629. CFStringRef mimeTypeRef = UTTypeCopyPreferredTagWithClass (UTI, kUTTagClassMIMEType);
  630. if (mimeTypeRef) {
  631. addObject.mimeType = (__bridge NSString *)mimeTypeRef;
  632. } else {
  633. addObject.mimeType = @"application/octet-stream";
  634. }
  635. addObject.serverUrl = metadata.serverUrl;
  636. addObject.version = [[NCManageDatabase sharedInstance] getEndToEndEncryptionVersionWithAccount:tableAccount.account];
  637. // Get the last metadata
  638. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", tableAccount.account, metadata.serverUrl]];
  639. error = [[NCNetworkingEndToEnd sharedManager] getEndToEndMetadata:&e2eeMetadata fileID:directory.fileID user:tableAccount.user userID:tableAccount.userID password:tableAccount.password url:tableAccount.url];
  640. if (error == nil) {
  641. if ([[NCEndToEndMetadata sharedInstance] decoderMetadata:e2eeMetadata privateKey:[CCUtility getEndToEndPrivateKey:tableAccount.account] serverUrl:metadata.serverUrl account:tableAccount.account url:tableAccount.url] == false) {
  642. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:fileID:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  643. [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];
  644. }
  645. return;
  646. }
  647. }
  648. // write new record e2ee
  649. if([[NCManageDatabase sharedInstance] addE2eEncryption:addObject] == NO) {
  650. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:fileID:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  651. [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];
  652. }
  653. return;
  654. }
  655. } else {
  656. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:fileID:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  657. [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];
  658. }
  659. return;
  660. }
  661. dispatch_async(dispatch_get_main_queue(), ^{
  662. // Now the fileName is fileNameIdentifier && flag e2eEncrypted
  663. metadata.fileName = fileNameIdentifier;
  664. metadata.e2eEncrypted = YES;
  665. // Update Metadata
  666. tableMetadata *metadataEncrypted = [[NCManageDatabase sharedInstance] addMetadata:metadata];
  667. [self uploadURLSessionMetadata:metadataEncrypted tableAccount:tableAccount taskStatus:taskStatus];
  668. });
  669. });
  670. }
  671. - (void)uploadURLSessionMetadata:(tableMetadata *)metadata tableAccount:(tableAccount *)tableAccount taskStatus:(NSInteger)taskStatus
  672. {
  673. NSURL *url;
  674. NSMutableURLRequest *request;
  675. PHAsset *asset;
  676. NSError *error;
  677. // calculate and store file size
  678. NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:[CCUtility getDirectoryProviderStorageFileID:metadata.fileID fileNameView:metadata.fileName] error:&error];
  679. long long fileSize = [[fileAttributes objectForKey:NSFileSize] longLongValue];
  680. metadata.size = fileSize;
  681. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  682. url = [NSURL URLWithString:[[NSString stringWithFormat:@"%@/%@", metadata.serverUrl, metadata.fileName] encodeString:NSUTF8StringEncoding]];
  683. request = [NSMutableURLRequest requestWithURL:url];
  684. NSData *authData = [[NSString stringWithFormat:@"%@:%@", tableAccount.user, tableAccount.password] dataUsingEncoding:NSUTF8StringEncoding];
  685. NSString *authValue = [NSString stringWithFormat: @"Basic %@",[authData base64EncodedStringWithOptions:0]];
  686. [request setHTTPMethod:@"PUT"];
  687. [request setValue:authValue forHTTPHeaderField:@"Authorization"];
  688. [request setValue:[CCUtility getUserAgent] forHTTPHeaderField:@"User-Agent"];
  689. // Create Image for Upload (gray scale)
  690. #ifndef EXTENSION
  691. [CCGraphics createNewImageFrom:metadata.fileNameView fileID:metadata.fileID extension:[metadata.fileNameView pathExtension] filterGrayScale:YES typeFile:metadata.typeFile writeImage:YES];
  692. #endif
  693. // Change date file upload with header : X-OC-Mtime (ctime assetLocalIdentifier) image/video
  694. if (metadata.assetLocalIdentifier) {
  695. PHFetchResult *result = [PHAsset fetchAssetsWithLocalIdentifiers:@[metadata.assetLocalIdentifier] options:nil];
  696. if (result.count) {
  697. asset = result[0];
  698. long dateFileCreation = [asset.creationDate timeIntervalSince1970];
  699. [request setValue:[NSString stringWithFormat:@"%ld", dateFileCreation] forHTTPHeaderField:@"X-OC-Mtime"];
  700. }
  701. }
  702. NSURLSession *sessionUpload;
  703. // NSURLSession
  704. if ([metadata.session isEqualToString:k_upload_session]) sessionUpload = [self sessionUpload];
  705. else if ([metadata.session isEqualToString:k_upload_session_wwan]) sessionUpload = [self sessionWWanUpload];
  706. else if ([metadata.session isEqualToString:k_upload_session_foreground]) sessionUpload = [self sessionUploadForeground];
  707. else if ([metadata.session isEqualToString:k_upload_session_extension]) sessionUpload = [self sessionUploadExtension];
  708. NSURLSessionUploadTask *uploadTask = [sessionUpload uploadTaskWithRequest:request fromFile:[NSURL fileURLWithPath:[CCUtility getDirectoryProviderStorageFileID:metadata.fileID fileNameView:metadata.fileName]]];
  709. // Error
  710. if (uploadTask == nil) {
  711. NSString *messageError = @"Serious internal error uploadTask not available";
  712. [[NCManageDatabase sharedInstance] setMetadataSession:metadata.session sessionError:messageError sessionSelector:nil sessionTaskIdentifier:k_taskIdentifierDone status:k_metadataStatusUploadError predicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID]];
  713. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:fileID:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  714. [self.delegate uploadFileSuccessFailure:metadata.fileNameView fileID:metadata.fileID assetLocalIdentifier:metadata.assetLocalIdentifier serverUrl:metadata.serverUrl selector:metadata.sessionSelector errorMessage:messageError errorCode:k_CCErrorInternalError];
  715. }
  716. } else {
  717. // E2EE : CREATE AND SEND METADATA
  718. if ([CCUtility isFolderEncrypted:metadata.serverUrl account:tableAccount.account] && [CCUtility isEndToEndEnabled:tableAccount.account]) {
  719. NSString *serverUrl = metadata.serverUrl;
  720. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  721. // Send Metadata
  722. NSError *error = [[NCNetworkingEndToEnd sharedManager] sendEndToEndMetadataOnServerUrl:serverUrl fileNameRename:nil fileNameNewRename:nil account:tableAccount.account user:tableAccount.user userID:tableAccount.userID password:tableAccount.password url:tableAccount.url];
  723. dispatch_async(dispatch_get_main_queue(), ^{
  724. if (error) {
  725. [uploadTask cancel];
  726. NSString *messageError = [NSString stringWithFormat:@"%@ (%d)", error.localizedDescription, (int)error.code];
  727. [[NCManageDatabase sharedInstance] setMetadataSession:metadata.session sessionError:messageError sessionSelector:nil sessionTaskIdentifier:k_taskIdentifierDone status:k_metadataStatusUploadError predicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID]];
  728. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:fileID:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  729. [self.delegate uploadFileSuccessFailure:metadata.fileNameView fileID:metadata.fileID assetLocalIdentifier:metadata.assetLocalIdentifier serverUrl:metadata.serverUrl selector:metadata.sessionSelector errorMessage:messageError errorCode:k_CCErrorInternalError];
  730. }
  731. } else {
  732. // Manage uploadTask cancel,suspend,resume
  733. if (taskStatus == k_taskStatusCancel) [uploadTask cancel];
  734. else if (taskStatus == k_taskStatusSuspend) [uploadTask suspend];
  735. else if (taskStatus == k_taskStatusResume) [uploadTask resume];
  736. // *** E2EE ***
  737. [[NCManageDatabase sharedInstance] setMetadataSession:metadata.session sessionError:@"" sessionSelector:nil sessionTaskIdentifier:uploadTask.taskIdentifier status:k_metadataStatusUploading predicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID]];
  738. NSLog(@"[LOG] Upload file %@ TaskIdentifier %lu", metadata.fileName, (unsigned long)uploadTask.taskIdentifier);
  739. NSString *fileID = metadata.fileID;
  740. NSString *account = metadata.account;
  741. dispatch_async(dispatch_get_main_queue(), ^{
  742. if ([self.delegate respondsToSelector:@selector(uploadStart:account:task:serverUrl:)]) {
  743. [self.delegate uploadStart:fileID account:account task:uploadTask serverUrl:metadata.serverUrl];
  744. }
  745. });
  746. }
  747. });
  748. });
  749. } else {
  750. // Manage uploadTask cancel,suspend,resume
  751. if (taskStatus == k_taskStatusCancel) [uploadTask cancel];
  752. else if (taskStatus == k_taskStatusSuspend) [uploadTask suspend];
  753. else if (taskStatus == k_taskStatusResume) [uploadTask resume];
  754. // *** PLAIN ***
  755. [[NCManageDatabase sharedInstance] setMetadataSession:metadata.session sessionError:@"" sessionSelector:nil sessionTaskIdentifier:uploadTask.taskIdentifier status:k_metadataStatusUploading predicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID]];
  756. NSLog(@"[LOG] Upload file %@ TaskIdentifier %lu", metadata.fileName, (unsigned long)uploadTask.taskIdentifier);
  757. NSString *fileID = metadata.fileID;
  758. NSString *account = metadata.account;
  759. dispatch_async(dispatch_get_main_queue(), ^{
  760. if ([self.delegate respondsToSelector:@selector(uploadStart:account:task:serverUrl:)]) {
  761. [self.delegate uploadStart:fileID account:account task:uploadTask serverUrl:metadata.serverUrl];
  762. }
  763. });
  764. }
  765. }
  766. }
  767. - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
  768. {
  769. }
  770. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend
  771. {
  772. NSString *url = [[[task currentRequest].URL absoluteString] stringByRemovingPercentEncoding];
  773. NSString *fileName = [url lastPathComponent];
  774. NSString *serverUrl = [self getServerUrlFromUrl:url];
  775. if (!serverUrl) return;
  776. if (totalBytesExpectedToSend < 1) {
  777. totalBytesExpectedToSend = totalBytesSent;
  778. }
  779. float progress = (float) totalBytesSent / (float)totalBytesExpectedToSend;
  780. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataInSessionFromFileName:fileName serverUrl:serverUrl taskIdentifier:task.taskIdentifier];
  781. if (metadata) {
  782. 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])};
  783. if (userInfo)
  784. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"NotificationProgressTask" object:nil userInfo:userInfo];
  785. }
  786. }
  787. - (void)uploadFileSuccessFailure:(tableMetadata *)metadata fileName:(NSString *)fileName fileID:(NSString *)fileID etag:(NSString *)etag date:(NSDate *)date serverUrl:(NSString *)serverUrl errorCode:(NSInteger)errorCode
  788. {
  789. NSString *tempFileID = metadata.fileID;
  790. NSString *tempSession = metadata.session;
  791. NSString *errorMessage = @"";
  792. BOOL isE2EEDirectory = false;
  793. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", metadata.account]];
  794. if (tableAccount == nil) {
  795. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", tempFileID]];
  796. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:fileID:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  797. [self.delegate uploadFileSuccessFailure:metadata.fileName fileID:metadata.fileID assetLocalIdentifier:metadata.assetLocalIdentifier serverUrl:serverUrl selector:metadata.sessionSelector errorMessage:errorMessage errorCode:errorCode];
  798. }
  799. return;
  800. }
  801. // is this a E2EE Directory ?
  802. if ([CCUtility isFolderEncrypted:serverUrl account:tableAccount.account] && [CCUtility isEndToEndEnabled:tableAccount.account]) {
  803. isE2EEDirectory = true;
  804. }
  805. // ERRORE
  806. if (errorCode != 0) {
  807. #ifndef EXTENSION
  808. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  809. [appDelegate.listProgressMetadata removeObjectForKey:metadata.fileID];
  810. #endif
  811. // Mark error only if not Cancelled Task
  812. if (errorCode == kCFURLErrorCancelled) {
  813. [[NSFileManager defaultManager] removeItemAtPath:[CCUtility getDirectoryProviderStorageFileID:tempFileID] error:nil];
  814. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", tempFileID]];
  815. } else {
  816. [[NCManageDatabase sharedInstance] setMetadataSession:nil sessionError:[CCError manageErrorKCF:errorCode withNumberError:NO] sessionSelector:nil sessionTaskIdentifier:k_taskIdentifierDone status:k_metadataStatusUploadError predicate:[NSPredicate predicateWithFormat:@"fileID == %@", tempFileID]];
  817. }
  818. errorMessage = [CCError manageErrorKCF:errorCode withNumberError:YES];
  819. } else {
  820. // Replace Metadata
  821. metadata.date = date;
  822. if (isE2EEDirectory) {
  823. metadata.e2eEncrypted = true;
  824. } else {
  825. metadata.e2eEncrypted = false;
  826. }
  827. metadata.etag = etag;
  828. metadata.fileID = fileID;
  829. metadata.session = @"";
  830. metadata.sessionError = @"";
  831. metadata.sessionTaskIdentifier = k_taskIdentifierDone;
  832. metadata.status = k_metadataStatusNormal;
  833. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@ AND fileName == %@", metadata.account, metadata.serverUrl, metadata.fileName]];
  834. metadata = [[NCManageDatabase sharedInstance] addMetadata:metadata];
  835. NSLog(@"[LOG] Insert new upload : %@ - fileID : %@", metadata.fileName, fileID);
  836. // remove tempFileID and adjust the directory provider storage
  837. if ([tempFileID isEqualToString:[CCUtility createMetadataIDFromAccount:metadata.account serverUrl:metadata.serverUrl fileNameView:metadata.fileNameView directory:metadata.directory]]) {
  838. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", tempFileID]];
  839. // adjust file system Directory Provider Storage
  840. if ([tempSession isEqualToString:k_upload_session_extension]) {
  841. // this is for File Provider Extension [Apple Works and ... ?]
  842. [CCUtility copyFileAtPath:[NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryProviderStorage], tempFileID] toPath:[NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryProviderStorage], metadata.fileID]];
  843. } else {
  844. [CCUtility moveFileAtPath:[NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryProviderStorage], tempFileID] toPath:[NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryProviderStorage], metadata.fileID]];
  845. }
  846. }
  847. #ifndef EXTENSION
  848. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  849. [appDelegate.listProgressMetadata removeObjectForKey:metadata.fileID];
  850. // Hardcoded for add new photo/video for tab Media view
  851. NSString *startDirectoryMediaTabView = [[NCManageDatabase sharedInstance] getAccountStartDirectoryMediaTabView:[CCUtility getHomeServerUrlActiveUrl:appDelegate.activeUrl]];
  852. if ([serverUrl containsString:startDirectoryMediaTabView] && ([metadata.typeFile isEqualToString:k_metadataTypeFile_image] || [metadata.typeFile isEqualToString:k_metadataTypeFile_video])) {
  853. [appDelegate.activeMedia.addMetadatasFromUpload addObject:metadata];
  854. }
  855. #endif
  856. // Add Local
  857. [[NCManageDatabase sharedInstance] addLocalFileWithMetadata:metadata];
  858. #ifndef EXTENSION
  859. // EXIF
  860. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image])
  861. [[CCExifGeo sharedInstance] setExifLocalTableEtag:metadata];
  862. // Create preview
  863. [CCGraphics createNewImageFrom:metadata.fileNameView fileID:metadata.fileID extension:[metadata.fileNameView pathExtension] filterGrayScale:NO typeFile:metadata.typeFile writeImage:YES];
  864. // Copy photo or video in the photo album for auto upload
  865. if ([metadata.assetLocalIdentifier length] > 0 && ([metadata.sessionSelector isEqualToString:selectorUploadAutoUpload] || [metadata.sessionSelector isEqualToString:selectorUploadFile])) {
  866. PHAsset *asset;
  867. PHFetchResult *result = [PHAsset fetchAssetsWithLocalIdentifiers:@[metadata.assetLocalIdentifier] options:nil];
  868. if(result.count){
  869. asset = result[0];
  870. [asset saveToAlbum:[NCBrandOptions sharedInstance].brand completionBlock:^(BOOL success) {
  871. if (success) NSLog(@"[LOG] Insert file %@ in %@", metadata.fileName, [NCBrandOptions sharedInstance].brand);
  872. else NSLog(@"[LOG] File %@ do not insert in %@", metadata.fileName, [NCBrandOptions sharedInstance].brand);
  873. }];
  874. }
  875. }
  876. #endif
  877. // Actvity
  878. [[NCManageDatabase sharedInstance] addActivityClient:metadata.fileNameView fileID:fileID action:k_activityDebugActionUpload selector:metadata.sessionSelector note:serverUrl type:k_activityTypeSuccess verbose:k_activityVerboseDefault activeUrl:tableAccount.url];
  879. }
  880. // Detect E2EE
  881. 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]];
  882. // E2EE : UNLOCK
  883. if (isE2EEDirectory && e2eeMetadataInSession == nil) {
  884. tableE2eEncryptionLock *tableLock = [[NCManageDatabase sharedInstance] getE2ETokenLockWithServerUrl:serverUrl];
  885. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  886. if (tableLock) {
  887. NSError *error = [[NCNetworkingEndToEnd sharedManager] unlockEndToEndFolderEncryptedOnServerUrl:serverUrl fileID:tableLock.fileID token:tableLock.token user:tableAccount.user userID:tableAccount.userID password:tableAccount.password url:tableAccount.url];
  888. if (error) {
  889. #ifndef EXTENSION
  890. dispatch_async(dispatch_get_main_queue(), ^{
  891. [(AppDelegate *)[[UIApplication sharedApplication] delegate] messageNotification:@"_e2e_error_unlock_" description:error.localizedDescription visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  892. });
  893. #endif
  894. }
  895. } else {
  896. NSLog(@"Error unlock not found");
  897. }
  898. dispatch_async(dispatch_get_main_queue(), ^{
  899. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:fileID:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  900. [self.delegate uploadFileSuccessFailure:metadata.fileName fileID:metadata.fileID assetLocalIdentifier:metadata.assetLocalIdentifier serverUrl:serverUrl selector:metadata.sessionSelector errorMessage:errorMessage errorCode:errorCode];
  901. }
  902. });
  903. });
  904. } else {
  905. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:fileID:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  906. [self.delegate uploadFileSuccessFailure:metadata.fileName fileID:metadata.fileID assetLocalIdentifier:metadata.assetLocalIdentifier serverUrl:serverUrl selector:metadata.sessionSelector errorMessage:errorMessage errorCode:errorCode];
  907. }
  908. }
  909. }
  910. #pragma --------------------------------------------------------------------------------------------
  911. #pragma mark ===== Utility =====
  912. #pragma --------------------------------------------------------------------------------------------
  913. - (NSString *)getServerUrlFromUrl:(NSString *)url
  914. {
  915. NSString *fileName = [url lastPathComponent];
  916. url = [url stringByReplacingOccurrencesOfString:[@"/" stringByAppendingString:fileName] withString:@""];
  917. return url;
  918. }
  919. @end