CCNetworking.m 72 KB

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