CCNetworking.m 101 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915
  1. //
  2. // CCNetworking.m
  3. // Crypto Cloud Technology Nextcloud
  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 "AppDelegate.h"
  25. #import "CCCertificate.h"
  26. #import "NSDate+ISO8601.h"
  27. #import "NSString+Encode.h"
  28. #import "NCBridgeSwift.h"
  29. @interface CCNetworking ()
  30. {
  31. NSMutableDictionary *_taskData;
  32. NSString *_activeAccount;
  33. NSString *_activePassword;
  34. NSString *_activeUser;
  35. NSString *_activeUrl;
  36. NSString *_directoryUser;
  37. }
  38. @end
  39. @implementation CCNetworking
  40. + (CCNetworking *)sharedNetworking {
  41. static CCNetworking *sharedNetworking;
  42. @synchronized(self)
  43. {
  44. if (!sharedNetworking) {
  45. sharedNetworking = [[CCNetworking alloc] init];
  46. }
  47. return sharedNetworking;
  48. }
  49. }
  50. - (id)init
  51. {
  52. self = [super init];
  53. _taskData = [[NSMutableDictionary alloc] init];
  54. _delegates = [[NSMutableDictionary alloc] init];
  55. // Initialization Sessions
  56. [self sessionDownload];
  57. [self sessionDownloadForeground];
  58. [self sessionWWanDownload];
  59. [self sessionUpload];
  60. [self sessionUploadForeground];
  61. [self sessionWWanUpload];
  62. [self sharedOCCommunication];
  63. [self settingAccount];
  64. return self;
  65. }
  66. - (void)settingAccount
  67. {
  68. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountActive];
  69. _activeAccount = tableAccount.account;
  70. _activePassword = tableAccount.password;
  71. _activeUser = tableAccount.user;
  72. _activeUrl = tableAccount.url;
  73. _directoryUser = [CCUtility getDirectoryActiveUser:_activeUser activeUrl:_activeUrl];
  74. }
  75. #pragma --------------------------------------------------------------------------------------------
  76. #pragma mark ===== Session =====
  77. #pragma --------------------------------------------------------------------------------------------
  78. - (NSURLSession *)sessionDownload
  79. {
  80. static NSURLSession *sessionDownload = nil;
  81. if (sessionDownload == nil) {
  82. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:k_download_session];
  83. configuration.allowsCellularAccess = YES;
  84. configuration.sessionSendsLaunchEvents = YES;
  85. configuration.discretionary = NO;
  86. configuration.HTTPMaximumConnectionsPerHost = 1;
  87. configuration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  88. sessionDownload = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
  89. sessionDownload.sessionDescription = k_download_session;
  90. }
  91. return sessionDownload;
  92. }
  93. - (NSURLSession *)sessionDownloadForeground
  94. {
  95. static NSURLSession *sessionDownloadForeground = nil;
  96. if (sessionDownloadForeground == nil) {
  97. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
  98. configuration.allowsCellularAccess = YES;
  99. configuration.discretionary = NO;
  100. configuration.HTTPMaximumConnectionsPerHost = 1;
  101. configuration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  102. sessionDownloadForeground = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
  103. sessionDownloadForeground.sessionDescription = k_download_session_foreground;
  104. }
  105. return sessionDownloadForeground;
  106. }
  107. - (NSURLSession *)sessionWWanDownload
  108. {
  109. static NSURLSession *sessionWWanDownload = nil;
  110. if (sessionWWanDownload == nil) {
  111. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:k_download_session_wwan];
  112. configuration.allowsCellularAccess = NO;
  113. configuration.sessionSendsLaunchEvents = YES;
  114. configuration.discretionary = NO;
  115. configuration.HTTPMaximumConnectionsPerHost = 1;
  116. configuration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  117. sessionWWanDownload = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
  118. sessionWWanDownload.sessionDescription = k_download_session_wwan;
  119. }
  120. return sessionWWanDownload;
  121. }
  122. - (NSURLSession *)sessionUpload
  123. {
  124. static NSURLSession *sessionUpload = nil;
  125. if (sessionUpload == nil) {
  126. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:k_upload_session];
  127. configuration.allowsCellularAccess = YES;
  128. configuration.sessionSendsLaunchEvents = YES;
  129. configuration.discretionary = NO;
  130. configuration.HTTPMaximumConnectionsPerHost = 1;
  131. configuration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  132. sessionUpload = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
  133. sessionUpload.sessionDescription = k_upload_session;
  134. }
  135. return sessionUpload;
  136. }
  137. - (NSURLSession *)sessionUploadForeground
  138. {
  139. static NSURLSession *sessionUploadForeground;
  140. if (sessionUploadForeground == nil) {
  141. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
  142. configuration.allowsCellularAccess = YES;
  143. configuration.discretionary = NO;
  144. configuration.HTTPMaximumConnectionsPerHost = 1;
  145. configuration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  146. sessionUploadForeground = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
  147. sessionUploadForeground.sessionDescription = k_upload_session_foreground;
  148. }
  149. return sessionUploadForeground;
  150. }
  151. - (NSURLSession *)sessionWWanUpload
  152. {
  153. static NSURLSession *sessionWWanUpload = nil;
  154. if (sessionWWanUpload == nil) {
  155. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:k_upload_session_wwan];
  156. configuration.allowsCellularAccess = NO;
  157. configuration.sessionSendsLaunchEvents = YES;
  158. configuration.discretionary = NO;
  159. configuration.HTTPMaximumConnectionsPerHost = 1;
  160. configuration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  161. sessionWWanUpload = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
  162. sessionWWanUpload.sessionDescription = k_upload_session_wwan;
  163. }
  164. return sessionWWanUpload;
  165. }
  166. - (OCCommunication *)sharedOCCommunication
  167. {
  168. static OCCommunication* sharedOCCommunication = nil;
  169. if (sharedOCCommunication == nil)
  170. {
  171. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
  172. configuration.allowsCellularAccess = YES;
  173. configuration.discretionary = NO;
  174. configuration.HTTPMaximumConnectionsPerHost = k_maxConcurrentOperation;
  175. configuration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
  176. OCURLSessionManager *networkSessionManager = [[OCURLSessionManager alloc] initWithSessionConfiguration:configuration];
  177. [networkSessionManager.operationQueue setMaxConcurrentOperationCount: k_maxConcurrentOperation];
  178. networkSessionManager.responseSerializer = [AFHTTPResponseSerializer serializer];
  179. sharedOCCommunication = [[OCCommunication alloc] initWithUploadSessionManager:nil andDownloadSessionManager:nil andNetworkSessionManager:networkSessionManager];
  180. }
  181. return sharedOCCommunication;
  182. }
  183. - (NSURLSession *)getSessionfromSessionDescription:(NSString *)sessionDescription
  184. {
  185. if ([sessionDescription isEqualToString:k_download_session]) return [self sessionDownload];
  186. if ([sessionDescription isEqualToString:k_download_session_foreground]) return [self sessionDownloadForeground];
  187. if ([sessionDescription isEqualToString:k_download_session_wwan]) return [self sessionWWanDownload];
  188. if ([sessionDescription isEqualToString:k_upload_session]) return [self sessionUpload];
  189. if ([sessionDescription isEqualToString:k_upload_session_foreground]) return [self sessionUploadForeground];
  190. if ([sessionDescription isEqualToString:k_upload_session_wwan]) return [self sessionWWanUpload];
  191. return nil;
  192. }
  193. - (void)invalidateAndCancelAllSession
  194. {
  195. [[self sessionDownload] invalidateAndCancel];
  196. [[self sessionDownloadForeground] invalidateAndCancel];
  197. [[self sessionWWanDownload] invalidateAndCancel];
  198. [[self sessionUpload] invalidateAndCancel];
  199. [[self sessionUploadForeground] invalidateAndCancel];
  200. [[self sessionWWanUpload] invalidateAndCancel];
  201. }
  202. - (void)settingSessionsDownload:(BOOL)download upload:(BOOL)upload taskStatus:(NSInteger)taskStatus activeAccount:(NSString *)activeAccount activeUser:(NSString *)activeUser activeUrl:(NSString *)activeUrl
  203. {
  204. if (download) {
  205. [[self sessionDownload] getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  206. for (NSURLSessionTask *task in downloadTasks)
  207. if (taskStatus == k_taskStatusCancel) [task cancel];
  208. else if (taskStatus == k_taskStatusSuspend) [task suspend];
  209. else if (taskStatus == k_taskStatusResume) [task resume];
  210. }];
  211. [[self sessionDownloadForeground] getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  212. for (NSURLSessionTask *task in downloadTasks)
  213. if (taskStatus == k_taskStatusCancel) [task cancel];
  214. else if (taskStatus == k_taskStatusSuspend) [task suspend];
  215. else if (taskStatus == k_taskStatusResume) [task resume];
  216. }];
  217. [[self sessionWWanDownload] getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  218. for (NSURLSessionTask *task in downloadTasks)
  219. if (taskStatus == k_taskStatusCancel) [task cancel];
  220. else if (taskStatus == k_taskStatusSuspend) [task suspend];
  221. else if (taskStatus == k_taskStatusResume) [task resume];
  222. }];
  223. }
  224. if (upload) {
  225. [[self sessionUpload] getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  226. for (NSURLSessionTask *task in uploadTasks)
  227. if (taskStatus == k_taskStatusCancel)[task cancel];
  228. else if (taskStatus == k_taskStatusSuspend) [task suspend];
  229. else if (taskStatus == k_taskStatusResume) [task resume];
  230. }];
  231. [[self sessionUploadForeground] getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  232. for (NSURLSessionTask *task in uploadTasks)
  233. if (taskStatus == k_taskStatusCancel) [task cancel];
  234. else if (taskStatus == k_taskStatusSuspend) [task suspend];
  235. else if (taskStatus == k_taskStatusResume) [task resume];
  236. }];
  237. [[self sessionWWanUpload] getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  238. for (NSURLSessionTask *task in uploadTasks)
  239. if (taskStatus == k_taskStatusCancel) [task cancel];
  240. else if (taskStatus == k_taskStatusSuspend) [task suspend];
  241. else if (taskStatus == k_taskStatusResume) [task resume];
  242. }];
  243. }
  244. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 3 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  245. if (download && taskStatus == k_taskStatusCancel) {
  246. [[NCManageDatabase sharedInstance] setMetadataSession:@"" sessionError:@"" sessionSelector:@"" sessionSelectorPost:@"" sessionTaskIdentifier:k_taskIdentifierDone sessionTaskIdentifierPlist:k_taskIdentifierDone predicate:[NSPredicate predicateWithFormat:@"account = %@ AND session CONTAINS 'download'", _activeAccount]];
  247. }
  248. if (upload && taskStatus == k_taskStatusCancel) {
  249. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"session CONTAINS 'upload'"] clearDateReadDirectoryID:nil];
  250. // File System
  251. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  252. [CCUtility removeAllFileID_UPLOAD_ActiveUser:activeUser activeUrl:activeUrl];
  253. });
  254. }
  255. });
  256. }
  257. - (void)settingSession:(NSString *)sessionDescription sessionTaskIdentifier:(NSUInteger)sessionTaskIdentifier taskStatus:(NSInteger)taskStatus
  258. {
  259. NSURLSession *session = [self getSessionfromSessionDescription:sessionDescription];
  260. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  261. if ([sessionDescription containsString:@"download"])
  262. for (NSURLSessionTask *task in downloadTasks)
  263. if (task.taskIdentifier == sessionTaskIdentifier) {
  264. if (taskStatus == k_taskStatusCancel) [task cancel];
  265. else if (taskStatus == k_taskStatusSuspend) [task suspend];
  266. else if (taskStatus == k_taskStatusResume) [task resume];
  267. }
  268. if ([sessionDescription containsString:@"upload"])
  269. for (NSURLSessionTask *task in uploadTasks)
  270. if (task.taskIdentifier == sessionTaskIdentifier) {
  271. if (taskStatus == k_taskStatusCancel) [task cancel];
  272. else if (taskStatus == k_taskStatusSuspend) [task suspend];
  273. else if (taskStatus == k_taskStatusResume) [task resume];
  274. }
  275. }];
  276. }
  277. #pragma --------------------------------------------------------------------------------------------
  278. #pragma mark ===== URLSession download/upload =====
  279. #pragma --------------------------------------------------------------------------------------------
  280. - (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler
  281. {
  282. // The pinnning check
  283. if ([[CCCertificate sharedManager] checkTrustedChallenge:challenge]) {
  284. completionHandler(NSURLSessionAuthChallengeUseCredential, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]);
  285. } else {
  286. completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
  287. }
  288. }
  289. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
  290. {
  291. NSString *url = [[[task currentRequest].URL absoluteString] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  292. if (!url)
  293. return;
  294. NSString *fileName = [url lastPathComponent];
  295. NSString *serverUrl = [self getServerUrlFromUrl:url];
  296. if (!serverUrl) return;
  297. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrl];
  298. if (!directoryID) return;
  299. tableMetadata *metadata;
  300. NSInteger errorCode;
  301. NSDate *date = [NSDate date];
  302. NSDateFormatter *dateFormatter = [NSDateFormatter new];
  303. NSLocale *enUSPOSIXLocale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
  304. [dateFormatter setLocale:enUSPOSIXLocale];
  305. [dateFormatter setDateFormat:@"EEE, dd MMM y HH:mm:ss zzz"];
  306. NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)task.response;
  307. if (httpResponse.statusCode >= 200 && httpResponse.statusCode < 300) {
  308. errorCode = error.code;
  309. } else {
  310. if (httpResponse.statusCode > 0)
  311. errorCode = httpResponse.statusCode;
  312. else
  313. errorCode = error.code;
  314. // Request trusted certificated
  315. if (errorCode == NSURLErrorServerCertificateUntrusted)
  316. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
  317. }
  318. // ----------------------- DOWNLOAD -----------------------
  319. if ([task isKindOfClass:[NSURLSessionDownloadTask class]]) {
  320. metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"session = %@ AND (sessionTaskIdentifier = %i OR sessionTaskIdentifierPlist = %i)",session.sessionDescription, task.taskIdentifier, task.taskIdentifier]];
  321. if (!metadata)
  322. metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"directoryID = %@ AND (fileName = %@ OR fileNameData = %@)", directoryID, fileName, fileName]];
  323. if (metadata) {
  324. NSString *etag = metadata.etag;
  325. NSString *fileID = metadata.fileID;
  326. NSDictionary *fields = [httpResponse allHeaderFields];
  327. if (errorCode == 0) {
  328. etag = [CCUtility removeForbiddenCharactersFileSystem:[fields objectForKey:@"OC-ETag"]];
  329. NSString *dateString = [fields objectForKey:@"Date"];
  330. if (![dateFormatter getObjectValue:&date forString:dateString range:nil error:&error]) {
  331. NSLog(@"Date '%@' could not be parsed: %@", dateString, error);
  332. date = [NSDate date];
  333. }
  334. }
  335. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, task, nil];
  336. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  337. if (fileName.length > 0 && serverUrl.length > 0)
  338. [self downloadFileSuccessFailure:fileName fileID:metadata.fileID etag:etag date:date serverUrl:serverUrl selector:metadata.sessionSelector selectorPost:metadata.sessionSelectorPost errorCode:errorCode];
  339. } else {
  340. NSLog(@"[LOG] Remove record ? : metadata not found %@", url);
  341. dispatch_async(dispatch_get_main_queue(), ^{
  342. if ([self.delegate respondsToSelector:@selector(downloadFileFailure:serverUrl:selector:message:errorCode:)])
  343. [self.delegate downloadFileFailure:@"" serverUrl:serverUrl selector:@"" message:@"" errorCode:k_CCErrorInternalError];
  344. });
  345. }
  346. }
  347. // ------------------------ UPLOAD -----------------------
  348. if ([task isKindOfClass:[NSURLSessionUploadTask class]]) {
  349. metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"session = %@ AND (sessionTaskIdentifier = %i OR sessionTaskIdentifierPlist = %i)",session.sessionDescription, task.taskIdentifier, task.taskIdentifier]];
  350. if (!metadata)
  351. metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"directoryID = %@ AND (fileName = %@ OR fileNameData = %@)", directoryID, fileName, fileName]];
  352. if (metadata) {
  353. NSDictionary *fields = [httpResponse allHeaderFields];
  354. NSString *fileID = metadata.fileID;
  355. NSString *etag = metadata.etag;
  356. if (errorCode == 0) {
  357. fileID = [CCUtility removeForbiddenCharactersFileSystem:[fields objectForKey:@"OC-FileId"]];
  358. etag = [CCUtility removeForbiddenCharactersFileSystem:[fields objectForKey:@"OC-ETag"]];
  359. NSString *dateString = [fields objectForKey:@"Date"];
  360. if (dateString) {
  361. if (![dateFormatter getObjectValue:&date forString:dateString range:nil error:&error]) {
  362. NSLog(@"Date '%@' could not be parsed: %@", dateString, error);
  363. date = [NSDate date];
  364. }
  365. } else {
  366. date = [NSDate date];
  367. }
  368. }
  369. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, task, nil];
  370. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  371. if (fileName.length > 0 && fileID.length > 0 && serverUrl.length > 0)
  372. [self uploadFileSuccessFailure:metadata fileName:fileName fileID:fileID etag:etag date:date serverUrl:serverUrl errorCode:errorCode];
  373. } else {
  374. NSLog(@"[LOG] Remove record ? : metadata not found %@", url);
  375. dispatch_async(dispatch_get_main_queue(), ^{
  376. if ([self.delegate respondsToSelector:@selector(uploadFileFailure:fileID:serverUrl:selector:message:errorCode:)])
  377. [self.delegate uploadFileFailure:nil fileID:@"" serverUrl:serverUrl selector:@"" message:@"" errorCode:k_CCErrorInternalError];
  378. });
  379. }
  380. }
  381. }
  382. #pragma --------------------------------------------------------------------------------------------
  383. #pragma mark ===== Download =====
  384. #pragma --------------------------------------------------------------------------------------------
  385. - (void)downloadFile:(NSString *)fileID serverUrl:(NSString *)serverUrl downloadData:(BOOL)downloadData downloadPlist:(BOOL)downloadPlist selector:(NSString *)selector selectorPost:(NSString *)selectorPost session:(NSString *)session taskStatus:(NSInteger)taskStatus delegate:(id)delegate
  386. {
  387. // add delegate
  388. [_delegates setObject:delegate forKey:fileID];
  389. if (fileID.length == 0) {
  390. dispatch_async(dispatch_get_main_queue(), ^{
  391. if ([[self getDelegate:fileID] respondsToSelector:@selector(downloadFileFailure:serverUrl:selector:message:errorCode:)])
  392. [[self getDelegate:fileID] downloadFileFailure:fileID serverUrl:serverUrl selector:selector message:NSLocalizedStringFromTable(@"_file_folder_not_exists_", @"Error", nil) errorCode:kOCErrorServerPathNotFound];
  393. });
  394. return;
  395. }
  396. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  397. if (!metadata) {
  398. dispatch_async(dispatch_get_main_queue(), ^{
  399. if ([[self getDelegate:fileID] respondsToSelector:@selector(downloadFileFailure:serverUrl:selector:message:errorCode:)])
  400. [[self getDelegate:fileID] downloadFileFailure:fileID serverUrl:serverUrl selector:selector message:NSLocalizedStringFromTable(@"_file_folder_not_exists_", @"Error", nil) errorCode:kOCErrorServerPathNotFound];
  401. });
  402. return;
  403. }
  404. if (downloadData) {
  405. // it's in download
  406. tableMetadata *result = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@ AND session CONTAINS 'download' AND sessionTaskIdentifier >= 0", _activeAccount, metadata.fileID]];
  407. if (result) {
  408. dispatch_async(dispatch_get_main_queue(), ^{
  409. if ([[self getDelegate:fileID] respondsToSelector:@selector(downloadFileFailure:serverUrl:selector:message:errorCode:)])
  410. [[self getDelegate:fileID] downloadFileFailure:fileID serverUrl:serverUrl selector:selector message:@"File already in download" errorCode:k_CCErrorFileAlreadyInDownload];
  411. });
  412. return;
  413. }
  414. // File exists ?
  415. tableLocalFile *localfile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadata.fileID]];
  416. if (localfile != nil && [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, metadata.fileID]]) {
  417. [[NCManageDatabase sharedInstance] setMetadataSession:@"" sessionError:@"" sessionSelector:@"" sessionSelectorPost:@"" sessionTaskIdentifier:k_taskIdentifierDone sessionTaskIdentifierPlist:k_taskIdentifierDone predicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadata.fileID]];
  418. dispatch_async(dispatch_get_main_queue(), ^{
  419. if ([[self getDelegate:metadata.fileID] respondsToSelector:@selector(downloadFileSuccess:serverUrl:selector:selectorPost:)])
  420. [[self getDelegate:metadata.fileID] downloadFileSuccess:metadata.fileID serverUrl:serverUrl selector:selector selectorPost:selectorPost];
  421. });
  422. return;
  423. }
  424. [[NCManageDatabase sharedInstance] setMetadataSession:session sessionError:@"" sessionSelector:selector sessionSelectorPost:selectorPost sessionTaskIdentifier:k_taskIdentifierNULL sessionTaskIdentifierPlist:k_taskIdentifierNULL predicate:[NSPredicate predicateWithFormat:@"fileID = %@",metadata.fileID]];
  425. [self downloaURLSession:metadata.fileNameData fileNamePrint:metadata.fileNamePrint serverUrl:serverUrl fileID:metadata.fileID session:session taskStatus:taskStatus selector:selector];
  426. }
  427. if (downloadPlist) {
  428. tableMetadata *result = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@ AND session CONTAINS 'download' AND sessionTaskIdentifierPlist >= 0", metadata.fileID]];
  429. // it's in download
  430. if (result) {
  431. dispatch_async(dispatch_get_main_queue(), ^{
  432. if ([[self getDelegate:fileID] respondsToSelector:@selector(downloadFileFailure:serverUrl:selector:message:errorCode:)])
  433. [[self getDelegate:fileID] downloadFileFailure:fileID serverUrl:serverUrl selector:selector message:@"File already in download" errorCode:k_CCErrorFileAlreadyInDownload];
  434. });
  435. return;
  436. }
  437. [[NCManageDatabase sharedInstance] setMetadataSession:session sessionError:@"" sessionSelector:selector sessionSelectorPost:selectorPost sessionTaskIdentifier:k_taskIdentifierNULL sessionTaskIdentifierPlist:k_taskIdentifierNULL predicate:[NSPredicate predicateWithFormat:@"fileID = %@",metadata.fileID]];
  438. [self downloaURLSession:metadata.fileName fileNamePrint:metadata.fileNamePrint serverUrl:serverUrl fileID:metadata.fileID session:session taskStatus:taskStatus selector:selector];
  439. }
  440. }
  441. - (void)downloaURLSession:(NSString *)fileName fileNamePrint:(NSString *)fileNamePrint serverUrl:(NSString *)serverUrl fileID:(NSString *)fileID session:(NSString *)session taskStatus:(NSInteger)taskStatus selector:(NSString *)selector
  442. {
  443. NSURLSession *sessionDownload;
  444. NSURL *url;
  445. NSMutableURLRequest *request;
  446. NSString *serverFileUrl = [[NSString stringWithFormat:@"%@/%@", serverUrl, fileName] encodeString:NSUTF8StringEncoding];
  447. url = [NSURL URLWithString:serverFileUrl];
  448. request = [NSMutableURLRequest requestWithURL:url];
  449. NSData *authData = [[NSString stringWithFormat:@"%@:%@", _activeUser, _activePassword] dataUsingEncoding:NSUTF8StringEncoding];
  450. NSString *authValue = [NSString stringWithFormat: @"Basic %@",[authData base64EncodedStringWithOptions:0]];
  451. [request setValue:authValue forHTTPHeaderField:@"Authorization"];
  452. if ([session isEqualToString:k_download_session]) sessionDownload = [self sessionDownload];
  453. else if ([session isEqualToString:k_download_session_foreground]) sessionDownload = [self sessionDownloadForeground];
  454. else if ([session isEqualToString:k_download_session_wwan]) sessionDownload = [self sessionWWanDownload];
  455. NSURLSessionDownloadTask *downloadTask = [sessionDownload downloadTaskWithRequest:request];
  456. if (downloadTask == nil) {
  457. NSUInteger sessionTaskIdentifier = k_taskIdentifierNULL;
  458. NSUInteger sessionTaskIdentifierPlist = k_taskIdentifierNULL;
  459. if ([CCUtility isFileNotCryptated:fileName] || [CCUtility isCryptoString:fileName]) sessionTaskIdentifier = k_taskIdentifierError;
  460. if ([CCUtility isCryptoPlistString:fileName]) sessionTaskIdentifierPlist = k_taskIdentifierError;
  461. [[NCManageDatabase sharedInstance] setMetadataSession:nil sessionError:[NSString stringWithFormat:@"%@", @k_CCErrorTaskNil] sessionSelector:nil sessionSelectorPost:nil sessionTaskIdentifier:sessionTaskIdentifier sessionTaskIdentifierPlist:sessionTaskIdentifierPlist predicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  462. NSLog(@"[LOG] downloadFileSession TaskIdentifier [error CCErrorTaskNil] - %@ - %@", fileName, fileNamePrint);
  463. } else {
  464. NSUInteger sessionTaskIdentifier = k_taskIdentifierNULL;
  465. NSUInteger sessionTaskIdentifierPlist = k_taskIdentifierNULL;
  466. if ([CCUtility isCryptoString:fileName] || [CCUtility isFileNotCryptated:fileName]) sessionTaskIdentifier = downloadTask.taskIdentifier;
  467. if ([CCUtility isCryptoPlistString:fileName]) sessionTaskIdentifierPlist = downloadTask.taskIdentifier;
  468. [[NCManageDatabase sharedInstance] setMetadataSession:nil sessionError:nil sessionSelector:nil sessionSelectorPost:nil sessionTaskIdentifier:sessionTaskIdentifier sessionTaskIdentifierPlist:sessionTaskIdentifierPlist predicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  469. // Manage uploadTask cancel,suspend,resume
  470. if (taskStatus == k_taskStatusCancel) [downloadTask cancel];
  471. else if (taskStatus == k_taskStatusSuspend) [downloadTask suspend];
  472. else if (taskStatus == k_taskStatusResume) [downloadTask resume];
  473. NSLog(@"[LOG] downloadFileSession %@ - %@ Task [%lu %lu]", fileID, fileNamePrint, (unsigned long)sessionTaskIdentifier, (unsigned long)sessionTaskIdentifierPlist);
  474. }
  475. dispatch_async(dispatch_get_main_queue(), ^{
  476. // Refresh datasource if is not a Plist
  477. if ([_delegate respondsToSelector:@selector(reloadDatasource:)] && [CCUtility isCryptoPlistString:fileName] == NO)
  478. [_delegate reloadDatasource:serverUrl];
  479. #ifndef EXTENSION
  480. [app updateApplicationIconBadgeNumber];
  481. #endif
  482. });
  483. }
  484. - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
  485. {
  486. NSString *url = [[[downloadTask currentRequest].URL absoluteString] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  487. NSString *fileName = [url lastPathComponent];
  488. NSString *serverUrl = [self getServerUrlFromUrl:url];
  489. if (!serverUrl) return;
  490. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrl];
  491. if (!directoryID) return;
  492. // if plist return
  493. if ([CCUtility getTypeFileName:fileName] == k_metadataTypeFilenamePlist)
  494. return;
  495. float progress = (float) totalBytesWritten / (float)totalBytesExpectedToWrite;
  496. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataFromFileName:fileName directoryID:directoryID];
  497. if (metadata) {
  498. NSDictionary* userInfo = @{@"fileID": (metadata.fileID), @"serverUrl": (serverUrl), @"cryptated": ([NSNumber numberWithBool:metadata.cryptated]), @"progress": ([NSNumber numberWithFloat:progress])};
  499. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"NotificationProgressTask" object:nil userInfo:userInfo];
  500. } else {
  501. NSLog(@"metadata not found");
  502. }
  503. }
  504. - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
  505. {
  506. NSURLRequest *url = [downloadTask currentRequest];
  507. NSString *fileName = [[url.URL absoluteString] lastPathComponent];
  508. NSString *serverUrl = [self getServerUrlFromUrl:[url.URL absoluteString]];
  509. if (!serverUrl) return;
  510. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"session = %@ AND (sessionTaskIdentifier = %i OR sessionTaskIdentifierPlist = %i)",session.sessionDescription, downloadTask.taskIdentifier, downloadTask.taskIdentifier]];
  511. // If the record metadata do not exists, exit
  512. if (!metadata) {
  513. [[NCManageDatabase sharedInstance] addActivityClient:fileName fileID:@"" action:k_activityDebugActionUpload selector:@"" note:[NSString stringWithFormat:@"Serius error internal download : metadata not found %@", url] type:k_activityTypeFailure verbose:k_activityVerboseDefault activeUrl:_activeUrl];
  514. NSLog(@"[LOG] Serius error internal download : metadata not found %@ ", url);
  515. dispatch_async(dispatch_get_main_queue(), ^{
  516. if ([self.delegate respondsToSelector:@selector(downloadFileFailure:serverUrl:selector:message:errorCode:)])
  517. [self.delegate downloadFileFailure:@"" serverUrl:serverUrl selector:@"" message:@"" errorCode:k_CCErrorInternalError];
  518. });
  519. return;
  520. }
  521. NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)downloadTask.response;
  522. if (httpResponse.statusCode >= 200 && httpResponse.statusCode < 300) {
  523. NSString *destinationFilePath;
  524. if ([CCUtility isCryptoPlistString:fileName]) {
  525. destinationFilePath = [NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryActiveUser:_activeUser activeUrl:_activeUrl], fileName];
  526. } else {
  527. if (metadata.cryptated) destinationFilePath = [NSString stringWithFormat:@"%@/%@.crypt", [CCUtility getDirectoryActiveUser:_activeUser activeUrl:_activeUrl], metadata.fileID];
  528. else destinationFilePath = [NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryActiveUser:_activeUser activeUrl:_activeUrl], metadata.fileID];
  529. }
  530. NSURL *destinationURL = [NSURL fileURLWithPath:destinationFilePath];
  531. [[NSFileManager defaultManager] removeItemAtURL:destinationURL error:NULL];
  532. [[NSFileManager defaultManager] copyItemAtURL:location toURL:destinationURL error:nil];
  533. }
  534. }
  535. - (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
  536. {
  537. #ifndef EXTENSION
  538. [app.listProgressMetadata removeObjectForKey:fileID];
  539. #endif
  540. // Progress Task
  541. NSDictionary* userInfo = @{@"fileID": (fileID), @"serverUrl": (serverUrl), @"cryptated": ([NSNumber numberWithBool:NO]), @"progress": ([NSNumber numberWithFloat:0.0])};
  542. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"NotificationProgressTask" object:nil userInfo:userInfo];
  543. if (errorCode != 0) {
  544. if (errorCode != kCFURLErrorCancelled) {
  545. if ([CCUtility isCryptoPlistString:fileName]) {
  546. [[NCManageDatabase sharedInstance] setMetadataSession:@"" sessionError:@"" sessionSelector:@"" sessionSelectorPost:@"" sessionTaskIdentifier:k_taskIdentifierDone sessionTaskIdentifierPlist:k_taskIdentifierDone predicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  547. } else {
  548. [[NCManageDatabase sharedInstance] setMetadataSession:nil sessionError:[NSString stringWithFormat:@"%@", @(errorCode)] sessionSelector:nil sessionSelectorPost:nil sessionTaskIdentifier:k_taskIdentifierError sessionTaskIdentifierPlist:k_taskIdentifierNULL predicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  549. }
  550. }
  551. dispatch_async(dispatch_get_main_queue(), ^{
  552. if ([[self getDelegate:fileID] respondsToSelector:@selector(downloadFileFailure:serverUrl:selector:message:errorCode:)])
  553. [[self getDelegate:fileID] downloadFileFailure:fileID serverUrl:serverUrl selector:selector message:[CCError manageErrorKCF:errorCode withNumberError:YES] errorCode:errorCode];
  554. });
  555. } else {
  556. __block tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  557. if (!metadata) {
  558. [[NCManageDatabase sharedInstance] addActivityClient:fileName fileID:fileID action:k_activityDebugActionUpload selector:@"" note:[NSString stringWithFormat:@"Serius error internal download : metadata not found %@", fileName] type:k_activityTypeFailure verbose:k_activityVerboseDefault activeUrl:_activeUrl];
  559. NSLog(@"[LOG] Serius error internal download : metadata not found %@ ", fileName);
  560. dispatch_async(dispatch_get_main_queue(), ^{
  561. if ([self.delegate respondsToSelector:@selector(downloadFileFailure:serverUrl:selector:message:errorCode:)])
  562. [self.delegate downloadFileFailure:fileID serverUrl:serverUrl selector:selector message:[NSString stringWithFormat:@"Serius error internal download : metadata not found %@", fileName] errorCode:k_CCErrorInternalError];
  563. });
  564. return;
  565. }
  566. NSInteger sessionTaskIdentifier = metadata.sessionTaskIdentifier;
  567. NSInteger sessionTaskIdentifierPlist = metadata.sessionTaskIdentifierPlist;
  568. if ([CCUtility isCryptoString:fileName] || [CCUtility isFileNotCryptated:fileName]) sessionTaskIdentifier = k_taskIdentifierDone;
  569. if ([CCUtility isCryptoPlistString:fileName]) sessionTaskIdentifierPlist = k_taskIdentifierDone;
  570. if (sessionTaskIdentifier == k_taskIdentifierDone && sessionTaskIdentifierPlist == k_taskIdentifierDone) {
  571. metadata.session = @"";
  572. metadata.sessionError = @"";
  573. metadata.sessionSelector = @"";
  574. metadata.sessionSelectorPost = @"";
  575. metadata.sessionTaskIdentifier = k_taskIdentifierDone;
  576. metadata.sessionTaskIdentifierPlist = k_taskIdentifierDone;
  577. // Fix Main Thread for insertInformationPlist
  578. if([selector isEqualToString:selectorLoadPlist] || [selector isEqualToString:selectorLoadModelView]) {
  579. dispatch_async(dispatch_get_main_queue(), ^{
  580. if([selector isEqualToString:selectorLoadPlist] || [selector isEqualToString:selectorLoadModelView]) {
  581. NSString *autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  582. NSString *autoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:_activeUrl];
  583. metadata = [CCUtility insertInformationPlist:metadata directoryUser:_directoryUser];
  584. metadata = [CCUtility insertTypeFileIconName:metadata serverUrl:serverUrl autoUploadFileName:autoUploadFileName autoUploadDirectory:autoUploadDirectory];
  585. }
  586. metadata = [[NCManageDatabase sharedInstance] updateMetadata:metadata];
  587. });
  588. } else {
  589. metadata = [[NCManageDatabase sharedInstance] updateMetadata:metadata];
  590. }
  591. } else {
  592. [[NCManageDatabase sharedInstance] setMetadataSession:nil sessionError:nil sessionSelector:nil sessionSelectorPost:nil sessionTaskIdentifier:sessionTaskIdentifier sessionTaskIdentifierPlist:sessionTaskIdentifierPlist predicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  593. }
  594. // DATA
  595. if ([CCUtility isCryptoString:fileName] || [CCUtility isFileNotCryptated:fileName]) {
  596. BOOL error = false;
  597. // if encrypted, rewrite
  598. if (metadata.cryptated == YES)
  599. if ([[CCCrypto sharedManager] decrypt:metadata.fileID fileNameDecrypted:metadata.fileID fileNamePrint:metadata.fileNamePrint password:[[CCCrypto sharedManager] getKeyPasscode:metadata.uuid] directoryUser:_directoryUser] == 0)
  600. error = true;
  601. if (!error) {
  602. [[NCManageDatabase sharedInstance] addLocalFileWithMetadata:metadata];
  603. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image])
  604. [[CCExifGeo sharedInstance] setExifLocalTableEtag:metadata directoryUser:_directoryUser activeAccount:_activeAccount];
  605. // Icon
  606. [CCGraphics createNewImageFrom:metadata.fileID directoryUser:_directoryUser fileNameTo:metadata.fileID fileNamePrint:metadata.fileNamePrint size:@"m" imageForUpload:NO typeFile:metadata.typeFile writePreview:YES optimizedFileName:[CCUtility getOptimizedPhoto]];
  607. // Activity
  608. [[NCManageDatabase sharedInstance] addActivityClient:fileName fileID:metadata.fileID action:k_activityDebugActionDownload selector:metadata.sessionSelector note:serverUrl type:k_activityTypeSuccess verbose:k_activityVerboseDefault activeUrl:_activeUrl];
  609. }
  610. }
  611. dispatch_async(dispatch_get_main_queue(), ^{
  612. if ([[self getDelegate:fileID] respondsToSelector:@selector(downloadFileSuccess:serverUrl:selector:selectorPost:)])
  613. [[self getDelegate:fileID] downloadFileSuccess:fileID serverUrl:serverUrl selector:selector selectorPost:selectorPost];
  614. });
  615. }
  616. }
  617. #pragma --------------------------------------------------------------------------------------------
  618. #pragma mark ===== Upload =====
  619. #pragma --------------------------------------------------------------------------------------------
  620. - (void)uploadFileFromAssetLocalIdentifier:(CCMetadataNet *)metadataNet delegate:(id)delegate
  621. {
  622. //delegate
  623. if (delegate == nil)
  624. delegate = self.delegate;
  625. PHFetchResult *result = [PHAsset fetchAssetsWithLocalIdentifiers:@[metadataNet.assetLocalIdentifier] options:nil];
  626. if (!result.count) {
  627. // Delete record on Table Auto Upload
  628. if ([metadataNet.selector isEqualToString:selectorUploadAutoUpload] || [metadataNet.selector isEqualToString:selectorUploadAutoUploadAll])
  629. [[NCManageDatabase sharedInstance] deleteQueueUploadWithAssetLocalIdentifier:metadataNet.assetLocalIdentifier selector:metadataNet.selector];
  630. [[NCManageDatabase sharedInstance] addActivityClient:metadataNet.fileName fileID:metadataNet.assetLocalIdentifier action:k_activityDebugActionUpload selector:metadataNet.selector note:@"Error photo/video not found, remove from upload" type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:_activeUrl];
  631. if ([delegate respondsToSelector:@selector(uploadFileFailure:fileID:serverUrl:selector:message:errorCode:)])
  632. [delegate uploadFileFailure:metadataNet fileID:nil serverUrl:metadataNet.serverUrl selector:metadataNet.selector message:@"Error photo/video not found, remove from upload" errorCode: k_CCErrorInternalError];
  633. return;
  634. }
  635. @synchronized (self) {
  636. PHAsset *assetResult = result[0];
  637. PHAssetMediaType assetMediaType = assetResult.mediaType;
  638. // IMAGE
  639. if (assetMediaType == PHAssetMediaTypeImage) {
  640. __block PHAsset *asset = result[0];
  641. __block NSError *error = nil;
  642. PHImageRequestOptions *options = [PHImageRequestOptions new];
  643. options.networkAccessAllowed = YES; // iCloud
  644. [[PHImageManager defaultManager] requestImageDataForAsset:asset options:options resultHandler:^(NSData *imageData, NSString *dataUTI, UIImageOrientation orientation, NSDictionary *info) {
  645. [imageData writeToFile:[NSString stringWithFormat:@"%@/%@", _directoryUser, metadataNet.fileName] options:NSDataWritingAtomic error:&error];
  646. if (error) {
  647. dispatch_async(dispatch_get_main_queue(), ^{
  648. if ([delegate respondsToSelector:@selector(uploadFileFailure:fileID:serverUrl:selector:message:errorCode:)])
  649. [delegate uploadFileFailure:metadataNet fileID:nil serverUrl:metadataNet.serverUrl selector:metadataNet.selector message:[NSString stringWithFormat:@"Image request failed [%@]", error.description] errorCode:error.code];
  650. });
  651. } else {
  652. // OOOOOK
  653. dispatch_async(dispatch_get_main_queue(), ^{
  654. [self upload:metadataNet.fileName serverUrl:metadataNet.serverUrl cryptated:metadataNet.cryptated template:NO onlyPlist:NO fileNameTemplate:nil assetLocalIdentifier:metadataNet.assetLocalIdentifier session:metadataNet.session taskStatus:metadataNet.taskStatus selector:metadataNet.selector selectorPost:metadataNet.selectorPost errorCode:metadataNet.errorCode delegate:delegate];
  655. });
  656. }
  657. }];
  658. }
  659. // VIDEO
  660. if (assetMediaType == PHAssetMediaTypeVideo) {
  661. __block PHAsset *asset = result[0];
  662. PHVideoRequestOptions *options = [PHVideoRequestOptions new];
  663. options.networkAccessAllowed = YES; // iCloud
  664. [[PHImageManager defaultManager] requestPlayerItemForVideo:asset options:options resultHandler:^(AVPlayerItem * _Nullable playerItem, NSDictionary * _Nullable info) {
  665. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, metadataNet.fileName]])
  666. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, metadataNet.fileName] error:nil];
  667. AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:playerItem.asset presetName:AVAssetExportPresetHighestQuality];
  668. if (exportSession) {
  669. exportSession.outputURL = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, metadataNet.fileName]];
  670. exportSession.outputFileType = AVFileTypeQuickTimeMovie;
  671. [exportSession exportAsynchronouslyWithCompletionHandler:^{
  672. if (AVAssetExportSessionStatusCompleted == exportSession.status) {
  673. // OOOOOOK
  674. dispatch_async(dispatch_get_main_queue(), ^{
  675. [self upload:metadataNet.fileName serverUrl:metadataNet.serverUrl cryptated:metadataNet.cryptated template:NO onlyPlist:NO fileNameTemplate:nil assetLocalIdentifier:metadataNet.assetLocalIdentifier session:metadataNet.session taskStatus:metadataNet.taskStatus selector:metadataNet.selector selectorPost:metadataNet.selectorPost errorCode:metadataNet.errorCode delegate:delegate];
  676. });
  677. } else {
  678. dispatch_async(dispatch_get_main_queue(), ^{
  679. if ([delegate respondsToSelector:@selector(uploadFileFailure:fileID:serverUrl:selector:message:errorCode:)])
  680. [delegate uploadFileFailure:metadataNet fileID:nil serverUrl:metadataNet.serverUrl selector:metadataNet.selector message:[NSString stringWithFormat:@"Video export failed [%@]", exportSession.error.description] errorCode:exportSession.error.code];
  681. });
  682. }
  683. }];
  684. } else {
  685. dispatch_async(dispatch_get_main_queue(), ^{
  686. if ([delegate respondsToSelector:@selector(uploadFileFailure:fileID:serverUrl:selector:message:errorCode:)])
  687. [delegate uploadFileFailure:metadataNet fileID:nil serverUrl:metadataNet.serverUrl selector:metadataNet.selector message:@"Create Video session failed [Internal error]" errorCode:k_CCErrorInternalError];
  688. });
  689. }
  690. }];
  691. }
  692. }
  693. }
  694. - (void)uploadFile:(NSString *)fileName serverUrl:(NSString *)serverUrl cryptated:(BOOL)cryptated onlyPlist:(BOOL)onlyPlist session:(NSString *)session taskStatus:(NSInteger)taskStatus selector:(NSString *)selector selectorPost:(NSString *)selectorPost errorCode:(NSInteger)errorCode delegate:(id)delegate
  695. {
  696. [self upload:fileName serverUrl:serverUrl cryptated:cryptated template:NO onlyPlist:onlyPlist fileNameTemplate:nil assetLocalIdentifier:nil session:session taskStatus:taskStatus selector:selector selectorPost:selectorPost errorCode:errorCode delegate:delegate];
  697. }
  698. - (void)uploadTemplate:(NSString *)fileNamePrint fileNameCrypto:(NSString *)fileNameCrypto serverUrl:(NSString *)serverUrl session:(NSString *)session taskStatus:(NSInteger)taskStatus selector:(NSString *)selector selectorPost:(NSString *)selectorPost errorCode:(NSInteger)errorCode delegate:(id)delegate
  699. {
  700. [self upload:fileNameCrypto serverUrl:serverUrl cryptated:YES template:YES onlyPlist:NO fileNameTemplate:fileNamePrint assetLocalIdentifier:nil session:session taskStatus:taskStatus selector:selector selectorPost:selectorPost errorCode:errorCode delegate:delegate];
  701. }
  702. - (void)upload:(NSString *)fileName serverUrl:(NSString *)serverUrl cryptated:(BOOL)cryptated template:(BOOL)template onlyPlist:(BOOL)onlyPlist fileNameTemplate:(NSString *)fileNameTemplate assetLocalIdentifier:(NSString *)assetLocalIdentifier session:(NSString *)session taskStatus:(NSInteger)taskStatus selector:(NSString *)selector selectorPost:(NSString *)selectorPost errorCode:(NSInteger)errorCode delegate:(id)delegate
  703. {
  704. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrl];
  705. if (!directoryID) return;
  706. NSString *fileNameCrypto;
  707. // create Metadata
  708. NSString *autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  709. NSString *autoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:_activeUrl];
  710. __block tableMetadata *metadata = [CCUtility insertFileSystemInMetadata:fileName directory:_directoryUser activeAccount:_activeAccount autoUploadFileName:autoUploadFileName autoUploadDirectory:autoUploadDirectory];
  711. //fileID
  712. NSString *uploadID = [k_uploadSessionID stringByAppendingString:[CCUtility createRandomString:16]];
  713. //add delegate
  714. if (delegate)
  715. [_delegates setObject:delegate forKey:uploadID];
  716. if (onlyPlist == YES) {
  717. [CCUtility moveFileAtPath:[NSTemporaryDirectory() stringByAppendingString:fileName] toPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, fileName]];
  718. metadata = [CCUtility insertInformationPlist:metadata directoryUser:_directoryUser];
  719. metadata.date = [NSDate new];
  720. metadata.fileID = uploadID;
  721. metadata.directoryID = directoryID;
  722. metadata.fileNameData = [CCUtility trasformedFileNamePlistInCrypto:fileName];
  723. metadata.assetLocalIdentifier = assetLocalIdentifier;
  724. metadata.session = session;
  725. metadata.sessionID = uploadID;
  726. metadata.sessionSelector = selector;
  727. metadata.sessionSelectorPost = selectorPost;
  728. metadata.typeFile = k_metadataTypeFile_unknown;
  729. metadata = [[NCManageDatabase sharedInstance] addMetadata:metadata];
  730. if (metadata)
  731. [self uploadURLSession:fileName fileNamePrint:metadata.fileNamePrint serverUrl:serverUrl sessionID:uploadID session:metadata.session taskStatus:taskStatus assetLocalIdentifier:assetLocalIdentifier cryptated:cryptated onlyPlist:onlyPlist selector:selector];
  732. }
  733. else if (cryptated == YES) {
  734. if (template == YES) {
  735. // copy from temp to directory user
  736. [CCUtility moveFileAtPath:[NSTemporaryDirectory() stringByAppendingString:fileName] toPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, fileName]];
  737. [CCUtility moveFileAtPath:[NSTemporaryDirectory() stringByAppendingString:[fileName stringByAppendingString:@".plist"]] toPath:[NSString stringWithFormat:@"%@/%@.plist", _directoryUser, fileName]];
  738. fileNameCrypto = fileName; // file Name Crypto
  739. fileName = fileNameTemplate; // file Name Print
  740. metadata = [CCUtility insertInformationPlist:metadata directoryUser:_directoryUser];
  741. metadata.date = [NSDate new];
  742. metadata.fileID = uploadID;
  743. metadata.directoryID = directoryID;
  744. metadata.fileName = [fileNameCrypto stringByAppendingString:@".plist"];
  745. metadata.fileNameData = fileNameCrypto;
  746. metadata.assetLocalIdentifier = assetLocalIdentifier;
  747. metadata.session = session;
  748. metadata.sessionID = uploadID;
  749. metadata.sessionSelector = selector;
  750. metadata.sessionSelectorPost = selectorPost;
  751. metadata.typeFile = k_metadataTypeFile_template;
  752. metadata = [[NCManageDatabase sharedInstance] addMetadata:metadata];
  753. if (metadata) {
  754. // DATA
  755. [self uploadURLSession:fileNameCrypto fileNamePrint:fileName serverUrl:serverUrl sessionID:uploadID session:metadata.session taskStatus:taskStatus assetLocalIdentifier:assetLocalIdentifier cryptated:cryptated onlyPlist:onlyPlist selector:selector];
  756. // PLIST
  757. [self uploadURLSession:[fileNameCrypto stringByAppendingString:@".plist"] fileNamePrint:fileName serverUrl:serverUrl sessionID:uploadID session:metadata.session taskStatus:taskStatus assetLocalIdentifier:assetLocalIdentifier cryptated:cryptated onlyPlist:onlyPlist selector:selector];
  758. }
  759. }
  760. if (template == NO) {
  761. NSString *passcode = [[CCCrypto sharedManager] getKeyPasscode:[CCUtility getUUID]];
  762. fileNameCrypto = [[CCCrypto sharedManager] encryptWithCreatePlist:fileName fileNameEncrypted:fileName passcode:passcode directoryUser:_directoryUser];
  763. // Encrypted file error
  764. if (fileNameCrypto == nil) {
  765. dispatch_async(dispatch_get_main_queue(), ^{
  766. NSString *msg = [NSString stringWithFormat:NSLocalizedString(@"_encrypt_error_", nil), fileName, @""];
  767. UIAlertController *alertController= [UIAlertController alertControllerWithTitle:nil message:msg preferredStyle:UIAlertControllerStyleAlert];
  768. UIAlertAction* ok = [UIAlertAction actionWithTitle: NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault
  769. handler:^(UIAlertAction * action) {
  770. [alertController dismissViewControllerAnimated:YES completion:nil];
  771. }];
  772. [alertController addAction:ok];
  773. UIWindow *alertWindow = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
  774. alertWindow.rootViewController = [[UIViewController alloc]init];
  775. alertWindow.windowLevel = UIWindowLevelAlert + 1;
  776. [alertWindow makeKeyAndVisible];
  777. [alertWindow.rootViewController presentViewController:alertController animated:YES completion:nil];
  778. // Error for uploadFileFailure
  779. if ([[self getDelegate:uploadID] respondsToSelector:@selector(uploadFileFailure:fileID:serverUrl:selector:message:errorCode:)])
  780. [[self getDelegate:uploadID] uploadFileFailure:nil fileID:nil serverUrl:serverUrl selector:selector message:NSLocalizedString(@"_encrypt_error_", nil) errorCode:0];
  781. });
  782. return;
  783. }
  784. metadata.cryptated = YES;
  785. metadata.date = [NSDate new];
  786. metadata.fileID = uploadID;
  787. metadata.directoryID = directoryID;
  788. metadata.fileName = [fileNameCrypto stringByAppendingString:@".plist"];
  789. metadata.fileNameData = fileNameCrypto;
  790. metadata.fileNamePrint = fileName;
  791. metadata.assetLocalIdentifier = assetLocalIdentifier;
  792. metadata.session = session;
  793. metadata.sessionID = uploadID;
  794. metadata.sessionSelector = selector;
  795. metadata.sessionSelectorPost = selectorPost;
  796. metadata.title = [self getTitleFromPlistName:fileNameCrypto];
  797. metadata.type = k_metadataType_file;
  798. #ifndef EXTENSION
  799. [CCGraphics createNewImageFrom:fileName directoryUser:_directoryUser fileNameTo:uploadID fileNamePrint:fileName size:@"m" imageForUpload:YES typeFile:metadata.typeFile writePreview:YES optimizedFileName:NO];
  800. #endif
  801. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video])
  802. [[CCCrypto sharedManager] addPlistImage:[NSString stringWithFormat:@"%@/%@", _directoryUser, [fileNameCrypto stringByAppendingString:@".plist"]] fileNamePathImage:[NSTemporaryDirectory() stringByAppendingString:uploadID]];
  803. metadata = [[NCManageDatabase sharedInstance] addMetadata:metadata];
  804. if (metadata) {
  805. // DATA
  806. [self uploadURLSession:fileNameCrypto fileNamePrint:fileName serverUrl:serverUrl sessionID:uploadID session:metadata.session taskStatus:taskStatus assetLocalIdentifier:assetLocalIdentifier cryptated:cryptated onlyPlist:onlyPlist selector:selector];
  807. // PLIST
  808. [self uploadURLSession:[fileNameCrypto stringByAppendingString:@".plist"] fileNamePrint:fileName serverUrl:serverUrl sessionID:uploadID session:metadata.session taskStatus:taskStatus assetLocalIdentifier:assetLocalIdentifier cryptated:cryptated onlyPlist:onlyPlist selector:selector];
  809. }
  810. }
  811. }
  812. else if (cryptated == NO) {
  813. metadata.cryptated = NO;
  814. metadata.date = [NSDate new];
  815. metadata.fileID = uploadID;
  816. metadata.directoryID = directoryID;
  817. metadata.fileName = fileName;
  818. metadata.fileNameData = fileName;
  819. metadata.fileNamePrint = fileName;
  820. metadata.assetLocalIdentifier = assetLocalIdentifier;
  821. metadata.session = session;
  822. metadata.sessionID = uploadID;
  823. metadata.sessionSelector = selector;
  824. metadata.sessionSelectorPost = selectorPost;
  825. metadata.type = k_metadataType_file;
  826. // File exists ???
  827. if (errorCode == 403) {
  828. dispatch_async(dispatch_get_main_queue(), ^{
  829. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:fileName message:NSLocalizedString(@"_file_already_exists_", nil) preferredStyle:UIAlertControllerStyleAlert];
  830. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  831. // Activity
  832. [[NCManageDatabase sharedInstance] addActivityClient:fileName fileID:uploadID action:k_activityDebugActionUpload selector:selector note:NSLocalizedString(@"_file_already_exists_", nil) type:k_activityTypeFailure verbose:k_activityVerboseDefault activeUrl:_activeUrl];
  833. // Error for uploadFileFailure
  834. if ([[self getDelegate:uploadID] respondsToSelector:@selector(uploadFileFailure:fileID:serverUrl:selector:message:errorCode:)])
  835. [[self getDelegate:uploadID] uploadFileFailure:nil fileID:nil serverUrl:serverUrl selector:selector message:NSLocalizedString(@"_file_already_exists_", nil) errorCode:403];
  836. return;
  837. }];
  838. UIAlertAction *overwriteAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_overwrite_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  839. // -- remove record --
  840. tableMetadata *metadataDelete = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND fileName = %@ AND directoryID = %@", _activeAccount, fileName, directoryID]];
  841. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, metadataDelete.fileID] error:nil];
  842. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@.ico", _directoryUser, metadataDelete.fileID] error:nil];
  843. if (metadataDelete.directory && serverUrl) {
  844. NSString *dirForDelete = [CCUtility stringAppendServerUrl:serverUrl addFileName:metadataDelete.fileNameData];
  845. [[NCManageDatabase sharedInstance] deleteDirectoryAndSubDirectoryWithServerUrl:dirForDelete];
  846. }
  847. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadataDelete.fileID] clearDateReadDirectoryID:nil];
  848. [[NCManageDatabase sharedInstance] deleteLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadataDelete.fileID]];
  849. // -- Go to Upload --
  850. [CCGraphics createNewImageFrom:metadata.fileNamePrint directoryUser:_directoryUser fileNameTo:metadata.fileID fileNamePrint:metadata.fileNamePrint size:@"m" imageForUpload:YES typeFile:metadata.typeFile writePreview:YES optimizedFileName:NO];
  851. metadata = [[NCManageDatabase sharedInstance] addMetadata:metadata];
  852. if (metadata) {
  853. [self uploadURLSession:fileName fileNamePrint:fileName serverUrl:serverUrl sessionID:uploadID session:metadata.session taskStatus:taskStatus assetLocalIdentifier:assetLocalIdentifier cryptated:cryptated onlyPlist:onlyPlist selector:selector];
  854. }
  855. }];
  856. [alertController addAction:cancelAction];
  857. [alertController addAction:overwriteAction];
  858. UIWindow *alertWindow = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
  859. alertWindow.rootViewController = [[UIViewController alloc] init];
  860. alertWindow.windowLevel = UIWindowLevelAlert + 1;
  861. [alertWindow makeKeyAndVisible];
  862. [alertWindow.rootViewController presentViewController:alertController animated:YES completion:nil];
  863. });
  864. } else {
  865. // -- Go to upload --
  866. #ifndef EXTENSION
  867. [CCGraphics createNewImageFrom:metadata.fileNamePrint directoryUser:_directoryUser fileNameTo:metadata.fileID fileNamePrint:metadata.fileNamePrint size:@"m" imageForUpload:YES typeFile:metadata.typeFile writePreview:YES optimizedFileName:NO];
  868. #endif
  869. metadata = [[NCManageDatabase sharedInstance] addMetadata:metadata];
  870. if (metadata) {
  871. [self uploadURLSession:fileName fileNamePrint:fileName serverUrl:serverUrl sessionID:uploadID session:metadata.session taskStatus:taskStatus assetLocalIdentifier:assetLocalIdentifier cryptated:cryptated onlyPlist:onlyPlist selector:selector];
  872. }
  873. }
  874. }
  875. }
  876. - (void)uploadFileMetadata:(tableMetadata *)metadata taskStatus:(NSInteger)taskStatus
  877. {
  878. BOOL reSend = NO;
  879. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  880. if (!serverUrl) return;
  881. if (metadata.cryptated) {
  882. // ENCRYPTED
  883. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, metadata.fileNameData]] && [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, metadata.fileName]]) {
  884. reSend = YES;
  885. NSLog(@"[LOG] Re-upload File : %@ - fileID : %@", metadata.fileNamePrint, metadata.fileID);
  886. [[NCManageDatabase sharedInstance] setMetadataSession:nil sessionError:@"" sessionSelector:nil sessionSelectorPost:nil sessionTaskIdentifier:k_taskIdentifierNULL sessionTaskIdentifierPlist:k_taskIdentifierNULL predicate:[NSPredicate predicateWithFormat:@"sessionID = %@ AND account = %@", metadata.sessionID, _activeAccount]];
  887. [self uploadURLSession:metadata.fileNameData fileNamePrint:metadata.fileNamePrint serverUrl:serverUrl sessionID:metadata.sessionID session:metadata.session taskStatus:taskStatus assetLocalIdentifier:nil cryptated:YES onlyPlist:NO selector:metadata.sessionSelector];
  888. [self uploadURLSession:metadata.fileName fileNamePrint:metadata.fileNamePrint serverUrl:serverUrl sessionID:metadata.sessionID session:metadata.session taskStatus:taskStatus assetLocalIdentifier:nil cryptated:YES onlyPlist:NO selector:metadata.sessionSelector];
  889. }
  890. } else {
  891. // PLAIN
  892. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, metadata.sessionID]]) {
  893. reSend = YES;
  894. NSLog(@"[LOG] Re-upload File : %@ - fileID : %@", metadata.fileNamePrint, metadata.fileID);
  895. [[NCManageDatabase sharedInstance] setMetadataSession:nil sessionError:@"" sessionSelector:nil sessionSelectorPost:nil sessionTaskIdentifier:k_taskIdentifierNULL sessionTaskIdentifierPlist:k_taskIdentifierNULL predicate:[NSPredicate predicateWithFormat:@"sessionID = %@ AND account = %@", metadata.sessionID, _activeAccount]];
  896. [self uploadURLSession:metadata.fileName fileNamePrint:metadata.fileNamePrint serverUrl:serverUrl sessionID:metadata.sessionID session:metadata.session taskStatus:taskStatus assetLocalIdentifier:nil cryptated:NO onlyPlist:NO selector:metadata.sessionSelector];
  897. }
  898. }
  899. if (!reSend) {
  900. NSLog(@"[LOG] Error reUploadBackground, file not found.");
  901. #ifndef EXTENSION
  902. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_no_reuploadfile_", nil) delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  903. [alertView show];
  904. #endif
  905. }
  906. }
  907. - (void)uploadURLSession:(NSString *)fileName fileNamePrint:(NSString *)fileNamePrint serverUrl:(NSString *)serverUrl sessionID:(NSString*)sessionID session:(NSString *)session taskStatus:(NSInteger)taskStatus assetLocalIdentifier:(NSString *)assetLocalIdentifier cryptated:(BOOL)cryptated onlyPlist:(BOOL)onlyPlist selector:(NSString *)selector
  908. {
  909. NSURLSession *sessionUpload;
  910. NSURL *url;
  911. NSMutableURLRequest *request;
  912. NSString *fileNamePath = [[NSString stringWithFormat:@"%@/%@", serverUrl, fileName] encodeString:NSUTF8StringEncoding];
  913. url = [NSURL URLWithString:fileNamePath];
  914. request = [NSMutableURLRequest requestWithURL:url];
  915. NSData *authData = [[NSString stringWithFormat:@"%@:%@", _activeUser, _activePassword] dataUsingEncoding:NSUTF8StringEncoding];
  916. NSString *authValue = [NSString stringWithFormat: @"Basic %@",[authData base64EncodedStringWithOptions:0]];
  917. [request setHTTPMethod:@"PUT"];
  918. [request setValue:authValue forHTTPHeaderField:@"Authorization"];
  919. // Rename with the SessionID
  920. NSString *fileNameForUpload;
  921. if ([CCUtility isFileNotCryptated:fileName]) fileNameForUpload = sessionID;
  922. else fileNameForUpload = fileName;
  923. if (!onlyPlist) {
  924. if ([CCUtility isFileNotCryptated:fileName])
  925. [[NSFileManager defaultManager] moveItemAtPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, fileName] toPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, fileNameForUpload] error:nil];
  926. if ([CCUtility isCryptoPlistString:fileName])
  927. [[NSFileManager defaultManager] moveItemAtPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, fileNamePrint] toPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, sessionID] error:nil];
  928. }
  929. // file NOT exists
  930. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, fileNameForUpload]] == NO) {
  931. // Activity
  932. [[NCManageDatabase sharedInstance] addActivityClient:fileName fileID:sessionID action:k_activityDebugActionUpload selector:selector note:NSLocalizedString(@"_file_not_present_", nil) type:k_activityTypeFailure verbose:k_activityVerboseDefault activeUrl:_activeUrl];
  933. // Delete record : Metadata
  934. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"sessionID = %@ AND account = %@", sessionID, _activeAccount] clearDateReadDirectoryID:nil];
  935. // Delete record : Table Auto Upload
  936. if ([selector isEqualToString:selectorUploadAutoUpload] || [selector isEqualToString:selectorUploadAutoUploadAll])
  937. [[NCManageDatabase sharedInstance] deleteQueueUploadWithAssetLocalIdentifier:assetLocalIdentifier selector:selector];
  938. dispatch_async(dispatch_get_main_queue(), ^{
  939. // Error for uploadFileFailure
  940. if ([[self getDelegate:sessionID] respondsToSelector:@selector(uploadFileFailure:fileID:serverUrl:selector:message:errorCode:)])
  941. [[self getDelegate:sessionID] uploadFileFailure:nil fileID:sessionID serverUrl:serverUrl selector:selector message:NSLocalizedString(@"_file_not_present_", nil) errorCode:404];
  942. });
  943. return;
  944. }
  945. if ([session isEqualToString:k_upload_session]) sessionUpload = [self sessionUpload];
  946. else if ([session isEqualToString:k_upload_session_foreground]) sessionUpload = [self sessionUploadForeground];
  947. else if ([session isEqualToString:k_upload_session_wwan]) sessionUpload = [self sessionWWanUpload];
  948. NSURLSessionUploadTask *uploadTask = [sessionUpload uploadTaskWithRequest:request fromFile:[NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, fileNameForUpload]]];
  949. // Error
  950. if (uploadTask == nil) {
  951. [[NCManageDatabase sharedInstance] addActivityClient:fileName fileID:assetLocalIdentifier action:k_activityDebugActionUpload selector:selector note:@"Upload task not available" type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:_activeUrl];
  952. NSUInteger sessionTaskIdentifier = k_taskIdentifierNULL;
  953. NSUInteger sessionTaskIdentifierPlist = k_taskIdentifierNULL;
  954. if ([CCUtility isFileNotCryptated:fileName] || [CCUtility isCryptoString:fileName]) sessionTaskIdentifier = k_taskIdentifierError;
  955. if ([CCUtility isCryptoPlistString:fileName]) sessionTaskIdentifierPlist = k_taskIdentifierError;
  956. [[NCManageDatabase sharedInstance] setMetadataSession:session sessionError:[NSString stringWithFormat:@"%@", @k_CCErrorTaskNil] sessionSelector:nil sessionSelectorPost:nil sessionTaskIdentifier:sessionTaskIdentifier sessionTaskIdentifierPlist:sessionTaskIdentifierPlist predicate:[NSPredicate predicateWithFormat:@"sessionID = %@ AND account = %@", sessionID, _activeAccount]];
  957. NSLog(@"[LOG] Upload file TaskIdentifier [error CCErrorTaskNil] - %@ - %@", fileName, fileNamePrint);
  958. } else {
  959. NSUInteger sessionTaskIdentifier = k_taskIdentifierNULL;
  960. NSUInteger sessionTaskIdentifierPlist = k_taskIdentifierNULL;
  961. if ([CCUtility isCryptoString:fileName] || [CCUtility isFileNotCryptated:fileName]) sessionTaskIdentifier = uploadTask.taskIdentifier;
  962. if ([CCUtility isCryptoPlistString:fileName]) sessionTaskIdentifierPlist = uploadTask.taskIdentifier;
  963. [[NCManageDatabase sharedInstance] setMetadataSession:session sessionError:@"" sessionSelector:nil sessionSelectorPost:nil sessionTaskIdentifier:sessionTaskIdentifier sessionTaskIdentifierPlist:sessionTaskIdentifierPlist predicate:[NSPredicate predicateWithFormat:@"sessionID = %@ AND account = %@", sessionID, _activeAccount]];
  964. // OOOOOOKKKK remove record on Table Auto Upload
  965. if ([selector isEqualToString:selectorUploadAutoUpload] || [selector isEqualToString:selectorUploadAutoUploadAll])
  966. [[NCManageDatabase sharedInstance] deleteQueueUploadWithAssetLocalIdentifier:assetLocalIdentifier selector:selector];
  967. // Manage uploadTask cancel,suspend,resume
  968. if (taskStatus == k_taskStatusCancel) [uploadTask cancel];
  969. else if (taskStatus == k_taskStatusSuspend) [uploadTask suspend];
  970. else if (taskStatus == k_taskStatusResume) [uploadTask resume];
  971. NSLog(@"[LOG] Upload file %@ - %@ TaskIdentifier %lu", fileName,fileNamePrint, (unsigned long)uploadTask.taskIdentifier);
  972. }
  973. dispatch_async(dispatch_get_main_queue(), ^{
  974. // refresh main
  975. if ([self.delegate respondsToSelector:@selector(reloadDatasource:)])
  976. [self.delegate reloadDatasource:serverUrl];
  977. #ifndef EXTENSION
  978. [app updateApplicationIconBadgeNumber];
  979. #endif
  980. });
  981. }
  982. - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
  983. {
  984. NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)dataTask.response;
  985. if (httpResponse.statusCode >= 200 && httpResponse.statusCode < 300) {
  986. NSNumber *taskIdentifier = [NSNumber numberWithLong:dataTask.taskIdentifier];
  987. if (data)
  988. [_taskData setObject:[data copy] forKey:taskIdentifier];
  989. }
  990. }
  991. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend
  992. {
  993. NSString *url = [[[task currentRequest].URL absoluteString] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  994. NSString *fileName = [url lastPathComponent];
  995. NSString *serverUrl = [self getServerUrlFromUrl:url];
  996. if (!serverUrl) return;
  997. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrl];
  998. if (!directoryID) return;
  999. // if plist return
  1000. if ([CCUtility getTypeFileName:fileName] == k_metadataTypeFilenamePlist)
  1001. return;
  1002. float progress = (float) totalBytesSent / (float)totalBytesExpectedToSend;
  1003. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataFromFileName:fileName directoryID:directoryID];
  1004. if (metadata) {
  1005. NSDictionary* userInfo = @{@"fileID": (metadata.fileID), @"serverUrl": (serverUrl), @"cryptated": ([NSNumber numberWithBool:metadata.cryptated]), @"progress": ([NSNumber numberWithFloat:progress])};
  1006. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"NotificationProgressTask" object:nil userInfo:userInfo];
  1007. }
  1008. }
  1009. - (void)uploadFileSuccessFailure:(tableMetadata *)metadata fileName:(NSString *)fileName fileID:(NSString *)fileID etag:(NSString *)etag date:(NSDate *)date serverUrl:(NSString *)serverUrl errorCode:(NSInteger)errorCode
  1010. {
  1011. NSString *sessionID = metadata.sessionID;
  1012. // Progress Task
  1013. NSDictionary* userInfo = @{@"fileID": (fileID), @"serverUrl": (serverUrl), @"cryptated": ([NSNumber numberWithBool:NO]), @"progress": ([NSNumber numberWithFloat:0.0])};
  1014. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"NotificationProgressTask" object:nil userInfo:userInfo];
  1015. // ERRORE
  1016. if (errorCode != 0) {
  1017. #ifndef EXTENSION
  1018. [app.listProgressMetadata removeObjectForKey:sessionID];
  1019. #endif
  1020. // Mark error only if not Cancelled Task
  1021. if (errorCode != kCFURLErrorCancelled) {
  1022. NSUInteger sessionTaskIdentifier = k_taskIdentifierNULL;
  1023. NSUInteger sessionTaskIdentifierPlist = k_taskIdentifierNULL;
  1024. if ([CCUtility isFileNotCryptated:fileName] || [CCUtility isCryptoString:fileName]) sessionTaskIdentifier = k_taskIdentifierError;
  1025. if ([CCUtility isCryptoPlistString:fileName]) sessionTaskIdentifierPlist = k_taskIdentifierError;
  1026. [[NCManageDatabase sharedInstance] setMetadataSession:nil sessionError:[NSString stringWithFormat:@"%@", @(errorCode)] sessionSelector:nil sessionSelectorPost:nil sessionTaskIdentifier:sessionTaskIdentifier sessionTaskIdentifierPlist:sessionTaskIdentifierPlist predicate:[NSPredicate predicateWithFormat:@"sessionID = %@ AND account = %@", metadata.sessionID, _activeAccount]];
  1027. }
  1028. dispatch_async(dispatch_get_main_queue(), ^{
  1029. if ([[self getDelegate:sessionID] respondsToSelector:@selector(uploadFileFailure:fileID:serverUrl:selector:message:errorCode:)])
  1030. [[self getDelegate:sessionID] uploadFileFailure:nil fileID:fileID serverUrl:serverUrl selector:metadata.sessionSelector message:[CCError manageErrorKCF:errorCode withNumberError:YES] errorCode:errorCode];
  1031. });
  1032. return;
  1033. }
  1034. // PLAIN or PLIST
  1035. if ([CCUtility isFileNotCryptated:fileName] || [CCUtility isCryptoPlistString:fileName]) {
  1036. // copy ico in new fileID
  1037. [CCUtility copyFileAtPath:[NSString stringWithFormat:@"%@/%@.ico", _directoryUser, sessionID] toPath:[NSString stringWithFormat:@"%@/%@.ico", _directoryUser, fileID]];
  1038. metadata.fileID = fileID;
  1039. metadata.etag = etag;
  1040. metadata.date = date;
  1041. metadata.sessionTaskIdentifierPlist = k_taskIdentifierDone;
  1042. if ([CCUtility isFileNotCryptated:fileName])
  1043. metadata.sessionTaskIdentifier = k_taskIdentifierDone;
  1044. // Add new metadata
  1045. if (metadata)
  1046. metadata = [[NCManageDatabase sharedInstance] addMetadata:metadata];
  1047. if (!metadata) {
  1048. dispatch_async(dispatch_get_main_queue(), ^{
  1049. if ([[self getDelegate:sessionID] respondsToSelector:@selector(uploadFileFailure:fileID:serverUrl:selector:message:errorCode:)])
  1050. [[self getDelegate:sessionID] uploadFileFailure:nil fileID:fileID serverUrl:serverUrl selector:@"" message:[NSString stringWithFormat:@"Serius error internal upload : metadata not found %@", fileName] errorCode:k_CCErrorInternalError];
  1051. });
  1052. return;
  1053. }
  1054. // Delete old ID_UPLOAD_XXXXX metadata
  1055. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", sessionID] clearDateReadDirectoryID:nil];
  1056. }
  1057. // CRYPTO
  1058. if ([CCUtility isCryptoString:fileName]) {
  1059. metadata.sessionTaskIdentifier = k_taskIdentifierDone;
  1060. metadata = [[NCManageDatabase sharedInstance] updateMetadata:metadata];
  1061. }
  1062. // ALL TASK DONE (PLAIN/CRYPTO)
  1063. if (metadata.sessionTaskIdentifier == k_taskIdentifierDone && metadata.sessionTaskIdentifierPlist == k_taskIdentifierDone) {
  1064. #ifndef EXTENSION
  1065. [app.listProgressMetadata removeObjectForKey:sessionID];
  1066. #endif
  1067. NSLog(@"[LOG] Insert new upload : %@ - FileNamePrint : %@ - fileID : %@", metadata.fileName, metadata.fileNamePrint, metadata.fileID);
  1068. metadata.session = @"";
  1069. metadata.sessionError = @"";
  1070. metadata.sessionID = @"";
  1071. metadata = [[NCManageDatabase sharedInstance] updateMetadata:metadata];
  1072. // rename file sessionID -> fileID
  1073. [CCUtility moveFileAtPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, sessionID] toPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, metadata.fileID]];
  1074. // remove temp icon
  1075. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@.ico", _directoryUser, sessionID] error:nil];
  1076. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@.ico", _directoryUser, metadata.fileID] error:nil];
  1077. // if crypto remove filename data
  1078. if (metadata.cryptated)
  1079. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, metadata.fileNameData] error:nil];
  1080. // Local
  1081. if (metadata.directory == NO)
  1082. [[NCManageDatabase sharedInstance] addLocalFileWithMetadata:metadata];
  1083. // EXIF
  1084. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image])
  1085. [[CCExifGeo sharedInstance] setExifLocalTableEtag:metadata directoryUser:_directoryUser activeAccount:_activeAccount];
  1086. // Create ICON
  1087. if (metadata.directory == NO)
  1088. [CCGraphics createNewImageFrom:metadata.fileID directoryUser:_directoryUser fileNameTo:metadata.fileID fileNamePrint:metadata.fileNamePrint size:@"m" imageForUpload:NO typeFile:metadata.typeFile writePreview:YES optimizedFileName:[CCUtility getOptimizedPhoto]];
  1089. // Optimization
  1090. if ([CCUtility getUploadAndRemovePhoto] || [metadata.sessionSelectorPost isEqualToString:selectorUploadRemovePhoto])
  1091. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, metadata.fileID] error:nil];
  1092. // Copy photo or video in the photo album for auto upload
  1093. if ([metadata.assetLocalIdentifier length] > 0 && [metadata.sessionSelector isEqualToString:selectorUploadAutoUpload]) {
  1094. PHAsset *asset;
  1095. PHFetchResult *result = [PHAsset fetchAssetsWithLocalIdentifiers:@[metadata.assetLocalIdentifier] options:nil];
  1096. if(result.count){
  1097. asset = result[0];
  1098. [asset saveToAlbum:[NCBrandOptions sharedInstance].brand completionBlock:^(BOOL success) {
  1099. if (success) NSLog(@"[LOG] Insert file %@ in %@", metadata.fileNamePrint, [NCBrandOptions sharedInstance].brand);
  1100. else NSLog(@"[LOG] File %@ do not insert in %@", metadata.fileNamePrint, [NCBrandOptions sharedInstance].brand);
  1101. }];
  1102. }
  1103. }
  1104. // Actvity
  1105. [[NCManageDatabase sharedInstance] addActivityClient:fileName fileID:fileID action:k_activityDebugActionUpload selector:metadata.sessionSelector note:serverUrl type:k_activityTypeSuccess verbose:k_activityVerboseDefault activeUrl:_activeUrl];
  1106. dispatch_async(dispatch_get_main_queue(), ^{
  1107. if ([[self getDelegate:sessionID] respondsToSelector:@selector(uploadFileSuccess:fileID:serverUrl:selector:selectorPost:)])
  1108. [[self getDelegate:sessionID] uploadFileSuccess:nil fileID:metadata.fileID serverUrl:serverUrl selector:metadata.sessionSelector selectorPost:metadata.sessionSelectorPost];
  1109. });
  1110. }
  1111. }
  1112. #pragma --------------------------------------------------------------------------------------------
  1113. #pragma mark ===== Download Verify =====
  1114. #pragma --------------------------------------------------------------------------------------------
  1115. - (void)verifyDownloadInProgress
  1116. {
  1117. #ifndef EXTENSION
  1118. // No in background
  1119. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground)
  1120. return;
  1121. NSArray *dataSourceDownload = [[NCManageDatabase sharedInstance] getTableMetadataDownload];
  1122. NSArray *dataSourceDownloadWWan = [[NCManageDatabase sharedInstance] getTableMetadataDownloadWWan];
  1123. NSMutableArray *dataSource = [NSMutableArray new];
  1124. [dataSource addObjectsFromArray:dataSourceDownload];
  1125. [dataSource addObjectsFromArray:dataSourceDownloadWWan];
  1126. NSLog(@"[LOG] Verify download file in progress n. %lu", (unsigned long)[dataSource count]);
  1127. for (tableMetadata *metadata in dataSource) {
  1128. NSURLSession *session = [self getSessionfromSessionDescription:metadata.session];
  1129. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1130. dispatch_async(dispatch_get_main_queue(), ^{
  1131. BOOL findTask = NO;
  1132. BOOL findTaskPlist = NO;
  1133. for (NSURLSessionDownloadTask *downloadTask in downloadTasks) {
  1134. NSLog(@"[LOG] Find metadata Tasks [%li %li] = [%lu] state : %lu", (long)metadata.sessionTaskIdentifier, (long)metadata.sessionTaskIdentifierPlist ,(unsigned long)downloadTask.taskIdentifier, (unsigned long)[downloadTask state]);
  1135. if (metadata.sessionTaskIdentifier == downloadTask.taskIdentifier) findTask = YES;
  1136. if (metadata.sessionTaskIdentifierPlist == downloadTask.taskIdentifier) findTaskPlist = YES;
  1137. if (findTask == YES || findTaskPlist == YES) break; // trovati, download ancora in corso
  1138. }
  1139. // DATA
  1140. if (findTask == NO && metadata.sessionTaskIdentifier >= 0) {
  1141. NSLog(@"[LOG] NOT Find metadata Task [%li] fileID : %@ - filename : %@", (long)metadata.sessionTaskIdentifier, metadata.fileID, metadata.fileNameData);
  1142. [[NCManageDatabase sharedInstance] setMetadataSession:nil sessionError:[NSString stringWithFormat:@"%@", @k_CCErrorTaskDownloadNotFound] sessionSelector:nil sessionSelectorPost:nil sessionTaskIdentifier:k_taskIdentifierError sessionTaskIdentifierPlist:k_taskIdentifierNULL predicate:[NSPredicate predicateWithFormat:@"fileID = %@ ", metadata.fileID]];
  1143. dispatch_async(dispatch_get_main_queue(), ^{
  1144. if ([self.delegate respondsToSelector:@selector(reloadDatasource:)])
  1145. [self.delegate reloadDatasource:[[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID]];
  1146. });
  1147. }
  1148. // PLIST
  1149. if (findTaskPlist == NO && metadata.sessionTaskIdentifierPlist >= 0) {
  1150. NSLog(@"[LOG] NOT Find metadata TaskPlist [%li] fileID : %@ - filename : %@", (long)metadata.sessionTaskIdentifierPlist, metadata.fileID, metadata.fileName);
  1151. [[NCManageDatabase sharedInstance] setMetadataSession:@"" sessionError:@"" sessionSelector:@"" sessionSelectorPost:@"" sessionTaskIdentifier:k_taskIdentifierNULL sessionTaskIdentifierPlist:k_taskIdentifierDone predicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadata.fileID]];
  1152. dispatch_async(dispatch_get_main_queue(), ^{
  1153. if ([self.delegate respondsToSelector:@selector(reloadDatasource:)])
  1154. [self.delegate reloadDatasource:[[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID]];
  1155. });
  1156. }
  1157. });
  1158. }];
  1159. }
  1160. /* Verify Download In Error */
  1161. NSMutableSet *serversUrl = [NSMutableSet new];
  1162. NSArray *metadatas = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND session CONTAINS 'download' AND (sessionTaskIdentifier = %i OR sessionTaskIdentifierPlist = %i)", _activeAccount, k_taskIdentifierError, k_taskIdentifierError] sorted:nil ascending:NO];
  1163. NSLog(@"[LOG] Verify re download n. %lu", (unsigned long)[metadatas count]);
  1164. for (tableMetadata *metadata in metadatas) {
  1165. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1166. if (!serverUrl) continue;
  1167. if (metadata.sessionTaskIdentifier == k_taskIdentifierError)
  1168. [self downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:metadata.sessionSelector selectorPost:nil session:k_download_session taskStatus: k_taskStatusResume delegate:app.activeMain];
  1169. if (metadata.sessionTaskIdentifierPlist == k_taskIdentifierError)
  1170. [self downloadFile:metadata.fileID serverUrl:serverUrl downloadData:NO downloadPlist:YES selector:metadata.sessionSelector selectorPost:nil session:k_download_session taskStatus: k_taskStatusResume delegate:app.activeMain];
  1171. [serversUrl addObject:serverUrl];
  1172. NSLog(@"[LOG] Re download file : %@ - %@ [%li %li]", metadata.fileName, metadata.fileNamePrint, (long)metadata.sessionTaskIdentifier, (long)metadata.sessionTaskIdentifierPlist);
  1173. }
  1174. dispatch_async(dispatch_get_main_queue(), ^{
  1175. for (NSString *serverUrl in serversUrl)
  1176. if ([self.delegate respondsToSelector:@selector(reloadDatasource:)])
  1177. [self.delegate reloadDatasource:serverUrl];
  1178. });
  1179. #endif
  1180. }
  1181. #pragma --------------------------------------------------------------------------------------------
  1182. #pragma mark ===== Upload Verify =====
  1183. #pragma --------------------------------------------------------------------------------------------
  1184. - (void)verifyUploadInProgress
  1185. {
  1186. #ifndef EXTENSION
  1187. // No in background
  1188. if ([[UIApplication sharedApplication] applicationState] != UIApplicationStateBackground) {
  1189. NSArray *dataSourceUpload = [[NCManageDatabase sharedInstance] getTableMetadataUpload];
  1190. NSArray *dataSourceUploadWWan = [[NCManageDatabase sharedInstance] getTableMetadataUploadWWan];
  1191. NSMutableArray *dataSource = [[NSMutableArray alloc] init];
  1192. [dataSource addObjectsFromArray:dataSourceUpload];
  1193. [dataSource addObjectsFromArray:dataSourceUploadWWan];
  1194. NSLog(@"[LOG] Verify upload file in progress n. %lu", (unsigned long)[dataSource count]);
  1195. for (tableMetadata *metadata in dataSource) {
  1196. __block NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1197. if (!serverUrl) continue;
  1198. NSURLSession *session = [self getSessionfromSessionDescription:metadata.session];
  1199. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1200. BOOL findTask = NO;
  1201. BOOL findTaskPlist = NO;
  1202. // cerchiamo la corrispondenza dei task
  1203. for (NSURLSessionUploadTask *uploadTask in uploadTasks) {
  1204. NSLog(@"[LOG] Find metadata Tasks [%li %li] = [%lu] state : %lu", (long)metadata.sessionTaskIdentifier, (long)metadata.sessionTaskIdentifierPlist , (unsigned long)uploadTask.taskIdentifier, (unsigned long)[uploadTask state]);
  1205. if (metadata.sessionTaskIdentifier == uploadTask.taskIdentifier) findTask = YES;
  1206. if (metadata.sessionTaskIdentifierPlist == uploadTask.taskIdentifier) findTaskPlist = YES;
  1207. if (findTask == YES || findTaskPlist == YES) break;
  1208. }
  1209. // se non c'è (ci sono) il relativo uploadTask.taskIdentifier allora chiediamolo
  1210. if ((metadata.cryptated == YES && findTask == NO && findTaskPlist == NO) || (metadata.cryptated == NO && findTask == NO)) {
  1211. NSLog(@"[LOG] Call ReadFileVerifyUpload because this file %@ (criptated %i) is in progress but there is no task : [%li %li]", metadata.fileNamePrint, metadata.cryptated, (long)metadata.sessionTaskIdentifier, (long)metadata.sessionTaskIdentifierPlist);
  1212. if (metadata.sessionTaskIdentifier >= 0) [self readFileVerifyUpload:metadata.fileNameData fileNamePrint:metadata.fileNamePrint serverUrl:serverUrl];
  1213. if (metadata.sessionTaskIdentifierPlist >= 0) [self readFileVerifyUpload:metadata.fileName fileNamePrint:metadata.fileNamePrint serverUrl:serverUrl];
  1214. }
  1215. }];
  1216. // Notification change session
  1217. NSArray *object = [[NSArray alloc] initWithObjects:session, metadata, nil];
  1218. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  1219. }
  1220. }
  1221. /* Verify Upload In Error */
  1222. NSMutableSet *directoryIDs = [NSMutableSet new];
  1223. NSArray *metadatas = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND session CONTAINS 'upload' AND (sessionTaskIdentifier = %i OR sessionTaskIdentifierPlist = %i OR sessionTaskIdentifier = %i OR sessionTaskIdentifierPlist = %i)", _activeAccount, k_taskIdentifierError, k_taskIdentifierError, k_taskIdentifierWaitStart, k_taskIdentifierWaitStart] sorted:nil ascending:NO];
  1224. NSLog(@"[LOG] Verify re upload n. %lu", (unsigned long)[metadatas count]);
  1225. for (tableMetadata *metadata in metadatas) {
  1226. [self uploadFileMetadata:metadata taskStatus: k_taskStatusResume];
  1227. [directoryIDs addObject:metadata.directoryID];
  1228. NSLog(@"[LOG] Re upload file : %@", metadata.fileName);
  1229. }
  1230. dispatch_async(dispatch_get_main_queue(), ^{
  1231. for (NSString *directoryID in directoryIDs)
  1232. if ([self.delegate respondsToSelector:@selector(reloadDatasource:)])
  1233. [self.delegate reloadDatasource:[[NCManageDatabase sharedInstance] getServerUrl:directoryID]];
  1234. });
  1235. #endif
  1236. }
  1237. - (void)readFileVerifyUpload:(NSString *)fileName fileNamePrint:(NSString *)fileNamePrint serverUrl:(NSString *)serverUrl
  1238. {
  1239. #ifndef EXTENSION
  1240. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:_activeAccount];
  1241. metadataNet.action = actionReadFile;
  1242. metadataNet.fileName = fileName;
  1243. metadataNet.fileNamePrint = fileNamePrint;
  1244. metadataNet.serverUrl = serverUrl;
  1245. metadataNet.selector = selectorReadFileVerifyUpload;
  1246. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1247. #else
  1248. NSLog(@"[LOG] Function not available for extension.");
  1249. #endif
  1250. }
  1251. //
  1252. // File exists : selectorReadFileVerifyUpload
  1253. //
  1254. - (void)readFileSuccess:(CCMetadataNet *)metadataNet metadata:(tableMetadata *)metadata
  1255. {
  1256. NSString *fileName;
  1257. if ([CCUtility isCryptoString:metadata.fileName])
  1258. fileName = [metadata.fileName stringByAppendingString:@".plist"];
  1259. else
  1260. fileName = metadataNet.fileName;
  1261. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:metadataNet.serverUrl];
  1262. if (!directoryID)
  1263. [self uploadFileSuccessFailure:metadata fileName:metadataNet.fileName fileID:metadata.fileID etag:metadata.etag date:metadata.date serverUrl:metadataNet.serverUrl errorCode:k_CCErrorFileUploadNotFound];
  1264. tableMetadata *metadataTemp = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileName = %@ AND directoryID = %@ AND account = %@", fileName , directoryID, _activeAccount]];
  1265. // is completed ?
  1266. if (metadataTemp.sessionTaskIdentifier == k_taskIdentifierDone && metadataTemp.sessionTaskIdentifierPlist == k_taskIdentifierDone) {
  1267. [CCGraphics createNewImageFrom:metadata.fileID directoryUser:_directoryUser fileNameTo:metadata.fileID fileNamePrint:metadata.fileNamePrint size:@"m" imageForUpload:NO typeFile:metadata.typeFile writePreview:YES optimizedFileName:[CCUtility getOptimizedPhoto]];
  1268. NSLog(@"[LOG] Verify read file success, but files already processed");
  1269. dispatch_async(dispatch_get_main_queue(), ^{
  1270. if ([self.delegate respondsToSelector:@selector(reloadDatasource:)])
  1271. [self.delegate reloadDatasource:[[NCManageDatabase sharedInstance] getServerUrl:directoryID]];
  1272. });
  1273. } else {
  1274. [self uploadFileSuccessFailure:metadataTemp fileName:metadataNet.fileName fileID:metadata.fileID etag:metadata.etag date:metadata.date serverUrl:metadataNet.serverUrl errorCode:0];
  1275. }
  1276. }
  1277. //
  1278. // File do not exists : selectorReadFileVerifyUpload
  1279. //
  1280. - (void)readFileFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1281. {
  1282. NSString *fileName;
  1283. if ([CCUtility isCryptoString:metadataNet.fileName])
  1284. fileName = [metadataNet.fileName stringByAppendingString:@".plist"];
  1285. else
  1286. fileName = metadataNet.fileName;
  1287. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:metadataNet.serverUrl];
  1288. if (!directoryID) return;
  1289. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileName = %@ AND directoryID = %@ AND account = %@",fileName , directoryID, _activeAccount]];
  1290. NSInteger error;
  1291. if (errorCode == kOCErrorServerPathNotFound)
  1292. error = k_CCErrorFileUploadNotFound;
  1293. else
  1294. error = errorCode;
  1295. // fix CCNetworking.m line 1340 2.17.2 (00005)
  1296. if (metadata)
  1297. [self uploadFileSuccessFailure:metadata fileName:metadataNet.fileName fileID:metadata.fileID etag:metadata.etag date:metadata.date serverUrl:metadataNet.serverUrl errorCode:error];
  1298. }
  1299. #pragma --------------------------------------------------------------------------------------------
  1300. #pragma mark ===== Utility =====
  1301. #pragma --------------------------------------------------------------------------------------------
  1302. - (id)getDelegate:(NSString *)fileID
  1303. {
  1304. id delegate = [_delegates objectForKey:fileID];
  1305. if (delegate)
  1306. return delegate;
  1307. else
  1308. return self.delegate;
  1309. }
  1310. - (NSString *)getServerUrlFromUrl:(NSString *)url
  1311. {
  1312. NSString *fileName = [url lastPathComponent];
  1313. url = [url stringByReplacingOccurrencesOfString:[@"/" stringByAppendingString:fileName] withString:@""];
  1314. return url;
  1315. }
  1316. - (NSString *)getTitleFromPlistName:(NSString *)fileName
  1317. {
  1318. if ([[fileName lastPathComponent] isEqualToString:@"plist"] == NO)
  1319. fileName = [fileName stringByAppendingString:@".plist"];
  1320. if (![[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, fileName]]) return nil;
  1321. NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithContentsOfFile:[NSString stringWithFormat:@"%@/%@", _directoryUser, fileName]];
  1322. return [data objectForKey:@"title"];
  1323. }
  1324. @end
  1325. #pragma --------------------------------------------------------------------------------------------
  1326. #pragma mark ===== CCMetadataNet =====
  1327. #pragma --------------------------------------------------------------------------------------------
  1328. @implementation CCMetadataNet
  1329. - (id)init
  1330. {
  1331. self = [super init];
  1332. self.priority = NSOperationQueuePriorityNormal;
  1333. return self;
  1334. }
  1335. - (id)initWithAccount:(NSString *)withAccount
  1336. {
  1337. self = [super init];
  1338. if (self) {
  1339. _account = withAccount;
  1340. _priority = NSOperationQueuePriorityNormal;
  1341. }
  1342. return self;
  1343. }
  1344. - (id)copyWithZone: (NSZone *) zone
  1345. {
  1346. CCMetadataNet *metadataNet = [[CCMetadataNet allocWithZone: zone] init];
  1347. [metadataNet setAccount: self.account];
  1348. [metadataNet setAction: self.action];
  1349. [metadataNet setAssetLocalIdentifier: self.assetLocalIdentifier];
  1350. [metadataNet setCryptated: self.cryptated];
  1351. [metadataNet setDate: self.date];
  1352. [metadataNet setDelegate: self.delegate];
  1353. [metadataNet setDepth: self.depth];
  1354. [metadataNet setDirectory: self.directory];
  1355. [metadataNet setDirectoryID: self.directoryID];
  1356. [metadataNet setDirectoryIDTo: self.directoryIDTo];
  1357. [metadataNet setDownloadData: self.downloadData];
  1358. [metadataNet setDownloadPlist: self.downloadPlist];
  1359. [metadataNet setErrorCode: self.errorCode];
  1360. [metadataNet setErrorRetry: self.errorRetry];
  1361. [metadataNet setEtag:self.etag];
  1362. [metadataNet setExpirationTime: self.expirationTime];
  1363. [metadataNet setFileID: self.fileID];
  1364. [metadataNet setFileName: self.fileName];
  1365. [metadataNet setFileNameTo: self.fileNameTo];
  1366. [metadataNet setFileNameLocal: self.fileNameLocal];
  1367. [metadataNet setFileNamePrint: self.fileNamePrint];
  1368. [metadataNet setOptions: self.options];
  1369. [metadataNet setPassword: self.password];
  1370. [metadataNet setPathFolder: self.pathFolder];
  1371. [metadataNet setPriority: self.priority];
  1372. [metadataNet setServerUrl: self.serverUrl];
  1373. [metadataNet setServerUrlTo: self.serverUrlTo];
  1374. [metadataNet setSelector: self.selector];
  1375. [metadataNet setSelectorPost: self.selectorPost];
  1376. [metadataNet setSession: self.session];
  1377. [metadataNet setSessionID: self.sessionID];
  1378. [metadataNet setShare: self.share];
  1379. [metadataNet setShareeType: self.shareeType];
  1380. [metadataNet setSharePermission: self.sharePermission];
  1381. [metadataNet setSize: self.size];
  1382. [metadataNet setTaskStatus: self.taskStatus];
  1383. return metadataNet;
  1384. }
  1385. @end