CCNetworking.m 96 KB

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