CCNetworking.m 76 KB

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