CCNetworking.m 106 KB

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