CCNetworking.m 71 KB

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