CCNetworking.m 93 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744
  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: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 = 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 = 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: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 = 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: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 = 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 = 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: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 = 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:download_session]) return [self sessionDownload];
  199. if ([sessionDescription isEqualToString:download_session_foreground]) return [self sessionDownloadForeground];
  200. if ([sessionDescription isEqualToString:download_session_wwan]) return [self sessionWWanDownload];
  201. if ([sessionDescription isEqualToString:upload_session]) return [self sessionUpload];
  202. if ([sessionDescription isEqualToString:upload_session_foreground]) return [self sessionUploadForeground];
  203. if ([sessionDescription isEqualToString: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: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: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. // select type of session
  390. metadata.session = session;
  391. [self downloaURLSession:metadata.fileNameData fileNamePrint:metadata.fileNamePrint serverUrl:serverUrl fileID:metadata.fileID session:metadata.session taskStatus:taskStatus selector:selector];
  392. [CCCoreData setMetadataSession:metadata.session sessionError:@"" sessionSelector:selector sessionSelectorPost:selectorPost sessionTaskIdentifier: k_taskIdentifierNULL sessionTaskIdentifierPlist:k_taskIdentifierNULL predicate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)",metadata.fileID, _activeAccount] context:_context];
  393. }
  394. if (downloadPlist) {
  395. // it's in download
  396. if ([CCCoreData getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"(account == %@) AND (fileID == %@) AND (session CONTAINS 'download') AND (sessionTaskIdentifierPlist >= 0)", _activeAccount, metadata.fileID] context:_context]) {
  397. NSLog(@"[LOG] Download file already in progress %@ - %@", metadata.fileName, metadata.fileNamePrint);
  398. return;
  399. }
  400. // select tye of session
  401. metadata.session = session;
  402. [self downloaURLSession:metadata.fileName fileNamePrint:metadata.fileNamePrint serverUrl:serverUrl fileID:metadata.fileID session:metadata.session taskStatus:taskStatus selector:selector];
  403. [CCCoreData setMetadataSession:metadata.session sessionError:@"" sessionSelector:selector sessionSelectorPost:selectorPost sessionTaskIdentifier: k_taskIdentifierNULL sessionTaskIdentifierPlist: k_taskIdentifierNULL predicate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)",metadata.fileID, _activeAccount] context:_context];
  404. }
  405. }
  406. - (void)downloaURLSession:(NSString *)fileName fileNamePrint:(NSString *)fileNamePrint serverUrl:(NSString *)serverUrl fileID:(NSString *)fileID session:(NSString *)session taskStatus:(NSInteger)taskStatus selector:(NSString *)selector
  407. {
  408. NSURLSession *sessionDownload;
  409. NSURL *url;
  410. NSMutableURLRequest *request;
  411. if ([_typeCloud isEqualToString:typeCloudNextcloud] || [_typeCloud isEqualToString:typeCloudOwnCloud]) {
  412. NSString *serverFileUrl = [[NSString stringWithFormat:@"%@/%@", serverUrl, fileName] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  413. url = [NSURL URLWithString:serverFileUrl];
  414. request = [NSMutableURLRequest requestWithURL:url];
  415. NSData *authData = [[NSString stringWithFormat:@"%@:%@", _activeUser, _activePassword] dataUsingEncoding:NSUTF8StringEncoding];
  416. NSString *authValue = [NSString stringWithFormat: @"Basic %@",[authData base64EncodedStringWithOptions:0]];
  417. [request setValue:authValue forHTTPHeaderField:@"Authorization"];
  418. }
  419. if ([session isEqualToString:download_session]) sessionDownload = [self sessionDownload];
  420. else if ([session isEqualToString:download_session_foreground]) sessionDownload = [self sessionDownloadForeground];
  421. else if ([session isEqualToString:download_session_wwan]) sessionDownload = [self sessionWWanDownload];
  422. NSURLSessionDownloadTask *downloadTask = [sessionDownload downloadTaskWithRequest:request];
  423. if (taskStatus == k_taskStatusCancel) [downloadTask cancel];
  424. else if (taskStatus == k_taskStatusSuspend) [downloadTask suspend];
  425. else if (taskStatus == k_taskStatusResume) [downloadTask resume];
  426. if ([[self getDelegate:fileID] respondsToSelector:@selector(downloadTaskSave:)])
  427. [[self getDelegate:fileID] downloadTaskSave:downloadTask];
  428. if (downloadTask == nil) {
  429. NSUInteger sessionTaskIdentifier = k_taskIdentifierNULL;
  430. NSUInteger sessionTaskIdentifierPlist = k_taskIdentifierNULL;
  431. if ([CCUtility isFileNotCryptated:fileName] || [CCUtility isCryptoString:fileName]) sessionTaskIdentifier = k_taskIdentifierError;
  432. if ([CCUtility isCryptoPlistString:fileName]) sessionTaskIdentifierPlist = k_taskIdentifierError;
  433. [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];
  434. NSLog(@"[LOG] downloadFileSession TaskIdentifier [error CCErrorTaskNil] - %@ - %@", fileName, fileNamePrint);
  435. } else {
  436. NSUInteger sessionTaskIdentifier = k_taskIdentifierNULL;
  437. NSUInteger sessionTaskIdentifierPlist = k_taskIdentifierNULL;
  438. if ([CCUtility isCryptoString:fileName] || [CCUtility isFileNotCryptated:fileName]) sessionTaskIdentifier = downloadTask.taskIdentifier;
  439. if ([CCUtility isCryptoPlistString:fileName]) sessionTaskIdentifierPlist = downloadTask.taskIdentifier;
  440. [CCCoreData setMetadataSession:nil sessionError:@"" sessionSelector:nil sessionSelectorPost:nil sessionTaskIdentifier:sessionTaskIdentifier sessionTaskIdentifierPlist:sessionTaskIdentifierPlist predicate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", fileID, _activeAccount] context:_context];
  441. NSLog(@"[LOG] downloadFileSession %@ - %@ Task [%lu %lu]", fileID, fileNamePrint, (unsigned long)sessionTaskIdentifier, (unsigned long)sessionTaskIdentifierPlist);
  442. }
  443. dispatch_async(dispatch_get_main_queue(), ^{
  444. // Refresh datasource if is not a Plist
  445. if ([_delegate respondsToSelector:@selector(reloadDatasource:fileID:selector:)] && [CCUtility isCryptoPlistString:fileName] == NO)
  446. [_delegate reloadDatasource:serverUrl fileID:fileID selector:selector];
  447. });
  448. }
  449. - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
  450. {
  451. NSString *url = [[[downloadTask currentRequest].URL absoluteString] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  452. NSString *fileName = [url lastPathComponent];
  453. NSString *serverUrl = [self getServerUrlFromUrl:url];
  454. // if plist return
  455. if ([CCUtility getTypeFileName:fileName] == k_metadataTypeFilenamePlist)
  456. return;
  457. float progress = (float) totalBytesWritten / (float)totalBytesExpectedToWrite;
  458. if ([_currentProgressMetadata.fileName isEqualToString:fileName] == NO && [_currentProgressMetadata.fileNameData isEqualToString:fileName] == NO)
  459. _currentProgressMetadata = [CCCoreData getMetadataFromFileName:fileName directoryID:[CCCoreData getDirectoryIDFromServerUrl:serverUrl activeAccount:_activeAccount] activeAccount:_activeAccount context:_context];
  460. dispatch_async(dispatch_get_main_queue(), ^{
  461. if (_currentProgressMetadata) {
  462. #ifndef EXTENSION
  463. // Control Center
  464. [app.controlCenter progressTask:_currentProgressMetadata.fileID serverUrl:serverUrl cryptated:_currentProgressMetadata.cryptated progress:progress];
  465. // Detail
  466. if (app.activeDetail)
  467. [app.activeDetail progressTask:_currentProgressMetadata.fileID serverUrl:serverUrl cryptated:_currentProgressMetadata.cryptated progress:progress];
  468. #endif
  469. if ([self.delegate respondsToSelector:@selector(progressTask:serverUrl:cryptated:progress:)])
  470. [self.delegate progressTask:_currentProgressMetadata.fileID serverUrl:serverUrl cryptated:_currentProgressMetadata.cryptated progress:progress];
  471. }
  472. });
  473. }
  474. - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
  475. {
  476. NSURLRequest *url = [downloadTask currentRequest];
  477. NSString *filename = [[url.URL absoluteString] lastPathComponent];
  478. CCMetadata *metadata = metadata = [CCCoreData getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"(session = %@) AND ((sessionTaskIdentifier == %i) OR (sessionTaskIdentifierPlist == %i))",session.sessionDescription, downloadTask.taskIdentifier, downloadTask.taskIdentifier] context:_context];
  479. NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)downloadTask.response;
  480. if (httpResponse.statusCode >= 200 && httpResponse.statusCode < 300) {
  481. NSString *destinationFilePath;
  482. if ([CCUtility isCryptoPlistString:filename]) {
  483. destinationFilePath = [NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryActiveUser:_activeUser activeUrl:_activeUrl], filename];
  484. } else {
  485. if (metadata.cryptated) destinationFilePath = [NSString stringWithFormat:@"%@/%@.crypt", [CCUtility getDirectoryActiveUser:_activeUser activeUrl:_activeUrl], metadata.fileID];
  486. else destinationFilePath = [NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryActiveUser:_activeUser activeUrl:_activeUrl], metadata.fileID];
  487. }
  488. NSURL *destinationURL = [NSURL fileURLWithPath:destinationFilePath];
  489. [[NSFileManager defaultManager] removeItemAtURL:destinationURL error:NULL];
  490. [[NSFileManager defaultManager] copyItemAtURL:location toURL:destinationURL error:nil];
  491. }
  492. }
  493. - (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
  494. {
  495. #ifndef EXTENSION
  496. if (fileID)
  497. [app.listProgressMetadata removeObjectForKey:fileID];
  498. #endif
  499. if (errorCode != 0) {
  500. //
  501. // if cancel or was a xxxxxx.plist delete session
  502. //
  503. if (errorCode == kCFURLErrorCancelled || [CCUtility isCryptoPlistString:fileName]) {
  504. [CCCoreData setMetadataSession:@"" sessionError:@"" sessionSelector:@"" sessionSelectorPost:@"" sessionTaskIdentifier: k_taskIdentifierDone sessionTaskIdentifierPlist: k_taskIdentifierDone predicate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", fileID, _activeAccount] context:_context];
  505. } else {
  506. [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];
  507. }
  508. // Delegate downloadFileFailure:
  509. dispatch_async(dispatch_get_main_queue(), ^{
  510. if ([[self getDelegate:fileID] respondsToSelector:@selector(downloadFileFailure:serverUrl:selector:message:errorCode:)])
  511. [[self getDelegate:fileID] downloadFileFailure:fileID serverUrl:serverUrl selector:selector message:[CCError manageErrorKCF:errorCode withNumberError:YES] errorCode:errorCode];
  512. });
  513. NSLog(@"[LOG] Download Failure Session Filename : %@ ERROR : %@", fileName, [NSString stringWithFormat:@"%@", @(errorCode)]);
  514. } else {
  515. CCMetadata *metadata = [CCCoreData getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", fileID, _activeAccount] context:_context];
  516. if ([CCUtility isCryptoString:fileName] || [CCUtility isFileNotCryptated:fileName]) metadata.sessionTaskIdentifier = k_taskIdentifierDone;
  517. if ([CCUtility isCryptoPlistString:fileName]) metadata.sessionTaskIdentifierPlist = k_taskIdentifierDone;
  518. if (metadata.sessionTaskIdentifier == k_taskIdentifierDone && metadata.sessionTaskIdentifierPlist == k_taskIdentifierDone) {
  519. [CCCoreData setMetadataSession:@"" sessionError:@"" sessionSelector:@"" sessionSelectorPost:@"" sessionTaskIdentifier:metadata.sessionTaskIdentifier sessionTaskIdentifierPlist:metadata.sessionTaskIdentifierPlist predicate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", fileID, _activeAccount] context:_context];
  520. } else {
  521. [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];
  522. }
  523. // DATA
  524. if ([CCUtility isCryptoString:fileName] || [CCUtility isFileNotCryptated:fileName]) {
  525. [CCCoreData downloadFile:metadata directoryUser:_directoryUser activeAccount:_activeAccount];
  526. }
  527. // download File Success
  528. dispatch_async(dispatch_get_main_queue(), ^{
  529. if ([[self getDelegate:fileID] respondsToSelector:@selector(downloadFileSuccess:serverUrl:selector:selectorPost:)])
  530. [[self getDelegate:fileID] downloadFileSuccess:fileID serverUrl:serverUrl selector:selector selectorPost:selectorPost];
  531. });
  532. NSLog(@"[LOG] Download Success Session Metadata : %@ - FileNamePrint : %@ - fileID : %@ - Task : [%i %i]", metadata.fileName, metadata.fileNamePrint, metadata.fileID, metadata.sessionTaskIdentifier, metadata.sessionTaskIdentifierPlist);
  533. }
  534. }
  535. #pragma --------------------------------------------------------------------------------------------
  536. #pragma mark ===== Upload =====
  537. #pragma --------------------------------------------------------------------------------------------
  538. - (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
  539. {
  540. PHFetchResult *result = [PHAsset fetchAssetsWithLocalIdentifiers:@[localIdentifier] options:nil];
  541. if (!result.count) {
  542. if ([delegate respondsToSelector:@selector(uploadFileFailure:fileID:serverUrl:selector:message:errorCode:)])
  543. [delegate uploadFileFailure:nil fileID:nil serverUrl:serverUrl selector:selector message:@"Internal error" errorCode: k_CCErrorInternalError];
  544. return;
  545. }
  546. PHAsset *asset = result[0];
  547. PHAssetMediaType assetMediaType = asset.mediaType;
  548. NSDate *assetDate = asset.creationDate;
  549. __block NSError *error = nil;
  550. // create fileName
  551. NSString *assetFileName = [asset valueForKey:@"filename"];
  552. NSString *fileNamePath = [NSString stringWithFormat:@"%@/%@", _directoryUser, fileName];
  553. //delegate
  554. if (delegate == nil)
  555. delegate = self.delegate;
  556. // VIDEO
  557. if (assetMediaType == PHAssetMediaTypeVideo) {
  558. // Automatic Upload video encrypted ?
  559. if ([selector isEqualToString:selectorUploadAutomatic] || [selector isEqualToString:selectorUploadAutomaticAll])
  560. cryptated = [CCCoreData getCameraUploadCryptatedVideoActiveAccount:_activeAccount];
  561. @autoreleasepool {
  562. dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
  563. PHVideoRequestOptions *options = [[PHVideoRequestOptions alloc] init];
  564. options.version = PHVideoRequestOptionsVersionOriginal;
  565. [[PHImageManager defaultManager] requestAVAssetForVideo:asset options:options resultHandler:^(AVAsset *asset, AVAudioMix *audioMix, NSDictionary *info) {
  566. if ([asset isKindOfClass:[AVURLAsset class]]) {
  567. NSData *data = [[NSData alloc] initWithContentsOfURL:[(AVURLAsset *)asset URL] options:0 error:&error];
  568. if (!error || [data length] > 0) {
  569. [data writeToFile:fileNamePath options:NSDataWritingAtomic error:&error];
  570. } else {
  571. if (!error)
  572. error = [NSError errorWithDomain:@"it.twsweb.cryptocloud" code:kCFURLErrorFileDoesNotExist userInfo:nil];
  573. }
  574. } else {
  575. error = [NSError errorWithDomain:@"it.twsweb.cryptocloud" code:kCFURLErrorFileDoesNotExist userInfo:nil];
  576. }
  577. dispatch_semaphore_signal(semaphore);
  578. }];
  579. while (dispatch_semaphore_wait(semaphore, DISPATCH_TIME_NOW))
  580. [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
  581. }
  582. }
  583. // IMAGE
  584. if (assetMediaType == PHAssetMediaTypeImage) {
  585. // Automatic Upload photo encrypted ?
  586. if ([selector isEqualToString:selectorUploadAutomatic] || [selector isEqualToString:selectorUploadAutomaticAll])
  587. cryptated = [CCCoreData getCameraUploadCryptatedPhotoActiveAccount:_activeAccount];
  588. @autoreleasepool {
  589. dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
  590. [[PHImageManager defaultManager] requestImageDataForAsset:asset options:nil resultHandler:^(NSData *imageData, NSString *dataUTI, UIImageOrientation orientation, NSDictionary *info) {
  591. [imageData writeToFile:fileNamePath options:NSDataWritingAtomic error:&error];
  592. dispatch_semaphore_signal(semaphore);
  593. }];
  594. while (dispatch_semaphore_wait(semaphore, DISPATCH_TIME_NOW))
  595. [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
  596. }
  597. }
  598. if (error) {
  599. // Error for uploadFileFailure
  600. if ([delegate respondsToSelector:@selector(uploadFileFailure:fileID:serverUrl:selector:message:errorCode:)])
  601. [delegate uploadFileFailure:nil fileID:nil serverUrl:serverUrl selector:selector message:@"_read_file_error_" errorCode:error.code];
  602. } else {
  603. [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];
  604. }
  605. }
  606. - (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
  607. {
  608. [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];
  609. }
  610. - (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
  611. {
  612. [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];
  613. }
  614. - (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
  615. {
  616. NSString *directoryID = [CCCoreData getDirectoryIDFromServerUrl:serverUrl activeAccount:_activeAccount];
  617. NSString *fileNameCrypto;
  618. CCCrypto *crypto = [[CCCrypto alloc] init];
  619. // create Metadata
  620. NSString *cameraFolderName = [CCCoreData getCameraUploadFolderNameActiveAccount:_activeAccount];
  621. NSString *cameraFolderPath = [CCCoreData getCameraUploadFolderPathActiveAccount:_activeAccount activeUrl:_activeUrl typeCloud:_typeCloud];
  622. CCMetadata *metadata = [CCUtility insertFileSystemInMetadata:fileName directory:_directoryUser activeAccount:_activeAccount cameraFolderName:cameraFolderName cameraFolderPath:cameraFolderPath];
  623. //fileID
  624. NSString *uploadID = [uploadSessionID stringByAppendingString:[CCUtility createID]];
  625. //add delegate
  626. if (delegate)
  627. [_delegates setObject:delegate forKey:uploadID];
  628. if (onlyPlist == YES) {
  629. [CCUtility moveFileAtPath:[NSTemporaryDirectory() stringByAppendingString:fileName] toPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, fileName]];
  630. [CCUtility insertInformationPlist:metadata directoryUser:_directoryUser];
  631. metadata.date = [NSDate new];
  632. metadata.fileID = uploadID;
  633. metadata.directoryID = directoryID;
  634. metadata.fileNameData = [CCUtility trasformedFileNamePlistInCrypto:fileName];
  635. metadata.localIdentifier = localIdentifier;
  636. metadata.session = session;
  637. metadata.sessionID = uploadID;
  638. metadata.sessionSelector = selector;
  639. metadata.sessionSelectorPost = selectorPost;
  640. metadata.typeCloud = _typeCloud;
  641. metadata.typeFile = k_metadataTypeFile_unknown;
  642. [CCCoreData addMetadata:metadata activeAccount:_activeAccount activeUrl:_activeUrl typeCloud:_typeCloud context:_context];
  643. [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];
  644. }
  645. else if (cryptated == YES) {
  646. if (template == YES) {
  647. // copy from temp to directory user
  648. [CCUtility moveFileAtPath:[NSTemporaryDirectory() stringByAppendingString:fileName] toPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, fileName]];
  649. [CCUtility moveFileAtPath:[NSTemporaryDirectory() stringByAppendingString:[fileName stringByAppendingString:@".plist"]] toPath:[NSString stringWithFormat:@"%@/%@.plist", _directoryUser, fileName]];
  650. fileNameCrypto = fileName; // file Name Crypto
  651. fileName = assetFileName; // file Name Print
  652. [CCUtility insertInformationPlist:metadata directoryUser:_directoryUser];
  653. metadata.date = [NSDate new];
  654. metadata.fileID = uploadID;
  655. metadata.directoryID = directoryID;
  656. metadata.fileName = [fileNameCrypto stringByAppendingString:@".plist"];
  657. metadata.fileNameData = fileNameCrypto;
  658. metadata.localIdentifier = localIdentifier;
  659. metadata.session = session;
  660. metadata.sessionID = uploadID;
  661. metadata.sessionSelector = selector;
  662. metadata.sessionSelectorPost = selectorPost;
  663. metadata.typeCloud = _typeCloud;
  664. metadata.typeFile = k_metadataTypeFile_template;
  665. [CCCoreData addMetadata:metadata activeAccount:_activeAccount activeUrl:_activeUrl typeCloud:_typeCloud context:_context];
  666. // DATA
  667. [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];
  668. // PLIST
  669. [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];
  670. }
  671. if (template == NO) {
  672. NSString *passcode = [crypto getKeyPasscode:[CCUtility getUUID]];
  673. fileNameCrypto = [crypto encryptWithCreatePlist:fileName fileNameEncrypted:fileName passcode:passcode directoryUser:_directoryUser];
  674. // Encrypted file error
  675. if (fileNameCrypto == nil) {
  676. dispatch_async(dispatch_get_main_queue(), ^{
  677. NSString *msg = [NSString stringWithFormat:NSLocalizedString(@"_encrypt_error_", nil), fileName, @""];
  678. UIAlertController *alertController= [UIAlertController alertControllerWithTitle:nil message:msg preferredStyle:UIAlertControllerStyleAlert];
  679. UIAlertAction* ok = [UIAlertAction actionWithTitle: NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault
  680. handler:^(UIAlertAction * action) {
  681. [alertController dismissViewControllerAnimated:YES completion:nil];
  682. }];
  683. [alertController addAction:ok];
  684. UIWindow *alertWindow = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
  685. alertWindow.rootViewController = [[UIViewController alloc]init];
  686. alertWindow.windowLevel = UIWindowLevelAlert + 1;
  687. [alertWindow makeKeyAndVisible];
  688. [alertWindow.rootViewController presentViewController:alertController animated:YES completion:nil];
  689. // Error for uploadFileFailure
  690. if ([[self getDelegate:uploadID] respondsToSelector:@selector(uploadFileFailure:fileID:serverUrl:selector:message:errorCode:)])
  691. [[self getDelegate:uploadID] uploadFileFailure:nil fileID:nil serverUrl:serverUrl selector:selector message:NSLocalizedString(@"_encrypt_error_", nil) errorCode:0];
  692. });
  693. return;
  694. }
  695. metadata.cryptated = YES;
  696. metadata.date = [NSDate new];
  697. metadata.fileID = uploadID;
  698. metadata.directoryID = directoryID;
  699. metadata.fileName = [fileNameCrypto stringByAppendingString:@".plist"];
  700. metadata.fileNameData = fileNameCrypto;
  701. metadata.fileNamePrint = fileName;
  702. metadata.localIdentifier = localIdentifier;
  703. metadata.session = session;
  704. metadata.sessionID = uploadID;
  705. metadata.sessionSelector = selector;
  706. metadata.sessionSelectorPost = selectorPost;
  707. metadata.typeCloud = _typeCloud;
  708. metadata.title = [self getTitleFromPlistName:fileNameCrypto];
  709. metadata.type = k_metadataType_file;
  710. if (errorCode == 403) {
  711. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:fileName message:NSLocalizedString(@"_file_already_exists_", nil) preferredStyle:UIAlertControllerStyleAlert];
  712. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  713. dispatch_async(dispatch_get_main_queue(), ^{
  714. // Change Asset Data only for automatic upload
  715. //if ([selector isEqualToString:selectorUploadAutomatic])
  716. // [CCCoreData setCameraUploadDateAssetType:assetMediaType assetDate:assetDate activeAccount:_activeAccount];
  717. // Error for uploadFileFailure
  718. if ([[self getDelegate:uploadID] respondsToSelector:@selector(uploadFileFailure:fileID:serverUrl:selector:message:errorCode:)])
  719. [[self getDelegate:uploadID] uploadFileFailure:nil fileID:nil serverUrl:serverUrl selector:selector message:NSLocalizedString(@"_file_already_exists_", nil) errorCode:403];
  720. });
  721. return;
  722. }];
  723. UIAlertAction *overwriteAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_overwrite_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  724. // -- remove record --
  725. CCMetadata *metadataDelete = [CCCoreData getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"(account == %@) AND (fileName == %@) AND (directoryID == %@)", _activeAccount, [fileNameCrypto stringByAppendingString:@".plist"], directoryID] context:nil];
  726. [CCCoreData deleteFile:metadataDelete serverUrl:serverUrl directoryUser:_directoryUser typeCloud:_typeCloud activeAccount:_activeAccount];
  727. #ifndef EXTENSION
  728. [CCGraphics createNewImageFrom:fileName directoryUser:_directoryUser fileNameTo:uploadID fileNamePrint:fileName size:@"m" imageForUpload:YES typeFile:metadata.typeFile writePreview:YES optimizedFileName:NO];
  729. #endif
  730. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video])
  731. [crypto addPlistImage:[NSString stringWithFormat:@"%@/%@", _directoryUser, [fileNameCrypto stringByAppendingString:@".plist"]] fileNamePathImage:[NSTemporaryDirectory() stringByAppendingString:uploadID]];
  732. [CCCoreData addMetadata:metadata activeAccount:_activeAccount activeUrl:_activeUrl typeCloud:_typeCloud context:_context];
  733. // DATA
  734. [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];
  735. // PLIST
  736. [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];
  737. }];
  738. [alertController addAction:cancelAction];
  739. [alertController addAction:overwriteAction];
  740. UIWindow *alertWindow = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
  741. alertWindow.rootViewController = [[UIViewController alloc]init];
  742. alertWindow.windowLevel = UIWindowLevelAlert + 1;
  743. [alertWindow makeKeyAndVisible];
  744. [alertWindow.rootViewController presentViewController:alertController animated:YES completion:nil];
  745. } else {
  746. #ifndef EXTENSION
  747. [CCGraphics createNewImageFrom:fileName directoryUser:_directoryUser fileNameTo:uploadID fileNamePrint:fileName size:@"m" imageForUpload:YES typeFile:metadata.typeFile writePreview:YES optimizedFileName:NO];
  748. #endif
  749. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video])
  750. [crypto addPlistImage:[NSString stringWithFormat:@"%@/%@", _directoryUser, [fileNameCrypto stringByAppendingString:@".plist"]] fileNamePathImage:[NSTemporaryDirectory() stringByAppendingString:uploadID]];
  751. [CCCoreData addMetadata:metadata activeAccount:_activeAccount activeUrl:_activeUrl typeCloud:_typeCloud context:_context];
  752. // DATA
  753. [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];
  754. // PLIST
  755. [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];
  756. }
  757. }
  758. }
  759. else if (cryptated == NO) {
  760. metadata.cryptated = NO;
  761. metadata.date = [NSDate new];
  762. metadata.fileID = uploadID;
  763. metadata.directoryID = directoryID;
  764. metadata.fileName = fileName;
  765. metadata.fileNameData = fileName;
  766. metadata.fileNamePrint = fileName;
  767. metadata.localIdentifier = localIdentifier;
  768. metadata.session = session;
  769. metadata.sessionID = uploadID;
  770. metadata.sessionSelector = selector;
  771. metadata.sessionSelectorPost = selectorPost;
  772. metadata.type = k_metadataType_file;
  773. metadata.typeCloud = _typeCloud;
  774. // File exists ???
  775. if (errorCode == 403) {
  776. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:fileName message:NSLocalizedString(@"_file_already_exists_", nil) preferredStyle:UIAlertControllerStyleAlert];
  777. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  778. dispatch_async(dispatch_get_main_queue(), ^{
  779. // Change Asset Data only for automatic upload
  780. //if ([selector isEqualToString:selectorUploadAutomatic])
  781. // [CCCoreData setCameraUploadDateAssetType:assetMediaType assetDate:assetDate activeAccount:_activeAccount];
  782. // Error for uploadFileFailure
  783. if ([[self getDelegate:uploadID] respondsToSelector:@selector(uploadFileFailure:fileID:serverUrl:selector:message:errorCode:)])
  784. [[self getDelegate:uploadID] uploadFileFailure:nil fileID:nil serverUrl:serverUrl selector:selector message:NSLocalizedString(@"_file_already_exists_", nil) errorCode:403];
  785. });
  786. return;
  787. }];
  788. UIAlertAction *overwriteAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_overwrite_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  789. // -- remove record --
  790. CCMetadata *metadataDelete = [CCCoreData getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"(account == %@) AND (fileName == %@) AND (directoryID == %@)", _activeAccount, fileName, directoryID] context:nil];
  791. [CCCoreData deleteFile:metadataDelete serverUrl:serverUrl directoryUser:_directoryUser typeCloud:_typeCloud activeAccount:_activeAccount];
  792. // -- Go to Upload --
  793. [CCGraphics createNewImageFrom:metadata.fileNamePrint directoryUser:_directoryUser fileNameTo:metadata.fileID fileNamePrint:metadata.fileNamePrint size:@"m" imageForUpload:YES typeFile:metadata.typeFile writePreview:YES optimizedFileName:NO];
  794. [CCCoreData addMetadata:metadata activeAccount:_activeAccount activeUrl:_activeUrl typeCloud:_typeCloud context:_context];
  795. [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];
  796. }];
  797. [alertController addAction:cancelAction];
  798. [alertController addAction:overwriteAction];
  799. UIWindow *alertWindow = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
  800. alertWindow.rootViewController = [[UIViewController alloc] init];
  801. alertWindow.windowLevel = UIWindowLevelAlert + 1;
  802. [alertWindow makeKeyAndVisible];
  803. [alertWindow.rootViewController presentViewController:alertController animated:YES completion:nil];
  804. } else {
  805. // -- Go to upload --
  806. #ifndef EXTENSION
  807. [CCGraphics createNewImageFrom:metadata.fileNamePrint directoryUser:_directoryUser fileNameTo:metadata.fileID fileNamePrint:metadata.fileNamePrint size:@"m" imageForUpload:YES typeFile:metadata.typeFile writePreview:YES optimizedFileName:NO];
  808. #endif
  809. [CCCoreData addMetadata:metadata activeAccount:_activeAccount activeUrl:_activeUrl typeCloud:_typeCloud context:_context];
  810. [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];
  811. }
  812. }
  813. }
  814. - (void)uploadFileMetadata:(CCMetadata *)metadata taskStatus:(NSInteger)taskStatus
  815. {
  816. BOOL send = NO;
  817. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:_activeAccount];
  818. if (metadata.cryptated) {
  819. // ENCRYPTED
  820. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, metadata.fileNameData]] && [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, metadata.fileName]]) {
  821. send = YES;
  822. [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];
  823. [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];
  824. }
  825. } else {
  826. // PLAIN
  827. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, metadata.sessionID]]) {
  828. send = YES;
  829. [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];
  830. }
  831. }
  832. if (send) {
  833. NSLog(@"[LOG] Re-upload File : %@ - fileID : %@", metadata.fileNamePrint, metadata.fileID);
  834. // update Coredata
  835. [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];
  836. } else {
  837. NSLog(@"[LOG] Error reUploadBackground, file not found.");
  838. #ifndef EXTENSION
  839. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_no_reuploadfile_", nil) delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  840. [alertView show];
  841. #endif
  842. }
  843. }
  844. - (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
  845. {
  846. NSURLSession *sessionUpload;
  847. NSURL *url;
  848. NSMutableURLRequest *request;
  849. if ([_typeCloud isEqualToString:typeCloudNextcloud] || [_typeCloud isEqualToString:typeCloudOwnCloud]) {
  850. NSString *fileNamePath = [[NSString stringWithFormat:@"%@/%@", serverUrl, fileName] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  851. url = [NSURL URLWithString:fileNamePath];
  852. request = [NSMutableURLRequest requestWithURL:url];
  853. NSData *authData = [[NSString stringWithFormat:@"%@:%@", _activeUser, _activePassword] dataUsingEncoding:NSUTF8StringEncoding];
  854. NSString *authValue = [NSString stringWithFormat: @"Basic %@",[authData base64EncodedStringWithOptions:0]];
  855. [request setHTTPMethod:@"PUT"];
  856. [request setValue:authValue forHTTPHeaderField:@"Authorization"];
  857. }
  858. // Rename with the SessionID
  859. NSString *fileNameForUpload;
  860. if ([CCUtility isFileNotCryptated:fileName]) fileNameForUpload = sessionID;
  861. else fileNameForUpload = fileName;
  862. if (!onlyPlist) {
  863. if ([CCUtility isFileNotCryptated:fileName])
  864. [[NSFileManager defaultManager] moveItemAtPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, fileName] toPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, fileNameForUpload] error:nil];
  865. if ([CCUtility isCryptoPlistString:fileName])
  866. [[NSFileManager defaultManager] moveItemAtPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, fileNamePrint] toPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, sessionID] error:nil];
  867. }
  868. // file exists ?
  869. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, fileNameForUpload]] == NO) {
  870. dispatch_async(dispatch_get_main_queue(), ^{
  871. // Error for uploadFileFailure
  872. if ([[self getDelegate:sessionID] respondsToSelector:@selector(uploadFileFailure:fileID:serverUrl:selector:message:errorCode:)])
  873. [[self getDelegate:sessionID] uploadFileFailure:nil fileID:sessionID serverUrl:serverUrl selector:selector message:NSLocalizedString(@"_file_not_present_", nil) errorCode:404];
  874. [CCCoreData deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"(sessionID == %@) AND (account == %@)", sessionID, _activeAccount]];
  875. });
  876. return;
  877. }
  878. if ([session isEqualToString:upload_session]) sessionUpload = [self sessionUpload];
  879. else if ([session isEqualToString:upload_session_foreground]) sessionUpload = [self sessionUploadForeground];
  880. else if ([session isEqualToString:upload_session_wwan]) sessionUpload = [self sessionWWanUpload];
  881. NSURLSessionUploadTask *uploadTask = [sessionUpload uploadTaskWithRequest:request fromFile:[NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, fileNameForUpload]]];
  882. if (taskStatus == k_taskStatusCancel) [uploadTask cancel];
  883. else if (taskStatus == k_taskStatusSuspend) [uploadTask suspend];
  884. else if (taskStatus == k_taskStatusResume) [uploadTask resume];
  885. if ([[self getDelegate:sessionID] respondsToSelector:@selector(uploadTaskSave:)])
  886. [[self getDelegate:sessionID] uploadTaskSave:uploadTask];
  887. // COREDATA
  888. if (uploadTask == nil) {
  889. NSUInteger sessionTaskIdentifier = k_taskIdentifierNULL;
  890. NSUInteger sessionTaskIdentifierPlist = k_taskIdentifierNULL;
  891. if ([CCUtility isFileNotCryptated:fileName] || [CCUtility isCryptoString:fileName]) sessionTaskIdentifier = k_taskIdentifierError;
  892. if ([CCUtility isCryptoPlistString:fileName]) sessionTaskIdentifierPlist = k_taskIdentifierError;
  893. [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];
  894. NSLog(@"[LOG] Upload file TaskIdentifier [error CCErrorTaskNil] - %@ - %@", fileName, fileNamePrint);
  895. } else {
  896. NSUInteger sessionTaskIdentifier = k_taskIdentifierNULL;
  897. NSUInteger sessionTaskIdentifierPlist = k_taskIdentifierNULL;
  898. if ([CCUtility isCryptoString:fileName] || [CCUtility isFileNotCryptated:fileName]) sessionTaskIdentifier = uploadTask.taskIdentifier;
  899. if ([CCUtility isCryptoPlistString:fileName]) sessionTaskIdentifierPlist = uploadTask.taskIdentifier;
  900. [CCCoreData setMetadataSession:session sessionError:@"" sessionSelector:nil sessionSelectorPost:nil sessionTaskIdentifier:sessionTaskIdentifier sessionTaskIdentifierPlist:sessionTaskIdentifierPlist predicate:[NSPredicate predicateWithFormat:@"(sessionID == %@) AND (account == %@)", sessionID, _activeAccount] context:_context];
  901. // Change Asset Data only for Automatic Upload
  902. //if ([selector isEqualToString:selectorUploadAutomatic])
  903. // [CCCoreData setCameraUploadDateAssetType:assetMediaType assetDate:assetDate activeAccount:_activeAccount];
  904. NSLog(@"[LOG] Upload file %@ - %@ TaskIdentifier %lu", fileName,fileNamePrint, (unsigned long)uploadTask.taskIdentifier);
  905. }
  906. dispatch_async(dispatch_get_main_queue(), ^{
  907. // refresh main
  908. if ([self.delegate respondsToSelector:@selector(reloadDatasource:fileID:selector:)])
  909. [self.delegate reloadDatasource:serverUrl fileID:nil selector:selector];
  910. });
  911. }
  912. - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
  913. {
  914. NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)dataTask.response;
  915. if (httpResponse.statusCode >= 200 && httpResponse.statusCode < 300) {
  916. NSNumber *taskIdentifier = [NSNumber numberWithLong:dataTask.taskIdentifier];
  917. if (data)
  918. [_taskData setObject:[data copy] forKey:taskIdentifier];
  919. }
  920. }
  921. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend
  922. {
  923. NSString *url = [[[task currentRequest].URL absoluteString] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  924. NSString *fileName = [url lastPathComponent];
  925. NSString *serverUrl = [self getServerUrlFromUrl:url];
  926. // if plist return
  927. if ([CCUtility getTypeFileName:fileName] == k_metadataTypeFilenamePlist)
  928. return;
  929. float progress = (float) totalBytesSent / (float)totalBytesExpectedToSend;
  930. if ([_currentProgressMetadata.fileName isEqualToString:fileName] == NO && [_currentProgressMetadata.fileNameData isEqualToString:fileName] == NO)
  931. _currentProgressMetadata = [CCCoreData getMetadataFromFileName:fileName directoryID:[CCCoreData getDirectoryIDFromServerUrl:serverUrl activeAccount:_activeAccount] activeAccount:_activeAccount context:_context];
  932. //NSLog(@"[LOG] %@ - %f", fileName, progress);
  933. dispatch_async(dispatch_get_main_queue(), ^{
  934. if (_currentProgressMetadata) {
  935. #ifndef EXTENSION
  936. // Control Center
  937. [app.controlCenter progressTask:_currentProgressMetadata.fileID serverUrl:serverUrl cryptated:_currentProgressMetadata.cryptated progress:progress];
  938. #endif
  939. if ([self.delegate respondsToSelector:@selector(progressTask:serverUrl:cryptated:progress:)])
  940. [self.delegate progressTask:_currentProgressMetadata.fileID serverUrl:serverUrl cryptated:_currentProgressMetadata.cryptated progress:progress];
  941. }
  942. });
  943. }
  944. - (void)uploadFileSuccessFailure:(CCMetadata *)metadata fileName:(NSString *)fileName fileID:(NSString *)fileID rev:(NSString *)rev date:(NSDate *)date serverUrl:(NSString *)serverUrl errorCode:(NSInteger)errorCode
  945. {
  946. NSString *sessionID = metadata.sessionID;
  947. // ERRORE
  948. if (errorCode != 0) {
  949. #ifndef EXTENSION
  950. if (sessionID)
  951. [app.listProgressMetadata removeObjectForKey:sessionID];
  952. #endif
  953. // Mark error only if not Cancelled Task
  954. if (errorCode != kCFURLErrorCancelled) {
  955. NSUInteger sessionTaskIdentifier = k_taskIdentifierNULL;
  956. NSUInteger sessionTaskIdentifierPlist = k_taskIdentifierNULL;
  957. if ([CCUtility isFileNotCryptated:fileName] || [CCUtility isCryptoString:fileName]) sessionTaskIdentifier = k_taskIdentifierError;
  958. if ([CCUtility isCryptoPlistString:fileName]) sessionTaskIdentifierPlist = k_taskIdentifierError;
  959. [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];
  960. }
  961. dispatch_async(dispatch_get_main_queue(), ^{
  962. if ([[self getDelegate:sessionID] respondsToSelector:@selector(uploadFileFailure:fileID:serverUrl:selector:message:errorCode:)])
  963. [[self getDelegate:sessionID] uploadFileFailure:nil fileID:fileID serverUrl:serverUrl selector:metadata.sessionSelector message:[CCError manageErrorKCF:errorCode withNumberError:YES] errorCode:errorCode];
  964. });
  965. return;
  966. }
  967. // PLAIN or PLIST
  968. if ([CCUtility isFileNotCryptated:fileName] || [CCUtility isCryptoPlistString:fileName]) {
  969. metadata.fileID = fileID;
  970. metadata.rev = rev;
  971. metadata.date = date;
  972. metadata.sessionTaskIdentifierPlist = k_taskIdentifierDone;
  973. if ([CCUtility isFileNotCryptated:fileName])
  974. metadata.sessionTaskIdentifier = k_taskIdentifierDone;
  975. // copy ico in new fileID
  976. [CCUtility copyFileAtPath:[NSString stringWithFormat:@"%@/%@.ico", _directoryUser, sessionID] toPath:[NSString stringWithFormat:@"%@/%@.ico", _directoryUser, fileID]];
  977. [CCCoreData updateMetadata:metadata predicate:[NSPredicate predicateWithFormat:@"(sessionID == %@) AND (account == %@)", sessionID, _activeAccount] activeAccount:_activeAccount activeUrl:_activeUrl typeCloud:_typeCloud context:_context];
  978. }
  979. // CRYPTO
  980. if ([CCUtility isCryptoString:fileName]) {
  981. metadata.sessionTaskIdentifier = k_taskIdentifierDone;
  982. [CCCoreData updateMetadata:metadata predicate:[NSPredicate predicateWithFormat:@"(sessionID == %@) AND (account == %@)", sessionID, _activeAccount] activeAccount:_activeAccount activeUrl:_activeUrl typeCloud:_typeCloud context:_context];
  983. }
  984. // ALL TASK DONE (PLAIN/CRYPTO)
  985. if (metadata.sessionTaskIdentifier == k_taskIdentifierDone && metadata.sessionTaskIdentifierPlist == k_taskIdentifierDone) {
  986. #ifndef EXTENSION
  987. if (sessionID)
  988. [app.listProgressMetadata removeObjectForKey:sessionID];
  989. #endif
  990. NSLog(@"[LOG] Insert new upload : %@ - FileNamePrint : %@ - fileID : %@", metadata.fileName, metadata.fileNamePrint, metadata.fileID);
  991. metadata.session = @"";
  992. metadata.sessionError = @"";
  993. metadata.sessionID = @"";
  994. [CCCoreData updateMetadata:metadata predicate:[NSPredicate predicateWithFormat:@"(sessionID == %@) AND (account == %@)", sessionID, _activeAccount] activeAccount:_activeAccount activeUrl:_activeUrl typeCloud:_typeCloud context:_context];
  995. // rename file sessionID -> fileID
  996. [CCUtility moveFileAtPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, sessionID] toPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, metadata.fileID]];
  997. // remove temp icon
  998. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@.ico", _directoryUser, sessionID] error:nil];
  999. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@.ico", _directoryUser, metadata.fileID] error:nil];
  1000. // if crypto remove filename data
  1001. if (metadata.cryptated)
  1002. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, metadata.fileNameData] error:nil];
  1003. // Local
  1004. if (metadata.directory == NO)
  1005. [CCCoreData addLocalFile:metadata activeAccount:_activeAccount];
  1006. // EXIF
  1007. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image])
  1008. [CCExifGeo setExifLocalTableFileID:metadata directoryUser:_directoryUser activeAccount:_activeAccount];
  1009. // Create ICON
  1010. if (metadata.directory == NO)
  1011. [CCGraphics createNewImageFrom:metadata.fileID directoryUser:_directoryUser fileNameTo:metadata.fileID fileNamePrint:metadata.fileNamePrint size:@"m" imageForUpload:NO typeFile:metadata.typeFile writePreview:YES optimizedFileName:[CCUtility getOptimizedPhoto]];
  1012. // Optimization
  1013. if ([CCUtility getUploadAndRemovePhoto] || [metadata.sessionSelectorPost isEqualToString:selectorUploadRemovePhoto])
  1014. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, metadata.fileID] error:nil];
  1015. // Copy photo or video in the photo album for automatic upload
  1016. if ([metadata.localIdentifier length] > 0 && [CCCoreData getCameraUploadSaveAlbumActiveAccount:_activeAccount] && [metadata.sessionSelector isEqualToString:selectorUploadAutomatic]) {
  1017. PHAsset *asset;
  1018. PHFetchResult *result = [PHAsset fetchAssetsWithLocalIdentifiers:@[metadata.localIdentifier] options:nil];
  1019. if(result.count){
  1020. asset = result[0];
  1021. [asset saveToAlbum:_brand_ completionBlock:^(BOOL success) {
  1022. if (success) NSLog(@"[LOG] Insert file %@ in %@", metadata.fileNamePrint, _brand_);
  1023. else NSLog(@"[LOG] File %@ do not insert in %@", metadata.fileNamePrint, _brand_);
  1024. }];
  1025. }
  1026. }
  1027. dispatch_async(dispatch_get_main_queue(), ^{
  1028. if ([[self getDelegate:sessionID] respondsToSelector:@selector(uploadFileSuccess:fileID:serverUrl:selector:selectorPost:)])
  1029. [[self getDelegate:sessionID] uploadFileSuccess:nil fileID:metadata.fileID serverUrl:serverUrl selector:metadata.sessionSelector selectorPost:metadata.sessionSelectorPost];
  1030. });
  1031. }
  1032. }
  1033. #pragma --------------------------------------------------------------------------------------------
  1034. #pragma mark ===== Download Verify =====
  1035. #pragma --------------------------------------------------------------------------------------------
  1036. - (void)verifyDownloadInProgress
  1037. {
  1038. NSArray *dataSourceDownload = [CCCoreData getTableMetadataDownloadAccount:_activeAccount];
  1039. NSArray *dataSourceDownloadWWan = [CCCoreData getTableMetadataDownloadWWanAccount:_activeAccount];
  1040. NSMutableArray *dataSource = [[NSMutableArray alloc] init];
  1041. [dataSource addObjectsFromArray:dataSourceDownload];
  1042. [dataSource addObjectsFromArray:dataSourceDownloadWWan];
  1043. NSLog(@"[LOG] Verify download file in progress n. %lu", (unsigned long)[dataSource count]);
  1044. for (TableMetadata *record in dataSource) {
  1045. __block CCMetadata *metadata = [CCCoreData insertEntityInMetadata:record];
  1046. NSURLSession *session = [self getSessionfromSessionDescription:metadata.session];
  1047. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1048. BOOL findTask = NO;
  1049. BOOL findTaskPlist = NO;
  1050. for (NSURLSessionDownloadTask *downloadTask in downloadTasks) {
  1051. NSLog(@"[LOG] Find metadata Tasks [%i %i] = [%lu] state : %lu", metadata.sessionTaskIdentifier, metadata.sessionTaskIdentifierPlist ,(unsigned long)downloadTask.taskIdentifier, (unsigned long)[downloadTask state]);
  1052. if (metadata.sessionTaskIdentifier == downloadTask.taskIdentifier) findTask = YES;
  1053. if (metadata.sessionTaskIdentifierPlist == downloadTask.taskIdentifier) findTaskPlist = YES;
  1054. if (findTask == YES || findTaskPlist == YES) break; // trovati, download ancora in corso
  1055. }
  1056. // DATA
  1057. if (findTask == NO && metadata.sessionTaskIdentifier >= 0) {
  1058. NSLog(@"[LOG] NOT Find metadata Task [%i] fileID : %@ - filename : %@", metadata.sessionTaskIdentifier, metadata.fileID, metadata.fileNameData);
  1059. [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];
  1060. dispatch_async(dispatch_get_main_queue(), ^{
  1061. if ([self.delegate respondsToSelector:@selector(reloadDatasource:fileID:selector:)])
  1062. [self.delegate reloadDatasource:[CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account] fileID:metadata.fileID selector:nil];
  1063. });
  1064. }
  1065. // PLIST
  1066. if (findTaskPlist == NO && metadata.sessionTaskIdentifierPlist >= 0) {
  1067. NSLog(@"[LOG] NOT Find metadata TaskPlist [%i] fileID : %@ - filename : %@", metadata.sessionTaskIdentifierPlist, metadata.fileID, metadata.fileName);
  1068. [CCCoreData setMetadataSession:@"" sessionError:@"" sessionSelector:@"" sessionSelectorPost:@"" sessionTaskIdentifier: k_taskIdentifierNULL sessionTaskIdentifierPlist: k_taskIdentifierDone predicate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", metadata.fileID, _activeAccount] context:_context];
  1069. dispatch_async(dispatch_get_main_queue(), ^{
  1070. if ([self.delegate respondsToSelector:@selector(reloadDatasource:fileID:selector:)])
  1071. [self.delegate reloadDatasource:[CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account] fileID:metadata.fileID selector:nil];
  1072. });
  1073. }
  1074. }];
  1075. }
  1076. [self automaticDownloadInError];
  1077. }
  1078. - (void)automaticDownloadInError
  1079. {
  1080. NSMutableSet *serversUrl = [[NSMutableSet alloc] init];
  1081. NSArray *records = [CCCoreData getTableMetadataWithPredicate:[NSPredicate predicateWithFormat:@"(account == %@) AND (session CONTAINS 'download') AND ((sessionTaskIdentifier == %i) OR (sessionTaskIdentifierPlist == %i))", _activeAccount, k_taskIdentifierError, k_taskIdentifierError] context:nil];
  1082. NSLog(@"[LOG] Verify re download n. %lu", (unsigned long)[records count]);
  1083. for (TableMetadata *record in records) {
  1084. CCMetadata *metadata = [CCCoreData insertEntityInMetadata:record];
  1085. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  1086. if (metadata.sessionTaskIdentifier == k_taskIdentifierError)
  1087. [self downloadFile:metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:metadata.sessionSelector selectorPost:nil session:download_session taskStatus: k_taskStatusResume delegate:nil];
  1088. if (metadata.sessionTaskIdentifierPlist == k_taskIdentifierError)
  1089. [self downloadFile:metadata serverUrl:serverUrl downloadData:NO downloadPlist:YES selector:metadata.sessionSelector selectorPost:nil session:download_session taskStatus: k_taskStatusResume delegate:nil];
  1090. [serversUrl addObject:serverUrl];
  1091. NSLog(@"[LOG] Re download file : %@ - %@ [%i %i]", metadata.fileName, metadata.fileNamePrint, metadata.sessionTaskIdentifier, metadata.sessionTaskIdentifierPlist);
  1092. }
  1093. dispatch_async(dispatch_get_main_queue(), ^{
  1094. for (NSString *serverUrl in serversUrl)
  1095. if ([self.delegate respondsToSelector:@selector(reloadDatasource:fileID:selector:)])
  1096. [self.delegate reloadDatasource:serverUrl fileID:nil selector:nil];
  1097. });
  1098. }
  1099. #pragma --------------------------------------------------------------------------------------------
  1100. #pragma mark ===== Upload Verify =====
  1101. #pragma --------------------------------------------------------------------------------------------
  1102. - (void)verifyUploadInProgress
  1103. {
  1104. NSArray *dataSourceUpload = [CCCoreData getTableMetadataUploadAccount:_activeAccount];
  1105. NSArray *dataSourceUploadWWan = [CCCoreData getTableMetadataUploadWWanAccount:_activeAccount];
  1106. NSMutableArray *dataSource = [[NSMutableArray alloc] init];
  1107. [dataSource addObjectsFromArray:dataSourceUpload];
  1108. [dataSource addObjectsFromArray:dataSourceUploadWWan];
  1109. NSLog(@"[LOG] Verify upload file in progress n. %lu", (unsigned long)[dataSource count]);
  1110. for (TableMetadata *record in dataSource) {
  1111. __block CCMetadata *metadata = [CCCoreData insertEntityInMetadata:record];
  1112. __block NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:_activeAccount];
  1113. NSURLSession *session = [self getSessionfromSessionDescription:metadata.session];
  1114. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1115. BOOL findTask = NO;
  1116. BOOL findTaskPlist = NO;
  1117. // cerchiamo la corrispondenza dei task
  1118. for (NSURLSessionUploadTask *uploadTask in uploadTasks) {
  1119. NSLog(@"[LOG] Find metadata Tasks [%i %i] = [%lu] state : %lu", metadata.sessionTaskIdentifier, metadata.sessionTaskIdentifierPlist , (unsigned long)uploadTask.taskIdentifier, (unsigned long)[uploadTask state]);
  1120. if (metadata.sessionTaskIdentifier == uploadTask.taskIdentifier) findTask = YES;
  1121. if (metadata.sessionTaskIdentifierPlist == uploadTask.taskIdentifier) findTaskPlist = YES;
  1122. if (findTask == YES || findTaskPlist == YES) break;
  1123. }
  1124. // se non c'è (ci sono) il relativo uploadTask.taskIdentifier allora chiediamolo
  1125. if ((metadata.cryptated == YES && findTask == NO && findTaskPlist == NO) || (metadata.cryptated == NO && findTask == NO)) {
  1126. 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);
  1127. if (metadata.sessionTaskIdentifier >= 0) [self readFileVerifyUpload:metadata.fileNameData fileNamePrint:metadata.fileNamePrint serverUrl:serverUrl];
  1128. if (metadata.sessionTaskIdentifierPlist >= 0) [self readFileVerifyUpload:metadata.fileName fileNamePrint:metadata.fileNamePrint serverUrl:serverUrl];
  1129. }
  1130. }];
  1131. // Notification change session
  1132. dispatch_async(dispatch_get_main_queue(), ^{
  1133. NSArray *object = [[NSArray alloc] initWithObjects:session, metadata, nil];
  1134. [[NSNotificationCenter defaultCenter] postNotificationName:networkingSessionNotification object:object];
  1135. });
  1136. }
  1137. [self automaticUploadInError];
  1138. }
  1139. - (void)automaticUploadInError
  1140. {
  1141. NSMutableSet *directoryIDs = [[NSMutableSet alloc] init];
  1142. NSArray *records = [CCCoreData getTableMetadataWithPredicate:[NSPredicate predicateWithFormat:@"(account == %@) AND (session CONTAINS 'upload') AND ((sessionTaskIdentifier == %i) OR (sessionTaskIdentifierPlist == %i))", _activeAccount, k_taskIdentifierError, k_taskIdentifierError] context:nil];
  1143. NSLog(@"[LOG] Verify re upload n. %lu", (unsigned long)[records count]);
  1144. for (TableMetadata *record in records) {
  1145. CCMetadata *metadata = [CCCoreData insertEntityInMetadata:record];
  1146. [self uploadFileMetadata:metadata taskStatus: k_taskStatusResume];
  1147. [directoryIDs addObject:metadata.directoryID];
  1148. NSLog(@"[LOG] Re upload file : %@", metadata.fileName);
  1149. }
  1150. dispatch_async(dispatch_get_main_queue(), ^{
  1151. for (NSString *directoryID in directoryIDs)
  1152. if ([self.delegate respondsToSelector:@selector(reloadDatasource:fileID:selector:)])
  1153. [self.delegate reloadDatasource:[CCCoreData getServerUrlFromDirectoryID:directoryID activeAccount:_activeAccount] fileID:nil selector:nil];
  1154. });
  1155. }
  1156. - (void)readFileVerifyUpload:(NSString *)fileName fileNamePrint:(NSString *)fileNamePrint serverUrl:(NSString *)serverUrl
  1157. {
  1158. #ifndef EXTENSION
  1159. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:_activeAccount];
  1160. metadataNet.action = actionReadFile;
  1161. metadataNet.fileName = fileName;
  1162. metadataNet.fileNamePrint = fileNamePrint;
  1163. metadataNet.serverUrl = serverUrl;
  1164. metadataNet.selector = selectorReadFileVerifyUpload;
  1165. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1166. #else
  1167. NSLog(@"[LOG] Function not available for extension.");
  1168. #endif
  1169. }
  1170. //
  1171. // File exists : selectorReadFileVerifyUpload
  1172. //
  1173. - (void)readFileSuccess:(CCMetadataNet *)metadataNet metadata:(CCMetadata *)metadata
  1174. {
  1175. NSString *fileName;
  1176. if ([CCUtility isCryptoString:metadata.fileName])
  1177. fileName = [metadata.fileName stringByAppendingString:@".plist"];
  1178. else
  1179. fileName = metadataNet.fileName;
  1180. NSString *directoryID = [CCCoreData getDirectoryIDFromServerUrl:metadataNet.serverUrl activeAccount:_activeAccount];
  1181. CCMetadata *metadataTemp = [CCCoreData getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"(fileName == %@) AND (directoryID == %@) AND (account == %@)", fileName , directoryID, _activeAccount] context:_context];
  1182. // is completed ?
  1183. if (metadataTemp.sessionTaskIdentifier == k_taskIdentifierDone && metadataTemp.sessionTaskIdentifierPlist == k_taskIdentifierDone) {
  1184. [CCGraphics createNewImageFrom:metadata.fileID directoryUser:_directoryUser fileNameTo:metadata.fileID fileNamePrint:metadata.fileNamePrint size:@"m" imageForUpload:NO typeFile:metadata.typeFile writePreview:YES optimizedFileName:[CCUtility getOptimizedPhoto]];
  1185. NSLog(@"[LOG] Verify read file success, but files already processed");
  1186. dispatch_async(dispatch_get_main_queue(), ^{
  1187. if ([self.delegate respondsToSelector:@selector(reloadDatasource:fileID:selector:)])
  1188. [self.delegate reloadDatasource:[CCCoreData getServerUrlFromDirectoryID:directoryID activeAccount:_activeAccount] fileID:metadataTemp.fileID selector:metadataNet.selector];
  1189. });
  1190. } else {
  1191. [self uploadFileSuccessFailure:metadataTemp fileName:metadataNet.fileName fileID:metadata.fileID rev:metadata.rev date:metadata.date serverUrl:metadataNet.serverUrl errorCode:0];
  1192. }
  1193. }
  1194. //
  1195. // File do not exists : selectorReadFileVerifyUpload
  1196. //
  1197. - (void)readFileFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1198. {
  1199. NSString *fileName;
  1200. if ([CCUtility isCryptoString:metadataNet.fileName])
  1201. fileName = [metadataNet.fileName stringByAppendingString:@".plist"];
  1202. else
  1203. fileName = metadataNet.fileName;
  1204. NSString *directoryID = [CCCoreData getDirectoryIDFromServerUrl:metadataNet.serverUrl activeAccount:_activeAccount];
  1205. CCMetadata *metadata = [CCCoreData getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"(fileName == %@) AND (directoryID == %@) AND (account == %@)",fileName , directoryID, _activeAccount] context:_context];
  1206. NSInteger error;
  1207. if (errorCode == kOCErrorServerPathNotFound)
  1208. error = k_CCErrorFileUploadNotFound;
  1209. else
  1210. error = errorCode;
  1211. [self uploadFileSuccessFailure:metadata fileName:metadataNet.fileName fileID:metadata.fileID rev:metadata.rev date:metadata.date serverUrl:metadataNet.serverUrl errorCode:error];
  1212. }
  1213. #pragma --------------------------------------------------------------------------------------------
  1214. #pragma mark ===== Utility =====
  1215. #pragma --------------------------------------------------------------------------------------------
  1216. - (id)getDelegate:(NSString *)fileID
  1217. {
  1218. id delegate = [_delegates objectForKey:fileID];
  1219. if (delegate)
  1220. return delegate;
  1221. else
  1222. return self.delegate;
  1223. }
  1224. - (NSString *)getServerUrlFromUrl:(NSString *)url
  1225. {
  1226. NSString *fileName = [url lastPathComponent];
  1227. if ([_typeCloud isEqualToString:typeCloudOwnCloud] || [_typeCloud isEqualToString:typeCloudNextcloud]) {
  1228. url = [url stringByReplacingOccurrencesOfString:[@"/" stringByAppendingString:fileName] withString:@""];
  1229. }
  1230. return url;
  1231. }
  1232. - (NSString *)getTitleFromPlistName:(NSString *)fileName
  1233. {
  1234. if ([[fileName lastPathComponent] isEqualToString:@"plist"] == NO)
  1235. fileName = [fileName stringByAppendingString:@".plist"];
  1236. if (![[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, fileName]]) return nil;
  1237. NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithContentsOfFile:[NSString stringWithFormat:@"%@/%@", _directoryUser, fileName]];
  1238. return [data objectForKey:@"title"];
  1239. }
  1240. @end