AppDelegate.m 92 KB

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