AppDelegate.m 81 KB

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