CCNetworking.m 108 KB

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