CCNetworking.m 101 KB

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