CCNetworking.m 72 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396
  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 = k_maxHTTPConnectionsPerHost;
  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 = k_maxHTTPConnectionsPerHost;
  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 = k_maxHTTPConnectionsPerHost;
  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 = k_maxHTTPConnectionsPerHost;
  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 = k_maxHTTPConnectionsPerHost;
  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 = k_maxHTTPConnectionsPerHost;
  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 = k_maxHTTPConnectionsPerHost;
  205. configurationDownload.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  206. configurationDownload.timeoutIntervalForRequest = k_timeout_upload;
  207. OCURLSessionManager *downloadSessionManager = [[OCURLSessionManager alloc] initWithSessionConfiguration:configurationDownload];
  208. [downloadSessionManager.operationQueue setMaxConcurrentOperationCount:k_maxHTTPConnectionsPerHost];
  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 = k_maxHTTPConnectionsPerHost;
  217. configurationUpload.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  218. configurationUpload.timeoutIntervalForRequest = k_timeout_upload;
  219. OCURLSessionManager *uploadSessionManager = [[OCURLSessionManager alloc] initWithSessionConfiguration:configurationUpload];
  220. [uploadSessionManager.operationQueue setMaxConcurrentOperationCount:k_maxHTTPConnectionsPerHost];
  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. if (fileName.length > 0 && serverUrl.length > 0) {
  333. dispatch_async(dispatch_get_main_queue(), ^{
  334. [self downloadFileSuccessFailure:fileName fileID:metadata.fileID etag:etag date:date serverUrl:serverUrl selector:metadata.sessionSelector errorCode:errorCode];
  335. });
  336. }
  337. } else {
  338. NSLog(@"[LOG] Remove record ? : metadata not found %@", url);
  339. dispatch_async(dispatch_get_main_queue(), ^{
  340. if ([self.delegate respondsToSelector:@selector(downloadFileSuccessFailure:fileID:serverUrl:selector:errorMessage:errorCode:)]) {
  341. [self.delegate downloadFileSuccessFailure:fileName fileID:@"" serverUrl:serverUrl selector:@"" errorMessage:@"Remove record ? : metadata not found" errorCode:k_CCErrorInternalError];
  342. }
  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. if (fileName.length > 0 && fileID.length > 0 && serverUrl.length > 0) {
  367. dispatch_async(dispatch_get_main_queue(), ^{
  368. [self uploadFileSuccessFailure:metadata fileName:fileName fileID:fileID etag:etag date:date serverUrl:serverUrl errorCode:errorCode];
  369. });
  370. }
  371. } else {
  372. NSLog(@"[LOG] Remove record ? : metadata not found %@", url);
  373. dispatch_async(dispatch_get_main_queue(), ^{
  374. if ([self.delegate respondsToSelector:@selector(uploadFileSuccessFailure:fileID:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  375. [self.delegate uploadFileSuccessFailure:fileName fileID:@"" assetLocalIdentifier:@"" serverUrl:serverUrl selector:@"" errorMessage:@"Remove record ? : metadata not found" errorCode:k_CCErrorInternalError];
  376. }
  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 (!serverUrl || (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. if ([delegate respondsToSelector:@selector(downloadFileSuccessFailure:fileID:serverUrl:selector:errorMessage:errorCode:)]) {
  394. [delegate downloadFileSuccessFailure:metadata.fileName fileID:metadata.fileID serverUrl:serverUrl selector:metadata.sessionSelector errorMessage:@"" errorCode:0];
  395. }
  396. return;
  397. }
  398. [self downloaURLSession:metadata serverUrl:serverUrl taskStatus:taskStatus];
  399. }
  400. - (void)downloaURLSession:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl taskStatus:(NSInteger)taskStatus
  401. {
  402. NSURLSession *sessionDownload;
  403. NSURL *url;
  404. NSMutableURLRequest *request;
  405. NSString *serverFileUrl = [[NSString stringWithFormat:@"%@/%@", serverUrl, metadata.fileName] encodeString:NSUTF8StringEncoding];
  406. url = [NSURL URLWithString:serverFileUrl];
  407. request = [NSMutableURLRequest requestWithURL:url];
  408. NSData *authData = [[NSString stringWithFormat:@"%@:%@", _activeUser, _activePassword] dataUsingEncoding:NSUTF8StringEncoding];
  409. NSString *authValue = [NSString stringWithFormat: @"Basic %@",[authData base64EncodedStringWithOptions:0]];
  410. [request setValue:authValue forHTTPHeaderField:@"Authorization"];
  411. [request setValue:[CCUtility getUserAgent] forHTTPHeaderField:@"User-Agent"];
  412. if ([metadata.session isEqualToString:k_download_session]) sessionDownload = [self sessionDownload];
  413. else if ([metadata.session isEqualToString:k_download_session_foreground]) sessionDownload = [self sessionDownloadForeground];
  414. else if ([metadata.session isEqualToString:k_download_session_wwan]) sessionDownload = [self sessionWWanDownload];
  415. NSURLSessionDownloadTask *downloadTask = [sessionDownload downloadTaskWithRequest:request];
  416. if (downloadTask == nil) {
  417. [[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];
  418. [[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]];
  419. if ([self.delegate respondsToSelector:@selector(downloadFileSuccessFailure:fileID:serverUrl:selector:errorMessage:errorCode:)]) {
  420. [self.delegate downloadFileSuccessFailure:metadata.fileName fileID:metadata.fileID serverUrl:serverUrl selector:metadata.sessionSelector errorMessage:@"Serious internal error downloadTask not available" errorCode:k_CCErrorInternalError];
  421. }
  422. } else {
  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. [[NCManageDatabase sharedInstance] setMetadataSession:nil sessionError:nil sessionSelector:nil sessionTaskIdentifier:downloadTask.taskIdentifier status:k_metadataStatusDownloading predicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID]];
  428. NSLog(@"[LOG] downloadFileSession %@ Task [%lu]", metadata.fileID, (unsigned long)downloadTask.taskIdentifier);
  429. }
  430. dispatch_async(dispatch_get_main_queue(), ^{
  431. if ([[self getDelegate:metadata.fileID] respondsToSelector:@selector(downloadStart:account:task:serverUrl:)]) {
  432. [[self getDelegate:metadata.fileID] downloadStart:metadata.fileID account:metadata.account task:downloadTask serverUrl:serverUrl];
  433. }
  434. });
  435. }
  436. - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
  437. {
  438. NSString *url = [[[downloadTask currentRequest].URL absoluteString] stringByRemovingPercentEncoding];
  439. NSString *fileName = [url lastPathComponent];
  440. NSString *serverUrl = [self getServerUrlFromUrl:url];
  441. if (!serverUrl) return;
  442. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrl];
  443. if (!directoryID) return;
  444. if (totalBytesExpectedToWrite < 1) {
  445. totalBytesExpectedToWrite = totalBytesWritten;
  446. }
  447. float progress = (float) totalBytesWritten / (float)totalBytesExpectedToWrite;
  448. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataInSessionFromFileName:fileName directoryID:directoryID];
  449. if (metadata) {
  450. NSDictionary* userInfo = @{@"fileID": (metadata.fileID), @"serverUrl": (serverUrl), @"status": ([NSNumber numberWithLong:k_metadataStatusInDownload]), @"progress": ([NSNumber numberWithFloat:progress]), @"totalBytes": ([NSNumber numberWithLongLong:totalBytesWritten]), @"totalBytesExpected": ([NSNumber numberWithLongLong:totalBytesExpectedToWrite])};
  451. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"NotificationProgressTask" object:nil userInfo:userInfo];
  452. } else {
  453. NSLog(@"[LOG] metadata not found");
  454. }
  455. }
  456. - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
  457. {
  458. NSString *url = [[[downloadTask currentRequest].URL absoluteString] stringByRemovingPercentEncoding];
  459. if (!url)
  460. return;
  461. NSString *fileName = [url lastPathComponent];
  462. NSString *serverUrl = [self getServerUrlFromUrl:url];
  463. if (!serverUrl) return;
  464. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrl];
  465. if (!directoryID) return;
  466. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"directoryID == %@ AND fileName == %@", directoryID, fileName]];
  467. if (!metadata) {
  468. [[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];
  469. NSLog(@"[LOG] Serious error internal download : metadata not found %@ ", url);
  470. dispatch_async(dispatch_get_main_queue(), ^{
  471. if ([self.delegate respondsToSelector:@selector(downloadFileSuccessFailure:fileID:serverUrl:selector:errorMessage:errorCode:)]) {
  472. [self.delegate downloadFileSuccessFailure:@"" fileID:@"" serverUrl:serverUrl selector:@"" errorMessage:@"Serious error internal download : metadata not found" errorCode:k_CCErrorInternalError];
  473. }
  474. });
  475. return;
  476. }
  477. NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)downloadTask.response;
  478. if (httpResponse.statusCode >= 200 && httpResponse.statusCode < 300) {
  479. NSString *destinationFilePath = [CCUtility getDirectoryProviderStorageFileID:metadata.fileID fileName:metadata.fileName];
  480. NSURL *destinationURL = [NSURL fileURLWithPath:destinationFilePath];
  481. [[NSFileManager defaultManager] removeItemAtURL:destinationURL error:NULL];
  482. [[NSFileManager defaultManager] copyItemAtURL:location toURL:destinationURL error:nil];
  483. }
  484. }
  485. - (void)downloadFileSuccessFailure:(NSString *)fileName fileID:(NSString *)fileID etag:(NSString *)etag date:(NSDate *)date serverUrl:(NSString *)serverUrl selector:(NSString *)selector errorCode:(NSInteger)errorCode
  486. {
  487. #ifndef EXTENSION
  488. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  489. [appDelegate.listProgressMetadata removeObjectForKey:fileID];
  490. #endif
  491. if (errorCode != 0) {
  492. if (errorCode == kCFURLErrorCancelled) {
  493. [[NCManageDatabase sharedInstance] setMetadataSession:@"" sessionError:@"" sessionSelector:@"" sessionTaskIdentifier:k_taskIdentifierDone status:k_metadataStatusNormal predicate:[NSPredicate predicateWithFormat:@"fileID == %@", fileID]];
  494. } else {
  495. [[NCManageDatabase sharedInstance] setMetadataSession:nil sessionError:[CCError manageErrorKCF:errorCode withNumberError:NO] sessionSelector:nil sessionTaskIdentifier:k_taskIdentifierDone status:k_metadataStatusDownloadError predicate:[NSPredicate predicateWithFormat:@"fileID == %@", fileID]];
  496. }
  497. if ([[self getDelegate:fileID] respondsToSelector:@selector(downloadFileSuccessFailure:fileID:serverUrl:selector:errorMessage:errorCode:)]) {
  498. [[self getDelegate:fileID] downloadFileSuccessFailure:fileName fileID:fileID serverUrl:serverUrl selector:selector errorMessage:[CCError manageErrorKCF:errorCode withNumberError:YES] errorCode:errorCode];
  499. }
  500. } else {
  501. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", fileID]];
  502. if (!metadata) {
  503. [[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];
  504. NSLog(@"[LOG] Serious error internal download : metadata not found %@ ", fileName);
  505. if ([[self getDelegate:fileID] respondsToSelector:@selector(downloadFileSuccessFailure:fileID:serverUrl:selector:errorMessage:errorCode:)]) {
  506. [[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];
  507. }
  508. return;
  509. }
  510. metadata.session = @"";
  511. metadata.sessionError = @"";
  512. metadata.sessionSelector = @"";
  513. metadata.sessionTaskIdentifier = k_taskIdentifierDone;
  514. metadata.status = k_metadataStatusNormal;
  515. metadata = [[NCManageDatabase sharedInstance] updateMetadata:metadata];
  516. [[NCManageDatabase sharedInstance] addLocalFileWithMetadata:metadata];
  517. // E2EE Decrypted
  518. tableE2eEncryption *object = [[NCManageDatabase sharedInstance] getE2eEncryptionWithPredicate:[NSPredicate predicateWithFormat:@"fileNameIdentifier == %@ AND serverUrl == %@", fileName, serverUrl]];
  519. if (object) {
  520. BOOL result = [[NCEndToEndEncryption sharedManager] decryptFileName:metadata.fileName fileNameView:metadata.fileNameView fileID:metadata.fileID key:object.key initializationVector:object.initializationVector authenticationTag:object.authenticationTag];
  521. if (!result) {
  522. [[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];
  523. if ([[self getDelegate:fileID] respondsToSelector:@selector(downloadFileSuccessFailure:fileID:serverUrl:selector:errorMessage:errorCode:)]) {
  524. [[self getDelegate:fileID] downloadFileSuccessFailure:fileName fileID:fileID serverUrl:serverUrl selector:selector errorMessage:[NSString stringWithFormat:@"Serious error internal download : decrypt error %@", fileName] errorCode:k_CCErrorInternalError];
  525. }
  526. return;
  527. }
  528. }
  529. // Exif
  530. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image])
  531. [[CCExifGeo sharedInstance] setExifLocalTableEtag:metadata];
  532. // Icon
  533. [CCGraphics createNewImageFrom:metadata.fileNameView fileID:metadata.fileID extension:[metadata.fileNameView pathExtension] size:@"m" imageForUpload:NO typeFile:metadata.typeFile writeImage:YES];
  534. // Activity
  535. [[NCManageDatabase sharedInstance] addActivityClient:metadata.fileNameView fileID:metadata.fileID action:k_activityDebugActionDownload selector:metadata.sessionSelector note:serverUrl type:k_activityTypeSuccess verbose:k_activityVerboseDefault activeUrl:_activeUrl];
  536. if ([[self getDelegate:fileID] respondsToSelector:@selector(downloadFileSuccessFailure:fileID:serverUrl:selector:errorMessage:errorCode:)]) {
  537. [[self getDelegate:fileID] downloadFileSuccessFailure:fileName fileID:fileID serverUrl:serverUrl selector:selector errorMessage:@"" errorCode:0];
  538. }
  539. }
  540. }
  541. #pragma --------------------------------------------------------------------------------------------
  542. #pragma mark ===== Upload =====
  543. #pragma --------------------------------------------------------------------------------------------
  544. - (void)uploadFile:(tableMetadata *)metadata taskStatus:(NSInteger)taskStatus delegate:(id)delegate
  545. {
  546. //delegate
  547. [_delegates setObject:delegate forKey:metadata.fileID];
  548. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  549. if (!serverUrl || [CCUtility fileProviderStorageExists:metadata.fileID fileName:metadata.fileNameView] == NO) {
  550. PHFetchResult *result = [PHAsset fetchAssetsWithLocalIdentifiers:@[metadata.assetLocalIdentifier] options:nil];
  551. if (!result.count) {
  552. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID] clearDateReadDirectoryID:metadata.directoryID];
  553. if ([delegate respondsToSelector:@selector(uploadFileSuccessFailure:fileID:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  554. [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];
  555. }
  556. return;
  557. }
  558. PHAsset *asset= result[0];
  559. // IMAGE
  560. if (asset.mediaType == PHAssetMediaTypeImage) {
  561. PHImageRequestOptions *options = [PHImageRequestOptions new];
  562. options.networkAccessAllowed = YES; // iCloud
  563. options.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
  564. options.synchronous = YES;
  565. options.progressHandler = ^(double progress, NSError *error, BOOL *stop, NSDictionary *info) {
  566. NSLog(@"cacheAsset: %f", progress);
  567. if (error) {
  568. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID] clearDateReadDirectoryID:metadata.directoryID];
  569. if ([delegate respondsToSelector:@selector(uploadFileSuccessFailure:fileID:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  570. [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];
  571. }
  572. }
  573. };
  574. [[PHImageManager defaultManager] requestImageDataForAsset:asset options:options resultHandler:^(NSData *imageData, NSString *dataUTI, UIImageOrientation orientation, NSDictionary *info) {
  575. NSError *error = nil;
  576. if ([dataUTI isEqualToString:@"public.heic"] && [CCUtility getFormatCompatibility]) {
  577. UIImage *image = [UIImage imageWithData:imageData];
  578. imageData = UIImageJPEGRepresentation(image, 1.0);
  579. NSString *fileNameJPEG = [[metadata.fileName lastPathComponent] stringByDeletingPathExtension];
  580. metadata.fileName = [fileNameJPEG stringByAppendingString:@".jpg"];
  581. metadata.fileNameView = metadata.fileName;
  582. // Change Metadata with new fileID, fileName, fileNameView
  583. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID] clearDateReadDirectoryID:metadata.directoryID];
  584. metadata.fileID = [metadata.directoryID stringByAppendingString:metadata.fileName];
  585. }
  586. tableMetadata *metadataForUpload = [[NCManageDatabase sharedInstance] addMetadata:[CCUtility insertFileSystemInMetadata:metadata]];
  587. [imageData writeToFile:[CCUtility getDirectoryProviderStorageFileID:metadataForUpload.fileID fileName:metadataForUpload.fileNameView] options:NSDataWritingAtomic error:&error];
  588. if (error) {
  589. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadataForUpload.fileID] clearDateReadDirectoryID:metadataForUpload.directoryID];
  590. if ([delegate respondsToSelector:@selector(uploadFileSuccessFailure:fileID:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  591. [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];
  592. }
  593. } else {
  594. // OOOOOK
  595. if ([CCUtility isFolderEncrypted:serverUrl account:_activeAccount] && [CCUtility isEndToEndEnabled:_activeAccount]) {
  596. [self e2eEncryptedFile:metadataForUpload serverUrl:serverUrl taskStatus:taskStatus];
  597. } else {
  598. [self uploadURLSessionMetadata:metadataForUpload serverUrl:serverUrl taskStatus:taskStatus];
  599. }
  600. }
  601. }];
  602. }
  603. // VIDEO
  604. if (asset.mediaType == PHAssetMediaTypeVideo) {
  605. PHVideoRequestOptions *options = [PHVideoRequestOptions new];
  606. options.networkAccessAllowed = YES;
  607. options.version = PHVideoRequestOptionsVersionOriginal;
  608. options.progressHandler = ^(double progress, NSError *error, BOOL *stop, NSDictionary *info) {
  609. NSLog(@"cacheAsset: %f", progress);
  610. if (error) {
  611. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID] clearDateReadDirectoryID:metadata.directoryID];
  612. if ([delegate respondsToSelector:@selector(uploadFileSuccessFailure:fileID:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  613. [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];
  614. }
  615. }
  616. };
  617. [[PHImageManager defaultManager] requestAVAssetForVideo:asset options:options resultHandler:^(AVAsset *asset, AVAudioMix *audioMix, NSDictionary *info) {
  618. if ([asset isKindOfClass:[AVURLAsset class]]) {
  619. NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:[CCUtility getDirectoryProviderStorageFileID:metadata.fileID fileName:metadata.fileNameView]];
  620. NSError *error = nil;
  621. [[NSFileManager defaultManager] removeItemAtURL:fileURL error:nil];
  622. [[NSFileManager defaultManager] copyItemAtURL:[(AVURLAsset *)asset URL] toURL:fileURL error:&error];
  623. if (error) {
  624. dispatch_async(dispatch_get_main_queue(), ^{
  625. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID] clearDateReadDirectoryID:metadata.directoryID];
  626. if ([delegate respondsToSelector:@selector(uploadFileSuccessFailure:fileID:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  627. [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];
  628. }
  629. });
  630. } else {
  631. dispatch_async(dispatch_get_main_queue(), ^{
  632. // create Metadata for Upload
  633. tableMetadata *metadataForUpload = [[NCManageDatabase sharedInstance] addMetadata:[CCUtility insertFileSystemInMetadata:metadata]];
  634. // OOOOOK
  635. if ([CCUtility isFolderEncrypted:serverUrl account:_activeAccount] && [CCUtility isEndToEndEnabled:_activeAccount]) {
  636. [self e2eEncryptedFile:metadataForUpload serverUrl:serverUrl taskStatus:taskStatus];
  637. } else {
  638. [self uploadURLSessionMetadata:metadataForUpload serverUrl:serverUrl taskStatus:taskStatus];
  639. }
  640. });
  641. }
  642. }
  643. }];
  644. }
  645. } else {
  646. // create Metadata for Upload
  647. tableMetadata *metadataForUpload = [[NCManageDatabase sharedInstance] addMetadata:[CCUtility insertFileSystemInMetadata:metadata]];
  648. // OOOOOK
  649. if ([CCUtility isFolderEncrypted:serverUrl account:_activeAccount] && [CCUtility isEndToEndEnabled:_activeAccount]) {
  650. [self e2eEncryptedFile:metadataForUpload serverUrl:serverUrl taskStatus:taskStatus];
  651. } else {
  652. [self uploadURLSessionMetadata:metadataForUpload serverUrl:serverUrl taskStatus:taskStatus];
  653. }
  654. }
  655. }
  656. - (void)e2eEncryptedFile:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl taskStatus:(NSInteger)taskStatus
  657. {
  658. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  659. NSString *errorMessage;
  660. NSString *fileNameIdentifier;
  661. NSString *e2eMetadata;
  662. [self encryptedE2EFile:metadata serverUrl:serverUrl account:_activeAccount user:_activeUser userID:_activeUserID password:_activePassword url:_activeUrl errorMessage:&errorMessage fileNameIdentifier:&fileNameIdentifier e2eMetadata:&e2eMetadata];
  663. if (errorMessage != nil || fileNameIdentifier == nil) {
  664. if ([[self getDelegate:metadata.fileID] respondsToSelector:@selector(uploadFileSuccessFailure:fileID:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  665. [[self getDelegate:metadata.fileID] uploadFileSuccessFailure:metadata.fileName fileID:metadata.fileID assetLocalIdentifier:metadata.assetLocalIdentifier serverUrl:serverUrl selector:metadata.sessionSelector errorMessage:errorMessage errorCode:k_CCErrorInternalError];
  666. }
  667. } else {
  668. dispatch_async(dispatch_get_main_queue(), ^{
  669. // Now the fileName is fileNameIdentifier && flag e2eEncrypted
  670. metadata.fileName = fileNameIdentifier;
  671. metadata.e2eEncrypted = YES;
  672. // Update Metadata
  673. tableMetadata *metadataEncrypted = [[NCManageDatabase sharedInstance] addMetadata:metadata];
  674. [self uploadURLSessionMetadata:metadataEncrypted serverUrl:serverUrl taskStatus:taskStatus];
  675. });
  676. }
  677. });
  678. }
  679. - (void)uploadURLSessionMetadata:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl taskStatus:(NSInteger)taskStatus
  680. {
  681. NSURL *url;
  682. NSMutableURLRequest *request;
  683. PHAsset *asset;
  684. NSError *error;
  685. // calculate and store file size
  686. NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:[CCUtility getDirectoryProviderStorageFileID:metadata.fileID fileName:metadata.fileName] error:&error];
  687. long long fileSize = [[fileAttributes objectForKey:NSFileSize] longLongValue];
  688. metadata.size = fileSize;
  689. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  690. url = [NSURL URLWithString:[[NSString stringWithFormat:@"%@/%@", serverUrl, metadata.fileName] encodeString:NSUTF8StringEncoding]];
  691. request = [NSMutableURLRequest requestWithURL:url];
  692. NSData *authData = [[NSString stringWithFormat:@"%@:%@", _activeUser, _activePassword] dataUsingEncoding:NSUTF8StringEncoding];
  693. NSString *authValue = [NSString stringWithFormat: @"Basic %@",[authData base64EncodedStringWithOptions:0]];
  694. [request setHTTPMethod:@"PUT"];
  695. [request setValue:authValue forHTTPHeaderField:@"Authorization"];
  696. [request setValue:[CCUtility getUserAgent] forHTTPHeaderField:@"User-Agent"];
  697. // Create Image for Upload
  698. #ifndef EXTENSION
  699. [CCGraphics createNewImageFrom:metadata.fileNameView fileID:metadata.fileID extension:[metadata.fileNameView pathExtension] size:@"m" imageForUpload:YES typeFile:metadata.typeFile writeImage:YES];
  700. #endif
  701. // Change date file upload with header : X-OC-Mtime (ctime assetLocalIdentifier) image/video
  702. if (metadata.assetLocalIdentifier) {
  703. PHFetchResult *result = [PHAsset fetchAssetsWithLocalIdentifiers:@[metadata.assetLocalIdentifier] options:nil];
  704. if (result.count) {
  705. asset = result[0];
  706. long dateFileCreation = [asset.creationDate timeIntervalSince1970];
  707. [request setValue:[NSString stringWithFormat:@"%ld", dateFileCreation] forHTTPHeaderField:@"X-OC-Mtime"];
  708. }
  709. }
  710. NSURLSession *sessionUpload;
  711. // NSURLSession
  712. if ([metadata.session isEqualToString:k_upload_session]) sessionUpload = [self sessionUpload];
  713. else if ([metadata.session isEqualToString:k_upload_session_wwan]) sessionUpload = [self sessionWWanUpload];
  714. else if ([metadata.session isEqualToString:k_upload_session_foreground]) sessionUpload = [self sessionUploadForeground];
  715. else if ([metadata.session isEqualToString:k_upload_session_extension]) sessionUpload = [self sessionUploadExtension];
  716. NSURLSessionUploadTask *uploadTask = [sessionUpload uploadTaskWithRequest:request fromFile:[NSURL fileURLWithPath:[CCUtility getDirectoryProviderStorageFileID:metadata.fileID fileName:metadata.fileName]]];
  717. // Error
  718. if (uploadTask == nil) {
  719. NSString *messageError = @"Serious internal error uploadTask not available";
  720. [[NCManageDatabase sharedInstance] setMetadataSession:metadata.session sessionError:messageError sessionSelector:nil sessionTaskIdentifier:k_taskIdentifierDone status:k_metadataStatusUploadError predicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID]];
  721. if ([[self getDelegate:metadata.fileID] respondsToSelector:@selector(uploadFileSuccessFailure:fileID:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  722. [[self getDelegate:metadata.fileID] uploadFileSuccessFailure:metadata.fileNameView fileID:metadata.fileID assetLocalIdentifier:metadata.assetLocalIdentifier serverUrl:serverUrl selector:metadata.sessionSelector errorMessage:messageError errorCode:k_CCErrorInternalError];
  723. }
  724. } else {
  725. // E2EE : CREATE AND SEND METADATA
  726. if ([CCUtility isFolderEncrypted:serverUrl account:_activeAccount] && [CCUtility isEndToEndEnabled:_activeAccount]) {
  727. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  728. // Send Metadata
  729. NSError *error = [[NCNetworkingEndToEnd sharedManager] sendEndToEndMetadataOnServerUrl:serverUrl fileNameRename:nil fileNameNewRename:nil account:_activeAccount user:_activeUser userID:_activeUserID password:_activePassword url:_activeUrl];
  730. dispatch_async(dispatch_get_main_queue(), ^{
  731. if (error) {
  732. [uploadTask cancel];
  733. NSString *messageError = [NSString stringWithFormat:@"%@ (%d)", error.localizedDescription, (int)error.code];
  734. [[NCManageDatabase sharedInstance] setMetadataSession:metadata.session sessionError:messageError sessionSelector:nil sessionTaskIdentifier:k_taskIdentifierDone status:k_metadataStatusUploadError predicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID]];
  735. if ([[self getDelegate:metadata.fileID] respondsToSelector:@selector(uploadFileSuccessFailure:fileID:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  736. [[self getDelegate:metadata.fileID] uploadFileSuccessFailure:metadata.fileNameView fileID:metadata.fileID assetLocalIdentifier:metadata.assetLocalIdentifier serverUrl:serverUrl selector:metadata.sessionSelector errorMessage:messageError errorCode:k_CCErrorInternalError];
  737. }
  738. } else {
  739. // Manage uploadTask cancel,suspend,resume
  740. if (taskStatus == k_taskStatusCancel) [uploadTask cancel];
  741. else if (taskStatus == k_taskStatusSuspend) [uploadTask suspend];
  742. else if (taskStatus == k_taskStatusResume) [uploadTask resume];
  743. // *** E2EE ***
  744. [[NCManageDatabase sharedInstance] setMetadataSession:metadata.session sessionError:@"" sessionSelector:nil sessionTaskIdentifier:uploadTask.taskIdentifier status:k_metadataStatusUploading predicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID]];
  745. NSLog(@"[LOG] Upload file %@ TaskIdentifier %lu", metadata.fileName, (unsigned long)uploadTask.taskIdentifier);
  746. NSString *fileID = metadata.fileID;
  747. NSString *account = metadata.account;
  748. dispatch_async(dispatch_get_main_queue(), ^{
  749. if ([[self getDelegate:fileID] respondsToSelector:@selector(uploadStart:account:task:serverUrl:)]) {
  750. [[self getDelegate:fileID] uploadStart:fileID account:account task:uploadTask serverUrl:serverUrl];
  751. }
  752. });
  753. }
  754. });
  755. });
  756. } else {
  757. // Manage uploadTask cancel,suspend,resume
  758. if (taskStatus == k_taskStatusCancel) [uploadTask cancel];
  759. else if (taskStatus == k_taskStatusSuspend) [uploadTask suspend];
  760. else if (taskStatus == k_taskStatusResume) [uploadTask resume];
  761. // *** PLAIN ***
  762. [[NCManageDatabase sharedInstance] setMetadataSession:metadata.session sessionError:@"" sessionSelector:nil sessionTaskIdentifier:uploadTask.taskIdentifier status:k_metadataStatusUploading predicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID]];
  763. NSLog(@"[LOG] Upload file %@ TaskIdentifier %lu", metadata.fileName, (unsigned long)uploadTask.taskIdentifier);
  764. NSString *fileID = metadata.fileID;
  765. NSString *account = metadata.account;
  766. dispatch_async(dispatch_get_main_queue(), ^{
  767. if ([[self getDelegate:fileID] respondsToSelector:@selector(uploadStart:account:task:serverUrl:)]) {
  768. [[self getDelegate:fileID] uploadStart:fileID account:account task:uploadTask serverUrl:serverUrl];
  769. }
  770. });
  771. }
  772. }
  773. }
  774. - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
  775. {
  776. NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)dataTask.response;
  777. if (httpResponse.statusCode >= 200 && httpResponse.statusCode < 300) {
  778. NSNumber *taskIdentifier = [NSNumber numberWithLong:dataTask.taskIdentifier];
  779. if (data)
  780. [_taskData setObject:[data copy] forKey:taskIdentifier];
  781. }
  782. }
  783. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend
  784. {
  785. NSString *url = [[[task currentRequest].URL absoluteString] stringByRemovingPercentEncoding];
  786. NSString *fileName = [url lastPathComponent];
  787. NSString *serverUrl = [self getServerUrlFromUrl:url];
  788. if (!serverUrl) return;
  789. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrl];
  790. if (!directoryID) return;
  791. if (totalBytesExpectedToSend < 1) {
  792. totalBytesExpectedToSend = totalBytesSent;
  793. }
  794. float progress = (float) totalBytesSent / (float)totalBytesExpectedToSend;
  795. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataInSessionFromFileName:fileName directoryID:directoryID];
  796. if (metadata) {
  797. NSDictionary* userInfo = @{@"fileID": (metadata.fileID), @"serverUrl": (serverUrl), @"status": ([NSNumber numberWithLong:k_metadataStatusInUpload]), @"progress": ([NSNumber numberWithFloat:progress]), @"totalBytes": ([NSNumber numberWithLongLong:totalBytesSent]), @"totalBytesExpected": ([NSNumber numberWithLongLong:totalBytesExpectedToSend])};
  798. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"NotificationProgressTask" object:nil userInfo:userInfo];
  799. }
  800. }
  801. - (void)uploadFileSuccessFailure:(tableMetadata *)metadata fileName:(NSString *)fileName fileID:(NSString *)fileID etag:(NSString *)etag date:(NSDate *)date serverUrl:(NSString *)serverUrl errorCode:(NSInteger)errorCode
  802. {
  803. NSString *tempFileID = metadata.fileID;
  804. NSString *tempSession = metadata.session;
  805. NSString *errorMessage = @"";
  806. BOOL isE2EEDirectory = false;
  807. // E2EE Directory ?
  808. if ([CCUtility isFolderEncrypted:serverUrl account:_activeAccount] && [CCUtility isEndToEndEnabled:_activeAccount]) {
  809. isE2EEDirectory = true;
  810. }
  811. // ERRORE
  812. if (errorCode != 0) {
  813. #ifndef EXTENSION
  814. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  815. [appDelegate.listProgressMetadata removeObjectForKey:metadata.fileID];
  816. #endif
  817. // Mark error only if not Cancelled Task
  818. if (errorCode == kCFURLErrorCancelled) {
  819. [[NSFileManager defaultManager] removeItemAtPath:[CCUtility getDirectoryProviderStorageFileID:tempFileID] error:nil];
  820. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", tempFileID] clearDateReadDirectoryID:metadata.directoryID];
  821. } else {
  822. [[NCManageDatabase sharedInstance] setMetadataSession:nil sessionError:[CCError manageErrorKCF:errorCode withNumberError:NO] sessionSelector:nil sessionTaskIdentifier:k_taskIdentifierDone status:k_metadataStatusUploadError predicate:[NSPredicate predicateWithFormat:@"fileID == %@", tempFileID]];
  823. }
  824. errorMessage = [CCError manageErrorKCF:errorCode withNumberError:YES];
  825. } else {
  826. // Replace Metadata
  827. metadata.date = date;
  828. if (isE2EEDirectory) {
  829. metadata.e2eEncrypted = true;
  830. } else {
  831. metadata.e2eEncrypted = false;
  832. }
  833. metadata.etag = etag;
  834. metadata.fileID = fileID;
  835. metadata.session = @"";
  836. metadata.sessionError = @"";
  837. metadata.sessionTaskIdentifier = k_taskIdentifierDone;
  838. metadata.status = k_metadataStatusNormal;
  839. metadata = [[NCManageDatabase sharedInstance] addMetadata:metadata];
  840. NSLog(@"[LOG] Insert new upload : %@ - fileID : %@", metadata.fileName, fileID);
  841. // remove tempFileID and adjust the directory provider storage
  842. if ([tempFileID isEqualToString:[metadata.directoryID stringByAppendingString:metadata.fileNameView]]) {
  843. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", tempFileID] clearDateReadDirectoryID:nil];
  844. // adjust file system Directory Provider Storage
  845. if ([tempSession isEqualToString:k_upload_session_extension]) {
  846. // this is for File Provider Extension [Apple Works and ... ?]
  847. [[NSFileManager defaultManager] copyItemAtPath:[NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryProviderStorage], tempFileID] toPath:[NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryProviderStorage], metadata.fileID] error:nil];
  848. } else {
  849. [[NSFileManager defaultManager] moveItemAtPath:[NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryProviderStorage], tempFileID] toPath:[NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryProviderStorage], metadata.fileID] error:nil];
  850. }
  851. }
  852. #ifndef EXTENSION
  853. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  854. [appDelegate.listProgressMetadata removeObjectForKey:metadata.fileID];
  855. // Hardcoded for add new Photos
  856. if ([metadata.typeFile isEqualToString:k_metadataTypeFile_image] || [metadata.typeFile isEqualToString:k_metadataTypeFile_video]) {
  857. [appDelegate.activePhotos.addMetadatasFromUpload addObject:metadata];
  858. }
  859. #endif
  860. // Local
  861. if (metadata.directory == NO)
  862. [[NCManageDatabase sharedInstance] addLocalFileWithMetadata:metadata];
  863. #ifndef EXTENSION
  864. // EXIF
  865. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image])
  866. [[CCExifGeo sharedInstance] setExifLocalTableEtag:metadata];
  867. // Create ICON
  868. if (metadata.directory == NO) {
  869. [CCGraphics createNewImageFrom:metadata.fileNameView fileID:metadata.fileID extension:[metadata.fileNameView pathExtension] size:@"m" imageForUpload:NO typeFile:metadata.typeFile writeImage:YES];
  870. }
  871. // Optimization
  872. if (([CCUtility getUploadAndRemovePhoto] || [metadata.sessionSelector isEqualToString:selectorUploadAutoUploadAll]) && [metadata.typeFile isEqualToString:k_metadataTypeFile_document] == NO && isE2EEDirectory == NO) {
  873. [[NSFileManager defaultManager] createFileAtPath:[CCUtility getDirectoryProviderStorageFileID:metadata.fileID fileName:metadata.fileNameView] contents:nil attributes:nil];
  874. }
  875. // Copy photo or video in the photo album for auto upload
  876. if ([metadata.assetLocalIdentifier length] > 0 && ([metadata.sessionSelector isEqualToString:selectorUploadAutoUpload] || [metadata.sessionSelector isEqualToString:selectorUploadFile])) {
  877. PHAsset *asset;
  878. PHFetchResult *result = [PHAsset fetchAssetsWithLocalIdentifiers:@[metadata.assetLocalIdentifier] options:nil];
  879. if(result.count){
  880. asset = result[0];
  881. [asset saveToAlbum:[NCBrandOptions sharedInstance].brand completionBlock:^(BOOL success) {
  882. if (success) NSLog(@"[LOG] Insert file %@ in %@", metadata.fileName, [NCBrandOptions sharedInstance].brand);
  883. else NSLog(@"[LOG] File %@ do not insert in %@", metadata.fileName, [NCBrandOptions sharedInstance].brand);
  884. }];
  885. }
  886. }
  887. #endif
  888. // Actvity
  889. [[NCManageDatabase sharedInstance] addActivityClient:metadata.fileNameView fileID:fileID action:k_activityDebugActionUpload selector:metadata.sessionSelector note:serverUrl type:k_activityTypeSuccess verbose:k_activityVerboseDefault activeUrl:_activeUrl];
  890. }
  891. // E2EE : UNLOCK
  892. if (isE2EEDirectory) {
  893. tableE2eEncryptionLock *tableLock = [[NCManageDatabase sharedInstance] getE2ETokenLockWithServerUrl:serverUrl];
  894. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  895. if (tableLock) {
  896. NSError *error = [[NCNetworkingEndToEnd sharedManager] unlockEndToEndFolderEncryptedOnServerUrl:serverUrl fileID:tableLock.fileID token:tableLock.token user:_activeUser userID:_activeUserID password:_activePassword url:_activeUrl];
  897. if (error) {
  898. #ifndef EXTENSION
  899. dispatch_async(dispatch_get_main_queue(), ^{
  900. [(AppDelegate *)[[UIApplication sharedApplication] delegate] messageNotification:@"_e2e_error_unlock_" description:error.localizedDescription visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  901. });
  902. #endif
  903. }
  904. } else {
  905. NSLog(@"Error unlock not found");
  906. }
  907. dispatch_async(dispatch_get_main_queue(), ^{
  908. if ([[self getDelegate:tempFileID] respondsToSelector:@selector(uploadFileSuccessFailure:fileID:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  909. [[self getDelegate:tempFileID] uploadFileSuccessFailure:metadata.fileName fileID:metadata.fileID assetLocalIdentifier:metadata.assetLocalIdentifier serverUrl:serverUrl selector:metadata.sessionSelector errorMessage:errorMessage errorCode:errorCode];
  910. }
  911. });
  912. });
  913. } else {
  914. if ([[self getDelegate:tempFileID] respondsToSelector:@selector(uploadFileSuccessFailure:fileID:assetLocalIdentifier:serverUrl:selector:errorMessage:errorCode:)]) {
  915. [[self getDelegate:tempFileID] uploadFileSuccessFailure:metadata.fileName fileID:metadata.fileID assetLocalIdentifier:metadata.assetLocalIdentifier serverUrl:serverUrl selector:metadata.sessionSelector errorMessage:errorMessage errorCode:errorCode];
  916. }
  917. }
  918. }
  919. #pragma --------------------------------------------------------------------------------------------
  920. #pragma mark ===== Utility =====
  921. #pragma --------------------------------------------------------------------------------------------
  922. - (id)getDelegate:(NSString *)fileID
  923. {
  924. id delegate = [_delegates objectForKey:fileID];
  925. if (delegate)
  926. return delegate;
  927. else
  928. return self.delegate;
  929. }
  930. - (NSString *)getServerUrlFromUrl:(NSString *)url
  931. {
  932. NSString *fileName = [url lastPathComponent];
  933. url = [url stringByReplacingOccurrencesOfString:[@"/" stringByAppendingString:fileName] withString:@""];
  934. return url;
  935. }
  936. #pragma --------------------------------------------------------------------------------------------
  937. #pragma mark ===== E2EE End To End Encryption =====
  938. #pragma --------------------------------------------------------------------------------------------
  939. // E2EE
  940. - (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
  941. {
  942. __block NSError *error;
  943. NSString *key;
  944. NSString *initializationVector;
  945. NSString *authenticationTag;
  946. NSString *metadataKey;
  947. NSInteger metadataKeyIndex;
  948. // Verify File Size
  949. NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:[CCUtility getDirectoryProviderStorageFileID:metadata.fileID fileName:metadata.fileNameView] error:&error];
  950. NSNumber *fileSizeNumber = [fileAttributes objectForKey:NSFileSize];
  951. long long fileSize = [fileSizeNumber longLongValue];
  952. if (fileSize > k_max_filesize_E2E) {
  953. // Error for uploadFileFailure
  954. *errorMessage = @"E2E Error file too big";
  955. return;
  956. }
  957. // if new file upload [directoryID + fileName] create a new encrypted filename
  958. if ([metadata.fileID isEqualToString:[metadata.directoryID stringByAppendingString:metadata.fileNameView]]) {
  959. *fileNameIdentifier = [CCUtility generateRandomIdentifier];
  960. } else {
  961. *fileNameIdentifier = metadata.fileName;
  962. }
  963. // Write to DB
  964. if ([[NCEndToEndEncryption sharedManager] encryptFileName:metadata.fileNameView fileNameIdentifier:*fileNameIdentifier directory:[CCUtility getDirectoryProviderStorageFileID:metadata.fileID] key:&key initializationVector:&initializationVector authenticationTag:&authenticationTag]) {
  965. tableE2eEncryption *object = [[NCManageDatabase sharedInstance] getE2eEncryptionWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", _activeAccount, serverUrl]];
  966. if (object) {
  967. metadataKey = object.metadataKey;
  968. metadataKeyIndex = object.metadataKeyIndex;
  969. } else {
  970. metadataKey = [[[NCEndToEndEncryption sharedManager] generateKey:16] base64EncodedStringWithOptions:0]; // AES_KEY_128_LENGTH
  971. metadataKeyIndex = 0;
  972. }
  973. tableE2eEncryption *addObject = [tableE2eEncryption new];
  974. addObject.account = _activeAccount;
  975. addObject.authenticationTag = authenticationTag;
  976. addObject.fileName = metadata.fileNameView;
  977. addObject.fileNameIdentifier = *fileNameIdentifier;
  978. addObject.fileNamePath = [CCUtility returnFileNamePathFromFileName:metadata.fileNameView serverUrl:serverUrl activeUrl:_activeUrl];
  979. addObject.key = key;
  980. addObject.initializationVector = initializationVector;
  981. addObject.metadataKey = metadataKey;
  982. addObject.metadataKeyIndex = metadataKeyIndex;
  983. CFStringRef UTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef)[metadata.fileNameView pathExtension], NULL);
  984. CFStringRef mimeTypeRef = UTTypeCopyPreferredTagWithClass (UTI, kUTTagClassMIMEType);
  985. if (mimeTypeRef) {
  986. addObject.mimeType = (__bridge NSString *)mimeTypeRef;
  987. } else {
  988. addObject.mimeType = @"application/octet-stream";
  989. }
  990. addObject.serverUrl = serverUrl;
  991. addObject.version = [[NCManageDatabase sharedInstance] getEndToEndEncryptionVersion];
  992. // Get the last metadata
  993. NSString *metadata;
  994. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", account, serverUrl]];
  995. error = [[NCNetworkingEndToEnd sharedManager] getEndToEndMetadata:&metadata fileID:directory.fileID user:user userID:userID password:password url:url];
  996. if (error == nil) {
  997. if ([[NCEndToEndMetadata sharedInstance] decoderMetadata:metadata privateKey:[CCUtility getEndToEndPrivateKey:account] serverUrl:serverUrl account:account url:url] == false) {
  998. *errorMessage = NSLocalizedString(@"_e2e_error_decode_metadata_", nil);
  999. return;
  1000. }
  1001. }
  1002. *e2eMetadata = metadata;
  1003. // write new record e2ee
  1004. if([[NCManageDatabase sharedInstance] addE2eEncryption:addObject] == NO)
  1005. *errorMessage = NSLocalizedString(@"_e2e_error_create_encrypted_", nil);
  1006. } else {
  1007. *errorMessage = NSLocalizedString(@"_e2e_error_create_encrypted_", nil);
  1008. }
  1009. }
  1010. @end
  1011. #pragma --------------------------------------------------------------------------------------------
  1012. #pragma mark ===== CCMetadataNet =====
  1013. #pragma --------------------------------------------------------------------------------------------
  1014. @implementation CCMetadataNet
  1015. - (id)init
  1016. {
  1017. self = [super init];
  1018. self.priority = NSOperationQueuePriorityNormal;
  1019. return self;
  1020. }
  1021. - (id)initWithAccount:(NSString *)withAccount
  1022. {
  1023. self = [self init];
  1024. if (self) {
  1025. _account = withAccount;
  1026. }
  1027. return self;
  1028. }
  1029. - (id)copyWithZone: (NSZone *) zone
  1030. {
  1031. CCMetadataNet *metadataNet = [[CCMetadataNet allocWithZone: zone] init];
  1032. [metadataNet setAccount: self.account];
  1033. [metadataNet setAction: self.action];
  1034. [metadataNet setContentType: self.contentType];
  1035. [metadataNet setDate: self.date];
  1036. [metadataNet setDelegate: self.delegate];
  1037. [metadataNet setDepth: self.depth];
  1038. [metadataNet setDirectory: self.directory];
  1039. [metadataNet setDirectoryID: self.directoryID];
  1040. [metadataNet setDirectoryIDTo: self.directoryIDTo];
  1041. [metadataNet setEncryptedMetadata: self.encryptedMetadata];
  1042. [metadataNet setEtag:self.etag];
  1043. [metadataNet setExpirationTime: self.expirationTime];
  1044. [metadataNet setFileID: self.fileID];
  1045. [metadataNet setFileName: self.fileName];
  1046. [metadataNet setFileNameTo: self.fileNameTo];
  1047. [metadataNet setFileNameView: self.fileNameView];
  1048. [metadataNet setKey: self.key];
  1049. [metadataNet setKeyCipher: self.keyCipher];
  1050. [metadataNet setOptionAny: self.optionAny];
  1051. [metadataNet setOptionString: self.optionString];
  1052. [metadataNet setPassword: self.password];
  1053. [metadataNet setPriority: self.priority];
  1054. [metadataNet setServerUrl: self.serverUrl];
  1055. [metadataNet setServerUrlTo: self.serverUrlTo];
  1056. [metadataNet setSelector: self.selector];
  1057. [metadataNet setShare: self.share];
  1058. [metadataNet setShareeType: self.shareeType];
  1059. [metadataNet setSharePermission: self.sharePermission];
  1060. [metadataNet setSize: self.size];
  1061. return metadataNet;
  1062. }
  1063. @end