AppDelegate.m 92 KB

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