CCNetworking.m 83 KB

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