AppDelegate.m 92 KB

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