CCNetworking.m 99 KB

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