CCNetworking.m 67 KB

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