AppDelegate.m 92 KB

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