CCNetworking.m 71 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357
  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. NSMutableDictionary *_taskData;
  34. NSString *_activeAccount;
  35. NSString *_activePassword;
  36. NSString *_activeUser;
  37. NSString *_activeUserID;
  38. NSString *_activeUrl;
  39. }
  40. @end
  41. @implementation CCNetworking
  42. + (CCNetworking *)sharedNetworking {
  43. static CCNetworking *sharedNetworking;
  44. @synchronized(self)
  45. {
  46. if (!sharedNetworking) {
  47. sharedNetworking = [[CCNetworking alloc] init];
  48. }
  49. return sharedNetworking;
  50. }
  51. }
  52. - (id)init
  53. {
  54. self = [super init];
  55. _taskData = [[NSMutableDictionary alloc] init];
  56. // Initialization Sessions
  57. [self sessionDownload];
  58. [self sessionDownloadForeground];
  59. [self sessionWWanDownload];
  60. [self sessionUpload];
  61. [self sessionWWanUpload];
  62. [self sessionUploadForeground];
  63. // *** NOT Initialize ONLY for EXTENSION !!!!! ***
  64. // [self sessionUploadExtension];
  65. [self sharedOCCommunication];
  66. [self settingAccount];
  67. return self;
  68. }
  69. - (void)settingAccount
  70. {
  71. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountActive];
  72. _activeAccount = tableAccount.account;
  73. _activePassword = tableAccount.password;
  74. _activeUser = tableAccount.user;
  75. _activeUserID = tableAccount.userID;
  76. _activeUrl = tableAccount.url;
  77. }
  78. #pragma --------------------------------------------------------------------------------------------
  79. #pragma mark ===== Session =====
  80. #pragma --------------------------------------------------------------------------------------------
  81. - (NSURLSession *)sessionDownload
  82. {
  83. static NSURLSession *sessionDownload = nil;
  84. if (sessionDownload == nil) {
  85. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:k_download_session];
  86. configuration.allowsCellularAccess = YES;
  87. configuration.sessionSendsLaunchEvents = YES;
  88. configuration.discretionary = NO;
  89. configuration.HTTPMaximumConnectionsPerHost = k_maxHTTPConnectionsPerHost;
  90. configuration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  91. sessionDownload = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
  92. sessionDownload.sessionDescription = k_download_session;
  93. }
  94. return sessionDownload;
  95. }
  96. - (NSURLSession *)sessionDownloadForeground
  97. {
  98. static NSURLSession *sessionDownloadForeground = nil;
  99. if (sessionDownloadForeground == nil) {
  100. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
  101. configuration.allowsCellularAccess = YES;
  102. configuration.discretionary = NO;
  103. configuration.HTTPMaximumConnectionsPerHost = k_maxHTTPConnectionsPerHost;
  104. configuration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  105. sessionDownloadForeground = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
  106. sessionDownloadForeground.sessionDescription = k_download_session_foreground;
  107. }
  108. return sessionDownloadForeground;
  109. }
  110. - (NSURLSession *)sessionWWanDownload
  111. {
  112. static NSURLSession *sessionWWanDownload = nil;
  113. if (sessionWWanDownload == nil) {
  114. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:k_download_session_wwan];
  115. configuration.allowsCellularAccess = NO;
  116. configuration.sessionSendsLaunchEvents = YES;
  117. configuration.discretionary = NO;
  118. configuration.HTTPMaximumConnectionsPerHost = k_maxHTTPConnectionsPerHost;
  119. configuration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  120. sessionWWanDownload = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
  121. sessionWWanDownload.sessionDescription = k_download_session_wwan;
  122. }
  123. return sessionWWanDownload;
  124. }
  125. - (NSURLSession *)sessionUpload
  126. {
  127. static NSURLSession *sessionUpload = nil;
  128. if (sessionUpload == nil) {
  129. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:k_upload_session];
  130. configuration.allowsCellularAccess = YES;
  131. configuration.sessionSendsLaunchEvents = YES;
  132. configuration.discretionary = NO;
  133. configuration.HTTPMaximumConnectionsPerHost = k_maxHTTPConnectionsPerHost;
  134. configuration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  135. sessionUpload = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
  136. sessionUpload.sessionDescription = k_upload_session;
  137. }
  138. return sessionUpload;
  139. }
  140. - (NSURLSession *)sessionWWanUpload
  141. {
  142. static NSURLSession *sessionWWanUpload = nil;
  143. if (sessionWWanUpload == nil) {
  144. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:k_upload_session_wwan];
  145. configuration.allowsCellularAccess = NO;
  146. configuration.sessionSendsLaunchEvents = YES;
  147. configuration.discretionary = NO;
  148. configuration.HTTPMaximumConnectionsPerHost = k_maxHTTPConnectionsPerHost;
  149. configuration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  150. sessionWWanUpload = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
  151. sessionWWanUpload.sessionDescription = k_upload_session_wwan;
  152. }
  153. return sessionWWanUpload;
  154. }
  155. - (NSURLSession *)sessionUploadForeground
  156. {
  157. static NSURLSession *sessionUploadForeground;
  158. if (sessionUploadForeground == nil) {
  159. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
  160. configuration.allowsCellularAccess = YES;
  161. configuration.discretionary = NO;
  162. configuration.HTTPMaximumConnectionsPerHost = k_maxHTTPConnectionsPerHost;
  163. configuration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  164. sessionUploadForeground = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
  165. sessionUploadForeground.sessionDescription = k_upload_session_foreground;
  166. }
  167. return sessionUploadForeground;
  168. }
  169. - (NSURLSession *)sessionUploadExtension
  170. {
  171. static NSURLSession *sessionUpload = nil;
  172. if (sessionUpload == nil) {
  173. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:k_upload_session_extension];
  174. configuration.allowsCellularAccess = YES;
  175. configuration.sessionSendsLaunchEvents = YES;
  176. configuration.discretionary = NO;
  177. configuration.HTTPMaximumConnectionsPerHost = 1;
  178. configuration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  179. configuration.sharedContainerIdentifier = [NCBrandOptions sharedInstance].capabilitiesGroups;
  180. sessionUpload = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
  181. sessionUpload.sessionDescription = k_upload_session_extension;
  182. }
  183. return sessionUpload;
  184. }
  185. - (OCCommunication *)sharedOCCommunication
  186. {
  187. static OCCommunication* sharedOCCommunication = nil;
  188. if (sharedOCCommunication == nil)
  189. {
  190. // Network
  191. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
  192. configuration.allowsCellularAccess = YES;
  193. configuration.discretionary = NO;
  194. configuration.HTTPMaximumConnectionsPerHost = k_maxConcurrentOperation;
  195. configuration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  196. OCURLSessionManager *networkSessionManager = [[OCURLSessionManager alloc] initWithSessionConfiguration:configuration];
  197. [networkSessionManager.operationQueue setMaxConcurrentOperationCount: k_maxConcurrentOperation];
  198. networkSessionManager.responseSerializer = [AFHTTPResponseSerializer serializer];
  199. // Download
  200. NSURLSessionConfiguration *configurationDownload = [NSURLSessionConfiguration defaultSessionConfiguration];
  201. configurationDownload.allowsCellularAccess = YES;
  202. configurationDownload.discretionary = NO;
  203. configurationDownload.HTTPMaximumConnectionsPerHost = k_maxHTTPConnectionsPerHost;
  204. configurationDownload.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  205. configurationDownload.timeoutIntervalForRequest = k_timeout_upload;
  206. OCURLSessionManager *downloadSessionManager = [[OCURLSessionManager alloc] initWithSessionConfiguration:configurationDownload];
  207. [downloadSessionManager.operationQueue setMaxConcurrentOperationCount:k_maxHTTPConnectionsPerHost];
  208. [downloadSessionManager setSessionDidReceiveAuthenticationChallengeBlock:^NSURLSessionAuthChallengeDisposition (NSURLSession *session, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *credential) {
  209. return NSURLSessionAuthChallengePerformDefaultHandling;
  210. }];
  211. // Upload
  212. NSURLSessionConfiguration *configurationUpload = [NSURLSessionConfiguration defaultSessionConfiguration];
  213. configurationUpload.allowsCellularAccess = YES;
  214. configurationUpload.discretionary = NO;
  215. configurationUpload.HTTPMaximumConnectionsPerHost = k_maxHTTPConnectionsPerHost;
  216. configurationUpload.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  217. configurationUpload.timeoutIntervalForRequest = k_timeout_upload;
  218. OCURLSessionManager *uploadSessionManager = [[OCURLSessionManager alloc] initWithSessionConfiguration:configurationUpload];
  219. [uploadSessionManager.operationQueue setMaxConcurrentOperationCount:k_maxHTTPConnectionsPerHost];
  220. [uploadSessionManager setSessionDidReceiveAuthenticationChallengeBlock:^NSURLSessionAuthChallengeDisposition (NSURLSession *session, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *credential) {
  221. return NSURLSessionAuthChallengePerformDefaultHandling;
  222. }];
  223. sharedOCCommunication = [[OCCommunication alloc] initWithUploadSessionManager:uploadSessionManager andDownloadSessionManager:downloadSessionManager andNetworkSessionManager:networkSessionManager];
  224. }
  225. return sharedOCCommunication;
  226. }
  227. - (OCCommunication *)sharedOCCommunicationExtensionDownload
  228. {
  229. static OCCommunication *sharedOCCommunicationExtensionDownload = nil;
  230. if (sharedOCCommunicationExtensionDownload == nil)
  231. {
  232. NSURLSessionConfiguration *config = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:k_download_session_extension];
  233. config.sharedContainerIdentifier = [NCBrandOptions sharedInstance].capabilitiesGroups;
  234. config.HTTPMaximumConnectionsPerHost = 1;
  235. config.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  236. config.timeoutIntervalForRequest = k_timeout_upload;
  237. config.sessionSendsLaunchEvents = YES;
  238. [config setAllowsCellularAccess:YES];
  239. OCURLSessionManager *sessionManager = [[OCURLSessionManager alloc] initWithSessionConfiguration:config];
  240. [sessionManager.operationQueue setMaxConcurrentOperationCount:1];
  241. [sessionManager setSessionDidReceiveAuthenticationChallengeBlock:^NSURLSessionAuthChallengeDisposition (NSURLSession *session, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *credential) {
  242. return NSURLSessionAuthChallengePerformDefaultHandling;
  243. }];
  244. sharedOCCommunicationExtensionDownload = [[OCCommunication alloc] initWithUploadSessionManager:nil andDownloadSessionManager:sessionManager andNetworkSessionManager:nil];
  245. }
  246. return sharedOCCommunicationExtensionDownload;
  247. }
  248. - (NSURLSession *)getSessionfromSessionDescription:(NSString *)sessionDescription
  249. {
  250. if ([sessionDescription isEqualToString:k_download_session]) return [self sessionDownload];
  251. if ([sessionDescription isEqualToString:k_download_session_foreground]) return [self sessionDownloadForeground];
  252. if ([sessionDescription isEqualToString:k_download_session_wwan]) return [self sessionWWanDownload];
  253. if ([sessionDescription isEqualToString:k_upload_session]) return [self sessionUpload];
  254. if ([sessionDescription isEqualToString:k_upload_session_wwan]) return [self sessionWWanUpload];
  255. if ([sessionDescription isEqualToString:k_upload_session_foreground]) return [self sessionUploadForeground];
  256. return nil;
  257. }
  258. - (void)invalidateAndCancelAllSession
  259. {
  260. [[self sessionDownload] invalidateAndCancel];
  261. [[self sessionDownloadForeground] invalidateAndCancel];
  262. [[self sessionWWanDownload] invalidateAndCancel];
  263. [[self sessionUpload] invalidateAndCancel];
  264. [[self sessionWWanUpload] invalidateAndCancel];
  265. [[self sessionUploadForeground] invalidateAndCancel];
  266. }
  267. - (NSArray *)getUploadTasksExtensionSession
  268. {
  269. __block NSArray *tasks = [NSArray new];
  270. [[self sessionUploadExtension] getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  271. tasks = uploadTasks;
  272. }];
  273. return tasks;
  274. }
  275. #pragma --------------------------------------------------------------------------------------------
  276. #pragma mark ===== URLSession download/upload =====
  277. #pragma --------------------------------------------------------------------------------------------
  278. - (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler
  279. {
  280. // The pinnning check
  281. if ([[CCCertificate sharedManager] checkTrustedChallenge:challenge]) {
  282. completionHandler(NSURLSessionAuthChallengeUseCredential, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]);
  283. } else {
  284. completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
  285. }
  286. }
  287. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
  288. {
  289. NSString *url = [[[task currentRequest].URL absoluteString] stringByRemovingPercentEncoding];
  290. if (!url)
  291. return;
  292. NSString *fileName = [url lastPathComponent];
  293. NSString *serverUrl = [self getServerUrlFromUrl:url];
  294. if (!serverUrl) return;
  295. NSInteger errorCode;
  296. NSDate *date = [NSDate date];
  297. NSDateFormatter *dateFormatter = [NSDateFormatter new];
  298. NSLocale *enUSPOSIXLocale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
  299. [dateFormatter setLocale:enUSPOSIXLocale];
  300. [dateFormatter setDateFormat:@"EEE, dd MMM y HH:mm:ss zzz"];
  301. NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)task.response;
  302. if (httpResponse.statusCode >= 200 && httpResponse.statusCode < 300) {
  303. errorCode = error.code;
  304. } else {
  305. if (httpResponse.statusCode > 0)
  306. errorCode = httpResponse.statusCode;
  307. else
  308. errorCode = error.code;
  309. }
  310. // ----------------------- DOWNLOAD -----------------------
  311. if ([task isKindOfClass:[NSURLSessionDownloadTask class]]) {
  312. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataInSessionFromFileName:fileName serverUrl:serverUrl taskIdentifier:task.taskIdentifier];
  313. if (metadata) {
  314. NSString *etag = metadata.etag;
  315. //NSString *fileID = metadata.fileID;
  316. NSDictionary *fields = [httpResponse allHeaderFields];
  317. if (errorCode == 0) {
  318. etag = [CCUtility removeForbiddenCharactersFileSystem:[fields objectForKey:@"OC-ETag"]];
  319. NSString *dateString = [fields objectForKey:@"Date"];
  320. if (dateString) {
  321. if (![dateFormatter getObjectValue:&date forString:dateString range:nil error:&error]) {
  322. date = [NSDate date];
  323. }
  324. } else {
  325. date = [NSDate date];
  326. }
  327. }
  328. if (fileName.length > 0 && serverUrl.length > 0) {
  329. dispatch_async(dispatch_get_main_queue(), ^{
  330. [self downloadFileSuccessFailure:fileName fileID:metadata.fileID etag:etag date:date serverUrl:serverUrl selector:metadata.sessionSelector errorCode:errorCode];
  331. });
  332. }
  333. } else {
  334. NSLog(@"[LOG] Remove record ? : metadata not found %@", url);
  335. dispatch_async(dispatch_get_main_queue(), ^{
  336. if ([self.delegate respondsToSelector:@selector(downloadFileSuccessFailure:fileID:serverUrl:selector:errorMessage:errorCode:)]) {
  337. [self.delegate downloadFileSuccessFailure:fileName fileID:@"" serverUrl:serverUrl selector:@"" errorMessage:@"" errorCode:k_CCErrorInternalError];
  338. }
  339. });
  340. }
  341. }
  342. // ------------------------ UPLOAD -----------------------
  343. if ([task isKindOfClass:[NSURLSessionUploadTask class]]) {
  344. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataInSessionFromFileName:fileName serverUrl:serverUrl taskIdentifier:task.taskIdentifier];
  345. if (metadata) {
  346. NSDictionary *fields = [httpResponse allHeaderFields];
  347. NSString *fileID = metadata.fileID;
  348. NSString *etag = metadata.etag;
  349. if (errorCode == 0) {
  350. fileID = [CCUtility removeForbiddenCharactersFileSystem:[fields objectForKey:@"OC-FileId"]];
  351. etag = [CCUtility removeForbiddenCharactersFileSystem:[fields objectForKey:@"OC-ETag"]];
  352. NSString *dateString = [fields objectForKey:@"Date"];
  353. if (dateString) {
  354. if (![dateFormatter getObjectValue:&date forString:dateString range:nil error:&error]) {
  355. NSLog(@"[LOG] Date '%@' could not be parsed: %@", dateString, error);
  356. date = [NSDate date];
  357. }
  358. } else {
  359. date = [NSDate date];
  360. }
  361. }
  362. if (fileName.length > 0 && fileID.length > 0 && serverUrl.length > 0) {
  363. dispatch_async(dispatch_get_main_queue(), ^{
  364. [self uploadFileSuccessFailure:metadata fileName:fileName fileID:fileID etag:etag date:date serverUrl:serverUrl errorCode:errorCode];
  365. });
  366. }
  367. } else {
  368. NSLog(@"[LOG] Remove record ? : metadata not found %@", url);
  369. dispatch_async(dispatch_get_main_queue(), ^{
  370. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:fileID:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  371. [self.delegate uploadFileSuccessFailure:fileName fileID:@"" assetLocalIdentifier:@"" serverUrl:serverUrl selector:@"" errorMessage:@"" errorCode:k_CCErrorInternalError];
  372. }
  373. });
  374. }
  375. }
  376. }
  377. #pragma --------------------------------------------------------------------------------------------
  378. #pragma mark ===== Download =====
  379. #pragma --------------------------------------------------------------------------------------------
  380. - (void)downloadFile:(tableMetadata *)metadata taskStatus:(NSInteger)taskStatus
  381. {
  382. // File exists ?
  383. tableLocalFile *localfile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID]];
  384. if (localfile != nil && [CCUtility fileProviderStorageExists:metadata.fileID fileNameView:metadata.fileNameView]) {
  385. [[NCManageDatabase sharedInstance] setMetadataSession:@"" sessionError:@"" sessionSelector:@"" sessionTaskIdentifier:k_taskIdentifierDone status:k_metadataStatusNormal predicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID]];
  386. if ([self.delegate respondsToSelector:@selector(downloadFileSuccessFailure:fileID:serverUrl:selector:errorMessage:errorCode:)]) {
  387. [self.delegate downloadFileSuccessFailure:metadata.fileName fileID:metadata.fileID serverUrl:metadata.serverUrl selector:metadata.sessionSelector errorMessage:@"" errorCode:0];
  388. }
  389. return;
  390. }
  391. [self downloaURLSession:metadata taskStatus:taskStatus];
  392. }
  393. - (void)downloaURLSession:(tableMetadata *)metadata taskStatus:(NSInteger)taskStatus
  394. {
  395. NSURLSession *sessionDownload;
  396. NSURL *url;
  397. NSMutableURLRequest *request;
  398. NSString *serverFileUrl = [[NSString stringWithFormat:@"%@/%@", metadata.serverUrl, metadata.fileName] encodeString:NSUTF8StringEncoding];
  399. url = [NSURL URLWithString:serverFileUrl];
  400. request = [NSMutableURLRequest requestWithURL:url];
  401. NSData *authData = [[NSString stringWithFormat:@"%@:%@", _activeUser, _activePassword] dataUsingEncoding:NSUTF8StringEncoding];
  402. NSString *authValue = [NSString stringWithFormat: @"Basic %@",[authData base64EncodedStringWithOptions:0]];
  403. [request setValue:authValue forHTTPHeaderField:@"Authorization"];
  404. [request setValue:[CCUtility getUserAgent] forHTTPHeaderField:@"User-Agent"];
  405. if ([metadata.session isEqualToString:k_download_session]) sessionDownload = [self sessionDownload];
  406. else if ([metadata.session isEqualToString:k_download_session_foreground]) sessionDownload = [self sessionDownloadForeground];
  407. else if ([metadata.session isEqualToString:k_download_session_wwan]) sessionDownload = [self sessionWWanDownload];
  408. NSURLSessionDownloadTask *downloadTask = [sessionDownload downloadTaskWithRequest:request];
  409. if (downloadTask == nil) {
  410. [[NCManageDatabase sharedInstance] addActivityClient:metadata.fileName fileID:metadata.fileID action:k_activityDebugActionUpload selector:metadata.sessionSelector note:@"Serious internal error downloadTask not available" type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:_activeUrl];
  411. [[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]];
  412. if ([self.delegate respondsToSelector:@selector(downloadFileSuccessFailure:fileID:serverUrl:selector:errorMessage:errorCode:)]) {
  413. [self.delegate downloadFileSuccessFailure:metadata.fileName fileID:metadata.fileID serverUrl:metadata.serverUrl selector:metadata.sessionSelector errorMessage:@"Serious internal error downloadTask not available" errorCode:k_CCErrorInternalError];
  414. }
  415. } else {
  416. // Manage uploadTask cancel,suspend,resume
  417. if (taskStatus == k_taskStatusCancel) [downloadTask cancel];
  418. else if (taskStatus == k_taskStatusSuspend) [downloadTask suspend];
  419. else if (taskStatus == k_taskStatusResume) [downloadTask resume];
  420. [[NCManageDatabase sharedInstance] setMetadataSession:nil sessionError:nil sessionSelector:nil sessionTaskIdentifier:downloadTask.taskIdentifier status:k_metadataStatusDownloading predicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID]];
  421. NSLog(@"[LOG] downloadFileSession %@ Task [%lu]", metadata.fileID, (unsigned long)downloadTask.taskIdentifier);
  422. }
  423. dispatch_async(dispatch_get_main_queue(), ^{
  424. if ([self.delegate respondsToSelector:@selector(downloadStart:account:task:serverUrl:)]) {
  425. [self.delegate downloadStart:metadata.fileID account:metadata.account task:downloadTask serverUrl:metadata.serverUrl];
  426. }
  427. });
  428. }
  429. - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
  430. {
  431. NSString *url = [[[downloadTask currentRequest].URL absoluteString] stringByRemovingPercentEncoding];
  432. NSString *fileName = [url lastPathComponent];
  433. NSString *serverUrl = [self getServerUrlFromUrl:url];
  434. if (!serverUrl) return;
  435. if (totalBytesExpectedToWrite < 1) {
  436. totalBytesExpectedToWrite = totalBytesWritten;
  437. }
  438. float progress = (float) totalBytesWritten / (float)totalBytesExpectedToWrite;
  439. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataInSessionFromFileName:fileName serverUrl:serverUrl taskIdentifier:downloadTask.taskIdentifier];
  440. if (metadata) {
  441. NSDictionary* userInfo = @{@"fileID": (metadata.fileID), @"serverUrl": (serverUrl), @"status": ([NSNumber numberWithLong:k_metadataStatusInDownload]), @"progress": ([NSNumber numberWithFloat:progress]), @"totalBytes": ([NSNumber numberWithLongLong:totalBytesWritten]), @"totalBytesExpected": ([NSNumber numberWithLongLong:totalBytesExpectedToWrite])};
  442. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"NotificationProgressTask" object:nil userInfo:userInfo];
  443. } else {
  444. NSLog(@"[LOG] metadata not found");
  445. }
  446. }
  447. - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
  448. {
  449. NSString *url = [[[downloadTask currentRequest].URL absoluteString] stringByRemovingPercentEncoding];
  450. if (!url)
  451. return;
  452. NSString *fileName = [url lastPathComponent];
  453. NSString *serverUrl = [self getServerUrlFromUrl:url];
  454. if (!serverUrl) return;
  455. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataInSessionFromFileName:fileName serverUrl:serverUrl taskIdentifier:downloadTask.taskIdentifier];
  456. if (!metadata) {
  457. [[NCManageDatabase sharedInstance] addActivityClient:fileName fileID:@"" action:k_activityDebugActionUpload selector:@"" note:[NSString stringWithFormat:@"Serious error internal download : metadata not found %@", url] type:k_activityTypeFailure verbose:k_activityVerboseDefault activeUrl:_activeUrl];
  458. NSLog(@"[LOG] Serious error internal download : metadata not found %@ ", url);
  459. dispatch_async(dispatch_get_main_queue(), ^{
  460. if ([self.delegate respondsToSelector:@selector(downloadFileSuccessFailure:fileID:serverUrl:selector:errorMessage:errorCode:)]) {
  461. [self.delegate downloadFileSuccessFailure:@"" fileID:@"" serverUrl:serverUrl selector:@"" errorMessage:@"Serious error internal download : metadata not found" errorCode:k_CCErrorInternalError];
  462. }
  463. });
  464. return;
  465. }
  466. NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)downloadTask.response;
  467. if (httpResponse.statusCode >= 200 && httpResponse.statusCode < 300) {
  468. NSString *destinationFilePath = [CCUtility getDirectoryProviderStorageFileID:metadata.fileID fileNameView:metadata.fileName];
  469. NSURL *destinationURL = [NSURL fileURLWithPath:destinationFilePath];
  470. [[NSFileManager defaultManager] removeItemAtURL:destinationURL error:NULL];
  471. [[NSFileManager defaultManager] copyItemAtURL:location toURL:destinationURL error:nil];
  472. }
  473. }
  474. - (void)downloadFileSuccessFailure:(NSString *)fileName fileID:(NSString *)fileID etag:(NSString *)etag date:(NSDate *)date serverUrl:(NSString *)serverUrl selector:(NSString *)selector errorCode:(NSInteger)errorCode
  475. {
  476. #ifndef EXTENSION
  477. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  478. [appDelegate.listProgressMetadata removeObjectForKey:fileID];
  479. #endif
  480. if (errorCode != 0) {
  481. if (errorCode == kCFURLErrorCancelled) {
  482. [[NCManageDatabase sharedInstance] setMetadataSession:@"" sessionError:@"" sessionSelector:@"" sessionTaskIdentifier:k_taskIdentifierDone status:k_metadataStatusNormal predicate:[NSPredicate predicateWithFormat:@"fileID == %@", fileID]];
  483. } else {
  484. [[NCManageDatabase sharedInstance] setMetadataSession:nil sessionError:[CCError manageErrorKCF:errorCode withNumberError:NO] sessionSelector:nil sessionTaskIdentifier:k_taskIdentifierDone status:k_metadataStatusDownloadError predicate:[NSPredicate predicateWithFormat:@"fileID == %@", fileID]];
  485. }
  486. if ([self.delegate respondsToSelector:@selector(downloadFileSuccessFailure:fileID:serverUrl:selector:errorMessage:errorCode:)]) {
  487. [self.delegate downloadFileSuccessFailure:fileName fileID:fileID serverUrl:serverUrl selector:selector errorMessage:[CCError manageErrorKCF:errorCode withNumberError:YES] errorCode:errorCode];
  488. }
  489. } else {
  490. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", fileID]];
  491. if (!metadata) {
  492. [[NCManageDatabase sharedInstance] addActivityClient:fileName fileID:fileID action:k_activityDebugActionUpload selector:@"" note:[NSString stringWithFormat:@"Serious error internal download : metadata not found %@", fileName] type:k_activityTypeFailure verbose:k_activityVerboseDefault activeUrl:_activeUrl];
  493. NSLog(@"[LOG] Serious error internal download : metadata not found %@ ", fileName);
  494. if ([self.delegate respondsToSelector:@selector(downloadFileSuccessFailure:fileID:serverUrl:selector:errorMessage:errorCode:)]) {
  495. [self.delegate downloadFileSuccessFailure:fileName fileID:fileID serverUrl:serverUrl selector:selector errorMessage:[NSString stringWithFormat:@"Serious error internal download : metadata not found %@", fileName] errorCode:k_CCErrorInternalError];
  496. }
  497. return;
  498. }
  499. metadata.session = @"";
  500. metadata.sessionError = @"";
  501. metadata.sessionSelector = @"";
  502. metadata.sessionTaskIdentifier = k_taskIdentifierDone;
  503. metadata.status = k_metadataStatusNormal;
  504. metadata = [[NCManageDatabase sharedInstance] updateMetadata:metadata];
  505. [[NCManageDatabase sharedInstance] addLocalFileWithMetadata:metadata];
  506. // E2EE Decrypted
  507. tableE2eEncryption *object = [[NCManageDatabase sharedInstance] getE2eEncryptionWithPredicate:[NSPredicate predicateWithFormat:@"fileNameIdentifier == %@ AND serverUrl == %@", fileName, serverUrl]];
  508. if (object) {
  509. BOOL result = [[NCEndToEndEncryption sharedManager] decryptFileName:metadata.fileName fileNameView:metadata.fileNameView fileID:metadata.fileID key:object.key initializationVector:object.initializationVector authenticationTag:object.authenticationTag];
  510. if (!result) {
  511. [[NCManageDatabase sharedInstance] addActivityClient:metadata.fileNameView fileID:fileID action:k_activityDebugActionUpload selector:@"" note:[NSString stringWithFormat:@"Serious error internal download : decrypt error %@", fileName] type:k_activityTypeFailure verbose:k_activityVerboseDefault activeUrl:_activeUrl];
  512. if ([self.delegate respondsToSelector:@selector(downloadFileSuccessFailure:fileID:serverUrl:selector:errorMessage:errorCode:)]) {
  513. [self.delegate downloadFileSuccessFailure:fileName fileID:fileID serverUrl:serverUrl selector:selector errorMessage:[NSString stringWithFormat:@"Serious error internal download : decrypt error %@", fileName] errorCode:k_CCErrorInternalError];
  514. }
  515. return;
  516. }
  517. }
  518. // Exif
  519. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image])
  520. [[CCExifGeo sharedInstance] setExifLocalTableEtag:metadata];
  521. // Icon
  522. if ([[NSFileManager defaultManager] fileExistsAtPath:[CCUtility getDirectoryProviderStorageIconFileID:metadata.fileID fileNameView:metadata.fileNameView]] == NO) {
  523. [CCGraphics createNewImageFrom:metadata.fileNameView fileID:metadata.fileID extension:[metadata.fileNameView pathExtension] filterGrayScale:NO typeFile:metadata.typeFile writeImage:YES];
  524. }
  525. // Activity
  526. [[NCManageDatabase sharedInstance] addActivityClient:metadata.fileNameView fileID:metadata.fileID action:k_activityDebugActionDownload selector:metadata.sessionSelector note:serverUrl type:k_activityTypeSuccess verbose:k_activityVerboseDefault activeUrl:_activeUrl];
  527. if ([self.delegate respondsToSelector:@selector(downloadFileSuccessFailure:fileID:serverUrl:selector:errorMessage:errorCode:)]) {
  528. [self.delegate downloadFileSuccessFailure:fileName fileID:fileID serverUrl:serverUrl selector:selector errorMessage:@"" errorCode:0];
  529. }
  530. }
  531. }
  532. #pragma --------------------------------------------------------------------------------------------
  533. #pragma mark ===== Upload =====
  534. #pragma --------------------------------------------------------------------------------------------
  535. - (void)uploadFile:(tableMetadata *)metadata taskStatus:(NSInteger)taskStatus
  536. {
  537. if ([CCUtility fileProviderStorageExists:metadata.fileID fileNameView:metadata.fileNameView] == NO) {
  538. PHFetchResult *result = [PHAsset fetchAssetsWithLocalIdentifiers:@[metadata.assetLocalIdentifier] options:nil];
  539. if (!result.count) {
  540. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID]];
  541. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:fileID:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  542. [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];
  543. }
  544. return;
  545. }
  546. PHAsset *asset= result[0];
  547. // IMAGE
  548. if (asset.mediaType == PHAssetMediaTypeImage) {
  549. PHImageRequestOptions *options = [PHImageRequestOptions new];
  550. options.networkAccessAllowed = YES; // iCloud
  551. options.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
  552. options.synchronous = YES;
  553. options.progressHandler = ^(double progress, NSError *error, BOOL *stop, NSDictionary *info) {
  554. NSLog(@"cacheAsset: %f", progress);
  555. if (error) {
  556. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID]];
  557. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:fileID:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  558. [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];
  559. }
  560. }
  561. };
  562. [[PHImageManager defaultManager] requestImageDataForAsset:asset options:options resultHandler:^(NSData *imageData, NSString *dataUTI, UIImageOrientation orientation, NSDictionary *info) {
  563. NSError *error = nil;
  564. NSString *extensionAsset = [[[asset valueForKey:@"filename"] pathExtension] uppercaseString];
  565. if ([extensionAsset isEqualToString:@"HEIC"] && [CCUtility getFormatCompatibility]) {
  566. UIImage *image = [UIImage imageWithData:imageData];
  567. imageData = UIImageJPEGRepresentation(image, 1.0);
  568. NSString *fileNameJPEG = [[metadata.fileName lastPathComponent] stringByDeletingPathExtension];
  569. metadata.fileName = [fileNameJPEG stringByAppendingString:@".jpg"];
  570. metadata.fileNameView = metadata.fileName;
  571. // Change Metadata with new fileID, fileName, fileNameView
  572. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID]];
  573. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:metadata.serverUrl account:metadata.account];
  574. metadata.fileID = [directoryID stringByAppendingString:metadata.fileName];
  575. }
  576. tableMetadata *metadataForUpload = [[NCManageDatabase sharedInstance] addMetadata:[CCUtility insertFileSystemInMetadata:metadata]];
  577. [imageData writeToFile:[CCUtility getDirectoryProviderStorageFileID:metadataForUpload.fileID fileNameView:metadataForUpload.fileNameView] options:NSDataWritingAtomic error:&error];
  578. if (error) {
  579. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadataForUpload.fileID]];
  580. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:fileID:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  581. [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];
  582. }
  583. } else {
  584. // OOOOOK
  585. if ([CCUtility isFolderEncrypted:metadataForUpload.serverUrl account:_activeAccount] && [CCUtility isEndToEndEnabled:_activeAccount]) {
  586. [self e2eEncryptedFile:metadataForUpload taskStatus:taskStatus];
  587. } else {
  588. [self uploadURLSessionMetadata:metadataForUpload taskStatus:taskStatus];
  589. }
  590. }
  591. }];
  592. }
  593. // VIDEO
  594. if (asset.mediaType == PHAssetMediaTypeVideo) {
  595. PHVideoRequestOptions *options = [PHVideoRequestOptions new];
  596. options.networkAccessAllowed = YES;
  597. options.version = PHVideoRequestOptionsVersionOriginal;
  598. options.progressHandler = ^(double progress, NSError *error, BOOL *stop, NSDictionary *info) {
  599. NSLog(@"cacheAsset: %f", progress);
  600. if (error) {
  601. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID]];
  602. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:fileID:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  603. [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];
  604. }
  605. }
  606. };
  607. [[PHImageManager defaultManager] requestAVAssetForVideo:asset options:options resultHandler:^(AVAsset *asset, AVAudioMix *audioMix, NSDictionary *info) {
  608. if ([asset isKindOfClass:[AVURLAsset class]]) {
  609. NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:[CCUtility getDirectoryProviderStorageFileID:metadata.fileID fileNameView:metadata.fileNameView]];
  610. NSError *error = nil;
  611. [[NSFileManager defaultManager] removeItemAtURL:fileURL error:nil];
  612. [[NSFileManager defaultManager] copyItemAtURL:[(AVURLAsset *)asset URL] toURL:fileURL error:&error];
  613. if (error) {
  614. dispatch_async(dispatch_get_main_queue(), ^{
  615. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID]];
  616. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:fileID:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  617. [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];
  618. }
  619. });
  620. } else {
  621. dispatch_async(dispatch_get_main_queue(), ^{
  622. // create Metadata for Upload
  623. tableMetadata *metadataForUpload = [[NCManageDatabase sharedInstance] addMetadata:[CCUtility insertFileSystemInMetadata:metadata]];
  624. // OOOOOK
  625. if ([CCUtility isFolderEncrypted:metadataForUpload.serverUrl account:_activeAccount] && [CCUtility isEndToEndEnabled:_activeAccount]) {
  626. [self e2eEncryptedFile:metadataForUpload taskStatus:taskStatus];
  627. } else {
  628. [self uploadURLSessionMetadata:metadataForUpload taskStatus:taskStatus];
  629. }
  630. });
  631. }
  632. }
  633. }];
  634. }
  635. } else {
  636. // create Metadata for Upload
  637. tableMetadata *metadataForUpload = [[NCManageDatabase sharedInstance] addMetadata:[CCUtility insertFileSystemInMetadata:metadata]];
  638. // OOOOOK
  639. if ([CCUtility isFolderEncrypted:metadataForUpload.serverUrl account:_activeAccount] && [CCUtility isEndToEndEnabled:_activeAccount]) {
  640. [self e2eEncryptedFile:metadataForUpload taskStatus:taskStatus];
  641. } else {
  642. [self uploadURLSessionMetadata:metadataForUpload taskStatus:taskStatus];
  643. }
  644. }
  645. }
  646. - (void)e2eEncryptedFile:(tableMetadata *)metadata taskStatus:(NSInteger)taskStatus
  647. {
  648. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  649. NSError *error;
  650. NSString *fileNameIdentifier;
  651. NSString *key;
  652. NSString *initializationVector;
  653. NSString *authenticationTag;
  654. NSString *metadataKey;
  655. NSInteger metadataKeyIndex;
  656. NSString *e2eMetadata;
  657. // Verify File Size
  658. NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:[CCUtility getDirectoryProviderStorageFileID:metadata.fileID fileNameView:metadata.fileNameView] error:&error];
  659. NSNumber *fileSizeNumber = [fileAttributes objectForKey:NSFileSize];
  660. long long fileSize = [fileSizeNumber longLongValue];
  661. if (fileSize > k_max_filesize_E2E) {
  662. // Error for uploadFileFailure
  663. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:fileID:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  664. [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];
  665. }
  666. return;
  667. }
  668. // if new file upload [directoryID + fileName] create a new encrypted filename
  669. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:metadata.serverUrl account:metadata.account];
  670. if ([metadata.fileID isEqualToString:[directoryID stringByAppendingString:metadata.fileNameView]]) {
  671. fileNameIdentifier = [CCUtility generateRandomIdentifier];
  672. } else {
  673. fileNameIdentifier = metadata.fileName;
  674. }
  675. if ([[NCEndToEndEncryption sharedManager] encryptFileName:metadata.fileNameView fileNameIdentifier:fileNameIdentifier directory:[CCUtility getDirectoryProviderStorageFileID:metadata.fileID] key:&key initializationVector:&initializationVector authenticationTag:&authenticationTag]) {
  676. tableE2eEncryption *object = [[NCManageDatabase sharedInstance] getE2eEncryptionWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", _activeAccount, metadata.serverUrl]];
  677. if (object) {
  678. metadataKey = object.metadataKey;
  679. metadataKeyIndex = object.metadataKeyIndex;
  680. } else {
  681. metadataKey = [[[NCEndToEndEncryption sharedManager] generateKey:16] base64EncodedStringWithOptions:0]; // AES_KEY_128_LENGTH
  682. metadataKeyIndex = 0;
  683. }
  684. tableE2eEncryption *addObject = [tableE2eEncryption new];
  685. addObject.account = _activeAccount;
  686. addObject.authenticationTag = authenticationTag;
  687. addObject.fileName = metadata.fileNameView;
  688. addObject.fileNameIdentifier = fileNameIdentifier;
  689. addObject.fileNamePath = [CCUtility returnFileNamePathFromFileName:metadata.fileNameView serverUrl:metadata.serverUrl activeUrl:_activeUrl];
  690. addObject.key = key;
  691. addObject.initializationVector = initializationVector;
  692. addObject.metadataKey = metadataKey;
  693. addObject.metadataKeyIndex = metadataKeyIndex;
  694. CFStringRef UTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef)[metadata.fileNameView pathExtension], NULL);
  695. CFStringRef mimeTypeRef = UTTypeCopyPreferredTagWithClass (UTI, kUTTagClassMIMEType);
  696. if (mimeTypeRef) {
  697. addObject.mimeType = (__bridge NSString *)mimeTypeRef;
  698. } else {
  699. addObject.mimeType = @"application/octet-stream";
  700. }
  701. addObject.serverUrl = metadata.serverUrl;
  702. addObject.version = [[NCManageDatabase sharedInstance] getEndToEndEncryptionVersionWithAccount:_activeAccount];
  703. // Get the last metadata
  704. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", _activeAccount, metadata.serverUrl]];
  705. error = [[NCNetworkingEndToEnd sharedManager] getEndToEndMetadata:&e2eMetadata fileID:directory.fileID user:_activeUser userID:_activeUserID password:_activePassword url:_activeUrl];
  706. if (error == nil) {
  707. if ([[NCEndToEndMetadata sharedInstance] decoderMetadata:e2eMetadata privateKey:[CCUtility getEndToEndPrivateKey:_activeAccount] serverUrl:metadata.serverUrl account:_activeAccount url:_activeUrl] == false) {
  708. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:fileID:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  709. [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];
  710. }
  711. return;
  712. }
  713. }
  714. // write new record e2ee
  715. if([[NCManageDatabase sharedInstance] addE2eEncryption:addObject] == NO) {
  716. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:fileID:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  717. [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];
  718. }
  719. return;
  720. }
  721. } else {
  722. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:fileID:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  723. [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];
  724. }
  725. return;
  726. }
  727. dispatch_async(dispatch_get_main_queue(), ^{
  728. // Now the fileName is fileNameIdentifier && flag e2eEncrypted
  729. metadata.fileName = fileNameIdentifier;
  730. metadata.e2eEncrypted = YES;
  731. // Update Metadata
  732. tableMetadata *metadataEncrypted = [[NCManageDatabase sharedInstance] addMetadata:metadata];
  733. [self uploadURLSessionMetadata:metadataEncrypted taskStatus:taskStatus];
  734. });
  735. });
  736. }
  737. - (void)uploadURLSessionMetadata:(tableMetadata *)metadata taskStatus:(NSInteger)taskStatus
  738. {
  739. NSURL *url;
  740. NSMutableURLRequest *request;
  741. PHAsset *asset;
  742. NSError *error;
  743. // calculate and store file size
  744. NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:[CCUtility getDirectoryProviderStorageFileID:metadata.fileID fileNameView:metadata.fileName] error:&error];
  745. long long fileSize = [[fileAttributes objectForKey:NSFileSize] longLongValue];
  746. metadata.size = fileSize;
  747. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  748. url = [NSURL URLWithString:[[NSString stringWithFormat:@"%@/%@", metadata.serverUrl, metadata.fileName] encodeString:NSUTF8StringEncoding]];
  749. request = [NSMutableURLRequest requestWithURL:url];
  750. NSData *authData = [[NSString stringWithFormat:@"%@:%@", _activeUser, _activePassword] dataUsingEncoding:NSUTF8StringEncoding];
  751. NSString *authValue = [NSString stringWithFormat: @"Basic %@",[authData base64EncodedStringWithOptions:0]];
  752. [request setHTTPMethod:@"PUT"];
  753. [request setValue:authValue forHTTPHeaderField:@"Authorization"];
  754. [request setValue:[CCUtility getUserAgent] forHTTPHeaderField:@"User-Agent"];
  755. // Create Image for Upload (gray scale)
  756. #ifndef EXTENSION
  757. [CCGraphics createNewImageFrom:metadata.fileNameView fileID:metadata.fileID extension:[metadata.fileNameView pathExtension] filterGrayScale:YES typeFile:metadata.typeFile writeImage:YES];
  758. #endif
  759. // Change date file upload with header : X-OC-Mtime (ctime assetLocalIdentifier) image/video
  760. if (metadata.assetLocalIdentifier) {
  761. PHFetchResult *result = [PHAsset fetchAssetsWithLocalIdentifiers:@[metadata.assetLocalIdentifier] options:nil];
  762. if (result.count) {
  763. asset = result[0];
  764. long dateFileCreation = [asset.creationDate timeIntervalSince1970];
  765. [request setValue:[NSString stringWithFormat:@"%ld", dateFileCreation] forHTTPHeaderField:@"X-OC-Mtime"];
  766. }
  767. }
  768. NSURLSession *sessionUpload;
  769. // NSURLSession
  770. if ([metadata.session isEqualToString:k_upload_session]) sessionUpload = [self sessionUpload];
  771. else if ([metadata.session isEqualToString:k_upload_session_wwan]) sessionUpload = [self sessionWWanUpload];
  772. else if ([metadata.session isEqualToString:k_upload_session_foreground]) sessionUpload = [self sessionUploadForeground];
  773. else if ([metadata.session isEqualToString:k_upload_session_extension]) sessionUpload = [self sessionUploadExtension];
  774. NSURLSessionUploadTask *uploadTask = [sessionUpload uploadTaskWithRequest:request fromFile:[NSURL fileURLWithPath:[CCUtility getDirectoryProviderStorageFileID:metadata.fileID fileNameView:metadata.fileName]]];
  775. // Error
  776. if (uploadTask == nil) {
  777. NSString *messageError = @"Serious internal error uploadTask not available";
  778. [[NCManageDatabase sharedInstance] setMetadataSession:metadata.session sessionError:messageError sessionSelector:nil sessionTaskIdentifier:k_taskIdentifierDone status:k_metadataStatusUploadError predicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID]];
  779. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:fileID:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  780. [self.delegate uploadFileSuccessFailure:metadata.fileNameView fileID:metadata.fileID assetLocalIdentifier:metadata.assetLocalIdentifier serverUrl:metadata.serverUrl selector:metadata.sessionSelector errorMessage:messageError errorCode:k_CCErrorInternalError];
  781. }
  782. } else {
  783. // E2EE : CREATE AND SEND METADATA
  784. if ([CCUtility isFolderEncrypted:metadata.serverUrl account:_activeAccount] && [CCUtility isEndToEndEnabled:_activeAccount]) {
  785. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  786. // Send Metadata
  787. NSError *error = [[NCNetworkingEndToEnd sharedManager] sendEndToEndMetadataOnServerUrl:metadata.serverUrl fileNameRename:nil fileNameNewRename:nil account:_activeAccount user:_activeUser userID:_activeUserID password:_activePassword url:_activeUrl];
  788. dispatch_async(dispatch_get_main_queue(), ^{
  789. if (error) {
  790. [uploadTask cancel];
  791. NSString *messageError = [NSString stringWithFormat:@"%@ (%d)", error.localizedDescription, (int)error.code];
  792. [[NCManageDatabase sharedInstance] setMetadataSession:metadata.session sessionError:messageError sessionSelector:nil sessionTaskIdentifier:k_taskIdentifierDone status:k_metadataStatusUploadError predicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID]];
  793. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:fileID:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  794. [self.delegate uploadFileSuccessFailure:metadata.fileNameView fileID:metadata.fileID assetLocalIdentifier:metadata.assetLocalIdentifier serverUrl:metadata.serverUrl selector:metadata.sessionSelector errorMessage:messageError errorCode:k_CCErrorInternalError];
  795. }
  796. } else {
  797. // Manage uploadTask cancel,suspend,resume
  798. if (taskStatus == k_taskStatusCancel) [uploadTask cancel];
  799. else if (taskStatus == k_taskStatusSuspend) [uploadTask suspend];
  800. else if (taskStatus == k_taskStatusResume) [uploadTask resume];
  801. // *** E2EE ***
  802. [[NCManageDatabase sharedInstance] setMetadataSession:metadata.session sessionError:@"" sessionSelector:nil sessionTaskIdentifier:uploadTask.taskIdentifier status:k_metadataStatusUploading predicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID]];
  803. NSLog(@"[LOG] Upload file %@ TaskIdentifier %lu", metadata.fileName, (unsigned long)uploadTask.taskIdentifier);
  804. NSString *fileID = metadata.fileID;
  805. NSString *account = metadata.account;
  806. dispatch_async(dispatch_get_main_queue(), ^{
  807. if ([self.delegate respondsToSelector:@selector(uploadStart:account:task:serverUrl:)]) {
  808. [self.delegate uploadStart:fileID account:account task:uploadTask serverUrl:metadata.serverUrl];
  809. }
  810. });
  811. }
  812. });
  813. });
  814. } else {
  815. // Manage uploadTask cancel,suspend,resume
  816. if (taskStatus == k_taskStatusCancel) [uploadTask cancel];
  817. else if (taskStatus == k_taskStatusSuspend) [uploadTask suspend];
  818. else if (taskStatus == k_taskStatusResume) [uploadTask resume];
  819. // *** PLAIN ***
  820. [[NCManageDatabase sharedInstance] setMetadataSession:metadata.session sessionError:@"" sessionSelector:nil sessionTaskIdentifier:uploadTask.taskIdentifier status:k_metadataStatusUploading predicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID]];
  821. NSLog(@"[LOG] Upload file %@ TaskIdentifier %lu", metadata.fileName, (unsigned long)uploadTask.taskIdentifier);
  822. NSString *fileID = metadata.fileID;
  823. NSString *account = metadata.account;
  824. dispatch_async(dispatch_get_main_queue(), ^{
  825. if ([self.delegate respondsToSelector:@selector(uploadStart:account:task:serverUrl:)]) {
  826. [self.delegate uploadStart:fileID account:account task:uploadTask serverUrl:metadata.serverUrl];
  827. }
  828. });
  829. }
  830. }
  831. }
  832. - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
  833. {
  834. NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)dataTask.response;
  835. if (httpResponse.statusCode >= 200 && httpResponse.statusCode < 300) {
  836. NSNumber *taskIdentifier = [NSNumber numberWithLong:dataTask.taskIdentifier];
  837. if (data)
  838. [_taskData setObject:[data copy] forKey:taskIdentifier];
  839. }
  840. }
  841. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend
  842. {
  843. NSString *url = [[[task currentRequest].URL absoluteString] stringByRemovingPercentEncoding];
  844. NSString *fileName = [url lastPathComponent];
  845. NSString *serverUrl = [self getServerUrlFromUrl:url];
  846. if (!serverUrl) return;
  847. if (totalBytesExpectedToSend < 1) {
  848. totalBytesExpectedToSend = totalBytesSent;
  849. }
  850. float progress = (float) totalBytesSent / (float)totalBytesExpectedToSend;
  851. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataInSessionFromFileName:fileName serverUrl:serverUrl taskIdentifier:task.taskIdentifier];
  852. if (metadata) {
  853. NSDictionary* userInfo = @{@"fileID": (metadata.fileID), @"serverUrl": (serverUrl), @"status": ([NSNumber numberWithLong:k_metadataStatusInUpload]), @"progress": ([NSNumber numberWithFloat:progress]), @"totalBytes": ([NSNumber numberWithLongLong:totalBytesSent]), @"totalBytesExpected": ([NSNumber numberWithLongLong:totalBytesExpectedToSend])};
  854. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"NotificationProgressTask" object:nil userInfo:userInfo];
  855. }
  856. }
  857. - (void)uploadFileSuccessFailure:(tableMetadata *)metadata fileName:(NSString *)fileName fileID:(NSString *)fileID etag:(NSString *)etag date:(NSDate *)date serverUrl:(NSString *)serverUrl errorCode:(NSInteger)errorCode
  858. {
  859. NSString *tempFileID = metadata.fileID;
  860. NSString *tempSession = metadata.session;
  861. NSString *errorMessage = @"";
  862. BOOL isE2EEDirectory = false;
  863. // is this a E2EE Directory ?
  864. if ([CCUtility isFolderEncrypted:serverUrl account:_activeAccount] && [CCUtility isEndToEndEnabled:_activeAccount]) {
  865. isE2EEDirectory = true;
  866. }
  867. // ERRORE
  868. if (errorCode != 0) {
  869. #ifndef EXTENSION
  870. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  871. [appDelegate.listProgressMetadata removeObjectForKey:metadata.fileID];
  872. #endif
  873. // Mark error only if not Cancelled Task
  874. if (errorCode == kCFURLErrorCancelled) {
  875. [[NSFileManager defaultManager] removeItemAtPath:[CCUtility getDirectoryProviderStorageFileID:tempFileID] error:nil];
  876. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", tempFileID]];
  877. } else {
  878. [[NCManageDatabase sharedInstance] setMetadataSession:nil sessionError:[CCError manageErrorKCF:errorCode withNumberError:NO] sessionSelector:nil sessionTaskIdentifier:k_taskIdentifierDone status:k_metadataStatusUploadError predicate:[NSPredicate predicateWithFormat:@"fileID == %@", tempFileID]];
  879. }
  880. errorMessage = [CCError manageErrorKCF:errorCode withNumberError:YES];
  881. } else {
  882. // Replace Metadata
  883. metadata.date = date;
  884. if (isE2EEDirectory) {
  885. metadata.e2eEncrypted = true;
  886. } else {
  887. metadata.e2eEncrypted = false;
  888. }
  889. metadata.etag = etag;
  890. metadata.fileID = fileID;
  891. metadata.session = @"";
  892. metadata.sessionError = @"";
  893. metadata.sessionTaskIdentifier = k_taskIdentifierDone;
  894. metadata.status = k_metadataStatusNormal;
  895. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@ AND fileName == %@", metadata.account, metadata.serverUrl, metadata.fileName]];
  896. metadata = [[NCManageDatabase sharedInstance] addMetadata:metadata];
  897. NSLog(@"[LOG] Insert new upload : %@ - fileID : %@", metadata.fileName, fileID);
  898. // remove tempFileID and adjust the directory provider storage
  899. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:metadata.serverUrl account:metadata.account];
  900. if ([tempFileID isEqualToString:[directoryID stringByAppendingString:metadata.fileNameView]]) {
  901. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", tempFileID]];
  902. // adjust file system Directory Provider Storage
  903. if ([tempSession isEqualToString:k_upload_session_extension]) {
  904. // this is for File Provider Extension [Apple Works and ... ?]
  905. [CCUtility copyFileAtPath:[NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryProviderStorage], tempFileID] toPath:[NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryProviderStorage], metadata.fileID]];
  906. } else {
  907. [CCUtility moveFileAtPath:[NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryProviderStorage], tempFileID] toPath:[NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryProviderStorage], metadata.fileID]];
  908. }
  909. }
  910. #ifndef EXTENSION
  911. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  912. [appDelegate.listProgressMetadata removeObjectForKey:metadata.fileID];
  913. // Hardcoded for add new photo/video for tab Media view
  914. NSString *startDirectoryMediaTabView = [[NCManageDatabase sharedInstance] getAccountStartDirectoryMediaTabView:[CCUtility getHomeServerUrlActiveUrl:appDelegate.activeUrl]];
  915. if ([serverUrl containsString:startDirectoryMediaTabView] && ([metadata.typeFile isEqualToString:k_metadataTypeFile_image] || [metadata.typeFile isEqualToString:k_metadataTypeFile_video])) {
  916. [appDelegate.activeMedia.addMetadatasFromUpload addObject:metadata];
  917. }
  918. #endif
  919. // Add Local
  920. [[NCManageDatabase sharedInstance] addLocalFileWithMetadata:metadata];
  921. #ifndef EXTENSION
  922. // EXIF
  923. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image])
  924. [[CCExifGeo sharedInstance] setExifLocalTableEtag:metadata];
  925. // Remove icon B/N
  926. [[NSFileManager defaultManager] removeItemAtPath:[CCUtility getDirectoryProviderStorageIconFileID:metadata.fileID fileNameView:metadata.fileNameView] error:nil];
  927. // Copy photo or video in the photo album for auto upload
  928. if ([metadata.assetLocalIdentifier length] > 0 && ([metadata.sessionSelector isEqualToString:selectorUploadAutoUpload] || [metadata.sessionSelector isEqualToString:selectorUploadFile])) {
  929. PHAsset *asset;
  930. PHFetchResult *result = [PHAsset fetchAssetsWithLocalIdentifiers:@[metadata.assetLocalIdentifier] options:nil];
  931. if(result.count){
  932. asset = result[0];
  933. [asset saveToAlbum:[NCBrandOptions sharedInstance].brand completionBlock:^(BOOL success) {
  934. if (success) NSLog(@"[LOG] Insert file %@ in %@", metadata.fileName, [NCBrandOptions sharedInstance].brand);
  935. else NSLog(@"[LOG] File %@ do not insert in %@", metadata.fileName, [NCBrandOptions sharedInstance].brand);
  936. }];
  937. }
  938. }
  939. #endif
  940. // Actvity
  941. [[NCManageDatabase sharedInstance] addActivityClient:metadata.fileNameView fileID:fileID action:k_activityDebugActionUpload selector:metadata.sessionSelector note:serverUrl type:k_activityTypeSuccess verbose:k_activityVerboseDefault activeUrl:_activeUrl];
  942. }
  943. // Detect E2EE
  944. tableMetadata *e2eeMetadataInSession = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@ AND e2eEncrypted == 1 AND (status == %d OR status == %d)", _activeAccount, metadata.serverUrl, k_metadataStatusInUpload, k_metadataStatusUploading]];
  945. // E2EE : UNLOCK
  946. if (isE2EEDirectory && e2eeMetadataInSession == nil) {
  947. tableE2eEncryptionLock *tableLock = [[NCManageDatabase sharedInstance] getE2ETokenLockWithServerUrl:serverUrl];
  948. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  949. if (tableLock) {
  950. NSError *error = [[NCNetworkingEndToEnd sharedManager] unlockEndToEndFolderEncryptedOnServerUrl:serverUrl fileID:tableLock.fileID token:tableLock.token user:_activeUser userID:_activeUserID password:_activePassword url:_activeUrl];
  951. if (error) {
  952. #ifndef EXTENSION
  953. dispatch_async(dispatch_get_main_queue(), ^{
  954. [(AppDelegate *)[[UIApplication sharedApplication] delegate] messageNotification:@"_e2e_error_unlock_" description:error.localizedDescription visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  955. });
  956. #endif
  957. }
  958. } else {
  959. NSLog(@"Error unlock not found");
  960. }
  961. dispatch_async(dispatch_get_main_queue(), ^{
  962. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:fileID:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  963. [self.delegate uploadFileSuccessFailure:metadata.fileName fileID:metadata.fileID assetLocalIdentifier:metadata.assetLocalIdentifier serverUrl:serverUrl selector:metadata.sessionSelector errorMessage:errorMessage errorCode:errorCode];
  964. }
  965. });
  966. });
  967. } else {
  968. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:fileID:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  969. [self.delegate uploadFileSuccessFailure:metadata.fileName fileID:metadata.fileID assetLocalIdentifier:metadata.assetLocalIdentifier serverUrl:serverUrl selector:metadata.sessionSelector errorMessage:errorMessage errorCode:errorCode];
  970. }
  971. }
  972. }
  973. #pragma --------------------------------------------------------------------------------------------
  974. #pragma mark ===== Utility =====
  975. #pragma --------------------------------------------------------------------------------------------
  976. - (NSString *)getServerUrlFromUrl:(NSString *)url
  977. {
  978. NSString *fileName = [url lastPathComponent];
  979. url = [url stringByReplacingOccurrencesOfString:[@"/" stringByAppendingString:fileName] withString:@""];
  980. return url;
  981. }
  982. @end
  983. #pragma --------------------------------------------------------------------------------------------
  984. #pragma mark ===== CCMetadataNet =====
  985. #pragma --------------------------------------------------------------------------------------------
  986. @implementation CCMetadataNet
  987. - (id)init
  988. {
  989. self = [super init];
  990. self.priority = NSOperationQueuePriorityNormal;
  991. return self;
  992. }
  993. - (id)initWithAccount:(NSString *)withAccount
  994. {
  995. self = [self init];
  996. if (self) {
  997. _account = withAccount;
  998. }
  999. return self;
  1000. }
  1001. - (id)copyWithZone: (NSZone *) zone
  1002. {
  1003. CCMetadataNet *metadataNet = [[CCMetadataNet allocWithZone: zone] init];
  1004. [metadataNet setAccount: self.account];
  1005. [metadataNet setAction: self.action];
  1006. [metadataNet setContentType: self.contentType];
  1007. [metadataNet setDate: self.date];
  1008. [metadataNet setDelegate: self.delegate];
  1009. [metadataNet setDepth: self.depth];
  1010. [metadataNet setDirectory: self.directory];
  1011. [metadataNet setEncryptedMetadata: self.encryptedMetadata];
  1012. [metadataNet setEtag:self.etag];
  1013. [metadataNet setExpirationTime: self.expirationTime];
  1014. [metadataNet setFileID: self.fileID];
  1015. [metadataNet setFileName: self.fileName];
  1016. [metadataNet setFileNameTo: self.fileNameTo];
  1017. [metadataNet setFileNameView: self.fileNameView];
  1018. [metadataNet setHideDownload: self.hideDownload];
  1019. [metadataNet setKey: self.key];
  1020. [metadataNet setKeyCipher: self.keyCipher];
  1021. [metadataNet setOptionAny: self.optionAny];
  1022. [metadataNet setOptionString: self.optionString];
  1023. [metadataNet setPassword: self.password];
  1024. [metadataNet setPriority: self.priority];
  1025. [metadataNet setServerUrl: self.serverUrl];
  1026. [metadataNet setServerUrlTo: self.serverUrlTo];
  1027. [metadataNet setSelector: self.selector];
  1028. [metadataNet setShare: self.share];
  1029. [metadataNet setShareeType: self.shareeType];
  1030. [metadataNet setSharePermission: self.sharePermission];
  1031. [metadataNet setSize: self.size];
  1032. return metadataNet;
  1033. }
  1034. @end