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