CCNetworking.m 67 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235
  1. //
  2. // CCNetworking.m
  3. // Nextcloud iOS
  4. //
  5. // Created by Marino Faggiana on 01/06/15.
  6. // Copyright (c) 2017 Marino Faggiana. All rights reserved.
  7. //
  8. // Author Marino Faggiana <marino.faggiana@nextcloud.com>
  9. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. //
  23. #import "CCNetworking.h"
  24. #import "NCEndToEndEncryption.h"
  25. #import "NCNetworkingEndToEnd.h"
  26. #import "AppDelegate.h"
  27. #import "CCCertificate.h"
  28. #import "NSDate+ISO8601.h"
  29. #import "NSString+Encode.h"
  30. #import "NCBridgeSwift.h"
  31. @interface CCNetworking ()
  32. {
  33. }
  34. @end
  35. @implementation CCNetworking
  36. + (CCNetworking *)sharedNetworking {
  37. static CCNetworking *sharedNetworking;
  38. @synchronized(self)
  39. {
  40. if (!sharedNetworking) {
  41. sharedNetworking = [[CCNetworking alloc] init];
  42. }
  43. return sharedNetworking;
  44. }
  45. }
  46. - (id)init
  47. {
  48. self = [super init];
  49. // Initialization Sessions
  50. [self sessionDownload];
  51. [self sessionDownloadForeground];
  52. [self sessionWWanDownload];
  53. [self sessionUpload];
  54. [self sessionWWanUpload];
  55. [self sessionUploadForeground];
  56. // *** NOT Initialize ONLY for EXTENSION !!!!! ***
  57. // [self sessionUploadExtension];
  58. return self;
  59. }
  60. #pragma --------------------------------------------------------------------------------------------
  61. #pragma mark ===== Session =====
  62. #pragma --------------------------------------------------------------------------------------------
  63. - (NSURLSession *)sessionDownload
  64. {
  65. static NSURLSession *sessionDownload = nil;
  66. if (sessionDownload == nil) {
  67. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:k_download_session];
  68. configuration.allowsCellularAccess = YES;
  69. configuration.sessionSendsLaunchEvents = YES;
  70. configuration.discretionary = NO;
  71. configuration.HTTPMaximumConnectionsPerHost = k_maxHTTPConnectionsPerHost;
  72. configuration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  73. sessionDownload = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
  74. sessionDownload.sessionDescription = k_download_session;
  75. }
  76. return sessionDownload;
  77. }
  78. - (NSURLSession *)sessionDownloadForeground
  79. {
  80. static NSURLSession *sessionDownloadForeground = nil;
  81. if (sessionDownloadForeground == nil) {
  82. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
  83. configuration.allowsCellularAccess = YES;
  84. configuration.discretionary = NO;
  85. configuration.HTTPMaximumConnectionsPerHost = k_maxHTTPConnectionsPerHost;
  86. configuration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  87. sessionDownloadForeground = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
  88. sessionDownloadForeground.sessionDescription = k_download_session_foreground;
  89. }
  90. return sessionDownloadForeground;
  91. }
  92. - (NSURLSession *)sessionWWanDownload
  93. {
  94. static NSURLSession *sessionWWanDownload = nil;
  95. if (sessionWWanDownload == nil) {
  96. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:k_download_session_wwan];
  97. configuration.allowsCellularAccess = NO;
  98. configuration.sessionSendsLaunchEvents = YES;
  99. configuration.discretionary = NO;
  100. configuration.HTTPMaximumConnectionsPerHost = k_maxHTTPConnectionsPerHost;
  101. configuration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  102. sessionWWanDownload = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
  103. sessionWWanDownload.sessionDescription = k_download_session_wwan;
  104. }
  105. return sessionWWanDownload;
  106. }
  107. - (NSURLSession *)sessionUpload
  108. {
  109. static NSURLSession *sessionUpload = nil;
  110. if (sessionUpload == nil) {
  111. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:k_upload_session];
  112. configuration.allowsCellularAccess = YES;
  113. configuration.sessionSendsLaunchEvents = YES;
  114. configuration.discretionary = NO;
  115. configuration.HTTPMaximumConnectionsPerHost = k_maxHTTPConnectionsPerHost;
  116. configuration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  117. sessionUpload = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
  118. sessionUpload.sessionDescription = k_upload_session;
  119. }
  120. return sessionUpload;
  121. }
  122. - (NSURLSession *)sessionWWanUpload
  123. {
  124. static NSURLSession *sessionWWanUpload = nil;
  125. if (sessionWWanUpload == nil) {
  126. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:k_upload_session_wwan];
  127. configuration.allowsCellularAccess = NO;
  128. configuration.sessionSendsLaunchEvents = YES;
  129. configuration.discretionary = NO;
  130. configuration.HTTPMaximumConnectionsPerHost = k_maxHTTPConnectionsPerHost;
  131. configuration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  132. sessionWWanUpload = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
  133. sessionWWanUpload.sessionDescription = k_upload_session_wwan;
  134. }
  135. return sessionWWanUpload;
  136. }
  137. - (NSURLSession *)sessionUploadForeground
  138. {
  139. static NSURLSession *sessionUploadForeground;
  140. if (sessionUploadForeground == nil) {
  141. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
  142. configuration.allowsCellularAccess = YES;
  143. configuration.discretionary = NO;
  144. configuration.HTTPMaximumConnectionsPerHost = k_maxHTTPConnectionsPerHost;
  145. configuration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  146. sessionUploadForeground = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
  147. sessionUploadForeground.sessionDescription = k_upload_session_foreground;
  148. }
  149. return sessionUploadForeground;
  150. }
  151. - (NSURLSession *)sessionUploadExtension
  152. {
  153. static NSURLSession *sessionUpload = nil;
  154. if (sessionUpload == nil) {
  155. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:k_upload_session_extension];
  156. configuration.allowsCellularAccess = YES;
  157. configuration.sessionSendsLaunchEvents = YES;
  158. configuration.discretionary = NO;
  159. configuration.HTTPMaximumConnectionsPerHost = 1;
  160. configuration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  161. configuration.sharedContainerIdentifier = [NCBrandOptions sharedInstance].capabilitiesGroups;
  162. sessionUpload = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
  163. sessionUpload.sessionDescription = k_upload_session_extension;
  164. }
  165. return sessionUpload;
  166. }
  167. - (NSURLSession *)getSessionfromSessionDescription:(NSString *)sessionDescription
  168. {
  169. if ([sessionDescription isEqualToString:k_download_session]) return [self sessionDownload];
  170. if ([sessionDescription isEqualToString:k_download_session_foreground]) return [self sessionDownloadForeground];
  171. if ([sessionDescription isEqualToString:k_download_session_wwan]) return [self sessionWWanDownload];
  172. if ([sessionDescription isEqualToString:k_upload_session]) return [self sessionUpload];
  173. if ([sessionDescription isEqualToString:k_upload_session_wwan]) return [self sessionWWanUpload];
  174. if ([sessionDescription isEqualToString:k_upload_session_foreground]) return [self sessionUploadForeground];
  175. if ([sessionDescription isEqualToString:k_upload_session_extension]) return [self sessionUploadExtension];
  176. return nil;
  177. }
  178. - (void)invalidateAndCancelAllSession
  179. {
  180. [[self sessionDownload] invalidateAndCancel];
  181. [[self sessionDownloadForeground] invalidateAndCancel];
  182. [[self sessionWWanDownload] invalidateAndCancel];
  183. [[self sessionUpload] invalidateAndCancel];
  184. [[self sessionWWanUpload] invalidateAndCancel];
  185. [[self sessionUploadForeground] invalidateAndCancel];
  186. }
  187. - (NSArray *)getUploadTasksExtensionSession
  188. {
  189. __block NSArray *tasks = [NSArray new];
  190. [[self sessionUploadExtension] getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  191. tasks = uploadTasks;
  192. }];
  193. return tasks;
  194. }
  195. #pragma --------------------------------------------------------------------------------------------
  196. #pragma mark ===== URLSession download/upload =====
  197. #pragma --------------------------------------------------------------------------------------------
  198. - (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler
  199. {
  200. // The pinnning check
  201. if ([[CCCertificate sharedManager] checkTrustedChallenge:challenge]) {
  202. completionHandler(NSURLSessionAuthChallengeUseCredential, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]);
  203. } else {
  204. completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
  205. }
  206. }
  207. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
  208. {
  209. NSString *url = [[[task currentRequest].URL absoluteString] stringByRemovingPercentEncoding];
  210. if (!url)
  211. return;
  212. NSString *fileName = [url lastPathComponent];
  213. NSString *serverUrl = [self getServerUrlFromUrl:url];
  214. if (!serverUrl) return;
  215. NSInteger errorCode;
  216. NSDate *date = [NSDate date];
  217. NSDateFormatter *dateFormatter = [NSDateFormatter new];
  218. NSLocale *enUSPOSIXLocale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
  219. [dateFormatter setLocale:enUSPOSIXLocale];
  220. [dateFormatter setDateFormat:@"EEE, dd MMM y HH:mm:ss zzz"];
  221. NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)task.response;
  222. if (httpResponse.statusCode >= 200 && httpResponse.statusCode < 300) {
  223. errorCode = error.code;
  224. } else {
  225. if (httpResponse.statusCode > 0)
  226. errorCode = httpResponse.statusCode;
  227. else
  228. errorCode = error.code;
  229. }
  230. // ----------------------- DOWNLOAD -----------------------
  231. if ([task isKindOfClass:[NSURLSessionDownloadTask class]]) {
  232. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataInSessionFromFileName:fileName serverUrl:serverUrl taskIdentifier:task.taskIdentifier];
  233. if (metadata) {
  234. NSString *etag = metadata.etag;
  235. //NSString *fileID = metadata.fileID;
  236. NSDictionary *fields = [httpResponse allHeaderFields];
  237. if (errorCode == 0) {
  238. etag = [CCUtility removeForbiddenCharactersFileSystem:[fields objectForKey:@"OC-ETag"]];
  239. NSString *dateString = [fields objectForKey:@"Date"];
  240. if (dateString) {
  241. if (![dateFormatter getObjectValue:&date forString:dateString range:nil error:&error]) {
  242. date = [NSDate date];
  243. }
  244. } else {
  245. date = [NSDate date];
  246. }
  247. }
  248. if (fileName.length > 0 && serverUrl.length > 0) {
  249. dispatch_async(dispatch_get_main_queue(), ^{
  250. [self downloadFileSuccessFailure:fileName fileID:metadata.fileID etag:etag date:date serverUrl:serverUrl selector:metadata.sessionSelector errorCode:errorCode];
  251. });
  252. }
  253. } else {
  254. NSLog(@"[LOG] Remove record ? : metadata not found %@", url);
  255. dispatch_async(dispatch_get_main_queue(), ^{
  256. if ([self.delegate respondsToSelector:@selector(downloadFileSuccessFailure:fileID:serverUrl:selector:errorMessage:errorCode:)]) {
  257. [self.delegate downloadFileSuccessFailure:fileName fileID:@"" serverUrl:serverUrl selector:@"" errorMessage:@"" errorCode:k_CCErrorInternalError];
  258. }
  259. });
  260. }
  261. }
  262. // ------------------------ UPLOAD -----------------------
  263. if ([task isKindOfClass:[NSURLSessionUploadTask class]]) {
  264. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataInSessionFromFileName:fileName serverUrl:serverUrl taskIdentifier:task.taskIdentifier];
  265. if (metadata) {
  266. NSDictionary *fields = [httpResponse allHeaderFields];
  267. NSString *fileID = metadata.fileID;
  268. NSString *etag = metadata.etag;
  269. if (errorCode == 0) {
  270. fileID = [CCUtility removeForbiddenCharactersFileSystem:[fields objectForKey:@"OC-FileId"]];
  271. etag = [CCUtility removeForbiddenCharactersFileSystem:[fields objectForKey:@"OC-ETag"]];
  272. NSString *dateString = [fields objectForKey:@"Date"];
  273. if (dateString) {
  274. if (![dateFormatter getObjectValue:&date forString:dateString range:nil error:&error]) {
  275. NSLog(@"[LOG] Date '%@' could not be parsed: %@", dateString, error);
  276. date = [NSDate date];
  277. }
  278. } else {
  279. date = [NSDate date];
  280. }
  281. }
  282. if (fileName.length > 0 && fileID.length > 0 && serverUrl.length > 0) {
  283. dispatch_async(dispatch_get_main_queue(), ^{
  284. [self uploadFileSuccessFailure:metadata fileName:fileName fileID:fileID etag:etag date:date serverUrl:serverUrl errorCode:errorCode];
  285. });
  286. }
  287. } else {
  288. NSLog(@"[LOG] Remove record ? : metadata not found %@", url);
  289. dispatch_async(dispatch_get_main_queue(), ^{
  290. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:fileID:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  291. [self.delegate uploadFileSuccessFailure:fileName fileID:@"" assetLocalIdentifier:@"" serverUrl:serverUrl selector:@"" errorMessage:@"" errorCode:k_CCErrorInternalError];
  292. }
  293. });
  294. }
  295. }
  296. }
  297. #pragma --------------------------------------------------------------------------------------------
  298. #pragma mark ===== Download =====
  299. #pragma --------------------------------------------------------------------------------------------
  300. - (void)downloadFile:(tableMetadata *)metadata taskStatus:(NSInteger)taskStatus
  301. {
  302. // No Password
  303. if ([CCUtility getPassword:metadata.account].length == 0) {
  304. [self.delegate downloadFileSuccessFailure:metadata.fileName fileID:metadata.fileID serverUrl:metadata.serverUrl selector:metadata.sessionSelector errorMessage:NSLocalizedString(@"_bad_username_password_", nil) errorCode:kOCErrorServerUnauthorized];
  305. return;
  306. } else if ([CCUtility getCertificateError:metadata.account]) {
  307. [self.delegate downloadFileSuccessFailure:metadata.fileName fileID:metadata.fileID 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:@"fileID == %@", metadata.fileID]];
  312. if (localfile != nil && [CCUtility fileProviderStorageExists:metadata.fileID fileNameView:metadata.fileNameView]) {
  313. [[NCManageDatabase sharedInstance] setMetadataSession:@"" sessionError:@"" sessionSelector:@"" sessionTaskIdentifier:k_taskIdentifierDone status:k_metadataStatusNormal predicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID]];
  314. if ([self.delegate respondsToSelector:@selector(downloadFileSuccessFailure:fileID:serverUrl:selector:errorMessage:errorCode:)]) {
  315. [self.delegate downloadFileSuccessFailure:metadata.fileName fileID:metadata.fileID 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:@"fileID == %@", metadata.fileID]];
  329. if ([self.delegate respondsToSelector:@selector(downloadFileSuccessFailure:fileID:serverUrl:selector:errorMessage:errorCode:)]) {
  330. [self.delegate downloadFileSuccessFailure:metadata.fileName fileID:metadata.fileID 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:@"fileID == %@", metadata.fileID]];
  347. if ([self.delegate respondsToSelector:@selector(downloadFileSuccessFailure:fileID:serverUrl:selector:errorMessage:errorCode:)]) {
  348. [self.delegate downloadFileSuccessFailure:metadata.fileName fileID:metadata.fileID 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:@"fileID == %@", metadata.fileID]];
  356. NSLog(@"[LOG] downloadFileSession %@ Task [%lu]", metadata.fileID, (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.fileID 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), @"fileID": (metadata.fileID), @"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:fileID:serverUrl:selector:errorMessage:errorCode:)]) {
  396. [self.delegate downloadFileSuccessFailure:@"" fileID:@"" 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 getDirectoryProviderStorageFileID:metadata.fileID 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 fileID:(NSString *)fileID 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:fileID];
  414. #endif
  415. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", fileID]];
  416. if (errorCode != 0) {
  417. if (errorCode == kCFURLErrorCancelled) {
  418. [[NCManageDatabase sharedInstance] setMetadataSession:@"" sessionError:@"" sessionSelector:@"" sessionTaskIdentifier:k_taskIdentifierDone status:k_metadataStatusNormal predicate:[NSPredicate predicateWithFormat:@"fileID == %@", fileID]];
  419. } else {
  420. if (metadata && errorCode == kOCErrorServerUnauthorized)
  421. [CCUtility setPassword:metadata.account password:nil];
  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:@"fileID == %@", fileID]];
  425. }
  426. if ([self.delegate respondsToSelector:@selector(downloadFileSuccessFailure:fileID:serverUrl:selector:errorMessage:errorCode:)]) {
  427. [self.delegate downloadFileSuccessFailure:fileName fileID:fileID 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:fileID:serverUrl:selector:errorMessage:errorCode:)]) {
  433. [self.delegate downloadFileSuccessFailure:fileName fileID:fileID 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 fileID:metadata.fileID key:object.key initializationVector:object.initializationVector authenticationTag:object.authenticationTag];
  448. if (!result) {
  449. if ([self.delegate respondsToSelector:@selector(downloadFileSuccessFailure:fileID:serverUrl:selector:errorMessage:errorCode:)]) {
  450. [self.delegate downloadFileSuccessFailure:fileName fileID:fileID 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 getDirectoryProviderStorageIconFileID:metadata.fileID fileNameView:metadata.fileNameView]] == NO) {
  460. [CCGraphics createNewImageFrom:metadata.fileNameView fileID:metadata.fileID extension:[metadata.fileNameView pathExtension] filterGrayScale:NO typeFile:metadata.typeFile writeImage:YES];
  461. }
  462. if ([self.delegate respondsToSelector:@selector(downloadFileSuccessFailure:fileID:serverUrl:selector:errorMessage:errorCode:)]) {
  463. [self.delegate downloadFileSuccessFailure:fileName fileID:fileID 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 fileID:metadata.fileID 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 fileID:metadata.fileID 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:@"fileID == %@", metadata.fileID]];
  483. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:fileID:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  484. [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];
  485. }
  486. return;
  487. }
  488. if ([CCUtility fileProviderStorageExists:metadata.fileID fileNameView:metadata.fileNameView] == NO) {
  489. PHFetchResult *result = [PHAsset fetchAssetsWithLocalIdentifiers:@[metadata.assetLocalIdentifier] options:nil];
  490. if (!result.count) {
  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:@"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:@"fileID == %@", metadata.fileID]];
  508. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:fileID:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  509. [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];
  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 fileID, fileName, fileNameView
  524. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID]];
  525. metadata.fileID = [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 getDirectoryProviderStorageFileID:metadataForUpload.fileID fileNameView:metadataForUpload.fileNameView] options:NSDataWritingAtomic error:&error];
  529. if (error) {
  530. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadataForUpload.fileID]];
  531. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:fileID:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  532. [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];
  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:@"fileID == %@", metadata.fileID]];
  553. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:fileID:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  554. [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];
  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 getDirectoryProviderStorageFileID:metadata.fileID 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:@"fileID == %@", metadata.fileID]];
  567. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:fileID:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  568. [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];
  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 getDirectoryProviderStorageFileID:metadata.fileID 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:fileID:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  615. [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];
  616. }
  617. return;
  618. }
  619. // if new file upload create a new encrypted filename
  620. if ([metadata.fileID 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 getDirectoryProviderStorageFileID:metadata.fileID] 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 fileID:directory.fileID 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:fileID:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  659. [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];
  660. }
  661. return;
  662. }
  663. }
  664. // write new record e2ee
  665. if([[NCManageDatabase sharedInstance] addE2eEncryption:addObject] == NO) {
  666. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:fileID:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  667. [self.delegate uploadFileSuccessFailure:metadata.fileName fileID:metadata.fileID assetLocalIdentifier:metadata.assetLocalIdentifier serverUrl:metadata.serverUrl selector:metadata.sessionSelector errorMessage:NSLocalizedString(@"_e2e_error_create_encrypted_", nil) errorCode:k_CCErrorInternalError];
  668. }
  669. return;
  670. }
  671. } else {
  672. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:fileID:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  673. [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];
  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 getDirectoryProviderStorageFileID:metadata.fileID 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 fileID:metadata.fileID 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 getDirectoryProviderStorageFileID:metadata.fileID 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:@"fileID == %@", metadata.fileID]];
  729. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:fileID:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  730. [self.delegate uploadFileSuccessFailure:metadata.fileNameView fileID:metadata.fileID 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:@"fileID == %@", metadata.fileID]];
  744. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:fileID:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  745. [self.delegate uploadFileSuccessFailure:metadata.fileNameView fileID:metadata.fileID 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:@"fileID == %@", metadata.fileID]];
  754. NSLog(@"[LOG] Upload file %@ TaskIdentifier %lu", metadata.fileName, (unsigned long)uploadTask.taskIdentifier);
  755. NSString *fileID = metadata.fileID;
  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:fileID 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:@"fileID == %@", metadata.fileID]];
  772. NSLog(@"[LOG] Upload file %@ TaskIdentifier %lu", metadata.fileName, (unsigned long)uploadTask.taskIdentifier);
  773. NSString *fileID = metadata.fileID;
  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:fileID 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), @"fileID": (metadata.fileID), @"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 fileID:(NSString *)fileID etag:(NSString *)etag date:(NSDate *)date serverUrl:(NSString *)serverUrl errorCode:(NSInteger)errorCode
  805. {
  806. NSString *tempFileID = metadata.fileID;
  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:@"fileID == %@", tempFileID]];
  813. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:fileID:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  814. [self.delegate uploadFileSuccessFailure:metadata.fileName fileID:metadata.fileID 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.fileID];
  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 getDirectoryProviderStorageFileID:tempFileID] error:nil];
  840. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", tempFileID]];
  841. errorMessage = [CCError manageErrorKCF:errorCode withNumberError:YES];
  842. }
  843. } else {
  844. if (metadata && errorCode == kOCErrorServerUnauthorized)
  845. [CCUtility setPassword:metadata.account password:nil];
  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:@"fileID == %@", tempFileID]];
  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.fileID = fileID;
  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 : %@ - fileID : %@", metadata.fileName, fileID);
  868. // remove tempFileID and adjust the directory provider storage
  869. if ([tempFileID isEqualToString:[CCUtility createMetadataIDFromAccount:metadata.account serverUrl:metadata.serverUrl fileNameView:metadata.fileNameView directory:metadata.directory]]) {
  870. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", tempFileID]];
  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], tempFileID] toPath:[NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryProviderStorage], metadata.fileID]];
  875. } else {
  876. [CCUtility moveFileAtPath:[NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryProviderStorage], tempFileID] toPath:[NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryProviderStorage], metadata.fileID]];
  877. }
  878. }
  879. // Add Local
  880. [[NCManageDatabase sharedInstance] addLocalFileWithMetadata:metadata];
  881. #ifndef EXTENSION
  882. // EXIF
  883. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image])
  884. [[CCExifGeo sharedInstance] setExifLocalTableEtag:metadata];
  885. // Create preview
  886. [CCGraphics createNewImageFrom:metadata.fileNameView fileID:metadata.fileID extension:[metadata.fileNameView pathExtension] filterGrayScale:NO typeFile:metadata.typeFile writeImage:YES];
  887. // Copy photo or video in the photo album for auto upload
  888. if ([metadata.assetLocalIdentifier length] > 0 && ([metadata.sessionSelector isEqualToString:selectorUploadAutoUpload] || [metadata.sessionSelector isEqualToString:selectorUploadFile])) {
  889. PHAsset *asset;
  890. PHFetchResult *result = [PHAsset fetchAssetsWithLocalIdentifiers:@[metadata.assetLocalIdentifier] options:nil];
  891. if(result.count){
  892. asset = result[0];
  893. [asset saveToAlbum:[NCBrandOptions sharedInstance].brand completionBlock:^(BOOL success) {
  894. if (success) NSLog(@"[LOG] Insert file %@ in %@", metadata.fileName, [NCBrandOptions sharedInstance].brand);
  895. else NSLog(@"[LOG] File %@ do not insert in %@", metadata.fileName, [NCBrandOptions sharedInstance].brand);
  896. }];
  897. }
  898. }
  899. #endif
  900. }
  901. // Detect E2EE
  902. 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]];
  903. // E2EE : UNLOCK
  904. if (isE2EEDirectory && e2eeMetadataInSession == nil) {
  905. tableE2eEncryptionLock *tableLock = [[NCManageDatabase sharedInstance] getE2ETokenLockWithServerUrl:serverUrl];
  906. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  907. if (tableLock) {
  908. NSError *error = [[NCNetworkingEndToEnd sharedManager] unlockEndToEndFolderEncryptedOnServerUrl:serverUrl fileID:tableLock.fileID token:tableLock.token user:tableAccount.user userID:tableAccount.userID password:[CCUtility getPassword:tableAccount.account] url:tableAccount.url];
  909. if (error) {
  910. #ifndef EXTENSION
  911. dispatch_async(dispatch_get_main_queue(), ^{
  912. [(AppDelegate *)[[UIApplication sharedApplication] delegate] messageNotification:@"_e2e_error_unlock_" description:error.localizedDescription visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  913. });
  914. #endif
  915. }
  916. } else {
  917. NSLog(@"Error unlock not found");
  918. }
  919. dispatch_async(dispatch_get_main_queue(), ^{
  920. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:fileID:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  921. [self.delegate uploadFileSuccessFailure:metadata.fileName fileID:metadata.fileID assetLocalIdentifier:metadata.assetLocalIdentifier serverUrl:serverUrl selector:metadata.sessionSelector errorMessage:errorMessage errorCode:errorCode];
  922. }
  923. });
  924. });
  925. } else {
  926. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:fileID:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  927. [self.delegate uploadFileSuccessFailure:metadata.fileName fileID:metadata.fileID assetLocalIdentifier:metadata.assetLocalIdentifier serverUrl:serverUrl selector:metadata.sessionSelector errorMessage:errorMessage errorCode:errorCode];
  928. }
  929. }
  930. }
  931. #pragma --------------------------------------------------------------------------------------------
  932. #pragma mark ===== Utility =====
  933. #pragma --------------------------------------------------------------------------------------------
  934. - (NSString *)getServerUrlFromUrl:(NSString *)url
  935. {
  936. NSString *fileName = [url lastPathComponent];
  937. url = [url stringByReplacingOccurrencesOfString:[@"/" stringByAppendingString:fileName] withString:@""];
  938. return url;
  939. }
  940. @end