AppDelegate.m 92 KB

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