CCNetworking.m 100 KB

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