CCNetworking.m 95 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762
  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 activeUrl:_activeUrl];
  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 activeUrl:_activeUrl];
  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 activeUrl:_activeUrl];
  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 activeUrl:_activeUrl];
  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:localIdentifier action:k_activityDebugActionUpload selector:selector note:@"Internal error image/video not found" type:k_activityVerboseDefault verbose:k_activityVerboseHigh account:_activeAccount activeUrl:_activeUrl];
  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 new];
  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. // Activity
  579. [CCCoreData addActivityClient:fileName fileID:localIdentifier action:k_activityDebugActionUpload selector:selector note:NSLocalizedString(@"_read_file_error_", nil) type:k_activityTypeFailure verbose:k_activityVerboseDefault account:_activeAccount activeUrl:_activeUrl];
  580. // Error for uploadFileFailure
  581. if ([delegate respondsToSelector:@selector(uploadFileFailure:fileID:serverUrl:selector:message:errorCode:)])
  582. [delegate uploadFileFailure:nil fileID:nil serverUrl:serverUrl selector:selector message:@"_read_file_error_" errorCode:error.code];
  583. } else {
  584. [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];
  585. }
  586. });
  587. }];
  588. }
  589. }
  590. // IMAGE
  591. if (assetMediaType == PHAssetMediaTypeImage) {
  592. // Automatic Upload photo encrypted ?
  593. if ([selector isEqualToString:selectorUploadAutomatic] || [selector isEqualToString:selectorUploadAutomaticAll])
  594. cryptated = [CCCoreData getCameraUploadCryptatedPhotoActiveAccount:_activeAccount];
  595. @autoreleasepool {
  596. PHImageRequestOptions *options = [PHImageRequestOptions new];
  597. options.synchronous = NO;
  598. [[PHImageManager defaultManager] requestImageDataForAsset:asset options:options resultHandler:^(NSData *imageData, NSString *dataUTI, UIImageOrientation orientation, NSDictionary *info) {
  599. [imageData writeToFile:fileNamePath options:NSDataWritingAtomic error:&error];
  600. dispatch_async(dispatch_get_main_queue(), ^{
  601. if (error) {
  602. // Activity
  603. [CCCoreData addActivityClient:fileName fileID:localIdentifier action:k_activityDebugActionUpload selector:selector note:NSLocalizedString(@"_read_file_error_", nil) type:k_activityTypeFailure verbose:k_activityVerboseDefault account:_activeAccount activeUrl:_activeUrl];
  604. // Error for uploadFileFailure
  605. if ([delegate respondsToSelector:@selector(uploadFileFailure:fileID:serverUrl:selector:message:errorCode:)])
  606. [delegate uploadFileFailure:nil fileID:nil serverUrl:serverUrl selector:selector message:@"_read_file_error_" errorCode:error.code];
  607. } else {
  608. [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];
  609. }
  610. });
  611. }];
  612. }
  613. }
  614. }
  615. - (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
  616. {
  617. [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];
  618. }
  619. - (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
  620. {
  621. [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];
  622. }
  623. - (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
  624. {
  625. NSString *directoryID = [CCCoreData getDirectoryIDFromServerUrl:serverUrl activeAccount:_activeAccount];
  626. NSString *fileNameCrypto;
  627. // create Metadata
  628. NSString *cameraFolderName = [CCCoreData getCameraUploadFolderNameActiveAccount:_activeAccount];
  629. NSString *cameraFolderPath = [CCCoreData getCameraUploadFolderPathActiveAccount:_activeAccount activeUrl:_activeUrl];
  630. CCMetadata *metadata = [CCUtility insertFileSystemInMetadata:fileName directory:_directoryUser activeAccount:_activeAccount cameraFolderName:cameraFolderName cameraFolderPath:cameraFolderPath];
  631. //fileID
  632. NSString *uploadID = [k_uploadSessionID stringByAppendingString:[CCUtility createRandomString:16]];
  633. //add delegate
  634. if (delegate)
  635. [_delegates setObject:delegate forKey:uploadID];
  636. if (onlyPlist == YES) {
  637. [CCUtility moveFileAtPath:[NSTemporaryDirectory() stringByAppendingString:fileName] toPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, fileName]];
  638. [CCUtility insertInformationPlist:metadata directoryUser:_directoryUser];
  639. metadata.date = [NSDate new];
  640. metadata.fileID = uploadID;
  641. metadata.directoryID = directoryID;
  642. metadata.fileNameData = [CCUtility trasformedFileNamePlistInCrypto:fileName];
  643. metadata.localIdentifier = localIdentifier;
  644. metadata.session = session;
  645. metadata.sessionID = uploadID;
  646. metadata.sessionSelector = selector;
  647. metadata.sessionSelectorPost = selectorPost;
  648. metadata.typeFile = k_metadataTypeFile_unknown;
  649. [CCCoreData addMetadata:metadata activeAccount:_activeAccount activeUrl:_activeUrl context:_context];
  650. [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];
  651. }
  652. else if (cryptated == YES) {
  653. if (template == YES) {
  654. // copy from temp to directory user
  655. [CCUtility moveFileAtPath:[NSTemporaryDirectory() stringByAppendingString:fileName] toPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, fileName]];
  656. [CCUtility moveFileAtPath:[NSTemporaryDirectory() stringByAppendingString:[fileName stringByAppendingString:@".plist"]] toPath:[NSString stringWithFormat:@"%@/%@.plist", _directoryUser, fileName]];
  657. fileNameCrypto = fileName; // file Name Crypto
  658. fileName = assetFileName; // file Name Print
  659. [CCUtility insertInformationPlist:metadata directoryUser:_directoryUser];
  660. metadata.date = [NSDate new];
  661. metadata.fileID = uploadID;
  662. metadata.directoryID = directoryID;
  663. metadata.fileName = [fileNameCrypto stringByAppendingString:@".plist"];
  664. metadata.fileNameData = fileNameCrypto;
  665. metadata.localIdentifier = localIdentifier;
  666. metadata.session = session;
  667. metadata.sessionID = uploadID;
  668. metadata.sessionSelector = selector;
  669. metadata.sessionSelectorPost = selectorPost;
  670. metadata.typeFile = k_metadataTypeFile_template;
  671. [CCCoreData addMetadata:metadata activeAccount:_activeAccount activeUrl:_activeUrl context:_context];
  672. // DATA
  673. [self uploadURLSession:fileNameCrypto fileNamePrint:fileName serverUrl:serverUrl sessionID:uploadID session:metadata.session taskStatus:taskStatus assetDate:assetDate assetMediaType:assetMediaType cryptated:cryptated onlyPlist:onlyPlist selector:selector];
  674. // PLIST
  675. [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];
  676. }
  677. if (template == NO) {
  678. NSString *passcode = [[CCCrypto sharedManager] getKeyPasscode:[CCUtility getUUID]];
  679. fileNameCrypto = [[CCCrypto sharedManager] encryptWithCreatePlist:fileName fileNameEncrypted:fileName passcode:passcode directoryUser:_directoryUser];
  680. // Encrypted file error
  681. if (fileNameCrypto == nil) {
  682. dispatch_async(dispatch_get_main_queue(), ^{
  683. NSString *msg = [NSString stringWithFormat:NSLocalizedString(@"_encrypt_error_", nil), fileName, @""];
  684. UIAlertController *alertController= [UIAlertController alertControllerWithTitle:nil message:msg preferredStyle:UIAlertControllerStyleAlert];
  685. UIAlertAction* ok = [UIAlertAction actionWithTitle: NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault
  686. handler:^(UIAlertAction * action) {
  687. [alertController dismissViewControllerAnimated:YES completion:nil];
  688. }];
  689. [alertController addAction:ok];
  690. UIWindow *alertWindow = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
  691. alertWindow.rootViewController = [[UIViewController alloc]init];
  692. alertWindow.windowLevel = UIWindowLevelAlert + 1;
  693. [alertWindow makeKeyAndVisible];
  694. [alertWindow.rootViewController presentViewController:alertController animated:YES completion:nil];
  695. // Error for uploadFileFailure
  696. if ([[self getDelegate:uploadID] respondsToSelector:@selector(uploadFileFailure:fileID:serverUrl:selector:message:errorCode:)])
  697. [[self getDelegate:uploadID] uploadFileFailure:nil fileID:nil serverUrl:serverUrl selector:selector message:NSLocalizedString(@"_encrypt_error_", nil) errorCode:0];
  698. });
  699. return;
  700. }
  701. metadata.cryptated = YES;
  702. metadata.date = [NSDate new];
  703. metadata.fileID = uploadID;
  704. metadata.directoryID = directoryID;
  705. metadata.fileName = [fileNameCrypto stringByAppendingString:@".plist"];
  706. metadata.fileNameData = fileNameCrypto;
  707. metadata.fileNamePrint = fileName;
  708. metadata.localIdentifier = localIdentifier;
  709. metadata.session = session;
  710. metadata.sessionID = uploadID;
  711. metadata.sessionSelector = selector;
  712. metadata.sessionSelectorPost = selectorPost;
  713. metadata.title = [self getTitleFromPlistName:fileNameCrypto];
  714. metadata.type = k_metadataType_file;
  715. if (errorCode == 403) {
  716. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:fileName message:NSLocalizedString(@"_file_already_exists_", nil) preferredStyle:UIAlertControllerStyleAlert];
  717. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  718. dispatch_async(dispatch_get_main_queue(), ^{
  719. // Change Asset Data only for automatic upload
  720. //if ([selector isEqualToString:selectorUploadAutomatic])
  721. // [CCCoreData setCameraUploadDateAssetType:assetMediaType assetDate:assetDate activeAccount:_activeAccount];
  722. // Activity
  723. [CCCoreData addActivityClient:fileName fileID:uploadID action:k_activityDebugActionUpload selector:selector note:NSLocalizedString(@"_file_already_exists_", nil) type:k_activityTypeFailure verbose:k_activityVerboseDefault account:_activeAccount activeUrl:_activeUrl];
  724. // Error for uploadFileFailure
  725. if ([[self getDelegate:uploadID] respondsToSelector:@selector(uploadFileFailure:fileID:serverUrl:selector:message:errorCode:)])
  726. [[self getDelegate:uploadID] uploadFileFailure:nil fileID:nil serverUrl:serverUrl selector:selector message:NSLocalizedString(@"_file_already_exists_", nil) errorCode:403];
  727. });
  728. return;
  729. }];
  730. UIAlertAction *overwriteAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_overwrite_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  731. // -- remove record --
  732. CCMetadata *metadataDelete = [CCCoreData getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"(account == %@) AND (fileName == %@) AND (directoryID == %@)", _activeAccount, [fileNameCrypto stringByAppendingString:@".plist"], directoryID] context:nil];
  733. [CCCoreData deleteFile:metadataDelete serverUrl:serverUrl directoryUser:_directoryUser activeAccount:_activeAccount];
  734. #ifndef EXTENSION
  735. [CCGraphics createNewImageFrom:fileName directoryUser:_directoryUser fileNameTo:uploadID fileNamePrint:fileName size:@"m" imageForUpload:YES typeFile:metadata.typeFile writePreview:YES optimizedFileName:NO];
  736. #endif
  737. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video])
  738. [[CCCrypto sharedManager] addPlistImage:[NSString stringWithFormat:@"%@/%@", _directoryUser, [fileNameCrypto stringByAppendingString:@".plist"]] fileNamePathImage:[NSTemporaryDirectory() stringByAppendingString:uploadID]];
  739. [CCCoreData addMetadata:metadata activeAccount:_activeAccount activeUrl:_activeUrl context:_context];
  740. // DATA
  741. [self uploadURLSession:fileNameCrypto fileNamePrint:fileName serverUrl:serverUrl sessionID:uploadID session:metadata.session taskStatus:taskStatus assetDate:assetDate assetMediaType:assetMediaType cryptated:cryptated onlyPlist:onlyPlist selector:selector];
  742. // PLIST
  743. [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];
  744. }];
  745. [alertController addAction:cancelAction];
  746. [alertController addAction:overwriteAction];
  747. UIWindow *alertWindow = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
  748. alertWindow.rootViewController = [[UIViewController alloc]init];
  749. alertWindow.windowLevel = UIWindowLevelAlert + 1;
  750. [alertWindow makeKeyAndVisible];
  751. [alertWindow.rootViewController presentViewController:alertController animated:YES completion:nil];
  752. } else {
  753. #ifndef EXTENSION
  754. [CCGraphics createNewImageFrom:fileName directoryUser:_directoryUser fileNameTo:uploadID fileNamePrint:fileName size:@"m" imageForUpload:YES typeFile:metadata.typeFile writePreview:YES optimizedFileName:NO];
  755. #endif
  756. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video])
  757. [[CCCrypto sharedManager] addPlistImage:[NSString stringWithFormat:@"%@/%@", _directoryUser, [fileNameCrypto stringByAppendingString:@".plist"]] fileNamePathImage:[NSTemporaryDirectory() stringByAppendingString:uploadID]];
  758. [CCCoreData addMetadata:metadata activeAccount:_activeAccount activeUrl:_activeUrl context:_context];
  759. // DATA
  760. [self uploadURLSession:fileNameCrypto fileNamePrint:fileName serverUrl:serverUrl sessionID:uploadID session:metadata.session taskStatus:taskStatus assetDate:assetDate assetMediaType:assetMediaType cryptated:cryptated onlyPlist:onlyPlist selector:selector];
  761. // PLIST
  762. [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];
  763. }
  764. }
  765. }
  766. else if (cryptated == NO) {
  767. metadata.cryptated = NO;
  768. metadata.date = [NSDate new];
  769. metadata.fileID = uploadID;
  770. metadata.directoryID = directoryID;
  771. metadata.fileName = fileName;
  772. metadata.fileNameData = fileName;
  773. metadata.fileNamePrint = fileName;
  774. metadata.localIdentifier = localIdentifier;
  775. metadata.session = session;
  776. metadata.sessionID = uploadID;
  777. metadata.sessionSelector = selector;
  778. metadata.sessionSelectorPost = selectorPost;
  779. metadata.type = k_metadataType_file;
  780. // File exists ???
  781. if (errorCode == 403) {
  782. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:fileName message:NSLocalizedString(@"_file_already_exists_", nil) preferredStyle:UIAlertControllerStyleAlert];
  783. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  784. dispatch_async(dispatch_get_main_queue(), ^{
  785. // Change Asset Data only for automatic upload
  786. //if ([selector isEqualToString:selectorUploadAutomatic])
  787. // [CCCoreData setCameraUploadDateAssetType:assetMediaType assetDate:assetDate activeAccount:_activeAccount];
  788. // Activity
  789. [CCCoreData addActivityClient:fileName fileID:uploadID action:k_activityDebugActionUpload selector:selector note:NSLocalizedString(@"_file_already_exists_", nil) type:k_activityTypeFailure verbose:k_activityVerboseDefault account:_activeAccount activeUrl:_activeUrl];
  790. // Error for uploadFileFailure
  791. if ([[self getDelegate:uploadID] respondsToSelector:@selector(uploadFileFailure:fileID:serverUrl:selector:message:errorCode:)])
  792. [[self getDelegate:uploadID] uploadFileFailure:nil fileID:nil serverUrl:serverUrl selector:selector message:NSLocalizedString(@"_file_already_exists_", nil) errorCode:403];
  793. });
  794. return;
  795. }];
  796. UIAlertAction *overwriteAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_overwrite_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  797. // -- remove record --
  798. CCMetadata *metadataDelete = [CCCoreData getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"(account == %@) AND (fileName == %@) AND (directoryID == %@)", _activeAccount, fileName, directoryID] context:nil];
  799. [CCCoreData deleteFile:metadataDelete serverUrl:serverUrl directoryUser:_directoryUser activeAccount:_activeAccount];
  800. // -- Go to Upload --
  801. [CCGraphics createNewImageFrom:metadata.fileNamePrint directoryUser:_directoryUser fileNameTo:metadata.fileID fileNamePrint:metadata.fileNamePrint size:@"m" imageForUpload:YES typeFile:metadata.typeFile writePreview:YES optimizedFileName:NO];
  802. [CCCoreData addMetadata:metadata activeAccount:_activeAccount activeUrl:_activeUrl context:_context];
  803. [self uploadURLSession:fileName fileNamePrint:fileName serverUrl:serverUrl sessionID:uploadID session:metadata.session taskStatus:taskStatus assetDate:assetDate assetMediaType:assetMediaType cryptated:cryptated onlyPlist:onlyPlist selector:selector];
  804. }];
  805. [alertController addAction:cancelAction];
  806. [alertController addAction:overwriteAction];
  807. UIWindow *alertWindow = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
  808. alertWindow.rootViewController = [[UIViewController alloc] init];
  809. alertWindow.windowLevel = UIWindowLevelAlert + 1;
  810. [alertWindow makeKeyAndVisible];
  811. [alertWindow.rootViewController presentViewController:alertController animated:YES completion:nil];
  812. } else {
  813. // -- Go to upload --
  814. #ifndef EXTENSION
  815. [CCGraphics createNewImageFrom:metadata.fileNamePrint directoryUser:_directoryUser fileNameTo:metadata.fileID fileNamePrint:metadata.fileNamePrint size:@"m" imageForUpload:YES typeFile:metadata.typeFile writePreview:YES optimizedFileName:NO];
  816. #endif
  817. [CCCoreData addMetadata:metadata activeAccount:_activeAccount activeUrl:_activeUrl context:_context];
  818. [self uploadURLSession:fileName fileNamePrint:fileName serverUrl:serverUrl sessionID:uploadID session:metadata.session taskStatus:taskStatus assetDate:assetDate assetMediaType:assetMediaType cryptated:cryptated onlyPlist:onlyPlist selector:selector];
  819. }
  820. }
  821. }
  822. - (void)uploadFileMetadata:(CCMetadata *)metadata taskStatus:(NSInteger)taskStatus
  823. {
  824. BOOL send = NO;
  825. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:_activeAccount];
  826. if (metadata.cryptated) {
  827. // ENCRYPTED
  828. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, metadata.fileNameData]] && [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, metadata.fileName]]) {
  829. send = YES;
  830. [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];
  831. [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];
  832. }
  833. } else {
  834. // PLAIN
  835. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, metadata.sessionID]]) {
  836. send = YES;
  837. [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];
  838. }
  839. }
  840. if (send) {
  841. NSLog(@"[LOG] Re-upload File : %@ - fileID : %@", metadata.fileNamePrint, metadata.fileID);
  842. // update Coredata
  843. [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];
  844. } else {
  845. NSLog(@"[LOG] Error reUploadBackground, file not found.");
  846. #ifndef EXTENSION
  847. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_no_reuploadfile_", nil) delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  848. [alertView show];
  849. #endif
  850. }
  851. }
  852. - (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
  853. {
  854. NSURLSession *sessionUpload;
  855. NSURL *url;
  856. NSMutableURLRequest *request;
  857. NSString *fileNamePath = [[NSString stringWithFormat:@"%@/%@", serverUrl, fileName] encodeString:NSUTF8StringEncoding];
  858. url = [NSURL URLWithString:fileNamePath];
  859. request = [NSMutableURLRequest requestWithURL:url];
  860. NSData *authData = [[NSString stringWithFormat:@"%@:%@", _activeUser, _activePassword] dataUsingEncoding:NSUTF8StringEncoding];
  861. NSString *authValue = [NSString stringWithFormat: @"Basic %@",[authData base64EncodedStringWithOptions:0]];
  862. [request setHTTPMethod:@"PUT"];
  863. [request setValue:authValue forHTTPHeaderField:@"Authorization"];
  864. // Rename with the SessionID
  865. NSString *fileNameForUpload;
  866. if ([CCUtility isFileNotCryptated:fileName]) fileNameForUpload = sessionID;
  867. else fileNameForUpload = fileName;
  868. if (!onlyPlist) {
  869. if ([CCUtility isFileNotCryptated:fileName])
  870. [[NSFileManager defaultManager] moveItemAtPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, fileName] toPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, fileNameForUpload] error:nil];
  871. if ([CCUtility isCryptoPlistString:fileName])
  872. [[NSFileManager defaultManager] moveItemAtPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, fileNamePrint] toPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, sessionID] error:nil];
  873. }
  874. // file NOT exists
  875. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, fileNameForUpload]] == NO) {
  876. dispatch_async(dispatch_get_main_queue(), ^{
  877. // Activity
  878. [CCCoreData addActivityClient:fileName fileID:sessionID action:k_activityDebugActionUpload selector:selector note:NSLocalizedString(@"_file_not_present_", nil) type:k_activityTypeFailure verbose:k_activityVerboseDefault account:_activeAccount activeUrl:_activeUrl];
  879. // Error for uploadFileFailure
  880. if ([[self getDelegate:sessionID] respondsToSelector:@selector(uploadFileFailure:fileID:serverUrl:selector:message:errorCode:)])
  881. [[self getDelegate:sessionID] uploadFileFailure:nil fileID:sessionID serverUrl:serverUrl selector:selector message:NSLocalizedString(@"_file_not_present_", nil) errorCode:404];
  882. [CCCoreData deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"(sessionID == %@) AND (account == %@)", sessionID, _activeAccount]];
  883. });
  884. return;
  885. }
  886. if ([session isEqualToString:k_upload_session]) sessionUpload = [self sessionUpload];
  887. else if ([session isEqualToString:k_upload_session_foreground]) sessionUpload = [self sessionUploadForeground];
  888. else if ([session isEqualToString:k_upload_session_wwan]) sessionUpload = [self sessionWWanUpload];
  889. NSURLSessionUploadTask *uploadTask = [sessionUpload uploadTaskWithRequest:request fromFile:[NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, fileNameForUpload]]];
  890. if (taskStatus == k_taskStatusCancel) [uploadTask cancel];
  891. else if (taskStatus == k_taskStatusSuspend) [uploadTask suspend];
  892. else if (taskStatus == k_taskStatusResume) [uploadTask resume];
  893. if ([[self getDelegate:sessionID] respondsToSelector:@selector(uploadTaskSave:)])
  894. [[self getDelegate:sessionID] uploadTaskSave:uploadTask];
  895. // COREDATA
  896. if (uploadTask == nil) {
  897. NSUInteger sessionTaskIdentifier = k_taskIdentifierNULL;
  898. NSUInteger sessionTaskIdentifierPlist = k_taskIdentifierNULL;
  899. if ([CCUtility isFileNotCryptated:fileName] || [CCUtility isCryptoString:fileName]) sessionTaskIdentifier = k_taskIdentifierError;
  900. if ([CCUtility isCryptoPlistString:fileName]) sessionTaskIdentifierPlist = k_taskIdentifierError;
  901. [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];
  902. NSLog(@"[LOG] Upload file TaskIdentifier [error CCErrorTaskNil] - %@ - %@", fileName, fileNamePrint);
  903. } else {
  904. NSUInteger sessionTaskIdentifier = k_taskIdentifierNULL;
  905. NSUInteger sessionTaskIdentifierPlist = k_taskIdentifierNULL;
  906. if ([CCUtility isCryptoString:fileName] || [CCUtility isFileNotCryptated:fileName]) sessionTaskIdentifier = uploadTask.taskIdentifier;
  907. if ([CCUtility isCryptoPlistString:fileName]) sessionTaskIdentifierPlist = uploadTask.taskIdentifier;
  908. [CCCoreData setMetadataSession:session sessionError:@"" sessionSelector:nil sessionSelectorPost:nil sessionTaskIdentifier:sessionTaskIdentifier sessionTaskIdentifierPlist:sessionTaskIdentifierPlist predicate:[NSPredicate predicateWithFormat:@"(sessionID == %@) AND (account == %@)", sessionID, _activeAccount] context:_context];
  909. // Change Asset Data only for Automatic Upload
  910. //if ([selector isEqualToString:selectorUploadAutomatic])
  911. // [CCCoreData setCameraUploadDateAssetType:assetMediaType assetDate:assetDate activeAccount:_activeAccount];
  912. NSLog(@"[LOG] Upload file %@ - %@ TaskIdentifier %lu", fileName,fileNamePrint, (unsigned long)uploadTask.taskIdentifier);
  913. }
  914. dispatch_async(dispatch_get_main_queue(), ^{
  915. // refresh main
  916. if ([self.delegate respondsToSelector:@selector(reloadDatasource:fileID:selector:)])
  917. [self.delegate reloadDatasource:serverUrl fileID:nil selector:selector];
  918. });
  919. }
  920. - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
  921. {
  922. NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)dataTask.response;
  923. if (httpResponse.statusCode >= 200 && httpResponse.statusCode < 300) {
  924. NSNumber *taskIdentifier = [NSNumber numberWithLong:dataTask.taskIdentifier];
  925. if (data)
  926. [_taskData setObject:[data copy] forKey:taskIdentifier];
  927. }
  928. }
  929. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend
  930. {
  931. NSString *url = [[[task currentRequest].URL absoluteString] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  932. NSString *fileName = [url lastPathComponent];
  933. NSString *serverUrl = [self getServerUrlFromUrl:url];
  934. // if plist return
  935. if ([CCUtility getTypeFileName:fileName] == k_metadataTypeFilenamePlist)
  936. return;
  937. float progress = (float) totalBytesSent / (float)totalBytesExpectedToSend;
  938. if ([_currentProgressMetadata.fileName isEqualToString:fileName] == NO && [_currentProgressMetadata.fileNameData isEqualToString:fileName] == NO)
  939. _currentProgressMetadata = [CCCoreData getMetadataFromFileName:fileName directoryID:[CCCoreData getDirectoryIDFromServerUrl:serverUrl activeAccount:_activeAccount] activeAccount:_activeAccount context:_context];
  940. //NSLog(@"[LOG] %@ - %f", fileName, progress);
  941. dispatch_async(dispatch_get_main_queue(), ^{
  942. if (_currentProgressMetadata) {
  943. if (_currentProgressMetadata) {
  944. NSDictionary* userInfo = @{@"fileID": (_currentProgressMetadata.fileID), @"serverUrl": (serverUrl), @"cryptated": ([NSNumber numberWithBool:_currentProgressMetadata.cryptated]), @"progress": ([NSNumber numberWithFloat:progress])};
  945. [[NSNotificationCenter defaultCenter] postNotificationName:@"NotificationProgressTask" object:nil userInfo:userInfo];
  946. }
  947. }
  948. });
  949. }
  950. - (void)uploadFileSuccessFailure:(CCMetadata *)metadata fileName:(NSString *)fileName fileID:(NSString *)fileID rev:(NSString *)rev date:(NSDate *)date serverUrl:(NSString *)serverUrl errorCode:(NSInteger)errorCode
  951. {
  952. NSString *sessionID = metadata.sessionID;
  953. // Progress Task
  954. NSDictionary* userInfo = @{@"fileID": (fileID), @"serverUrl": (serverUrl), @"cryptated": ([NSNumber numberWithBool:NO]), @"progress": ([NSNumber numberWithFloat:0.0])};
  955. [[NSNotificationCenter defaultCenter] postNotificationName:@"NotificationProgressTask" object:nil userInfo:userInfo];
  956. // ERRORE
  957. if (errorCode != 0) {
  958. #ifndef EXTENSION
  959. if (sessionID)
  960. [app.listProgressMetadata removeObjectForKey:sessionID];
  961. #endif
  962. // Mark error only if not Cancelled Task
  963. if (errorCode != kCFURLErrorCancelled) {
  964. NSUInteger sessionTaskIdentifier = k_taskIdentifierNULL;
  965. NSUInteger sessionTaskIdentifierPlist = k_taskIdentifierNULL;
  966. if ([CCUtility isFileNotCryptated:fileName] || [CCUtility isCryptoString:fileName]) sessionTaskIdentifier = k_taskIdentifierError;
  967. if ([CCUtility isCryptoPlistString:fileName]) sessionTaskIdentifierPlist = k_taskIdentifierError;
  968. [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];
  969. }
  970. dispatch_async(dispatch_get_main_queue(), ^{
  971. if ([[self getDelegate:sessionID] respondsToSelector:@selector(uploadFileFailure:fileID:serverUrl:selector:message:errorCode:)])
  972. [[self getDelegate:sessionID] uploadFileFailure:nil fileID:fileID serverUrl:serverUrl selector:metadata.sessionSelector message:[CCError manageErrorKCF:errorCode withNumberError:YES] errorCode:errorCode];
  973. });
  974. return;
  975. }
  976. // PLAIN or PLIST
  977. if ([CCUtility isFileNotCryptated:fileName] || [CCUtility isCryptoPlistString:fileName]) {
  978. metadata.fileID = fileID;
  979. metadata.rev = rev;
  980. metadata.date = date;
  981. metadata.sessionTaskIdentifierPlist = k_taskIdentifierDone;
  982. if ([CCUtility isFileNotCryptated:fileName])
  983. metadata.sessionTaskIdentifier = k_taskIdentifierDone;
  984. // copy ico in new fileID
  985. [CCUtility copyFileAtPath:[NSString stringWithFormat:@"%@/%@.ico", _directoryUser, sessionID] toPath:[NSString stringWithFormat:@"%@/%@.ico", _directoryUser, fileID]];
  986. [CCCoreData updateMetadata:metadata predicate:[NSPredicate predicateWithFormat:@"(sessionID == %@) AND (account == %@)", sessionID, _activeAccount] activeAccount:_activeAccount activeUrl:_activeUrl context:_context];
  987. }
  988. // CRYPTO
  989. if ([CCUtility isCryptoString:fileName]) {
  990. metadata.sessionTaskIdentifier = k_taskIdentifierDone;
  991. [CCCoreData updateMetadata:metadata predicate:[NSPredicate predicateWithFormat:@"(sessionID == %@) AND (account == %@)", sessionID, _activeAccount] activeAccount:_activeAccount activeUrl:_activeUrl context:_context];
  992. }
  993. // ALL TASK DONE (PLAIN/CRYPTO)
  994. if (metadata.sessionTaskIdentifier == k_taskIdentifierDone && metadata.sessionTaskIdentifierPlist == k_taskIdentifierDone) {
  995. #ifndef EXTENSION
  996. if (sessionID)
  997. [app.listProgressMetadata removeObjectForKey:sessionID];
  998. #endif
  999. NSLog(@"[LOG] Insert new upload : %@ - FileNamePrint : %@ - fileID : %@", metadata.fileName, metadata.fileNamePrint, metadata.fileID);
  1000. metadata.session = @"";
  1001. metadata.sessionError = @"";
  1002. metadata.sessionID = @"";
  1003. [CCCoreData updateMetadata:metadata predicate:[NSPredicate predicateWithFormat:@"(sessionID == %@) AND (account == %@)", sessionID, _activeAccount] activeAccount:_activeAccount activeUrl:_activeUrl context:_context];
  1004. // rename file sessionID -> fileID
  1005. [CCUtility moveFileAtPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, sessionID] toPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, metadata.fileID]];
  1006. // remove temp icon
  1007. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@.ico", _directoryUser, sessionID] error:nil];
  1008. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@.ico", _directoryUser, metadata.fileID] error:nil];
  1009. // if crypto remove filename data
  1010. if (metadata.cryptated)
  1011. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, metadata.fileNameData] error:nil];
  1012. // Local
  1013. if (metadata.directory == NO)
  1014. [CCCoreData addLocalFile:metadata activeAccount:_activeAccount];
  1015. // EXIF
  1016. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image])
  1017. [CCExifGeo setExifLocalTableFileID:metadata directoryUser:_directoryUser activeAccount:_activeAccount];
  1018. // Create ICON
  1019. if (metadata.directory == NO)
  1020. [CCGraphics createNewImageFrom:metadata.fileID directoryUser:_directoryUser fileNameTo:metadata.fileID fileNamePrint:metadata.fileNamePrint size:@"m" imageForUpload:NO typeFile:metadata.typeFile writePreview:YES optimizedFileName:[CCUtility getOptimizedPhoto]];
  1021. // Optimization
  1022. if ([CCUtility getUploadAndRemovePhoto] || [metadata.sessionSelectorPost isEqualToString:selectorUploadRemovePhoto])
  1023. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, metadata.fileID] error:nil];
  1024. // Copy photo or video in the photo album for automatic upload
  1025. if ([metadata.localIdentifier length] > 0 && [metadata.sessionSelector isEqualToString:selectorUploadAutomatic]) {
  1026. PHAsset *asset;
  1027. PHFetchResult *result = [PHAsset fetchAssetsWithLocalIdentifiers:@[metadata.localIdentifier] options:nil];
  1028. if(result.count){
  1029. asset = result[0];
  1030. [asset saveToAlbum:k_brand completionBlock:^(BOOL success) {
  1031. if (success) NSLog(@"[LOG] Insert file %@ in %@", metadata.fileNamePrint, k_brand);
  1032. else NSLog(@"[LOG] File %@ do not insert in %@", metadata.fileNamePrint, k_brand);
  1033. }];
  1034. }
  1035. }
  1036. dispatch_async(dispatch_get_main_queue(), ^{
  1037. if ([[self getDelegate:sessionID] respondsToSelector:@selector(uploadFileSuccess:fileID:serverUrl:selector:selectorPost:)])
  1038. [[self getDelegate:sessionID] uploadFileSuccess:nil fileID:metadata.fileID serverUrl:serverUrl selector:metadata.sessionSelector selectorPost:metadata.sessionSelectorPost];
  1039. });
  1040. }
  1041. }
  1042. #pragma --------------------------------------------------------------------------------------------
  1043. #pragma mark ===== Download Verify =====
  1044. #pragma --------------------------------------------------------------------------------------------
  1045. - (void)verifyDownloadInProgress
  1046. {
  1047. NSArray *dataSourceDownload = [CCCoreData getTableMetadataDownloadAccount:_activeAccount];
  1048. NSArray *dataSourceDownloadWWan = [CCCoreData getTableMetadataDownloadWWanAccount:_activeAccount];
  1049. NSMutableArray *dataSource = [[NSMutableArray alloc] init];
  1050. [dataSource addObjectsFromArray:dataSourceDownload];
  1051. [dataSource addObjectsFromArray:dataSourceDownloadWWan];
  1052. NSLog(@"[LOG] Verify download file in progress n. %lu", (unsigned long)[dataSource count]);
  1053. for (TableMetadata *record in dataSource) {
  1054. __block CCMetadata *metadata = [CCCoreData insertEntityInMetadata:record];
  1055. NSURLSession *session = [self getSessionfromSessionDescription:metadata.session];
  1056. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1057. BOOL findTask = NO;
  1058. BOOL findTaskPlist = NO;
  1059. for (NSURLSessionDownloadTask *downloadTask in downloadTasks) {
  1060. NSLog(@"[LOG] Find metadata Tasks [%i %i] = [%lu] state : %lu", metadata.sessionTaskIdentifier, metadata.sessionTaskIdentifierPlist ,(unsigned long)downloadTask.taskIdentifier, (unsigned long)[downloadTask state]);
  1061. if (metadata.sessionTaskIdentifier == downloadTask.taskIdentifier) findTask = YES;
  1062. if (metadata.sessionTaskIdentifierPlist == downloadTask.taskIdentifier) findTaskPlist = YES;
  1063. if (findTask == YES || findTaskPlist == YES) break; // trovati, download ancora in corso
  1064. }
  1065. // DATA
  1066. if (findTask == NO && metadata.sessionTaskIdentifier >= 0) {
  1067. NSLog(@"[LOG] NOT Find metadata Task [%i] fileID : %@ - filename : %@", metadata.sessionTaskIdentifier, metadata.fileID, metadata.fileNameData);
  1068. [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];
  1069. dispatch_async(dispatch_get_main_queue(), ^{
  1070. if ([self.delegate respondsToSelector:@selector(reloadDatasource:fileID:selector:)])
  1071. [self.delegate reloadDatasource:[CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account] fileID:metadata.fileID selector:nil];
  1072. });
  1073. }
  1074. // PLIST
  1075. if (findTaskPlist == NO && metadata.sessionTaskIdentifierPlist >= 0) {
  1076. NSLog(@"[LOG] NOT Find metadata TaskPlist [%i] fileID : %@ - filename : %@", metadata.sessionTaskIdentifierPlist, metadata.fileID, metadata.fileName);
  1077. [CCCoreData setMetadataSession:@"" sessionError:@"" sessionSelector:@"" sessionSelectorPost:@"" sessionTaskIdentifier: k_taskIdentifierNULL sessionTaskIdentifierPlist: k_taskIdentifierDone predicate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", metadata.fileID, _activeAccount] context:_context];
  1078. dispatch_async(dispatch_get_main_queue(), ^{
  1079. if ([self.delegate respondsToSelector:@selector(reloadDatasource:fileID:selector:)])
  1080. [self.delegate reloadDatasource:[CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account] fileID:metadata.fileID selector:nil];
  1081. });
  1082. }
  1083. }];
  1084. }
  1085. [self automaticDownloadInError];
  1086. }
  1087. - (void)automaticDownloadInError
  1088. {
  1089. NSMutableSet *serversUrl = [[NSMutableSet alloc] init];
  1090. NSArray *records = [CCCoreData getTableMetadataWithPredicate:[NSPredicate predicateWithFormat:@"(account == %@) AND (session CONTAINS 'download') AND ((sessionTaskIdentifier == %i) OR (sessionTaskIdentifierPlist == %i))", _activeAccount, k_taskIdentifierError, k_taskIdentifierError] context:nil];
  1091. NSLog(@"[LOG] Verify re download n. %lu", (unsigned long)[records count]);
  1092. for (TableMetadata *record in records) {
  1093. CCMetadata *metadata = [CCCoreData insertEntityInMetadata:record];
  1094. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  1095. if (metadata.sessionTaskIdentifier == k_taskIdentifierError)
  1096. [self downloadFile:metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:metadata.sessionSelector selectorPost:nil session:k_download_session taskStatus: k_taskStatusResume delegate:nil];
  1097. if (metadata.sessionTaskIdentifierPlist == k_taskIdentifierError)
  1098. [self downloadFile:metadata serverUrl:serverUrl downloadData:NO downloadPlist:YES selector:metadata.sessionSelector selectorPost:nil session:k_download_session taskStatus: k_taskStatusResume delegate:nil];
  1099. [serversUrl addObject:serverUrl];
  1100. NSLog(@"[LOG] Re download file : %@ - %@ [%i %i]", metadata.fileName, metadata.fileNamePrint, metadata.sessionTaskIdentifier, metadata.sessionTaskIdentifierPlist);
  1101. }
  1102. dispatch_async(dispatch_get_main_queue(), ^{
  1103. for (NSString *serverUrl in serversUrl)
  1104. if ([self.delegate respondsToSelector:@selector(reloadDatasource:fileID:selector:)])
  1105. [self.delegate reloadDatasource:serverUrl fileID:nil selector:nil];
  1106. });
  1107. }
  1108. #pragma --------------------------------------------------------------------------------------------
  1109. #pragma mark ===== Upload Verify =====
  1110. #pragma --------------------------------------------------------------------------------------------
  1111. - (void)verifyUploadInProgress
  1112. {
  1113. NSArray *dataSourceUpload = [CCCoreData getTableMetadataUploadAccount:_activeAccount];
  1114. NSArray *dataSourceUploadWWan = [CCCoreData getTableMetadataUploadWWanAccount:_activeAccount];
  1115. NSMutableArray *dataSource = [[NSMutableArray alloc] init];
  1116. [dataSource addObjectsFromArray:dataSourceUpload];
  1117. [dataSource addObjectsFromArray:dataSourceUploadWWan];
  1118. NSLog(@"[LOG] Verify upload file in progress n. %lu", (unsigned long)[dataSource count]);
  1119. for (TableMetadata *record in dataSource) {
  1120. __block CCMetadata *metadata = [CCCoreData insertEntityInMetadata:record];
  1121. __block NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:_activeAccount];
  1122. NSURLSession *session = [self getSessionfromSessionDescription:metadata.session];
  1123. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1124. BOOL findTask = NO;
  1125. BOOL findTaskPlist = NO;
  1126. // cerchiamo la corrispondenza dei task
  1127. for (NSURLSessionUploadTask *uploadTask in uploadTasks) {
  1128. NSLog(@"[LOG] Find metadata Tasks [%i %i] = [%lu] state : %lu", metadata.sessionTaskIdentifier, metadata.sessionTaskIdentifierPlist , (unsigned long)uploadTask.taskIdentifier, (unsigned long)[uploadTask state]);
  1129. if (metadata.sessionTaskIdentifier == uploadTask.taskIdentifier) findTask = YES;
  1130. if (metadata.sessionTaskIdentifierPlist == uploadTask.taskIdentifier) findTaskPlist = YES;
  1131. if (findTask == YES || findTaskPlist == YES) break;
  1132. }
  1133. // se non c'è (ci sono) il relativo uploadTask.taskIdentifier allora chiediamolo
  1134. if ((metadata.cryptated == YES && findTask == NO && findTaskPlist == NO) || (metadata.cryptated == NO && findTask == NO)) {
  1135. 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);
  1136. if (metadata.sessionTaskIdentifier >= 0) [self readFileVerifyUpload:metadata.fileNameData fileNamePrint:metadata.fileNamePrint serverUrl:serverUrl];
  1137. if (metadata.sessionTaskIdentifierPlist >= 0) [self readFileVerifyUpload:metadata.fileName fileNamePrint:metadata.fileNamePrint serverUrl:serverUrl];
  1138. }
  1139. }];
  1140. // Notification change session
  1141. dispatch_async(dispatch_get_main_queue(), ^{
  1142. NSArray *object = [[NSArray alloc] initWithObjects:session, metadata, nil];
  1143. [[NSNotificationCenter defaultCenter] postNotificationName:k_networkingSessionNotification object:object];
  1144. });
  1145. }
  1146. [self automaticUploadInError];
  1147. }
  1148. - (void)automaticUploadInError
  1149. {
  1150. NSMutableSet *directoryIDs = [[NSMutableSet alloc] init];
  1151. NSArray *records = [CCCoreData getTableMetadataWithPredicate:[NSPredicate predicateWithFormat:@"(account == %@) AND (session CONTAINS 'upload') AND ((sessionTaskIdentifier == %i) OR (sessionTaskIdentifierPlist == %i))", _activeAccount, k_taskIdentifierError, k_taskIdentifierError] context:nil];
  1152. NSLog(@"[LOG] Verify re upload n. %lu", (unsigned long)[records count]);
  1153. for (TableMetadata *record in records) {
  1154. CCMetadata *metadata = [CCCoreData insertEntityInMetadata:record];
  1155. [self uploadFileMetadata:metadata taskStatus: k_taskStatusResume];
  1156. [directoryIDs addObject:metadata.directoryID];
  1157. NSLog(@"[LOG] Re upload file : %@", metadata.fileName);
  1158. }
  1159. dispatch_async(dispatch_get_main_queue(), ^{
  1160. for (NSString *directoryID in directoryIDs)
  1161. if ([self.delegate respondsToSelector:@selector(reloadDatasource:fileID:selector:)])
  1162. [self.delegate reloadDatasource:[CCCoreData getServerUrlFromDirectoryID:directoryID activeAccount:_activeAccount] fileID:nil selector:nil];
  1163. });
  1164. }
  1165. - (void)readFileVerifyUpload:(NSString *)fileName fileNamePrint:(NSString *)fileNamePrint serverUrl:(NSString *)serverUrl
  1166. {
  1167. #ifndef EXTENSION
  1168. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:_activeAccount];
  1169. metadataNet.action = actionReadFile;
  1170. metadataNet.fileName = fileName;
  1171. metadataNet.fileNamePrint = fileNamePrint;
  1172. metadataNet.serverUrl = serverUrl;
  1173. metadataNet.selector = selectorReadFileVerifyUpload;
  1174. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1175. #else
  1176. NSLog(@"[LOG] Function not available for extension.");
  1177. #endif
  1178. }
  1179. //
  1180. // File exists : selectorReadFileVerifyUpload
  1181. //
  1182. - (void)readFileSuccess:(CCMetadataNet *)metadataNet metadata:(CCMetadata *)metadata
  1183. {
  1184. NSString *fileName;
  1185. if ([CCUtility isCryptoString:metadata.fileName])
  1186. fileName = [metadata.fileName stringByAppendingString:@".plist"];
  1187. else
  1188. fileName = metadataNet.fileName;
  1189. NSString *directoryID = [CCCoreData getDirectoryIDFromServerUrl:metadataNet.serverUrl activeAccount:_activeAccount];
  1190. CCMetadata *metadataTemp = [CCCoreData getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"(fileName == %@) AND (directoryID == %@) AND (account == %@)", fileName , directoryID, _activeAccount] context:_context];
  1191. // is completed ?
  1192. if (metadataTemp.sessionTaskIdentifier == k_taskIdentifierDone && metadataTemp.sessionTaskIdentifierPlist == k_taskIdentifierDone) {
  1193. [CCGraphics createNewImageFrom:metadata.fileID directoryUser:_directoryUser fileNameTo:metadata.fileID fileNamePrint:metadata.fileNamePrint size:@"m" imageForUpload:NO typeFile:metadata.typeFile writePreview:YES optimizedFileName:[CCUtility getOptimizedPhoto]];
  1194. NSLog(@"[LOG] Verify read file success, but files already processed");
  1195. dispatch_async(dispatch_get_main_queue(), ^{
  1196. if ([self.delegate respondsToSelector:@selector(reloadDatasource:fileID:selector:)])
  1197. [self.delegate reloadDatasource:[CCCoreData getServerUrlFromDirectoryID:directoryID activeAccount:_activeAccount] fileID:metadataTemp.fileID selector:metadataNet.selector];
  1198. });
  1199. } else {
  1200. [self uploadFileSuccessFailure:metadataTemp fileName:metadataNet.fileName fileID:metadata.fileID rev:metadata.rev date:metadata.date serverUrl:metadataNet.serverUrl errorCode:0];
  1201. }
  1202. }
  1203. //
  1204. // File do not exists : selectorReadFileVerifyUpload
  1205. //
  1206. - (void)readFileFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1207. {
  1208. NSString *fileName;
  1209. if ([CCUtility isCryptoString:metadataNet.fileName])
  1210. fileName = [metadataNet.fileName stringByAppendingString:@".plist"];
  1211. else
  1212. fileName = metadataNet.fileName;
  1213. NSString *directoryID = [CCCoreData getDirectoryIDFromServerUrl:metadataNet.serverUrl activeAccount:_activeAccount];
  1214. CCMetadata *metadata = [CCCoreData getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"(fileName == %@) AND (directoryID == %@) AND (account == %@)",fileName , directoryID, _activeAccount] context:_context];
  1215. NSInteger error;
  1216. if (errorCode == kOCErrorServerPathNotFound)
  1217. error = k_CCErrorFileUploadNotFound;
  1218. else
  1219. error = errorCode;
  1220. [self uploadFileSuccessFailure:metadata fileName:metadataNet.fileName fileID:metadata.fileID rev:metadata.rev date:metadata.date serverUrl:metadataNet.serverUrl errorCode:error];
  1221. }
  1222. #pragma --------------------------------------------------------------------------------------------
  1223. #pragma mark ===== Utility =====
  1224. #pragma --------------------------------------------------------------------------------------------
  1225. - (id)getDelegate:(NSString *)fileID
  1226. {
  1227. id delegate = [_delegates objectForKey:fileID];
  1228. if (delegate)
  1229. return delegate;
  1230. else
  1231. return self.delegate;
  1232. }
  1233. - (NSString *)getServerUrlFromUrl:(NSString *)url
  1234. {
  1235. NSString *fileName = [url lastPathComponent];
  1236. url = [url stringByReplacingOccurrencesOfString:[@"/" stringByAppendingString:fileName] withString:@""];
  1237. return url;
  1238. }
  1239. - (NSString *)getTitleFromPlistName:(NSString *)fileName
  1240. {
  1241. if ([[fileName lastPathComponent] isEqualToString:@"plist"] == NO)
  1242. fileName = [fileName stringByAppendingString:@".plist"];
  1243. if (![[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", _directoryUser, fileName]]) return nil;
  1244. NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithContentsOfFile:[NSString stringWithFormat:@"%@/%@", _directoryUser, fileName]];
  1245. return [data objectForKey:@"title"];
  1246. }
  1247. @end