AppDelegate.m 92 KB

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