CCNetworking.m 71 KB

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