CCNetworking.m 100 KB

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