CCNetworking.m 68 KB

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