AppDelegate.m 92 KB

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