AppDelegate.m 93 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906
  1. //
  2. // AppDelegate.m
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 04/09/14.
  6. // Copyright (c) 2017 Marino Faggiana. All rights reserved.
  7. //
  8. // Author Marino Faggiana <marino.faggiana@nextcloud.com>
  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 "AppDelegate.h"
  24. #import "CCNetworking.h"
  25. #import "CCGraphics.h"
  26. #import "CCSynchronize.h"
  27. #import "CCMain.h"
  28. #import <Fabric/Fabric.h>
  29. #import <Crashlytics/Crashlytics.h>
  30. #import "NCBridgeSwift.h"
  31. #import "NCAutoUpload.h"
  32. #import "NCPushNotificationEncryption.h"
  33. @class NCViewerRichdocument;
  34. @implementation AppDelegate
  35. + (void)initialize
  36. {
  37. [[NSUserDefaults standardUserDefaults] registerDefaults:@{@"UserAgent": [CCUtility getUserAgent]}];
  38. }
  39. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
  40. {
  41. // Fabric
  42. if (![CCUtility getDisableCrashservice] && NCBrandOptions.sharedInstance.disable_crash_service == false) {
  43. [Fabric with:@[[Crashlytics class]]];
  44. }
  45. [CCUtility createDirectoryStandard];
  46. // Networking
  47. [[NCCommunicationCommon sharedInstance] setupWithUserAgent:[CCUtility getUserAgent] capabilitiesGroup:[NCBrandOptions sharedInstance].capabilitiesGroups delegate:[NCNetworking sharedInstance]];
  48. // Verify upgrade
  49. if ([self upgrade]) {
  50. // Set account, if no exists clear all
  51. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountActive];
  52. if (tableAccount == nil) {
  53. // remove all the keys Chain
  54. [CCUtility deleteAllChainStore];
  55. // remove all the App group key
  56. [[NSUserDefaults standardUserDefaults] removePersistentDomainForName:[[NSBundle mainBundle] bundleIdentifier]];
  57. } else {
  58. [self settingActiveAccount:tableAccount.account activeUrl:tableAccount.url activeUser:tableAccount.user activeUserID:tableAccount.userID activePassword:[CCUtility getPassword:tableAccount.account]];
  59. }
  60. }
  61. // UserDefaults
  62. self.ncUserDefaults = [[NSUserDefaults alloc] initWithSuiteName:[NCBrandOptions sharedInstance].capabilitiesGroups];
  63. // Initialization Notification
  64. self.listOfNotifications = [NSMutableArray new];
  65. // Background Fetch
  66. [application setMinimumBackgroundFetchInterval:UIApplicationBackgroundFetchIntervalMinimum];
  67. // Initialization List & Array
  68. self.listProgressMetadata = [[NSMutableDictionary alloc] init];
  69. self.listMainVC = [[NSMutableDictionary alloc] init];
  70. self.arrayDeleteMetadata = [NSMutableArray new];
  71. self.arrayMoveMetadata = [NSMutableArray new];
  72. self.arrayMoveServerUrlTo = [NSMutableArray new];
  73. self.arrayCopyMetadata = [NSMutableArray new];
  74. self.arrayCopyServerUrlTo = [NSMutableArray new];
  75. self.sessionPendingStatusInUpload = [NSMutableArray new];
  76. // Push Notification
  77. [application registerForRemoteNotifications];
  78. // Display notification (sent via APNS)
  79. [UNUserNotificationCenter currentNotificationCenter].delegate = self;
  80. UNAuthorizationOptions authOptions = UNAuthorizationOptionAlert | UNAuthorizationOptionSound | UNAuthorizationOptionBadge;
  81. [[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:authOptions completionHandler:^(BOOL granted, NSError * _Nullable error) {
  82. }];
  83. // setting Reachable in back
  84. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  85. self.reachability = [Reachability reachabilityForInternetConnection];
  86. self.lastReachability = [self.reachability isReachable];
  87. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
  88. [self.reachability startNotifier];
  89. });
  90. //AV Session
  91. [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error:nil];
  92. // [[AVAudioSession sharedInstance] setActive:YES error:nil];
  93. [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
  94. /*
  95. // APPEARANCE: How to hide UINavigationBar 1px bottom line < iOS 11
  96. [[UINavigationBar appearance] setBackgroundImage:[[UIImage alloc] init] forBarPosition:UIBarPositionAny barMetrics:UIBarMetricsDefault];
  97. [[UINavigationBar appearance] setShadowImage:[[UIImage alloc] init]];
  98. [UINavigationBar appearance].translucent = NO;
  99. */
  100. // ProgressView Detail
  101. self.progressViewDetail = [[UIProgressView alloc] initWithProgressViewStyle: UIProgressViewStyleBar];
  102. // passcode
  103. [[BKPasscodeLockScreenManager sharedManager] setDelegate:self];
  104. dispatch_async(dispatch_get_main_queue(), ^{
  105. [[BKPasscodeLockScreenManager sharedManager] showLockScreen:NO];
  106. });
  107. // Quick Actions
  108. if([[UIApplicationShortcutItem class] respondsToSelector:@selector(new)]) {
  109. [self configDynamicShortcutItems];
  110. UIApplicationShortcutItem *shortcutItem = [launchOptions objectForKeyedSubscript:UIApplicationLaunchOptionsShortcutItemKey];
  111. if (shortcutItem)
  112. [self handleShortCutItem:shortcutItem];
  113. }
  114. // Start Timer
  115. self.timerProcessAutoDownloadUpload = [NSTimer scheduledTimerWithTimeInterval:k_timerProcessAutoDownloadUpload target:self selector:@selector(loadAutoDownloadUpload) userInfo:nil repeats:YES];
  116. self.timerUpdateApplicationIconBadgeNumber = [NSTimer scheduledTimerWithTimeInterval:k_timerUpdateApplicationIconBadgeNumber target:self selector:@selector(updateApplicationIconBadgeNumber) userInfo:nil repeats:YES];
  117. [self startTimerErrorNetworking];
  118. // Store review
  119. if ([[NCUtility sharedInstance] isSimulatorOrTestFlight] == false) {
  120. NCStoreReview *review = [NCStoreReview new];
  121. [review incrementAppRuns];
  122. [review showStoreReview];
  123. }
  124. // Detect Dark mode
  125. if (@available(iOS 13.0, *)) {
  126. if ([CCUtility getDarkModeDetect]) {
  127. if ([[UITraitCollection currentTraitCollection] userInterfaceStyle] == UIUserInterfaceStyleDark) {
  128. [CCUtility setDarkMode:YES];
  129. } else {
  130. [CCUtility setDarkMode:NO];
  131. }
  132. }
  133. }
  134. if ([NCBrandOptions sharedInstance].disable_intro) {
  135. [CCUtility setIntro:YES];
  136. if (self.activeAccount.length == 0) {
  137. [self openLoginView:nil selector:k_intro_login openLoginWeb:false];
  138. }
  139. } else {
  140. if ([CCUtility getIntro] == NO) {
  141. UIViewController *introViewController = [[UIStoryboard storyboardWithName:@"NCIntro" bundle:[NSBundle mainBundle]] instantiateInitialViewController];
  142. UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController: introViewController];
  143. self.window.rootViewController = navController;
  144. [self.window makeKeyAndVisible];
  145. }
  146. }
  147. // init home
  148. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_initializeMain object:nil userInfo:nil];
  149. // Observer
  150. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deleteFile:) name:k_notificationCenter_deleteFile object:nil];
  151. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moveFile:) name:k_notificationCenter_moveFile object:nil];
  152. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(copyFile:) name:k_notificationCenter_copyFile object:nil];
  153. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(uploadedFile:) name:k_notificationCenter_uploadedFile object:nil];
  154. return YES;
  155. }
  156. //
  157. // L' applicazione si dimetterà dallo stato di attivo
  158. //
  159. - (void)applicationWillResignActive:(UIApplication *)application
  160. {
  161. // Test Maintenance
  162. if (self.activeAccount.length == 0 || self.maintenanceMode)
  163. return;
  164. [self updateApplicationIconBadgeNumber];
  165. }
  166. //
  167. // L' applicazione entrerà in primo piano (attivo solo dopo il background)
  168. //
  169. - (void)applicationWillEnterForeground:(UIApplication *)application
  170. {
  171. // Test Maintenance
  172. if (self.activeAccount.length == 0 || self.maintenanceMode)
  173. return;
  174. NSLog(@"[LOG] Request Service Server Nextcloud");
  175. [[NCService sharedInstance] startRequestServicesServer];
  176. NSLog(@"[LOG] Initialize Auto upload");
  177. [[NCAutoUpload sharedInstance] initStateAutoUpload];
  178. NSLog(@"[LOG] Read active directory");
  179. [self.activeMain readFileReloadFolder];
  180. NSLog(@"[LOG] Required unsubscribing / subscribing");
  181. [self pushNotification];
  182. NSLog(@"[LOG] RichDocument");
  183. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_richdocumentGrabFocus object:nil];
  184. }
  185. //
  186. // L' applicazione entrerà in primo piano (attivo sempre)
  187. //
  188. - (void)applicationDidBecomeActive:(UIApplication *)application
  189. {
  190. // Test Maintenance
  191. if (self.activeAccount.length == 0 || self.maintenanceMode)
  192. return;
  193. // middelware ping
  194. if ([[NCBrandOptions sharedInstance] use_middlewarePing]) {
  195. NSLog(@"[LOG] Middleware Ping");
  196. [[NCService sharedInstance] middlewarePing];
  197. }
  198. // verify task (download/upload) lost
  199. [self verifyTaskLost];
  200. // verify delete Asset Local Identifiers in auto upload
  201. [[NCUtility sharedInstance] deleteAssetLocalIdentifiersWithAccount:self.activeAccount sessionSelector:selectorUploadAutoUpload];
  202. // Brand
  203. #if defined(HC)
  204. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  205. if (account.hcIsTrial == true || account.hcTrialExpired == true || account.hcNextGroupExpirationGroupExpired == true) {
  206. HCTrial *vc = [[UIStoryboard storyboardWithName:@"HCTrial" bundle:nil] instantiateInitialViewController];
  207. vc.account = account;
  208. [self.window.rootViewController presentViewController:vc animated:YES completion:nil];
  209. }
  210. #endif
  211. }
  212. //
  213. // L' applicazione è entrata nello sfondo
  214. //
  215. - (void)applicationDidEnterBackground:(UIApplication *)application
  216. {
  217. NSLog(@"[LOG] Enter in Background");
  218. [[BKPasscodeLockScreenManager sharedManager] showLockScreen:YES];
  219. if([[UIDevice currentDevice] respondsToSelector:@selector(isMultitaskingSupported)]) {
  220. __block UIBackgroundTaskIdentifier background_task;
  221. background_task = [application beginBackgroundTaskWithExpirationHandler:^ {
  222. //Clean up code. Tell the system that we are done.
  223. [application endBackgroundTask: background_task];
  224. background_task = UIBackgroundTaskInvalid;
  225. }];
  226. }
  227. }
  228. //
  229. // L'applicazione terminerà
  230. //
  231. - (void)applicationWillTerminate:(UIApplication *)application
  232. {
  233. NSLog(@"[LOG] bye bye, Nextcloud !");
  234. }
  235. #pragma --------------------------------------------------------------------------------------------
  236. #pragma mark ===== Login / checkErrorNetworking =====
  237. #pragma --------------------------------------------------------------------------------------------
  238. - (void)checkErrorNetworking
  239. {
  240. // test
  241. if (self.activeAccount.length == 0 || self.maintenanceMode)
  242. return;
  243. // check unauthorized server (401)
  244. if ([CCUtility getPassword:self.activeAccount].length == 0) {
  245. [self openLoginView:self.window.rootViewController selector:k_intro_login openLoginWeb:true];
  246. }
  247. // check certificate untrusted (-1202)
  248. if ([CCUtility getCertificateError:self.activeAccount]) {
  249. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_ssl_certificate_untrusted_", nil) message:NSLocalizedString(@"_connect_server_anyway_", nil) preferredStyle:UIAlertControllerStyleAlert];
  250. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_yes_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  251. [[NCNetworking sharedInstance] wrtiteCertificateWithDirectoryCertificate:[CCUtility getDirectoryCerificates]];
  252. [self startTimerErrorNetworking];
  253. }]];
  254. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_no_", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  255. [self startTimerErrorNetworking];
  256. }]];
  257. [self.window.rootViewController presentViewController:alertController animated:YES completion:^{
  258. // Stop timer error network
  259. [self.timerErrorNetworking invalidate];
  260. }];
  261. }
  262. }
  263. - (void)openLoginView:(UIViewController *)viewController selector:(NSInteger)selector openLoginWeb:(BOOL)openLoginWeb
  264. {
  265. // use appConfig [MDM]
  266. if ([NCBrandOptions sharedInstance].use_configuration) {
  267. if (!(_appConfigView.isViewLoaded && _appConfigView.view.window)) {
  268. self.appConfigView = [[UIStoryboard storyboardWithName:@"CCLogin" bundle:nil] instantiateViewControllerWithIdentifier:@"NCAppConfigView"];
  269. [self showLoginViewController:self.appConfigView forContext:viewController];
  270. }
  271. return;
  272. }
  273. // only for personalized LoginWeb [customer]
  274. if ([NCBrandOptions sharedInstance].use_login_web_personalized) {
  275. if (!(_activeLoginWeb.isViewLoaded && _activeLoginWeb.view.window)) {
  276. self.activeLoginWeb = [[UIStoryboard storyboardWithName:@"CCLogin" bundle:nil] instantiateViewControllerWithIdentifier:@"NCLoginWeb"];
  277. self.activeLoginWeb.urlBase = [[NCBrandOptions sharedInstance] loginBaseUrl];
  278. [self showLoginViewController:self.activeLoginWeb forContext:viewController];
  279. }
  280. return;
  281. }
  282. // normal login
  283. if (selector == k_intro_signup) {
  284. if (!(_activeLoginWeb.isViewLoaded && _activeLoginWeb.view.window)) {
  285. self.activeLoginWeb = [[UIStoryboard storyboardWithName:@"CCLogin" bundle:nil] instantiateViewControllerWithIdentifier:@"NCLoginWeb"];
  286. if (selector == k_intro_signup) {
  287. self.activeLoginWeb.urlBase = [[NCBrandOptions sharedInstance] linkloginPreferredProviders];
  288. } else {
  289. self.activeLoginWeb.urlBase = self.activeUrl;
  290. }
  291. [self showLoginViewController:self.activeLoginWeb forContext:viewController];
  292. }
  293. } else if ([NCBrandOptions sharedInstance].disable_intro && [NCBrandOptions sharedInstance].disable_request_login_url) {
  294. self.activeLoginWeb = [[UIStoryboard storyboardWithName:@"CCLogin" bundle:nil] instantiateViewControllerWithIdentifier:@"NCLoginWeb"];
  295. self.activeLoginWeb.urlBase = [[NCBrandOptions sharedInstance] loginBaseUrl];
  296. [self showLoginViewController:self.activeLoginWeb forContext:viewController];
  297. } else if (openLoginWeb) {
  298. if (!(_activeLoginWeb.isViewLoaded && _activeLoginWeb.view.window)) {
  299. self.activeLoginWeb = [[UIStoryboard storyboardWithName:@"CCLogin" bundle:nil] instantiateViewControllerWithIdentifier:@"NCLoginWeb"];
  300. self.activeLoginWeb.urlBase = self.activeUrl;
  301. [self showLoginViewController:self.activeLoginWeb forContext:viewController];
  302. }
  303. } else {
  304. if (!(_activeLogin.isViewLoaded && _activeLogin.view.window)) {
  305. _activeLogin = [[UIStoryboard storyboardWithName:@"CCLogin" bundle:nil] instantiateViewControllerWithIdentifier:@"CCLoginNextcloud"];
  306. [self showLoginViewController:_activeLogin forContext:viewController];
  307. }
  308. }
  309. }
  310. -(void)showLoginViewController:(UIViewController *)viewController forContext:(UIViewController *)contextViewController
  311. {
  312. if (contextViewController == NULL) {
  313. UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:viewController];
  314. navController.navigationBar.tintColor = NCBrandColor.sharedInstance.customerText;
  315. navController.navigationBar.barTintColor = NCBrandColor.sharedInstance.customer;
  316. self.window.rootViewController = navController;
  317. [self.window makeKeyAndVisible];
  318. } else if ([contextViewController isKindOfClass:[UINavigationController class]]) {
  319. UINavigationController *navController = ((UINavigationController *)contextViewController);
  320. [navController pushViewController:viewController animated:true];
  321. } else {
  322. UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:viewController];
  323. navController.modalPresentationStyle = UIModalPresentationFullScreen;
  324. navController.navigationBar.tintColor = NCBrandColor.sharedInstance.customerText;
  325. navController.navigationBar.barTintColor = NCBrandColor.sharedInstance.customer;
  326. [contextViewController presentViewController:navController animated:true completion:nil];
  327. }
  328. }
  329. - (void)startTimerErrorNetworking
  330. {
  331. self.timerErrorNetworking = [NSTimer scheduledTimerWithTimeInterval:k_timerErrorNetworking target:self selector:@selector(checkErrorNetworking) userInfo:nil repeats:YES];
  332. }
  333. #pragma --------------------------------------------------------------------------------------------
  334. #pragma mark ===== Account =====
  335. #pragma --------------------------------------------------------------------------------------------
  336. - (void)settingActiveAccount:(NSString *)activeAccount activeUrl:(NSString *)activeUrl activeUser:(NSString *)activeUser activeUserID:(NSString *)activeUserID activePassword:(NSString *)activePassword
  337. {
  338. self.activeAccount = activeAccount;
  339. self.activeUrl = activeUrl;
  340. self.activeUser = activeUser;
  341. self.activeUserID = activeUserID;
  342. self.activePassword = activePassword;
  343. tableCapabilities *capabilities = [[NCManageDatabase sharedInstance] getCapabilitesWithAccount:activeAccount];
  344. (void)[NCNetworkingNotificationCenter shared];
  345. [[NCCommunicationCommon sharedInstance] setupWithUser:activeUser userId:activeUserID password:activePassword url:activeUrl userAgent:[CCUtility getUserAgent] capabilitiesGroup:[NCBrandOptions sharedInstance].capabilitiesGroups nextcloudVersion:capabilities.versionMajor delegate:[NCNetworking sharedInstance]];
  346. OCCommunication *communication = [OCNetworking sharedManager].sharedOCCommunication;
  347. [communication setupNextcloudVersion:[[NCManageDatabase sharedInstance] getServerVersionWithAccount:activeAccount]];
  348. }
  349. - (void)settingWebDavRoot:(NSString *)webdavRoot
  350. {
  351. if (webdavRoot != nil) {
  352. [[NCCommunicationCommon sharedInstance] setupWithWebDavRoot:webdavRoot];
  353. }
  354. }
  355. - (void)deleteAccount:(NSString *)account wipe:(BOOL)wipe
  356. {
  357. [self unsubscribingNextcloudServerPushNotification:account url:self.activeUrl withSubscribing:false];
  358. [self settingActiveAccount:nil activeUrl:nil activeUser:nil activeUserID:nil activePassword:nil];
  359. /* DELETE ALL FILES LOCAL FS */
  360. NSArray *results = [[NCManageDatabase sharedInstance] getTableLocalFilesWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account] sorted:@"ocId" ascending:NO];
  361. for (tableLocalFile *result in results) {
  362. [CCUtility removeFileAtPath:[CCUtility getDirectoryProviderStorageOcId:result.ocId]];
  363. }
  364. // Clear database
  365. [[NCManageDatabase sharedInstance] clearDatabaseWithAccount:account removeAccount:true];
  366. [CCUtility clearAllKeysEndToEnd:account];
  367. [CCUtility clearAllKeysPushNotification:account];
  368. [CCUtility setCertificateError:account error:false];
  369. [CCUtility setPassword:account password:nil];
  370. if (wipe) {
  371. NSArray *listAccount = [[NCManageDatabase sharedInstance] getAccounts];
  372. if ([listAccount count] > 0) {
  373. NSString *newAccount = listAccount[0];
  374. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] setAccountActive:newAccount];
  375. [self settingActiveAccount:newAccount activeUrl:tableAccount.url activeUser:tableAccount.user activeUserID:tableAccount.userID activePassword:[CCUtility getPassword:tableAccount.account]];
  376. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_initializeMain object:nil userInfo:nil];
  377. } else {
  378. [self openLoginView:self.window.rootViewController selector:k_intro_login openLoginWeb:false];
  379. }
  380. }
  381. }
  382. #pragma --------------------------------------------------------------------------------------------
  383. #pragma mark ===== Push Notifications =====
  384. #pragma --------------------------------------------------------------------------------------------
  385. - (void)pushNotification
  386. {
  387. // test
  388. if (self.activeAccount.length == 0 || self.maintenanceMode || self.pushKitToken.length == 0)
  389. return;
  390. for (tableAccount *result in [[NCManageDatabase sharedInstance] getAllAccount]) {
  391. NSString *token = [CCUtility getPushNotificationToken:result.account];
  392. if (![token isEqualToString:self.pushKitToken]) {
  393. if (token != nil) {
  394. // unsubscribing + subscribing
  395. [self unsubscribingNextcloudServerPushNotification:result.account url:result.url withSubscribing:true];
  396. } else {
  397. [self subscribingNextcloudServerPushNotification:result.account url:result.url];
  398. }
  399. }
  400. }
  401. }
  402. - (void)subscribingNextcloudServerPushNotification:(NSString *)account url:(NSString *)url
  403. {
  404. // test
  405. if (self.activeAccount.length == 0 || self.maintenanceMode || self.pushKitToken.length == 0)
  406. return;
  407. [[NCPushNotificationEncryption sharedInstance] generatePushNotificationsKeyPair:account];
  408. NSString *pushTokenHash = [[NCEndToEndEncryption sharedManager] createSHA512:self.pushKitToken];
  409. NSData *pushPublicKey = [CCUtility getPushNotificationPublicKey:account];
  410. NSString *pushDevicePublicKey = [[NSString alloc] initWithData:pushPublicKey encoding:NSUTF8StringEncoding];
  411. [[OCNetworking sharedManager] subscribingPushNotificationWithAccount:account url:url pushToken:self.pushKitToken Hash:pushTokenHash devicePublicKey:pushDevicePublicKey completion:^(NSString *accountCompletion, NSString *deviceIdentifier, NSString *deviceIdentifierSignature, NSString *publicKey, NSString *message, NSInteger errorCode) {
  412. if (errorCode == 0 && [accountCompletion isEqualToString:account]) {
  413. NSLog(@"[LOG] Subscribed to Push Notification server & proxy successfully.");
  414. [CCUtility setPushNotificationToken:account token:self.pushKitToken];
  415. [CCUtility setPushNotificationDeviceIdentifier:account deviceIdentifier:deviceIdentifier];
  416. [CCUtility setPushNotificationDeviceIdentifierSignature:account deviceIdentifierSignature:deviceIdentifierSignature];
  417. [CCUtility setPushNotificationSubscribingPublicKey:account publicKey:publicKey];
  418. } else if (errorCode != 0) {
  419. NSLog(@"[LOG] Subscribed to Push Notification server & proxy error.");
  420. } else {
  421. NSLog(@"[LOG] It has been changed user during networking process, error.");
  422. }
  423. }];
  424. }
  425. - (void)unsubscribingNextcloudServerPushNotification:(NSString *)account url:(NSString *)url withSubscribing:(BOOL)subscribing
  426. {
  427. // test
  428. if (self.activeAccount.length == 0 || self.maintenanceMode)
  429. return;
  430. NSString *deviceIdentifier = [CCUtility getPushNotificationDeviceIdentifier:account];
  431. NSString *deviceIdentifierSignature = [CCUtility getPushNotificationDeviceIdentifierSignature:account];
  432. NSString *publicKey = [CCUtility getPushNotificationSubscribingPublicKey:account];
  433. [[OCNetworking sharedManager] unsubscribingPushNotificationWithAccount:account url:url deviceIdentifier:deviceIdentifier deviceIdentifierSignature:deviceIdentifierSignature publicKey:publicKey completion:^(NSString *account, NSString *message, NSInteger errorCode) {
  434. if (errorCode == 0) {
  435. NSLog(@"[LOG] Unsubscribed to Push Notification server & proxy successfully.");
  436. [CCUtility setPushNotificationPublicKey:account data:nil];
  437. [CCUtility setPushNotificationSubscribingPublicKey:account publicKey:nil];
  438. [CCUtility setPushNotificationPrivateKey:account data:nil];
  439. [CCUtility setPushNotificationToken:account token:nil];
  440. [CCUtility setPushNotificationDeviceIdentifier:account deviceIdentifier:nil];
  441. [CCUtility setPushNotificationDeviceIdentifierSignature:account deviceIdentifierSignature:nil];
  442. if (self.pushKitToken != nil && subscribing) {
  443. [self subscribingNextcloudServerPushNotification:account url:url];
  444. }
  445. } else if (errorCode != 0) {
  446. NSLog(@"[LOG] Unsubscribed to Push Notification server & proxy error.");
  447. } else {
  448. NSLog(@"[LOG] It has been changed user during networking process, error.");
  449. }
  450. }];
  451. }
  452. -(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler
  453. {
  454. //Called when a notification is delivered to a foreground app.
  455. completionHandler(UNNotificationPresentationOptionAlert);
  456. }
  457. -(void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(nonnull UNNotificationResponse *)response withCompletionHandler:(nonnull void (^)(void))completionHandler
  458. {
  459. completionHandler();
  460. }
  461. - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
  462. {
  463. self.pushKitToken = [self stringWithDeviceToken:deviceToken];
  464. [self pushNotification];
  465. }
  466. - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
  467. {
  468. NSString *message = [userInfo objectForKey:@"subject"];
  469. if (message) {
  470. NSArray *results = [[NCManageDatabase sharedInstance] getAllAccount];
  471. for (tableAccount *result in results) {
  472. if ([CCUtility getPushNotificationPrivateKey:result.account]) {
  473. NSData *decryptionKey = [CCUtility getPushNotificationPrivateKey:result.account];
  474. NSString *decryptedMessage = [[NCPushNotificationEncryption sharedInstance] decryptPushNotification:message withDevicePrivateKey:decryptionKey];
  475. if (decryptedMessage) {
  476. NSData *data = [decryptedMessage dataUsingEncoding:NSUTF8StringEncoding];
  477. NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
  478. NSInteger nid = [[json objectForKey:@"nid"] integerValue];
  479. BOOL delete = [[json objectForKey:@"delete"] boolValue];
  480. BOOL deleteAll = [[json objectForKey:@"delete-all"] boolValue];
  481. if (delete) {
  482. [self removeNotificationWithNotificationId:nid usingDecryptionKey:decryptionKey];
  483. } else if (deleteAll) {
  484. [self cleanAllNotifications];
  485. }
  486. }
  487. }
  488. }
  489. }
  490. completionHandler(UIBackgroundFetchResultNoData);
  491. }
  492. - (void)cleanAllNotifications
  493. {
  494. [[UNUserNotificationCenter currentNotificationCenter] removeAllDeliveredNotifications];
  495. }
  496. - (void)removeNotificationWithNotificationId:(NSInteger)notificationId usingDecryptionKey:(NSData *)key
  497. {
  498. // Check in pending notifications
  499. [[UNUserNotificationCenter currentNotificationCenter] getPendingNotificationRequestsWithCompletionHandler:^(NSArray<UNNotificationRequest *> * _Nonnull requests) {
  500. for (UNNotificationRequest *notificationRequest in requests) {
  501. NSString *message = [notificationRequest.content.userInfo objectForKey:@"subject"];
  502. NSString *decryptedMessage = [[NCPushNotificationEncryption sharedInstance] decryptPushNotification:message withDevicePrivateKey:key];
  503. if (decryptedMessage) {
  504. NSData *data = [decryptedMessage dataUsingEncoding:NSUTF8StringEncoding];
  505. NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
  506. NSInteger nid = [[json objectForKey:@"nid"] integerValue];
  507. if (nid == notificationId) {
  508. [[UNUserNotificationCenter currentNotificationCenter] removePendingNotificationRequestsWithIdentifiers:@[notificationRequest.identifier]];
  509. }
  510. }
  511. }
  512. }];
  513. // Check in delivered notifications
  514. [[UNUserNotificationCenter currentNotificationCenter] getDeliveredNotificationsWithCompletionHandler:^(NSArray<UNNotification *> * _Nonnull notifications) {
  515. for (UNNotification *notification in notifications) {
  516. NSString *message = [notification.request.content.userInfo objectForKey:@"subject"];
  517. NSString *decryptedMessage = [[NCPushNotificationEncryption sharedInstance] decryptPushNotification:message withDevicePrivateKey:key];
  518. if (decryptedMessage) {
  519. NSData *data = [decryptedMessage dataUsingEncoding:NSUTF8StringEncoding];
  520. NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
  521. NSInteger nid = [[json objectForKey:@"nid"] integerValue];
  522. if (nid == notificationId) {
  523. [[UNUserNotificationCenter currentNotificationCenter] removeDeliveredNotificationsWithIdentifiers:@[notification.request.identifier]];
  524. }
  525. }
  526. }
  527. }];
  528. }
  529. - (NSString *)stringWithDeviceToken:(NSData *)deviceToken
  530. {
  531. const char *data = [deviceToken bytes];
  532. NSMutableString *token = [NSMutableString string];
  533. for (NSUInteger i = 0; i < [deviceToken length]; i++) {
  534. [token appendFormat:@"%02.2hhX", data[i]];
  535. }
  536. return [token copy];
  537. }
  538. #pragma --------------------------------------------------------------------------------------------
  539. #pragma mark ==== NotificationCenter ====
  540. #pragma --------------------------------------------------------------------------------------------
  541. - (void)deleteFile:(NSNotification *)notification
  542. {
  543. if (self.arrayDeleteMetadata.count > 0) {
  544. tableMetadata *metadata = self.arrayDeleteMetadata.firstObject;
  545. [self.arrayDeleteMetadata removeObjectAtIndex:0];
  546. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", metadata.account]];
  547. if (account) {
  548. [[NCNetworking sharedInstance] deleteMetadata:metadata account:metadata.account user:account.user userID:account.userID password:[CCUtility getPassword:metadata.account] url:account.url completion:^(NSInteger errorCode, NSString *errorDescription) { }];
  549. } else {
  550. [self deleteFile:[NSNotification new]];
  551. }
  552. }
  553. }
  554. - (void)moveFile:(NSNotification *)notification
  555. {
  556. if (self.arrayMoveMetadata.count > 0) {
  557. tableMetadata *metadata = self.arrayMoveMetadata.firstObject;
  558. NSString *serverUrlTo = self.arrayMoveServerUrlTo.firstObject;
  559. [self.arrayMoveMetadata removeObjectAtIndex:0];
  560. [self.arrayMoveServerUrlTo removeObjectAtIndex:0];
  561. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", metadata.account]];
  562. if (account) {
  563. [[NCNetworking sharedInstance] moveMetadata:metadata serverUrlTo:serverUrlTo overwrite:true completion:^(NSInteger errorCode, NSString *errorDescription) { }];
  564. } else {
  565. [self moveFile:[NSNotification new]];
  566. }
  567. }
  568. }
  569. - (void)copyFile:(NSNotification *)notification
  570. {
  571. if (self.arrayCopyMetadata.count > 0) {
  572. tableMetadata *metadata = self.arrayCopyMetadata.firstObject;
  573. NSString *serverUrlTo = self.arrayCopyServerUrlTo.firstObject;
  574. [self.arrayCopyMetadata removeObjectAtIndex:0];
  575. [self.arrayCopyServerUrlTo removeObjectAtIndex:0];
  576. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", metadata.account]];
  577. if (account) {
  578. [[NCNetworking sharedInstance] copyMetadata:metadata serverUrlTo:serverUrlTo overwrite:true completion:^(NSInteger errorCode, NSString *errorDescription) { }];
  579. } else {
  580. [self copyFile:[NSNotification new]];
  581. }
  582. }
  583. }
  584. - (void)uploadedFile:(NSNotification *)notification
  585. {
  586. NSArray *metadatasSessionUpload = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND session CONTAINS[cd] %@", self.activeAccount, @"upload"] sorted:nil ascending:true];
  587. if (metadatasSessionUpload.count == 0) {
  588. // verify delete Asset Local Identifiers in auto upload
  589. [[NCUtility sharedInstance] deleteAssetLocalIdentifiersWithAccount:self.activeAccount sessionSelector:selectorUploadAutoUpload];
  590. }
  591. }
  592. #pragma --------------------------------------------------------------------------------------------
  593. #pragma mark ===== Quick Actions - ShotcutItem =====
  594. #pragma --------------------------------------------------------------------------------------------
  595. - (void)configDynamicShortcutItems
  596. {
  597. NSString *bundleId = [NSBundle mainBundle].bundleIdentifier;
  598. UIApplicationShortcutIcon *shortcutMediaIcon = [UIApplicationShortcutIcon iconWithTemplateImageName:@"media"];
  599. UIApplicationShortcutItem *shortcutMedia = [[UIApplicationShortcutItem alloc] initWithType:[NSString stringWithFormat:@"%@.media", bundleId] localizedTitle:NSLocalizedString(@"_media_", nil) localizedSubtitle:nil icon:shortcutMediaIcon userInfo:nil];
  600. // add the array to our app
  601. if (shortcutMedia)
  602. [UIApplication sharedApplication].shortcutItems = @[shortcutMedia];
  603. }
  604. - (void)application:(UIApplication *)application performActionForShortcutItem:(UIApplicationShortcutItem *)shortcutItem completionHandler:(void (^)(BOOL))completionHandler
  605. {
  606. BOOL handledShortCutItem = [self handleShortCutItem:shortcutItem];
  607. completionHandler(handledShortCutItem);
  608. }
  609. - (BOOL)handleShortCutItem:(UIApplicationShortcutItem *)shortcutItem
  610. {
  611. BOOL handled = NO;
  612. NSString *bundleId = [NSBundle mainBundle].bundleIdentifier;
  613. NSString *shortcutMedia = [NSString stringWithFormat:@"%@.media", bundleId];
  614. if ([shortcutItem.type isEqualToString:shortcutMedia] && self.activeAccount) {
  615. dispatch_async(dispatch_get_main_queue(), ^{
  616. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  617. if ([splitViewController isKindOfClass:[UISplitViewController class]]) {
  618. UINavigationController *navigationControllerMaster = (UINavigationController *)splitViewController.viewControllers.firstObject;
  619. if ([navigationControllerMaster isKindOfClass:[UINavigationController class]]) {
  620. UITabBarController *tabBarController = (UITabBarController *)navigationControllerMaster.topViewController;
  621. if ([tabBarController isKindOfClass:[UITabBarController class]]) {
  622. if (splitViewController.isCollapsed) {
  623. [navigationControllerMaster popToRootViewControllerAnimated:false];
  624. UINavigationController *navigationControllerMaster = (UINavigationController *)splitViewController.viewControllers.firstObject;
  625. if ([navigationControllerMaster isKindOfClass:[UINavigationController class]]) {
  626. UITabBarController *tabBarController = (UITabBarController *)navigationControllerMaster.topViewController;
  627. if ([tabBarController isKindOfClass:[UITabBarController class]]) {
  628. [tabBarController setSelectedIndex: k_tabBarApplicationIndexMedia];
  629. }
  630. }
  631. } else {
  632. if ([tabBarController isKindOfClass:[UITabBarController class]]) {
  633. [tabBarController setSelectedIndex: k_tabBarApplicationIndexMedia];
  634. }
  635. }
  636. }
  637. }
  638. }
  639. });
  640. handled = YES;
  641. }
  642. return handled;
  643. }
  644. #pragma --------------------------------------------------------------------------------------------
  645. #pragma mark ===== ApplicationIconBadgeNumber =====
  646. #pragma --------------------------------------------------------------------------------------------
  647. - (void)updateApplicationIconBadgeNumber
  648. {
  649. if (self.activeAccount.length == 0 || self.maintenanceMode)
  650. return;
  651. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  652. NSInteger counterDownload = [[[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"status = %d OR status == %d OR status == %d", k_metadataStatusWaitDownload, k_metadataStatusInDownload, k_metadataStatusDownloading] sorted:@"fileName" ascending:true] count];
  653. NSInteger counterUpload = [[[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"status == %d OR status == %d OR status == %d", k_metadataStatusWaitUpload, k_metadataStatusInUpload, k_metadataStatusUploading] sorted:@"fileName" ascending:true] count];
  654. NSInteger total = counterDownload + counterUpload;
  655. dispatch_async(dispatch_get_main_queue(), ^{
  656. [UIApplication sharedApplication].applicationIconBadgeNumber = total;
  657. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  658. if ([splitViewController isKindOfClass:[UISplitViewController class]]) {
  659. UINavigationController *navigationController = (UINavigationController *)[splitViewController.viewControllers firstObject];
  660. if ([navigationController isKindOfClass:[UINavigationController class]]) {
  661. UITabBarController *tabBarController = (UITabBarController *)navigationController.topViewController;
  662. if ([tabBarController isKindOfClass:[UITabBarController class]]) {
  663. UITabBarItem *tabBarItem = [tabBarController.tabBar.items objectAtIndex:0];
  664. if (total > 0) {
  665. [tabBarItem setBadgeValue:[NSString stringWithFormat:@"%li", (unsigned long)total]];
  666. } else {
  667. [tabBarItem setBadgeValue:nil];
  668. }
  669. }
  670. }
  671. }
  672. });
  673. });
  674. }
  675. #pragma --------------------------------------------------------------------------------------------
  676. #pragma mark ===== TabBarController =====
  677. #pragma --------------------------------------------------------------------------------------------
  678. - (void)createTabBarController:(UITabBarController *)tabBarController
  679. {
  680. UITabBarItem *item;
  681. NSLayoutConstraint *constraint;
  682. CGFloat safeAreaBottom = safeAreaBottom = [UIApplication sharedApplication].delegate.window.safeAreaInsets.bottom;
  683. // File
  684. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexFile];
  685. [item setTitle:NSLocalizedString(@"_home_", nil)];
  686. item.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarFiles"] width:50 height:50 color:NCBrandColor.sharedInstance.brandElement];
  687. item.selectedImage = item.image;
  688. // Favorites
  689. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexFavorite];
  690. [item setTitle:NSLocalizedString(@"_favorites_", nil)];
  691. item.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarFavorites"] width:50 height:50 color:NCBrandColor.sharedInstance.brandElement];
  692. item.selectedImage = item.image;
  693. // (PLUS INVISIBLE)
  694. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexPlusHide];
  695. item.title = @"";
  696. item.image = nil;
  697. item.enabled = false;
  698. // Media
  699. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexMedia];
  700. [item setTitle:NSLocalizedString(@"_media_", nil)];
  701. item.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarMedia"] width:50 height:50 color:NCBrandColor.sharedInstance.brandElement];
  702. item.selectedImage = item.image;
  703. // More
  704. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexMore];
  705. [item setTitle:NSLocalizedString(@"_more_", nil)];
  706. item.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarMore"] width:50 height:50 color:NCBrandColor.sharedInstance.brandElement];
  707. item.selectedImage = item.image;
  708. // Plus Button
  709. UIImage *buttonImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarPlus"] width:120 height:120 color:NCBrandColor.sharedInstance.brandElement];
  710. UIButton *buttonPlus = [UIButton buttonWithType:UIButtonTypeCustom];
  711. buttonPlus.tag = 99;
  712. [buttonPlus setBackgroundImage:buttonImage forState:UIControlStateNormal];
  713. [buttonPlus setBackgroundImage:buttonImage forState:UIControlStateHighlighted];
  714. [buttonPlus addTarget:self action:@selector(handleTouchTabbarCenter:) forControlEvents:UIControlEventTouchUpInside];
  715. [buttonPlus setTranslatesAutoresizingMaskIntoConstraints:NO];
  716. [tabBarController.tabBar addSubview:buttonPlus];
  717. if (safeAreaBottom > 0) {
  718. // X
  719. constraint = [NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:tabBarController.tabBar attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0];
  720. [tabBarController.view addConstraint:constraint];
  721. // Y
  722. constraint = [NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:tabBarController.tabBar attribute:NSLayoutAttributeTop multiplier:1.0 constant:5];
  723. [tabBarController.view addConstraint:constraint];
  724. // Width
  725. constraint = [NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:0 multiplier:1.0 constant:40];
  726. [tabBarController.view addConstraint:constraint];
  727. // Height
  728. constraint = [NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:0 multiplier:1.0 constant:40];
  729. [tabBarController.view addConstraint:constraint];
  730. } else {
  731. // X
  732. constraint = [NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:tabBarController.tabBar attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0];
  733. [tabBarController.view addConstraint:constraint];
  734. // Y
  735. constraint = [NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:tabBarController.tabBar attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0];
  736. [tabBarController.view addConstraint:constraint];
  737. // Width
  738. constraint = [NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:0 multiplier:1.0 constant:33];
  739. [tabBarController.view addConstraint:constraint];
  740. // Height
  741. constraint = [NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:0 multiplier:1.0 constant:33];
  742. [tabBarController.view addConstraint:constraint];
  743. }
  744. }
  745. - (void)handleTouchTabbarCenter:(id)sender
  746. {
  747. // Test Maintenance
  748. if (self.maintenanceMode)
  749. return;
  750. tableDirectory *tableDirectory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", self.activeAccount, self.activeMain.serverUrl]];
  751. if ([tableDirectory.permissions containsString:@"CK"]) {
  752. UIViewController *vc = _activeMain.splitViewController.viewControllers[0];
  753. [self showMenuInViewController: vc];
  754. } else {
  755. [[NCContentPresenter shared] messageNotification:@"_warning_" description:@"_no_permission_add_file_" delay:k_dismissAfterSecond type:messageTypeInfo errorCode:0];
  756. }
  757. }
  758. - (NSString *)getTabBarControllerActiveServerUrl
  759. {
  760. NSString *serverUrl = [CCUtility getHomeServerUrlActiveUrl:self.activeUrl];
  761. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  762. if ([splitViewController isKindOfClass:[UISplitViewController class]]) {
  763. UINavigationController *masterNavigationController = [splitViewController.viewControllers firstObject];
  764. if ([masterNavigationController isKindOfClass:[UINavigationController class]]) {
  765. UITabBarController *tabBarController = [masterNavigationController.viewControllers firstObject];
  766. if ([tabBarController isKindOfClass:[UITabBarController class]]) {
  767. NSInteger index = tabBarController.selectedIndex;
  768. // select active serverUrl
  769. if (index == k_tabBarApplicationIndexFile) {
  770. serverUrl = self.activeMain.serverUrl;
  771. } else if (index == k_tabBarApplicationIndexFavorite) {
  772. if (self.activeFavorites.serverUrl)
  773. serverUrl = self.activeFavorites.serverUrl;
  774. } else if (index == k_tabBarApplicationIndexMedia) {
  775. serverUrl = [[NCManageDatabase sharedInstance] getAccountAutoUploadPath:self.activeUrl];
  776. }
  777. }
  778. }
  779. }
  780. return serverUrl;
  781. }
  782. #pragma --------------------------------------------------------------------------------------------
  783. #pragma mark ===== Theming Color =====
  784. #pragma --------------------------------------------------------------------------------------------
  785. - (void)settingThemingColorBrand
  786. {
  787. if (self.activeAccount.length == 0 || self.maintenanceMode)
  788. return;
  789. if ([NCBrandOptions sharedInstance].use_themingColor) {
  790. tableCapabilities *capabilities = [[NCManageDatabase sharedInstance] getCapabilitesWithAccount:self.activeAccount];
  791. [CCGraphics settingThemingColor:capabilities.themingColor themingColorElement:capabilities.themingColorElement themingColorText:capabilities.themingColorText];
  792. UIColor *color = NCBrandColor.sharedInstance.brand;
  793. BOOL isTooLight = NCBrandColor.sharedInstance.brand.isTooLight;
  794. BOOL isTooDark = NCBrandColor.sharedInstance.brand.isTooDark;
  795. if (isTooLight) {
  796. color = [NCBrandColor.sharedInstance.brand darkerBy:10];
  797. } else if (isTooDark) {
  798. color = [NCBrandColor.sharedInstance.brand lighterBy:10];
  799. }
  800. NCBrandColor.sharedInstance.brand = color;
  801. } else {
  802. NCBrandColor.sharedInstance.brand = NCBrandColor.sharedInstance.customer;
  803. NCBrandColor.sharedInstance.brandElement = NCBrandColor.sharedInstance.customer;
  804. NCBrandColor.sharedInstance.brandText = NCBrandColor.sharedInstance.customerText;
  805. }
  806. [[NCMainCommon sharedInstance] createImagesThemingColor];
  807. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_changeTheming object:nil];
  808. }
  809. - (void)changeTheming:(UIViewController *)viewController tableView:(UITableView *)tableView collectionView:(UICollectionView *)collectionView form:(BOOL)form
  810. {
  811. // Dark Mode
  812. [NCBrandColor.sharedInstance setDarkMode];
  813. // Appearance
  814. UINavigationBar.appearance.tintColor = NCBrandColor.sharedInstance.brandText;
  815. UINavigationBar.appearance.barTintColor = NCBrandColor.sharedInstance.brand;
  816. [UINavigationBar.appearance setBackgroundImage:[[NCUtility sharedInstance] fromColorWithColor:NCBrandColor.sharedInstance.brand] forBarMetrics: UIBarMetricsDefault];
  817. UINavigationBar.appearance.titleTextAttributes = @{NSForegroundColorAttributeName : NCBrandColor.sharedInstance.brandText};
  818. UINavigationBar.appearance.translucent = false;
  819. // Refresh UIAppearance after application loaded
  820. NSArray *windows = [UIApplication sharedApplication].windows;
  821. for (UIWindow *window in windows) {
  822. for (UIView *view in window.subviews) {
  823. [view removeFromSuperview];
  824. [window addSubview:view];
  825. }
  826. }
  827. // View
  828. if (form) viewController.view.backgroundColor = NCBrandColor.sharedInstance.backgroundForm;
  829. else viewController.view.backgroundColor = NCBrandColor.sharedInstance.backgroundView;
  830. // NavigationBar
  831. if (viewController.navigationController.navigationBar) {
  832. viewController.navigationController.navigationBar.translucent = NO;
  833. viewController.navigationController.navigationBar.barTintColor = NCBrandColor.sharedInstance.brand;
  834. viewController.navigationController.navigationBar.tintColor = NCBrandColor.sharedInstance.brandText;
  835. if ([self.reachability isReachable]) {
  836. [viewController.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName : NCBrandColor.sharedInstance.brandText}];
  837. } else {
  838. [viewController.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName : NCBrandColor.sharedInstance.connectionNo}];
  839. }
  840. viewController.navigationController.navigationBar.shadowImage = [CCGraphics generateSinglePixelImageWithColor:NCBrandColor.sharedInstance.brand];
  841. [viewController.navigationController.navigationBar setAlpha:1];
  842. }
  843. //tabBar
  844. if (viewController.tabBarController.tabBar) {
  845. viewController.tabBarController.tabBar.translucent = NO;
  846. viewController.tabBarController.tabBar.barTintColor = NCBrandColor.sharedInstance.tabBar;
  847. viewController.tabBarController.tabBar.tintColor = NCBrandColor.sharedInstance.brandElement;
  848. [viewController.tabBarController.tabBar setAlpha:1];
  849. }
  850. //tabBar button Plus
  851. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  852. if ([splitViewController isKindOfClass:[UISplitViewController class]]) {
  853. UINavigationController *navigationController = (UINavigationController *)[splitViewController.viewControllers firstObject];
  854. if ([navigationController isKindOfClass:[UINavigationController class]]) {
  855. UITabBarController *tabBarController = (UITabBarController *)navigationController.topViewController;
  856. if ([tabBarController isKindOfClass:[UITabBarController class]]) {
  857. UIButton *button = [tabBarController.view viewWithTag:99];
  858. UIImage *buttonImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarPlus"] multiplier:3 color:NCBrandColor.sharedInstance.brandElement];
  859. [button setBackgroundImage:buttonImage forState:UIControlStateNormal];
  860. [button setBackgroundImage:buttonImage forState:UIControlStateHighlighted];
  861. }
  862. }
  863. }
  864. // TableView
  865. if (tableView) {
  866. if (form) tableView.backgroundColor = NCBrandColor.sharedInstance.backgroundForm;
  867. else tableView.backgroundColor = NCBrandColor.sharedInstance.backgroundView;
  868. tableView.separatorColor = NCBrandColor.sharedInstance.separator;
  869. [tableView reloadData];
  870. }
  871. // CollectionView
  872. if (collectionView) {
  873. if (form) collectionView.backgroundColor = NCBrandColor.sharedInstance.backgroundForm;
  874. else collectionView.backgroundColor = NCBrandColor.sharedInstance.backgroundView;
  875. [collectionView reloadData];
  876. }
  877. // Tint Color GLOBAL WINDOW
  878. [self.window setTintColor:NCBrandColor.sharedInstance.textView];
  879. }
  880. #pragma --------------------------------------------------------------------------------------------
  881. #pragma mark ===== Manager Passcode =====
  882. #pragma --------------------------------------------------------------------------------------------
  883. - (BOOL)lockScreenManagerShouldShowLockScreen:(BKPasscodeLockScreenManager *)aManager
  884. {
  885. // ServerUrl active
  886. NSString *serverUrl = self.activeMain.serverUrl;
  887. BOOL isBlockZone = false;
  888. // fermiamo la data della sessione
  889. self.sessionePasscodeLock = nil;
  890. // se il block code è a zero esci con NON attivare la richiesta password
  891. if ([[CCUtility getBlockCode] length] == 0) return NO;
  892. // se non c'è attivo un account esci con NON attivare la richiesta password
  893. if ([self.activeAccount length] == 0) return NO;
  894. // se non è attivo il OnlyLockDir esci con NON attivare la richiesta password
  895. if (serverUrl && _activeUrl) {
  896. while (![serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:_activeUrl]]) {
  897. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", self.activeAccount, serverUrl]];
  898. if (directory.lock) {
  899. isBlockZone = true;
  900. break;
  901. } else {
  902. serverUrl = [CCUtility deletingLastPathComponentFromServerUrl:serverUrl];
  903. if (serverUrl == self.activeUrl)
  904. break;
  905. }
  906. }
  907. }
  908. if ([CCUtility getOnlyLockDir] && !isBlockZone) return NO;
  909. return YES;
  910. }
  911. - (UIViewController *)lockScreenManagerPasscodeViewController:(BKPasscodeLockScreenManager *)aManager
  912. {
  913. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  914. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  915. viewController.delegate = self;
  916. viewController.title = [NCBrandOptions sharedInstance].brand;
  917. viewController.fromType = CCBKPasscodeFromLockScreen;
  918. viewController.inputViewTitlePassword = YES;
  919. if ([CCUtility getSimplyBlockCode]) {
  920. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  921. viewController.passcodeInputView.maximumLength = 6;
  922. } else {
  923. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  924. viewController.passcodeInputView.maximumLength = 64;
  925. }
  926. viewController.touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName: k_serviceShareKeyChain];
  927. viewController.touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  928. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  929. navigationController.modalPresentationStyle = UIModalPresentationFullScreen;
  930. return navigationController;
  931. }
  932. - (void)passcodeViewController:(CCBKPasscode *)aViewController didFinishWithPasscode:(NSString *)aPasscode
  933. {
  934. [aViewController dismissViewControllerAnimated:YES completion:nil];
  935. // is a lock screen
  936. if (aViewController.fromType == CCBKPasscodeFromLockScreen) {
  937. [aViewController dismissViewControllerAnimated:YES completion:nil];
  938. // start session Passcode Lock
  939. BOOL isBlockZone = false;
  940. NSString *serverUrl = self.activeMain.serverUrl;
  941. while (![serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:_activeUrl]]) {
  942. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", self.activeAccount, serverUrl]];
  943. if (directory.lock) {
  944. isBlockZone = true;
  945. break;
  946. } else {
  947. serverUrl = [CCUtility deletingLastPathComponentFromServerUrl:serverUrl];
  948. if (serverUrl == self.activeUrl)
  949. break;
  950. }
  951. }
  952. if (isBlockZone)
  953. self.sessionePasscodeLock = [NSDate date];
  954. }
  955. }
  956. - (void)passcodeViewController:(CCBKPasscode *)aViewController authenticatePasscode:(NSString *)aPasscode resultHandler:(void (^)(BOOL))aResultHandler
  957. {
  958. if (aViewController.fromType == CCBKPasscodeFromLockScreen || aViewController.fromType == CCBKPasscodeFromInit) {
  959. if ([aPasscode isEqualToString:[CCUtility getBlockCode]]) {
  960. //self.lockUntilDate = nil;
  961. //self.failedAttempts = 0;
  962. aResultHandler(YES);
  963. } else aResultHandler(NO);
  964. } else aResultHandler(YES);
  965. }
  966. #pragma --------------------------------------------------------------------------------------------
  967. #pragma mark ===== reachabilityChanged =====
  968. #pragma --------------------------------------------------------------------------------------------
  969. -(void)reachabilityChanged:(SCNetworkReachabilityFlags)flags
  970. {
  971. if ([self.reachability isReachable]) {
  972. if (self.lastReachability == NO) {
  973. NSLog(@"[LOG] Request Service Server Nextcloud");
  974. [[NCService sharedInstance] startRequestServicesServer];
  975. }
  976. NSLog(@"[LOG] Reachability Changed: Reachable");
  977. self.lastReachability = YES;
  978. } else {
  979. if (self.lastReachability == YES) {
  980. [[NCContentPresenter shared] messageNotification:@"_network_not_available_" description:nil delay:k_dismissAfterSecond type:messageTypeInfo errorCode:kCFURLErrorNotConnectedToInternet];
  981. }
  982. NSLog(@"[LOG] Reachability Changed: NOT Reachable");
  983. self.lastReachability = NO;
  984. }
  985. if ([self.reachability isReachableViaWiFi]) NSLog(@"[LOG] Reachability Changed: WiFi");
  986. if ([self.reachability isReachableViaWWAN]) NSLog(@"[LOG] Reachability Changed: WWAn");
  987. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_setTitleMain object:nil];
  988. }
  989. #pragma --------------------------------------------------------------------------------------------
  990. #pragma mark ===== Fetch =====
  991. #pragma --------------------------------------------------------------------------------------------
  992. - (void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
  993. {
  994. // Test Maintenance
  995. if (self.activeAccount.length == 0 || self.maintenanceMode) {
  996. completionHandler(UIBackgroundFetchResultNoData);
  997. return;
  998. }
  999. NSLog(@"[LOG] Start perform Fetch With Completion Handler");
  1000. // Verify new photo
  1001. [[NCAutoUpload sharedInstance] initStateAutoUpload];
  1002. // after 20 sec
  1003. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 20 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  1004. NSArray *records = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"session != ''"] sorted:nil ascending:NO];
  1005. if ([records count] > 0) {
  1006. completionHandler(UIBackgroundFetchResultNewData);
  1007. } else {
  1008. completionHandler(UIBackgroundFetchResultNoData);
  1009. }
  1010. NSLog(@"[LOG] End 20 sec. perform Fetch With Completion Handler");
  1011. });
  1012. }
  1013. #pragma --------------------------------------------------------------------------------------------
  1014. #pragma mark ===== Operation Networking & Session =====
  1015. #pragma --------------------------------------------------------------------------------------------
  1016. //
  1017. // Method called by the system when all the background task has end
  1018. //
  1019. - (void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)(void))completionHandler
  1020. {
  1021. NSLog(@"[LOG] Start handle Events For Background URLSession: %@", identifier);
  1022. // after 20 sec
  1023. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 20 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  1024. self.backgroundSessionCompletionHandler = completionHandler;
  1025. void (^completionHandler)() = self.backgroundSessionCompletionHandler;
  1026. self.backgroundSessionCompletionHandler = nil;
  1027. completionHandler();
  1028. NSLog(@"[LOG] End 20 sec. Start handle Events For Background URLSession: %@", identifier);
  1029. });
  1030. }
  1031. #pragma --------------------------------------------------------------------------------------------
  1032. #pragma mark ===== Process Load Download/Upload < k_timerProcess seconds > =====
  1033. #pragma --------------------------------------------------------------------------------------------
  1034. - (void)loadAutoDownloadUpload
  1035. {
  1036. if (self.activeAccount.length == 0 || self.maintenanceMode)
  1037. return;
  1038. tableMetadata *metadataForUpload, *metadataForDownload;
  1039. long counterDownload = 0, counterUpload = 0;
  1040. NSUInteger sizeDownload = 0, sizeUpload = 0;
  1041. NSMutableArray *uploaded = [NSMutableArray new];
  1042. NSPredicate *predicate;
  1043. long maxConcurrentOperationDownloadUpload = k_maxConcurrentOperation;
  1044. NSArray *metadatasDownload = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"status == %d OR status == %d", k_metadataStatusInDownload, k_metadataStatusDownloading] sorted:nil ascending:true];
  1045. NSArray *metadatasUpload = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"status == %d OR status == %d", k_metadataStatusInUpload, k_metadataStatusUploading] sorted:nil ascending:true];
  1046. // E2EE only 1
  1047. for(tableMetadata *metadata in metadatasDownload) {
  1048. if ([CCUtility isFolderEncrypted:metadata.serverUrl e2eEncrypted:metadata.e2eEncrypted account:metadata.account]) return;
  1049. }
  1050. for(tableMetadata *metadata in metadatasUpload) {
  1051. if ([CCUtility isFolderEncrypted:metadata.serverUrl e2eEncrypted:metadata.e2eEncrypted account:metadata.account]) return;
  1052. }
  1053. // Counter
  1054. counterDownload = [metadatasDownload count];
  1055. counterUpload = [metadatasUpload count];
  1056. // Size
  1057. for (tableMetadata *metadata in metadatasDownload) {
  1058. sizeDownload = sizeDownload + metadata.size;
  1059. }
  1060. for (tableMetadata *metadata in metadatasUpload) {
  1061. sizeUpload = sizeUpload + metadata.size;
  1062. }
  1063. NSLog(@"%@", [NSString stringWithFormat:@"[LOG] PROCESS-AUTO-UPLOAD | Download %ld - %@ | Upload %ld - %@", counterDownload, [CCUtility transformedSize:sizeDownload], counterUpload, [CCUtility transformedSize:sizeUpload]]);
  1064. // Stop Timer
  1065. [_timerProcessAutoDownloadUpload invalidate];
  1066. // ------------------------- <selector Download> -------------------------
  1067. while (counterDownload < maxConcurrentOperationDownloadUpload) {
  1068. metadataForDownload = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"status == %d", k_metadataStatusWaitDownload] sorted:@"date" ascending:YES];
  1069. if (metadataForDownload) {
  1070. if ([CCUtility isFolderEncrypted:metadataForDownload.serverUrl e2eEncrypted:metadataForDownload.e2eEncrypted account:metadataForDownload.account]) {
  1071. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) { break; }
  1072. maxConcurrentOperationDownloadUpload = 1;
  1073. metadataForDownload.status = k_metadataStatusInDownload;
  1074. tableMetadata *metadata = [[NCManageDatabase sharedInstance] addMetadata:metadataForDownload];
  1075. [[CCNetworking sharedNetworking] downloadFile:metadata taskStatus:k_taskStatusResume];
  1076. break;
  1077. } else {
  1078. metadataForDownload.status = k_metadataStatusInDownload;
  1079. tableMetadata *metadata = [[NCManageDatabase sharedInstance] addMetadata:metadataForDownload];
  1080. [[CCNetworking sharedNetworking] downloadFile:metadata taskStatus:k_taskStatusResume];
  1081. counterDownload++;
  1082. sizeDownload = sizeDownload + metadata.size;
  1083. }
  1084. } else {
  1085. break;
  1086. }
  1087. }
  1088. // ------------------------- <selector Upload> -------------------------
  1089. while (counterUpload < maxConcurrentOperationDownloadUpload) {
  1090. if (sizeUpload > k_maxSizeOperationUpload) {
  1091. break;
  1092. }
  1093. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) {
  1094. predicate = [NSPredicate predicateWithFormat:@"sessionSelector == %@ AND status == %d AND typeFile != %@", selectorUploadFile, k_metadataStatusWaitUpload, k_metadataTypeFile_video];
  1095. } else {
  1096. predicate = [NSPredicate predicateWithFormat:@"sessionSelector == %@ AND status == %d", selectorUploadFile, k_metadataStatusWaitUpload];
  1097. }
  1098. metadataForUpload = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:predicate sorted:@"date" ascending:YES];
  1099. // Verify modify file
  1100. if ([uploaded containsObject:[NSString stringWithFormat:@"%@%@%@", metadataForUpload.account, metadataForUpload.serverUrl, metadataForUpload.fileName]]) {
  1101. break;
  1102. }
  1103. if (metadataForUpload) {
  1104. // Verify modify file
  1105. BOOL isAleadyInUpload = false;
  1106. for (tableMetadata *metadata in metadatasUpload) {
  1107. if ([metadataForUpload.account isEqualToString:metadata.account] && [metadataForUpload.serverUrl isEqualToString:metadata.serverUrl] && [metadataForUpload.fileName isEqualToString:metadata.fileName]) {
  1108. isAleadyInUpload = true;
  1109. }
  1110. }
  1111. if (isAleadyInUpload == false) {
  1112. if ([CCUtility isFolderEncrypted:metadataForUpload.serverUrl e2eEncrypted:metadataForUpload.e2eEncrypted account:metadataForUpload.account]) {
  1113. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) { break; }
  1114. maxConcurrentOperationDownloadUpload = 1;
  1115. metadataForUpload.status = k_metadataStatusInUpload;
  1116. tableMetadata *metadata = [[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  1117. [[CCNetworking sharedNetworking] uploadFile:metadata taskStatus:k_taskStatusResume];
  1118. break;
  1119. } else {
  1120. metadataForUpload.status = k_metadataStatusInUpload;
  1121. tableMetadata *metadata = [[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  1122. [[CCNetworking sharedNetworking] uploadFile:metadata taskStatus:k_taskStatusResume];
  1123. counterUpload++;
  1124. sizeUpload = sizeUpload + metadata.size;
  1125. // For verify modify file
  1126. [uploaded addObject:[NSString stringWithFormat:@"%@%@%@", metadata.account, metadata.serverUrl, metadata.fileName]];
  1127. }
  1128. } else {
  1129. break;
  1130. }
  1131. } else {
  1132. break;
  1133. }
  1134. }
  1135. // ------------------------- <selector Auto Upload> -------------------------
  1136. while (counterUpload < maxConcurrentOperationDownloadUpload) {
  1137. if (sizeUpload > k_maxSizeOperationUpload) {
  1138. break;
  1139. }
  1140. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) {
  1141. predicate = [NSPredicate predicateWithFormat:@"sessionSelector == %@ AND status == %d AND typeFile != %@", selectorUploadAutoUpload, k_metadataStatusWaitUpload, k_metadataTypeFile_video];
  1142. } else {
  1143. predicate = [NSPredicate predicateWithFormat:@"sessionSelector == %@ AND status == %d", selectorUploadAutoUpload, k_metadataStatusWaitUpload];
  1144. }
  1145. metadataForUpload = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:predicate sorted:@"date" ascending:YES];
  1146. if (metadataForUpload) {
  1147. if ([CCUtility isFolderEncrypted:metadataForUpload.serverUrl e2eEncrypted:metadataForUpload.e2eEncrypted account:metadataForUpload.account]) {
  1148. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) { break; }
  1149. maxConcurrentOperationDownloadUpload = 1;
  1150. metadataForUpload.status = k_metadataStatusInUpload;
  1151. tableMetadata *metadata = [[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  1152. [[CCNetworking sharedNetworking] uploadFile:metadata taskStatus:k_taskStatusResume];
  1153. break;
  1154. } else {
  1155. metadataForUpload.status = k_metadataStatusInUpload;
  1156. tableMetadata *metadata = [[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  1157. [[CCNetworking sharedNetworking] uploadFile:metadata taskStatus:k_taskStatusResume];
  1158. counterUpload++;
  1159. sizeUpload = sizeUpload + metadata.size;
  1160. }
  1161. } else {
  1162. break;
  1163. }
  1164. }
  1165. // ------------------------- <selector Auto Upload All> ----------------------
  1166. // Verify num error k_maxErrorAutoUploadAll after STOP (100)
  1167. NSArray *metadatas = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"sessionSelector == %@ AND status == %i", selectorUploadAutoUploadAll, k_metadataStatusUploadError] sorted:@"date" ascending:YES];
  1168. NSInteger errorCount = [metadatas count];
  1169. if (errorCount >= k_maxErrorAutoUploadAll) {
  1170. [[NCContentPresenter shared] messageNotification:@"_error_" description:@"_too_errors_automatic_all_" delay:k_dismissAfterSecond type:messageTypeError errorCode:k_CCErrorInternalError];
  1171. } else {
  1172. while (counterUpload < maxConcurrentOperationDownloadUpload) {
  1173. if (sizeUpload > k_maxSizeOperationUpload) {
  1174. break;
  1175. }
  1176. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) {
  1177. predicate = [NSPredicate predicateWithFormat:@"sessionSelector == %@ AND status == %d AND typeFile != %@", selectorUploadAutoUploadAll, k_metadataStatusWaitUpload, k_metadataTypeFile_video];
  1178. } else {
  1179. predicate = [NSPredicate predicateWithFormat:@"sessionSelector == %@ AND status == %d", selectorUploadAutoUploadAll, k_metadataStatusWaitUpload];
  1180. }
  1181. metadataForUpload = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:predicate sorted:@"session" ascending:YES];
  1182. if (metadataForUpload) {
  1183. if ([CCUtility isFolderEncrypted:metadataForUpload.serverUrl e2eEncrypted:metadataForUpload.e2eEncrypted account:metadataForUpload.account]) {
  1184. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) { break; }
  1185. maxConcurrentOperationDownloadUpload = 1;
  1186. metadataForUpload.status = k_metadataStatusInUpload;
  1187. tableMetadata *metadata = [[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  1188. [[CCNetworking sharedNetworking] uploadFile:metadata taskStatus:k_taskStatusResume];
  1189. break;
  1190. } else {
  1191. metadataForUpload.status = k_metadataStatusInUpload;
  1192. tableMetadata *metadata = [[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  1193. [[CCNetworking sharedNetworking] uploadFile:metadata taskStatus:k_taskStatusResume];
  1194. counterUpload++;
  1195. sizeUpload = sizeUpload + metadata.size;
  1196. }
  1197. } else {
  1198. break;
  1199. }
  1200. }
  1201. }
  1202. // No Download/upload available ? --> remove errors for retry
  1203. //
  1204. if (counterDownload+counterUpload < maxConcurrentOperationDownloadUpload+1) {
  1205. NSArray *metadatas = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"status == %d OR status == %d", k_metadataStatusDownloadError, k_metadataStatusUploadError] sorted:nil ascending:NO];
  1206. for (tableMetadata *metadata in metadatas) {
  1207. if (metadata.status == k_metadataStatusDownloadError)
  1208. metadata.status = k_metadataStatusWaitDownload;
  1209. else if (metadata.status == k_metadataStatusUploadError)
  1210. metadata.status = k_metadataStatusWaitUpload;
  1211. [[NCManageDatabase sharedInstance] addMetadata:metadata];
  1212. }
  1213. }
  1214. // Upload in pending
  1215. //
  1216. NSArray *metadatasInUpload = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"session != %@ AND status == %d AND sessionTaskIdentifier == 0", k_upload_session_extension, k_metadataStatusInUpload] sorted:nil ascending:true];
  1217. for (tableMetadata *metadata in metadatasInUpload) {
  1218. if ([self.sessionPendingStatusInUpload containsObject:metadata.ocId]) {
  1219. metadata.status = k_metadataStatusWaitUpload;
  1220. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1221. } else {
  1222. [self.sessionPendingStatusInUpload addObject:metadata.ocId];
  1223. }
  1224. }
  1225. if (metadatasInUpload.count == 0) {
  1226. [self.sessionPendingStatusInUpload removeAllObjects];
  1227. }
  1228. // Start Timer
  1229. _timerProcessAutoDownloadUpload = [NSTimer scheduledTimerWithTimeInterval:k_timerProcessAutoDownloadUpload target:self selector:@selector(loadAutoDownloadUpload) userInfo:nil repeats:YES];
  1230. }
  1231. - (void)startLoadAutoDownloadUpload
  1232. {
  1233. if (self.timerProcessAutoDownloadUpload.isValid) {
  1234. [self performSelectorOnMainThread:@selector(loadAutoDownloadUpload) withObject:nil waitUntilDone:YES];
  1235. }
  1236. }
  1237. - (void)verifyTaskLost
  1238. {
  1239. // DOWNLOAD
  1240. //
  1241. NSArray *matadatasInDownloading = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"status == %d", k_metadataStatusDownloading] sorted:nil ascending:true];
  1242. for (tableMetadata *metadata in matadatasInDownloading) {
  1243. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1244. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1245. NSURLSessionTask *findTask;
  1246. for (NSURLSessionTask *task in downloadTasks) {
  1247. if (task.taskIdentifier == metadata.sessionTaskIdentifier) {
  1248. findTask = task;
  1249. }
  1250. }
  1251. if (!findTask) {
  1252. metadata.sessionTaskIdentifier = k_taskIdentifierDone;
  1253. metadata.status = k_metadataStatusWaitDownload;
  1254. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1255. }
  1256. }];
  1257. }
  1258. // UPLOAD
  1259. //
  1260. NSArray *metadatasUploading = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"session != %@ AND status == %d", k_upload_session_extension, k_metadataStatusUploading] sorted:nil ascending:true];
  1261. for (tableMetadata *metadata in metadatasUploading) {
  1262. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1263. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1264. NSURLSessionTask *findTask;
  1265. for (NSURLSessionTask *task in uploadTasks) {
  1266. if (task.taskIdentifier == metadata.sessionTaskIdentifier) {
  1267. findTask = task;
  1268. }
  1269. }
  1270. if (!findTask) {
  1271. metadata.sessionTaskIdentifier = k_taskIdentifierDone;
  1272. metadata.status = k_metadataStatusWaitUpload;
  1273. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1274. }
  1275. }];
  1276. }
  1277. }
  1278. #pragma --------------------------------------------------------------------------------------------
  1279. #pragma mark ===== OpenURL =====
  1280. #pragma --------------------------------------------------------------------------------------------
  1281. // Method called from iOS system to send a file from other app.
  1282. - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url options:(NSDictionary<NSString *,id> *)options
  1283. {
  1284. if (self.activeAccount.length == 0 || self.maintenanceMode)
  1285. return YES;
  1286. NSString *scheme = url.scheme;
  1287. dispatch_time_t timer = 0;
  1288. if (self.activeMain == nil) timer = 1;
  1289. if ([scheme isEqualToString:@"nextcloud"]) {
  1290. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, timer * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1291. NSString *action = url.host;
  1292. if ([action isEqualToString:@"open-file"]) {
  1293. NSURLComponents *urlComponents = [NSURLComponents componentsWithURL:url resolvingAgainstBaseURL:NO];
  1294. NSArray *queryItems = urlComponents.queryItems;
  1295. NSString *user = [CCUtility valueForKey:@"user" fromQueryItems:queryItems];
  1296. NSString *path = [CCUtility valueForKey:@"path" fromQueryItems:queryItems];
  1297. NSString *link = [CCUtility valueForKey:@"link" fromQueryItems:queryItems];
  1298. tableAccount *matchedAccount = nil;
  1299. // verify parameter
  1300. if (user.length == 0 || path.length == 0 || [[NSURL URLWithString:link] host].length == 0) {
  1301. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_error_parameter_schema_", nil) preferredStyle:UIAlertControllerStyleAlert];
  1302. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  1303. [alertController addAction:okAction];
  1304. [self.window.rootViewController presentViewController:alertController animated:YES completion:nil];
  1305. } else {
  1306. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  1307. if (account) {
  1308. NSURL *activeAccountURL = [NSURL URLWithString:account.url];
  1309. NSString *activeAccountUser = account.user;
  1310. if ([link containsString:activeAccountURL.host] && [user isEqualToString:activeAccountUser]) {
  1311. matchedAccount = account;
  1312. } else {
  1313. NSArray *accounts = [[NCManageDatabase sharedInstance] getAllAccount];
  1314. for (tableAccount *account in accounts) {
  1315. NSURL *accountURL = [NSURL URLWithString:account.url];
  1316. NSString *accountUser = account.user;
  1317. if ([link containsString:accountURL.host] && [user isEqualToString:accountUser]) {
  1318. matchedAccount = [[NCManageDatabase sharedInstance] setAccountActive:account.account];
  1319. [self settingActiveAccount:matchedAccount.account activeUrl:matchedAccount.url activeUser:matchedAccount.user activeUserID:matchedAccount.userID activePassword:[CCUtility getPassword:matchedAccount.account]];
  1320. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_initializeMain object:nil userInfo:nil];
  1321. }
  1322. }
  1323. }
  1324. if (matchedAccount) {
  1325. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  1326. if ([splitViewController isKindOfClass:[UISplitViewController class]]) {
  1327. UINavigationController *navigationControllerMaster = (UINavigationController *)splitViewController.viewControllers.firstObject;
  1328. if ([navigationControllerMaster isKindOfClass:[UINavigationController class]]) {
  1329. UITabBarController *tabBarController = (UITabBarController *)navigationControllerMaster.topViewController;
  1330. if ([tabBarController isKindOfClass:[UITabBarController class]]) {
  1331. if (splitViewController.isCollapsed) {
  1332. [navigationControllerMaster popToRootViewControllerAnimated:false];
  1333. UINavigationController *navigationControllerMaster = (UINavigationController *)splitViewController.viewControllers.firstObject;
  1334. if ([navigationControllerMaster isKindOfClass:[UINavigationController class]]) {
  1335. UITabBarController *tabBarController = (UITabBarController *)navigationControllerMaster.topViewController;
  1336. if ([tabBarController isKindOfClass:[UITabBarController class]]) {
  1337. if ([tabBarController isKindOfClass:[UITabBarController class]]) {
  1338. [tabBarController setSelectedIndex: k_tabBarApplicationIndexFile];
  1339. }
  1340. }
  1341. }
  1342. } else {
  1343. if ([tabBarController isKindOfClass:[UITabBarController class]]) {
  1344. [tabBarController setSelectedIndex: k_tabBarApplicationIndexFile];
  1345. }
  1346. }
  1347. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1348. [self.activeMain.navigationController popToRootViewControllerAnimated:NO];
  1349. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1350. NSString *fileNamePath = [NSString stringWithFormat:@"%@%@/%@", matchedAccount.url, k_webDAV, path];
  1351. if ([path containsString:@"/"]) {
  1352. // Push
  1353. NSString *fileName = [[path stringByDeletingLastPathComponent] lastPathComponent];
  1354. NSString *serverUrl = [CCUtility deletingLastPathComponentFromServerUrl:[NSString stringWithFormat:@"%@%@/%@", matchedAccount.url, k_webDAV, [path stringByDeletingLastPathComponent]]];
  1355. tableMetadata *metadata = [[NCManageDatabase sharedInstance] createMetadataWithAccount:matchedAccount.account fileName:fileName ocId:[[NSUUID UUID] UUIDString] serverUrl:serverUrl url:@"" contentType:@""];
  1356. [self.activeMain performSegueDirectoryWithControlPasscode:true metadata:metadata blinkFileNamePath:fileNamePath];
  1357. } else {
  1358. // Reload folder
  1359. NSString *serverUrl = [NSString stringWithFormat:@"%@%@", matchedAccount.url, k_webDAV];
  1360. self.activeMain.blinkFileNamePath = fileNamePath;
  1361. [self.activeMain readFolder:serverUrl];
  1362. }
  1363. });
  1364. });
  1365. }
  1366. }
  1367. }
  1368. } else {
  1369. NSString *domain = [[NSURL URLWithString:link] host];
  1370. NSString *fileName = [path lastPathComponent];
  1371. NSString *message = [NSString stringWithFormat:NSLocalizedString(@"_account_not_available_", nil), user, domain, fileName];
  1372. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_info_", nil) message:message preferredStyle:UIAlertControllerStyleAlert];
  1373. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  1374. [alertController addAction:okAction];
  1375. [self.window.rootViewController presentViewController:alertController animated:YES completion:nil];
  1376. }
  1377. }
  1378. }
  1379. }
  1380. });
  1381. return YES;
  1382. }
  1383. NSError *error;
  1384. NSLog(@"[LOG] the path is: %@", url.path);
  1385. NSArray *splitedUrl = [url.path componentsSeparatedByString:@"/"];
  1386. self.fileNameUpload = [NSString stringWithFormat:@"%@",[splitedUrl objectAtIndex:([splitedUrl count]-1)]];
  1387. if (self.activeAccount) {
  1388. [[NSFileManager defaultManager]removeItemAtPath:[NSTemporaryDirectory() stringByAppendingString:self.fileNameUpload] error:nil];
  1389. [[NSFileManager defaultManager]moveItemAtPath:url.path toPath:[NSTemporaryDirectory() stringByAppendingString:self.fileNameUpload] error:&error];
  1390. if (error == nil) {
  1391. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  1392. if ([splitViewController isKindOfClass:[UISplitViewController class]]) {
  1393. UINavigationController *navigationControllerMaster = (UINavigationController *)splitViewController.viewControllers.firstObject;
  1394. if ([navigationControllerMaster isKindOfClass:[UINavigationController class]]) {
  1395. UIViewController *uploadNavigationViewController = [[UIStoryboard storyboardWithName:@"CCUploadFromOtherUpp" bundle:nil] instantiateViewControllerWithIdentifier:@"CCUploadNavigationViewController"];
  1396. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, timer * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  1397. [navigationControllerMaster presentViewController:uploadNavigationViewController animated:YES completion:nil];
  1398. });
  1399. }
  1400. }
  1401. }
  1402. }
  1403. return YES;
  1404. }
  1405. #pragma --------------------------------------------------------------------------------------------
  1406. #pragma mark ===== Maintenance Mode =====
  1407. #pragma --------------------------------------------------------------------------------------------
  1408. - (void)maintenanceMode:(BOOL)mode
  1409. {
  1410. self.maintenanceMode = mode;
  1411. }
  1412. #pragma --------------------------------------------------------------------------------------------
  1413. #pragma mark ===== UPGRADE =====
  1414. #pragma --------------------------------------------------------------------------------------------
  1415. - (BOOL)upgrade
  1416. {
  1417. #ifdef DEBUG
  1418. //self.maintenanceMode = YES;
  1419. #endif
  1420. NSString *actualVersion = [CCUtility getVersion];
  1421. NSString *actualBuild = [CCUtility getBuild];
  1422. /* ---------------------- UPGRADE VERSION ----------------------- */
  1423. // VERSION < 2.17.6
  1424. if (([actualVersion compare:@"2.17.6" options:NSNumericSearch] == NSOrderedAscending)) {
  1425. // Remove All old Photo Library
  1426. [[NCManageDatabase sharedInstance] clearTable:[tablePhotoLibrary class] account:nil];
  1427. }
  1428. // VERSION == 2.17.6
  1429. if ([actualVersion isEqualToString:@"2.17.6"]) {
  1430. // Build < 10
  1431. if (([actualBuild compare:@"10" options:NSNumericSearch] == NSOrderedAscending) || actualBuild == nil) {
  1432. // Remove All old Photo Library
  1433. //[[NCManageDatabase sharedInstance] clearTable:[tablePhotoLibrary class] account:nil];
  1434. }
  1435. }
  1436. if (([actualVersion compare:@"2.19.1" options:NSNumericSearch] == NSOrderedAscending)) {
  1437. [[NCManageDatabase sharedInstance] clearTable:[tableMetadata class] account:nil];
  1438. [[NCManageDatabase sharedInstance] setClearAllDateReadDirectory];
  1439. }
  1440. if (([actualVersion compare:@"2.22.0" options:NSNumericSearch] == NSOrderedAscending)) {
  1441. NSArray *records = [[NCManageDatabase sharedInstance] getTableLocalFilesWithPredicate:[NSPredicate predicateWithFormat:@"#size > 0"] sorted:@"account" ascending:NO];
  1442. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  1443. NSString *account = @"";
  1444. NSString *directoryUser = @"";
  1445. NSString *fileName;
  1446. for (tableLocalFile *record in records) {
  1447. if (![account isEqualToString:record.account]) {
  1448. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", record.account]];
  1449. if (tableAccount) {
  1450. directoryUser = [CCUtility getDirectoryActiveUser:tableAccount.user activeUrl:tableAccount.url];
  1451. account = record.account;
  1452. }
  1453. }
  1454. fileName = [NSString stringWithFormat:@"%@/%@", directoryUser, record.ocId];
  1455. if (![directoryUser isEqualToString:@""] && [[NSFileManager defaultManager] fileExistsAtPath:fileName]) {
  1456. [CCUtility moveFileAtPath:fileName toPath:[CCUtility getDirectoryProviderStorageOcId:record.ocId fileNameView:record.fileName]];
  1457. }
  1458. }
  1459. });
  1460. }
  1461. if ([actualVersion isEqualToString:@"2.22.9"]) {
  1462. if (([actualBuild compare:@"8" options:NSNumericSearch] == NSOrderedAscending) || actualBuild == nil) {
  1463. [[NCManageDatabase sharedInstance] clearTable:[tableActivity class] account:nil];
  1464. [[NCManageDatabase sharedInstance] clearTable:[tableActivitySubjectRich class] account:nil];
  1465. [[NCManageDatabase sharedInstance] clearTable:[tableActivityPreview class] account:nil];
  1466. }
  1467. }
  1468. if (([actualVersion compare:@"2.23.4" options:NSNumericSearch] == NSOrderedAscending)) {
  1469. NSArray *records = [[NCManageDatabase sharedInstance] getAllAccount];
  1470. for (tableAccount *record in records) {
  1471. [CCUtility setPassword:record.account password:record.password];
  1472. [[NCManageDatabase sharedInstance] removePasswordAccount:record.account];
  1473. }
  1474. }
  1475. return YES;
  1476. }
  1477. @end