CCNetworking.m 67 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211
  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. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"NotificationProgressTask" object:nil userInfo:userInfo];
  370. } else {
  371. NSLog(@"[LOG] metadata not found");
  372. }
  373. }
  374. - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
  375. {
  376. NSString *url = [[[downloadTask currentRequest].URL absoluteString] stringByRemovingPercentEncoding];
  377. if (!url)
  378. return;
  379. NSString *fileName = [url lastPathComponent];
  380. NSString *serverUrl = [self getServerUrlFromUrl:url];
  381. if (!serverUrl) return;
  382. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataInSessionFromFileName:fileName serverUrl:serverUrl taskIdentifier:downloadTask.taskIdentifier];
  383. if (!metadata) {
  384. [[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:@""];
  385. NSLog(@"[LOG] Serious error internal download : metadata not found %@ ", url);
  386. dispatch_async(dispatch_get_main_queue(), ^{
  387. if ([self.delegate respondsToSelector:@selector(downloadFileSuccessFailure:fileID:serverUrl:selector:errorMessage:errorCode:)]) {
  388. [self.delegate downloadFileSuccessFailure:@"" fileID:@"" serverUrl:serverUrl selector:@"" errorMessage:@"Serious error internal download : metadata not found" errorCode:k_CCErrorInternalError];
  389. }
  390. });
  391. return;
  392. }
  393. NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)downloadTask.response;
  394. if (httpResponse.statusCode >= 200 && httpResponse.statusCode < 300) {
  395. NSString *destinationFilePath = [CCUtility getDirectoryProviderStorageFileID:metadata.fileID fileNameView:metadata.fileName];
  396. NSURL *destinationURL = [NSURL fileURLWithPath:destinationFilePath];
  397. [[NSFileManager defaultManager] removeItemAtURL:destinationURL error:NULL];
  398. [[NSFileManager defaultManager] copyItemAtURL:location toURL:destinationURL error:nil];
  399. }
  400. }
  401. - (void)downloadFileSuccessFailure:(NSString *)fileName fileID:(NSString *)fileID etag:(NSString *)etag date:(NSDate *)date serverUrl:(NSString *)serverUrl selector:(NSString *)selector errorCode:(NSInteger)errorCode
  402. {
  403. #ifndef EXTENSION
  404. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  405. [appDelegate.listProgressMetadata removeObjectForKey:fileID];
  406. #endif
  407. if (errorCode != 0) {
  408. if (errorCode == kCFURLErrorCancelled) {
  409. [[NCManageDatabase sharedInstance] setMetadataSession:@"" sessionError:@"" sessionSelector:@"" sessionTaskIdentifier:k_taskIdentifierDone status:k_metadataStatusNormal predicate:[NSPredicate predicateWithFormat:@"fileID == %@", fileID]];
  410. } else {
  411. [[NCManageDatabase sharedInstance] setMetadataSession:nil sessionError:[CCError manageErrorKCF:errorCode withNumberError:NO] sessionSelector:nil sessionTaskIdentifier:k_taskIdentifierDone status:k_metadataStatusDownloadError predicate:[NSPredicate predicateWithFormat:@"fileID == %@", fileID]];
  412. }
  413. if ([self.delegate respondsToSelector:@selector(downloadFileSuccessFailure:fileID:serverUrl:selector:errorMessage:errorCode:)]) {
  414. [self.delegate downloadFileSuccessFailure:fileName fileID:fileID serverUrl:serverUrl selector:selector errorMessage:[CCError manageErrorKCF:errorCode withNumberError:YES] errorCode:errorCode];
  415. }
  416. } else {
  417. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", fileID]];
  418. if (!metadata) {
  419. [[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:@""];
  420. NSLog(@"[LOG] Serious error internal download : metadata not found %@ ", fileName);
  421. if ([self.delegate respondsToSelector:@selector(downloadFileSuccessFailure:fileID:serverUrl:selector:errorMessage:errorCode:)]) {
  422. [self.delegate downloadFileSuccessFailure:fileName fileID:fileID serverUrl:serverUrl selector:selector errorMessage:[NSString stringWithFormat:@"Serious error internal download : metadata not found %@", fileName] errorCode:k_CCErrorInternalError];
  423. }
  424. return;
  425. }
  426. metadata.session = @"";
  427. metadata.sessionError = @"";
  428. metadata.sessionSelector = @"";
  429. metadata.sessionTaskIdentifier = k_taskIdentifierDone;
  430. metadata.status = k_metadataStatusNormal;
  431. metadata = [[NCManageDatabase sharedInstance] updateMetadata:metadata];
  432. [[NCManageDatabase sharedInstance] addLocalFileWithMetadata:metadata];
  433. // E2EE Decrypted
  434. tableE2eEncryption *object = [[NCManageDatabase sharedInstance] getE2eEncryptionWithPredicate:[NSPredicate predicateWithFormat:@"fileNameIdentifier == %@ AND serverUrl == %@", fileName, serverUrl]];
  435. if (object) {
  436. BOOL result = [[NCEndToEndEncryption sharedManager] decryptFileName:metadata.fileName fileNameView:metadata.fileNameView fileID:metadata.fileID key:object.key initializationVector:object.initializationVector authenticationTag:object.authenticationTag];
  437. if (!result) {
  438. [[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:@""];
  439. if ([self.delegate respondsToSelector:@selector(downloadFileSuccessFailure:fileID:serverUrl:selector:errorMessage:errorCode:)]) {
  440. [self.delegate downloadFileSuccessFailure:fileName fileID:fileID serverUrl:serverUrl selector:selector errorMessage:[NSString stringWithFormat:@"Serious error internal download : decrypt error %@", fileName] errorCode:k_CCErrorInternalError];
  441. }
  442. return;
  443. }
  444. }
  445. // Exif
  446. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image])
  447. [[CCExifGeo sharedInstance] setExifLocalTableEtag:metadata];
  448. // Icon
  449. if ([[NSFileManager defaultManager] fileExistsAtPath:[CCUtility getDirectoryProviderStorageIconFileID:metadata.fileID fileNameView:metadata.fileNameView]] == NO) {
  450. [CCGraphics createNewImageFrom:metadata.fileNameView fileID:metadata.fileID extension:[metadata.fileNameView pathExtension] filterGrayScale:NO typeFile:metadata.typeFile writeImage:YES];
  451. }
  452. // Activity
  453. [[NCManageDatabase sharedInstance] addActivityClient:metadata.fileNameView fileID:metadata.fileID action:k_activityDebugActionDownload selector:metadata.sessionSelector note:serverUrl type:k_activityTypeSuccess verbose:k_activityVerboseDefault activeUrl:@""];
  454. if ([self.delegate respondsToSelector:@selector(downloadFileSuccessFailure:fileID:serverUrl:selector:errorMessage:errorCode:)]) {
  455. [self.delegate downloadFileSuccessFailure:fileName fileID:fileID serverUrl:serverUrl selector:selector errorMessage:@"" errorCode:0];
  456. }
  457. }
  458. }
  459. #pragma --------------------------------------------------------------------------------------------
  460. #pragma mark ===== Upload =====
  461. #pragma --------------------------------------------------------------------------------------------
  462. - (void)uploadFile:(tableMetadata *)metadata taskStatus:(NSInteger)taskStatus
  463. {
  464. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", metadata.account]];
  465. if (tableAccount == nil) {
  466. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID]];
  467. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:fileID:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  468. [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];
  469. }
  470. return;
  471. }
  472. if ([CCUtility fileProviderStorageExists:metadata.fileID fileNameView:metadata.fileNameView] == NO) {
  473. PHFetchResult *result = [PHAsset fetchAssetsWithLocalIdentifiers:@[metadata.assetLocalIdentifier] options:nil];
  474. if (!result.count) {
  475. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID]];
  476. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:fileID:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  477. [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];
  478. }
  479. return;
  480. }
  481. PHAsset *asset= result[0];
  482. // IMAGE
  483. if (asset.mediaType == PHAssetMediaTypeImage) {
  484. PHImageRequestOptions *options = [PHImageRequestOptions new];
  485. options.networkAccessAllowed = YES; // iCloud
  486. options.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
  487. options.synchronous = YES;
  488. options.progressHandler = ^(double progress, NSError *error, BOOL *stop, NSDictionary *info) {
  489. NSLog(@"cacheAsset: %f", progress);
  490. if (error) {
  491. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID]];
  492. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:fileID:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  493. [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];
  494. }
  495. }
  496. };
  497. [[PHImageManager defaultManager] requestImageDataForAsset:asset options:options resultHandler:^(NSData *imageData, NSString *dataUTI, UIImageOrientation orientation, NSDictionary *info) {
  498. NSError *error = nil;
  499. NSString *extensionAsset = [[[asset valueForKey:@"filename"] pathExtension] uppercaseString];
  500. if ([extensionAsset isEqualToString:@"HEIC"] && [CCUtility getFormatCompatibility]) {
  501. UIImage *image = [UIImage imageWithData:imageData];
  502. imageData = UIImageJPEGRepresentation(image, 1.0);
  503. NSString *fileNameJPEG = [[metadata.fileName lastPathComponent] stringByDeletingPathExtension];
  504. metadata.fileName = [fileNameJPEG stringByAppendingString:@".jpg"];
  505. metadata.fileNameView = metadata.fileName;
  506. // Change Metadata with new fileID, fileName, fileNameView
  507. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID]];
  508. metadata.fileID = [CCUtility createMetadataIDFromAccount:metadata.account serverUrl:metadata.serverUrl fileNameView:metadata.fileNameView directory:false];
  509. }
  510. tableMetadata *metadataForUpload = [[NCManageDatabase sharedInstance] addMetadata:[CCUtility insertFileSystemInMetadata:metadata]];
  511. [imageData writeToFile:[CCUtility getDirectoryProviderStorageFileID:metadataForUpload.fileID fileNameView:metadataForUpload.fileNameView] options:NSDataWritingAtomic error:&error];
  512. if (error) {
  513. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadataForUpload.fileID]];
  514. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:fileID:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  515. [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];
  516. }
  517. } else {
  518. // OOOOOK
  519. if ([CCUtility isFolderEncrypted:metadataForUpload.serverUrl account:tableAccount.account] && [CCUtility isEndToEndEnabled:tableAccount.account]) {
  520. [self e2eEncryptedFile:metadataForUpload tableAccount:tableAccount taskStatus:taskStatus];
  521. } else {
  522. [self uploadURLSessionMetadata:metadataForUpload tableAccount:tableAccount taskStatus:taskStatus];
  523. }
  524. }
  525. }];
  526. }
  527. // VIDEO
  528. if (asset.mediaType == PHAssetMediaTypeVideo) {
  529. PHVideoRequestOptions *options = [PHVideoRequestOptions new];
  530. options.networkAccessAllowed = YES;
  531. options.version = PHVideoRequestOptionsVersionOriginal;
  532. options.progressHandler = ^(double progress, NSError *error, BOOL *stop, NSDictionary *info) {
  533. NSLog(@"cacheAsset: %f", progress);
  534. if (error) {
  535. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID]];
  536. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:fileID:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  537. [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];
  538. }
  539. }
  540. };
  541. [[PHImageManager defaultManager] requestAVAssetForVideo:asset options:options resultHandler:^(AVAsset *asset, AVAudioMix *audioMix, NSDictionary *info) {
  542. if ([asset isKindOfClass:[AVURLAsset class]]) {
  543. NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:[CCUtility getDirectoryProviderStorageFileID:metadata.fileID fileNameView:metadata.fileNameView]];
  544. NSError *error = nil;
  545. [[NSFileManager defaultManager] removeItemAtURL:fileURL error:nil];
  546. [[NSFileManager defaultManager] copyItemAtURL:[(AVURLAsset *)asset URL] toURL:fileURL error:&error];
  547. if (error) {
  548. dispatch_async(dispatch_get_main_queue(), ^{
  549. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID]];
  550. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:fileID:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  551. [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];
  552. }
  553. });
  554. } else {
  555. dispatch_async(dispatch_get_main_queue(), ^{
  556. // create Metadata for Upload
  557. tableMetadata *metadataForUpload = [[NCManageDatabase sharedInstance] addMetadata:[CCUtility insertFileSystemInMetadata:metadata]];
  558. // OOOOOK
  559. if ([CCUtility isFolderEncrypted:metadataForUpload.serverUrl account:tableAccount.account] && [CCUtility isEndToEndEnabled:tableAccount.account]) {
  560. [self e2eEncryptedFile:metadataForUpload tableAccount:tableAccount taskStatus:taskStatus];
  561. } else {
  562. [self uploadURLSessionMetadata:metadataForUpload tableAccount:tableAccount taskStatus:taskStatus];
  563. }
  564. });
  565. }
  566. }
  567. }];
  568. }
  569. } else {
  570. // create Metadata for Upload
  571. tableMetadata *metadataForUpload = [[NCManageDatabase sharedInstance] addMetadata:[CCUtility insertFileSystemInMetadata:metadata]];
  572. // OOOOOK
  573. if ([CCUtility isFolderEncrypted:metadataForUpload.serverUrl account:tableAccount.account] && [CCUtility isEndToEndEnabled:tableAccount.account]) {
  574. [self e2eEncryptedFile:metadataForUpload tableAccount:tableAccount taskStatus:taskStatus];
  575. } else {
  576. [self uploadURLSessionMetadata:metadataForUpload tableAccount:tableAccount taskStatus:taskStatus];
  577. }
  578. }
  579. }
  580. - (void)e2eEncryptedFile:(tableMetadata *)metadata tableAccount:(tableAccount *)tableAccount taskStatus:(NSInteger)taskStatus
  581. {
  582. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  583. NSError *error;
  584. NSString *fileNameIdentifier;
  585. NSString *key;
  586. NSString *initializationVector;
  587. NSString *authenticationTag;
  588. NSString *metadataKey;
  589. NSInteger metadataKeyIndex;
  590. NSString *e2eeMetadata;
  591. // Verify File Size
  592. NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:[CCUtility getDirectoryProviderStorageFileID:metadata.fileID fileNameView:metadata.fileNameView] error:&error];
  593. NSNumber *fileSizeNumber = [fileAttributes objectForKey:NSFileSize];
  594. long long fileSize = [fileSizeNumber longLongValue];
  595. if (fileSize > k_max_filesize_E2EE) {
  596. // Error for uploadFileFailure
  597. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:fileID:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  598. [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];
  599. }
  600. return;
  601. }
  602. // if new file upload create a new encrypted filename
  603. if ([metadata.fileID isEqualToString:[CCUtility createMetadataIDFromAccount:metadata.account serverUrl:metadata.serverUrl fileNameView:metadata.fileNameView directory:false]]) {
  604. fileNameIdentifier = [CCUtility generateRandomIdentifier];
  605. } else {
  606. fileNameIdentifier = metadata.fileName;
  607. }
  608. if ([[NCEndToEndEncryption sharedManager] encryptFileName:metadata.fileNameView fileNameIdentifier:fileNameIdentifier directory:[CCUtility getDirectoryProviderStorageFileID:metadata.fileID] key:&key initializationVector:&initializationVector authenticationTag:&authenticationTag]) {
  609. tableE2eEncryption *object = [[NCManageDatabase sharedInstance] getE2eEncryptionWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", tableAccount.account, metadata.serverUrl]];
  610. if (object) {
  611. metadataKey = object.metadataKey;
  612. metadataKeyIndex = object.metadataKeyIndex;
  613. } else {
  614. metadataKey = [[[NCEndToEndEncryption sharedManager] generateKey:16] base64EncodedStringWithOptions:0]; // AES_KEY_128_LENGTH
  615. metadataKeyIndex = 0;
  616. }
  617. tableE2eEncryption *addObject = [tableE2eEncryption new];
  618. addObject.account = tableAccount.account;
  619. addObject.authenticationTag = authenticationTag;
  620. addObject.fileName = metadata.fileNameView;
  621. addObject.fileNameIdentifier = fileNameIdentifier;
  622. addObject.fileNamePath = [CCUtility returnFileNamePathFromFileName:metadata.fileNameView serverUrl:metadata.serverUrl activeUrl:tableAccount.url];
  623. addObject.key = key;
  624. addObject.initializationVector = initializationVector;
  625. addObject.metadataKey = metadataKey;
  626. addObject.metadataKeyIndex = metadataKeyIndex;
  627. CFStringRef UTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef)[metadata.fileNameView pathExtension], NULL);
  628. CFStringRef mimeTypeRef = UTTypeCopyPreferredTagWithClass (UTI, kUTTagClassMIMEType);
  629. if (mimeTypeRef) {
  630. addObject.mimeType = (__bridge NSString *)mimeTypeRef;
  631. } else {
  632. addObject.mimeType = @"application/octet-stream";
  633. }
  634. addObject.serverUrl = metadata.serverUrl;
  635. addObject.version = [[NCManageDatabase sharedInstance] getEndToEndEncryptionVersionWithAccount:tableAccount.account];
  636. // Get the last metadata
  637. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", tableAccount.account, metadata.serverUrl]];
  638. error = [[NCNetworkingEndToEnd sharedManager] getEndToEndMetadata:&e2eeMetadata fileID:directory.fileID user:tableAccount.user userID:tableAccount.userID password:tableAccount.password url:tableAccount.url];
  639. if (error == nil) {
  640. if ([[NCEndToEndMetadata sharedInstance] decoderMetadata:e2eeMetadata privateKey:[CCUtility getEndToEndPrivateKey:tableAccount.account] serverUrl:metadata.serverUrl account:tableAccount.account url:tableAccount.url] == false) {
  641. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:fileID:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  642. [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];
  643. }
  644. return;
  645. }
  646. }
  647. // write new record e2ee
  648. if([[NCManageDatabase sharedInstance] addE2eEncryption:addObject] == NO) {
  649. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:fileID:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  650. [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];
  651. }
  652. return;
  653. }
  654. } else {
  655. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:fileID:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  656. [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];
  657. }
  658. return;
  659. }
  660. dispatch_async(dispatch_get_main_queue(), ^{
  661. // Now the fileName is fileNameIdentifier && flag e2eEncrypted
  662. metadata.fileName = fileNameIdentifier;
  663. metadata.e2eEncrypted = YES;
  664. // Update Metadata
  665. tableMetadata *metadataEncrypted = [[NCManageDatabase sharedInstance] addMetadata:metadata];
  666. [self uploadURLSessionMetadata:metadataEncrypted tableAccount:tableAccount taskStatus:taskStatus];
  667. });
  668. });
  669. }
  670. - (void)uploadURLSessionMetadata:(tableMetadata *)metadata tableAccount:(tableAccount *)tableAccount taskStatus:(NSInteger)taskStatus
  671. {
  672. NSURL *url;
  673. NSMutableURLRequest *request;
  674. PHAsset *asset;
  675. NSError *error;
  676. // calculate and store file size
  677. NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:[CCUtility getDirectoryProviderStorageFileID:metadata.fileID fileNameView:metadata.fileName] error:&error];
  678. long long fileSize = [[fileAttributes objectForKey:NSFileSize] longLongValue];
  679. metadata.size = fileSize;
  680. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  681. url = [NSURL URLWithString:[[NSString stringWithFormat:@"%@/%@", metadata.serverUrl, metadata.fileName] encodeString:NSUTF8StringEncoding]];
  682. request = [NSMutableURLRequest requestWithURL:url];
  683. NSData *authData = [[NSString stringWithFormat:@"%@:%@", tableAccount.user, tableAccount.password] dataUsingEncoding:NSUTF8StringEncoding];
  684. NSString *authValue = [NSString stringWithFormat: @"Basic %@",[authData base64EncodedStringWithOptions:0]];
  685. [request setHTTPMethod:@"PUT"];
  686. [request setValue:authValue forHTTPHeaderField:@"Authorization"];
  687. [request setValue:[CCUtility getUserAgent] forHTTPHeaderField:@"User-Agent"];
  688. // Create Image for Upload (gray scale)
  689. #ifndef EXTENSION
  690. [CCGraphics createNewImageFrom:metadata.fileNameView fileID:metadata.fileID extension:[metadata.fileNameView pathExtension] filterGrayScale:YES typeFile:metadata.typeFile writeImage:YES];
  691. #endif
  692. // Change date file upload with header : X-OC-Mtime (ctime assetLocalIdentifier) image/video
  693. if (metadata.assetLocalIdentifier) {
  694. PHFetchResult *result = [PHAsset fetchAssetsWithLocalIdentifiers:@[metadata.assetLocalIdentifier] options:nil];
  695. if (result.count) {
  696. asset = result[0];
  697. long dateFileCreation = [asset.creationDate timeIntervalSince1970];
  698. [request setValue:[NSString stringWithFormat:@"%ld", dateFileCreation] forHTTPHeaderField:@"X-OC-Mtime"];
  699. }
  700. }
  701. NSURLSession *sessionUpload;
  702. // NSURLSession
  703. if ([metadata.session isEqualToString:k_upload_session]) sessionUpload = [self sessionUpload];
  704. else if ([metadata.session isEqualToString:k_upload_session_wwan]) sessionUpload = [self sessionWWanUpload];
  705. else if ([metadata.session isEqualToString:k_upload_session_foreground]) sessionUpload = [self sessionUploadForeground];
  706. else if ([metadata.session isEqualToString:k_upload_session_extension]) sessionUpload = [self sessionUploadExtension];
  707. NSURLSessionUploadTask *uploadTask = [sessionUpload uploadTaskWithRequest:request fromFile:[NSURL fileURLWithPath:[CCUtility getDirectoryProviderStorageFileID:metadata.fileID fileNameView:metadata.fileName]]];
  708. // Error
  709. if (uploadTask == nil) {
  710. NSString *messageError = @"Serious internal error uploadTask not available";
  711. [[NCManageDatabase sharedInstance] setMetadataSession:metadata.session sessionError:messageError sessionSelector:nil sessionTaskIdentifier:k_taskIdentifierDone status:k_metadataStatusUploadError predicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID]];
  712. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:fileID:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  713. [self.delegate uploadFileSuccessFailure:metadata.fileNameView fileID:metadata.fileID assetLocalIdentifier:metadata.assetLocalIdentifier serverUrl:metadata.serverUrl selector:metadata.sessionSelector errorMessage:messageError errorCode:k_CCErrorInternalError];
  714. }
  715. } else {
  716. // E2EE : CREATE AND SEND METADATA
  717. if ([CCUtility isFolderEncrypted:metadata.serverUrl account:tableAccount.account] && [CCUtility isEndToEndEnabled:tableAccount.account]) {
  718. NSString *serverUrl = metadata.serverUrl;
  719. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  720. // Send Metadata
  721. 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];
  722. dispatch_async(dispatch_get_main_queue(), ^{
  723. if (error) {
  724. [uploadTask cancel];
  725. NSString *messageError = [NSString stringWithFormat:@"%@ (%d)", error.localizedDescription, (int)error.code];
  726. [[NCManageDatabase sharedInstance] setMetadataSession:metadata.session sessionError:messageError sessionSelector:nil sessionTaskIdentifier:k_taskIdentifierDone status:k_metadataStatusUploadError predicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID]];
  727. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:fileID:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  728. [self.delegate uploadFileSuccessFailure:metadata.fileNameView fileID:metadata.fileID assetLocalIdentifier:metadata.assetLocalIdentifier serverUrl:metadata.serverUrl selector:metadata.sessionSelector errorMessage:messageError errorCode:k_CCErrorInternalError];
  729. }
  730. } else {
  731. // Manage uploadTask cancel,suspend,resume
  732. if (taskStatus == k_taskStatusCancel) [uploadTask cancel];
  733. else if (taskStatus == k_taskStatusSuspend) [uploadTask suspend];
  734. else if (taskStatus == k_taskStatusResume) [uploadTask resume];
  735. // *** E2EE ***
  736. [[NCManageDatabase sharedInstance] setMetadataSession:metadata.session sessionError:@"" sessionSelector:nil sessionTaskIdentifier:uploadTask.taskIdentifier status:k_metadataStatusUploading predicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID]];
  737. NSLog(@"[LOG] Upload file %@ TaskIdentifier %lu", metadata.fileName, (unsigned long)uploadTask.taskIdentifier);
  738. NSString *fileID = metadata.fileID;
  739. NSString *account = metadata.account;
  740. dispatch_async(dispatch_get_main_queue(), ^{
  741. if ([self.delegate respondsToSelector:@selector(uploadStart:account:task:serverUrl:)]) {
  742. [self.delegate uploadStart:fileID account:account task:uploadTask serverUrl:metadata.serverUrl];
  743. }
  744. });
  745. }
  746. });
  747. });
  748. } else {
  749. // Manage uploadTask cancel,suspend,resume
  750. if (taskStatus == k_taskStatusCancel) [uploadTask cancel];
  751. else if (taskStatus == k_taskStatusSuspend) [uploadTask suspend];
  752. else if (taskStatus == k_taskStatusResume) [uploadTask resume];
  753. // *** PLAIN ***
  754. [[NCManageDatabase sharedInstance] setMetadataSession:metadata.session sessionError:@"" sessionSelector:nil sessionTaskIdentifier:uploadTask.taskIdentifier status:k_metadataStatusUploading predicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID]];
  755. NSLog(@"[LOG] Upload file %@ TaskIdentifier %lu", metadata.fileName, (unsigned long)uploadTask.taskIdentifier);
  756. NSString *fileID = metadata.fileID;
  757. NSString *account = metadata.account;
  758. dispatch_async(dispatch_get_main_queue(), ^{
  759. if ([self.delegate respondsToSelector:@selector(uploadStart:account:task:serverUrl:)]) {
  760. [self.delegate uploadStart:fileID account:account task:uploadTask serverUrl:metadata.serverUrl];
  761. }
  762. });
  763. }
  764. }
  765. }
  766. - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
  767. {
  768. }
  769. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend
  770. {
  771. NSString *url = [[[task currentRequest].URL absoluteString] stringByRemovingPercentEncoding];
  772. NSString *fileName = [url lastPathComponent];
  773. NSString *serverUrl = [self getServerUrlFromUrl:url];
  774. if (!serverUrl) return;
  775. if (totalBytesExpectedToSend < 1) {
  776. totalBytesExpectedToSend = totalBytesSent;
  777. }
  778. float progress = (float) totalBytesSent / (float)totalBytesExpectedToSend;
  779. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataInSessionFromFileName:fileName serverUrl:serverUrl taskIdentifier:task.taskIdentifier];
  780. if (metadata) {
  781. 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])};
  782. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"NotificationProgressTask" object:nil userInfo:userInfo];
  783. }
  784. }
  785. - (void)uploadFileSuccessFailure:(tableMetadata *)metadata fileName:(NSString *)fileName fileID:(NSString *)fileID etag:(NSString *)etag date:(NSDate *)date serverUrl:(NSString *)serverUrl errorCode:(NSInteger)errorCode
  786. {
  787. NSString *tempFileID = metadata.fileID;
  788. NSString *tempSession = metadata.session;
  789. NSString *errorMessage = @"";
  790. BOOL isE2EEDirectory = false;
  791. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", metadata.account]];
  792. if (tableAccount == nil) {
  793. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", tempFileID]];
  794. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:fileID:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  795. [self.delegate uploadFileSuccessFailure:metadata.fileName fileID:metadata.fileID assetLocalIdentifier:metadata.assetLocalIdentifier serverUrl:serverUrl selector:metadata.sessionSelector errorMessage:errorMessage errorCode:errorCode];
  796. }
  797. return;
  798. }
  799. // is this a E2EE Directory ?
  800. if ([CCUtility isFolderEncrypted:serverUrl account:tableAccount.account] && [CCUtility isEndToEndEnabled:tableAccount.account]) {
  801. isE2EEDirectory = true;
  802. }
  803. // ERRORE
  804. if (errorCode != 0) {
  805. #ifndef EXTENSION
  806. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  807. [appDelegate.listProgressMetadata removeObjectForKey:metadata.fileID];
  808. #endif
  809. // Mark error only if not Cancelled Task
  810. if (errorCode == kCFURLErrorCancelled) {
  811. [[NSFileManager defaultManager] removeItemAtPath:[CCUtility getDirectoryProviderStorageFileID:tempFileID] error:nil];
  812. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", tempFileID]];
  813. } else {
  814. [[NCManageDatabase sharedInstance] setMetadataSession:nil sessionError:[CCError manageErrorKCF:errorCode withNumberError:NO] sessionSelector:nil sessionTaskIdentifier:k_taskIdentifierDone status:k_metadataStatusUploadError predicate:[NSPredicate predicateWithFormat:@"fileID == %@", tempFileID]];
  815. }
  816. errorMessage = [CCError manageErrorKCF:errorCode withNumberError:YES];
  817. } else {
  818. // Replace Metadata
  819. metadata.date = date;
  820. if (isE2EEDirectory) {
  821. metadata.e2eEncrypted = true;
  822. } else {
  823. metadata.e2eEncrypted = false;
  824. }
  825. metadata.etag = etag;
  826. metadata.fileID = fileID;
  827. metadata.session = @"";
  828. metadata.sessionError = @"";
  829. metadata.sessionTaskIdentifier = k_taskIdentifierDone;
  830. metadata.status = k_metadataStatusNormal;
  831. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@ AND fileName == %@", metadata.account, metadata.serverUrl, metadata.fileName]];
  832. metadata = [[NCManageDatabase sharedInstance] addMetadata:metadata];
  833. NSLog(@"[LOG] Insert new upload : %@ - fileID : %@", metadata.fileName, fileID);
  834. // remove tempFileID and adjust the directory provider storage
  835. if ([tempFileID isEqualToString:[CCUtility createMetadataIDFromAccount:metadata.account serverUrl:metadata.serverUrl fileNameView:metadata.fileNameView directory:metadata.directory]]) {
  836. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", tempFileID]];
  837. // adjust file system Directory Provider Storage
  838. if ([tempSession isEqualToString:k_upload_session_extension]) {
  839. // this is for File Provider Extension [Apple Works and ... ?]
  840. [CCUtility copyFileAtPath:[NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryProviderStorage], tempFileID] toPath:[NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryProviderStorage], metadata.fileID]];
  841. } else {
  842. [CCUtility moveFileAtPath:[NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryProviderStorage], tempFileID] toPath:[NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryProviderStorage], metadata.fileID]];
  843. }
  844. }
  845. #ifndef EXTENSION
  846. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  847. [appDelegate.listProgressMetadata removeObjectForKey:metadata.fileID];
  848. // Hardcoded for add new photo/video for tab Media view
  849. NSString *startDirectoryMediaTabView = [[NCManageDatabase sharedInstance] getAccountStartDirectoryMediaTabView:[CCUtility getHomeServerUrlActiveUrl:appDelegate.activeUrl]];
  850. if ([serverUrl containsString:startDirectoryMediaTabView] && ([metadata.typeFile isEqualToString:k_metadataTypeFile_image] || [metadata.typeFile isEqualToString:k_metadataTypeFile_video])) {
  851. [appDelegate.activeMedia.addMetadatasFromUpload addObject:metadata];
  852. }
  853. #endif
  854. // Add Local
  855. [[NCManageDatabase sharedInstance] addLocalFileWithMetadata:metadata];
  856. #ifndef EXTENSION
  857. // EXIF
  858. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image])
  859. [[CCExifGeo sharedInstance] setExifLocalTableEtag:metadata];
  860. // Create preview
  861. [CCGraphics createNewImageFrom:metadata.fileNameView fileID:metadata.fileID extension:[metadata.fileNameView pathExtension] filterGrayScale:NO typeFile:metadata.typeFile writeImage:YES];
  862. // Copy photo or video in the photo album for auto upload
  863. if ([metadata.assetLocalIdentifier length] > 0 && ([metadata.sessionSelector isEqualToString:selectorUploadAutoUpload] || [metadata.sessionSelector isEqualToString:selectorUploadFile])) {
  864. PHAsset *asset;
  865. PHFetchResult *result = [PHAsset fetchAssetsWithLocalIdentifiers:@[metadata.assetLocalIdentifier] options:nil];
  866. if(result.count){
  867. asset = result[0];
  868. [asset saveToAlbum:[NCBrandOptions sharedInstance].brand completionBlock:^(BOOL success) {
  869. if (success) NSLog(@"[LOG] Insert file %@ in %@", metadata.fileName, [NCBrandOptions sharedInstance].brand);
  870. else NSLog(@"[LOG] File %@ do not insert in %@", metadata.fileName, [NCBrandOptions sharedInstance].brand);
  871. }];
  872. }
  873. }
  874. #endif
  875. // Actvity
  876. [[NCManageDatabase sharedInstance] addActivityClient:metadata.fileNameView fileID:fileID action:k_activityDebugActionUpload selector:metadata.sessionSelector note:serverUrl type:k_activityTypeSuccess verbose:k_activityVerboseDefault activeUrl:tableAccount.url];
  877. }
  878. // Detect E2EE
  879. 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]];
  880. // E2EE : UNLOCK
  881. if (isE2EEDirectory && e2eeMetadataInSession == nil) {
  882. tableE2eEncryptionLock *tableLock = [[NCManageDatabase sharedInstance] getE2ETokenLockWithServerUrl:serverUrl];
  883. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  884. if (tableLock) {
  885. NSError *error = [[NCNetworkingEndToEnd sharedManager] unlockEndToEndFolderEncryptedOnServerUrl:serverUrl fileID:tableLock.fileID token:tableLock.token user:tableAccount.user userID:tableAccount.userID password:tableAccount.password url:tableAccount.url];
  886. if (error) {
  887. #ifndef EXTENSION
  888. dispatch_async(dispatch_get_main_queue(), ^{
  889. [(AppDelegate *)[[UIApplication sharedApplication] delegate] messageNotification:@"_e2e_error_unlock_" description:error.localizedDescription visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  890. });
  891. #endif
  892. }
  893. } else {
  894. NSLog(@"Error unlock not found");
  895. }
  896. dispatch_async(dispatch_get_main_queue(), ^{
  897. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:fileID:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  898. [self.delegate uploadFileSuccessFailure:metadata.fileName fileID:metadata.fileID assetLocalIdentifier:metadata.assetLocalIdentifier serverUrl:serverUrl selector:metadata.sessionSelector errorMessage:errorMessage errorCode:errorCode];
  899. }
  900. });
  901. });
  902. } else {
  903. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:fileID:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  904. [self.delegate uploadFileSuccessFailure:metadata.fileName fileID:metadata.fileID assetLocalIdentifier:metadata.assetLocalIdentifier serverUrl:serverUrl selector:metadata.sessionSelector errorMessage:errorMessage errorCode:errorCode];
  905. }
  906. }
  907. }
  908. #pragma --------------------------------------------------------------------------------------------
  909. #pragma mark ===== Utility =====
  910. #pragma --------------------------------------------------------------------------------------------
  911. - (NSString *)getServerUrlFromUrl:(NSString *)url
  912. {
  913. NSString *fileName = [url lastPathComponent];
  914. url = [url stringByReplacingOccurrencesOfString:[@"/" stringByAppendingString:fileName] withString:@""];
  915. return url;
  916. }
  917. @end