CCNetworking.m 92 KB

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