CCNetworking.m 102 KB

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