AppDelegate.m 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279
  1. //
  2. // AppDelegate.m
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 04/09/14.
  6. // Copyright (c) 2014 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 "CCGraphics.h"
  25. #import "NCBridgeSwift.h"
  26. #import "NCAutoUpload.h"
  27. #import "NCPushNotificationEncryption.h"
  28. #import <QuartzCore/QuartzCore.h>
  29. @import Firebase;
  30. @class NCViewerRichdocument;
  31. @interface AppDelegate() <TOPasscodeViewControllerDelegate>
  32. @end
  33. @implementation AppDelegate
  34. + (void)initialize
  35. {
  36. [[NSUserDefaults standardUserDefaults] registerDefaults:@{@"UserAgent": [CCUtility getUserAgent]}];
  37. }
  38. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
  39. {
  40. BOOL isSimulatorOrTestFlight = [[NCUtility shared] isSimulatorOrTestFlight];
  41. if (![CCUtility getDisableCrashservice] && NCBrandOptions.sharedInstance.disable_crash_service == false) {
  42. [FIRApp configure];
  43. }
  44. [CCUtility createDirectoryStandard];
  45. [CCUtility emptyTemporaryDirectory];
  46. // Networking
  47. [[NCCommunicationCommon shared] setupWithDelegate:[NCNetworking shared]];
  48. [[NCCommunicationCommon shared] setupWithUserAgent:[CCUtility getUserAgent]];
  49. NSInteger logLevel = [CCUtility getLogLevel];
  50. [[NCCommunicationCommon shared] setFileLogWithLevel:logLevel];
  51. NSString *versionApp = [NSString stringWithFormat:@"%@.%@", [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"], [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"]];
  52. NSString *versionNextcloudiOS = [NSString stringWithFormat:[NCBrandOptions sharedInstance].textCopyrightNextcloudiOS, versionApp];
  53. if (isSimulatorOrTestFlight) {
  54. [[NCCommunicationCommon shared] writeLog:[NSString stringWithFormat:@"Start session with level %lu %@ (Simulator / TestFlight)", (unsigned long)logLevel, versionNextcloudiOS]];
  55. } else {
  56. [[NCCommunicationCommon shared] writeLog:[NSString stringWithFormat:@"Start session with level %lu %@", (unsigned long)logLevel, versionNextcloudiOS]];
  57. }
  58. //
  59. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(initializeMain:) name:k_notificationCenter_initializeMain object:nil];
  60. // Set account, if no exists clear all
  61. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountActive];
  62. if (tableAccount == nil) {
  63. // remove all the keys Chain
  64. [CCUtility deleteAllChainStore];
  65. // remove all the App group key
  66. [[NSUserDefaults standardUserDefaults] removePersistentDomainForName:[[NSBundle mainBundle] bundleIdentifier]];
  67. } else {
  68. // FIX 3.0.5 lost urlbase
  69. if (tableAccount.urlBase.length == 0) {
  70. NSString *user = [tableAccount.user stringByAppendingString:@" "];
  71. NSString *urlBase = [tableAccount.account stringByReplacingOccurrencesOfString:user withString:@""];
  72. tableAccount.urlBase = urlBase;
  73. [[NCManageDatabase sharedInstance] updateAccount:tableAccount];
  74. tableAccount = [[NCManageDatabase sharedInstance] getAccountActive];
  75. }
  76. [self settingAccount:tableAccount.account urlBase:tableAccount.urlBase user:tableAccount.user userID:tableAccount.userID password:[CCUtility getPassword:tableAccount.account]];
  77. }
  78. // UserDefaults
  79. self.ncUserDefaults = [[NSUserDefaults alloc] initWithSuiteName:[NCBrandOptions sharedInstance].capabilitiesGroups];
  80. // Background Fetch
  81. [application setMinimumBackgroundFetchInterval:UIApplicationBackgroundFetchIntervalMinimum];
  82. self.listProgressMetadata = [NSMutableDictionary new];
  83. self.listFilesVC = [NSMutableDictionary new];
  84. self.listMainVC = [NSMutableDictionary new];
  85. self.listFavoriteVC = [NSMutableDictionary new];
  86. self.listOfflineVC = [NSMutableDictionary new];
  87. // Push Notification
  88. [application registerForRemoteNotifications];
  89. // Display notification
  90. [UNUserNotificationCenter currentNotificationCenter].delegate = self;
  91. UNAuthorizationOptions authOptions = UNAuthorizationOptionAlert | UNAuthorizationOptionSound | UNAuthorizationOptionBadge;
  92. [[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:authOptions completionHandler:^(BOOL granted, NSError * _Nullable error) { }];
  93. //AV Session
  94. [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error:nil];
  95. [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
  96. // ProgressView Detail
  97. self.progressViewDetail = [[UIProgressView alloc] initWithProgressViewStyle: UIProgressViewStyleBar];
  98. // Quick Actions
  99. if([[UIApplicationShortcutItem class] respondsToSelector:@selector(new)]) {
  100. [self configDynamicShortcutItems];
  101. UIApplicationShortcutItem *shortcutItem = [launchOptions objectForKeyedSubscript:UIApplicationLaunchOptionsShortcutItemKey];
  102. if (shortcutItem)
  103. [self handleShortCutItem:shortcutItem];
  104. }
  105. // Start Timer
  106. self.timerUpdateApplicationIconBadgeNumber = [NSTimer scheduledTimerWithTimeInterval:k_timerUpdateApplicationIconBadgeNumber target:self selector:@selector(updateApplicationIconBadgeNumber) userInfo:nil repeats:YES];
  107. [self startTimerErrorNetworking];
  108. // Store review
  109. if ([[NCUtility shared] isSimulatorOrTestFlight] == false) {
  110. NCStoreReview *review = [NCStoreReview new];
  111. [review incrementAppRuns];
  112. [review showStoreReview];
  113. }
  114. // Detect Dark mode
  115. if (@available(iOS 13.0, *)) {
  116. if ([CCUtility getDarkModeDetect]) {
  117. if ([[UITraitCollection currentTraitCollection] userInterfaceStyle] == UIUserInterfaceStyleDark) {
  118. [CCUtility setDarkMode:YES];
  119. } else {
  120. [CCUtility setDarkMode:NO];
  121. }
  122. }
  123. }
  124. if ([NCBrandOptions sharedInstance].disable_intro) {
  125. [CCUtility setIntro:YES];
  126. if (self.account.length == 0) {
  127. [self openLoginView:nil selector:k_intro_login openLoginWeb:false];
  128. }
  129. } else {
  130. if ([CCUtility getIntro] == NO) {
  131. UIViewController *introViewController = [[UIStoryboard storyboardWithName:@"NCIntro" bundle:[NSBundle mainBundle]] instantiateInitialViewController];
  132. UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController: introViewController];
  133. self.window.rootViewController = navController;
  134. [self.window makeKeyAndVisible];
  135. }
  136. }
  137. // init home
  138. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_initializeMain object:nil userInfo:nil];
  139. // Passcode
  140. dispatch_async(dispatch_get_main_queue(), ^{
  141. [self passcodeWithAutomaticallyPromptForBiometricValidation:true];
  142. });
  143. // Auto upload
  144. self.networkingAutoUpload = [NCNetworkingAutoUpload new];
  145. [[NCCommunicationCommon shared] writeLog:@"Application did finish launching"];
  146. return YES;
  147. }
  148. //
  149. // L' applicazione si dimetterà dallo stato di attivo
  150. //
  151. - (void)applicationWillResignActive:(UIApplication *)application
  152. {
  153. // Test Maintenance
  154. if (self.account.length == 0 || self.maintenanceMode)
  155. return;
  156. // Dismiss FileViewInFolder
  157. if (self.activeFileViewInFolder != nil ) {
  158. [self.activeFileViewInFolder dismissViewControllerAnimated:false completion:^{
  159. self.activeFileViewInFolder = nil;
  160. }];
  161. }
  162. [self updateApplicationIconBadgeNumber];
  163. }
  164. //
  165. // L' applicazione entrerà in primo piano (attivo solo dopo il background)
  166. //
  167. - (void)applicationWillEnterForeground:(UIApplication *)application
  168. {
  169. if (self.account.length == 0 || self.maintenanceMode) { return; }
  170. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_applicationWillEnterForeground object:nil];
  171. // Request Passcode
  172. [self passcodeWithAutomaticallyPromptForBiometricValidation:true];
  173. // Initialize Auto upload
  174. [[NCAutoUpload sharedInstance] initStateAutoUpload];
  175. // Read active directory
  176. [self.activeFiles reloadDataSourceNetworkWithForced:true];
  177. // Required unsubscribing / subscribing
  178. [self pushNotification];
  179. // RichDocument
  180. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_richdocumentGrabFocus object:nil];
  181. // Request Service Server Nextcloud
  182. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  183. [[NCService shared] startRequestServicesServer];
  184. });
  185. [[NCCommunicationCommon shared] writeLog:@"The application Will enter in foreground"];
  186. }
  187. //
  188. // L' applicazione entrerà in primo piano (attivo sempre)
  189. //
  190. - (void)applicationDidBecomeActive:(UIApplication *)application
  191. {
  192. if (self.account.length == 0 || self.maintenanceMode) { return; }
  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. [[NCNetworking shared] verifyUploadZombie];
  203. [[NCCommunicationCommon shared] writeLog:@"The application did become active"];
  204. }
  205. //
  206. // L' applicazione è entrata nello sfondo
  207. //
  208. - (void)applicationDidEnterBackground:(UIApplication *)application
  209. {
  210. if (self.account.length == 0 || self.maintenanceMode) { return; }
  211. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_applicationDidEnterBackground object:nil];
  212. [self passcodeWithAutomaticallyPromptForBiometricValidation:false];
  213. }
  214. //
  215. // L'applicazione terminerà
  216. //
  217. - (void)applicationWillTerminate:(UIApplication *)application
  218. {
  219. [[NCCommunicationCommon shared] writeLog:@"bye bye"];
  220. }
  221. // NotificationCenter
  222. - (void)initializeMain:(NSNotification *)notification
  223. {
  224. if (self.account.length == 0) return;
  225. // Clear error certificate
  226. [CCUtility setCertificateError:self.account error:NO];
  227. // Setting Theming
  228. [self settingThemingColorBrand];
  229. // If AVPlayer in play -> Stop
  230. if (self.player != nil && self.player.rate != 0) {
  231. [self.player pause];
  232. }
  233. // close detail
  234. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_menuDetailClose object:nil];
  235. // Not Photos Video in library ? then align and Init Auto Upload
  236. NSArray *recordsPhotoLibrary = [[NCManageDatabase sharedInstance] getPhotoLibraryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", self.account]];
  237. if ([recordsPhotoLibrary count] == 0) {
  238. [[NCAutoUpload sharedInstance] alignPhotoLibrary];
  239. }
  240. // Start Auto Upload
  241. [[NCAutoUpload sharedInstance] initStateAutoUpload];
  242. // Start services
  243. [[NCCommunicationCommon shared] writeLog:@"Request Service Server Nextcloud"];
  244. [[NCService shared] startRequestServicesServer];
  245. // Registeration push notification
  246. [self pushNotification];
  247. //Registeration domain File Provider
  248. //FileProviderDomain *fileProviderDomain = [FileProviderDomain new];
  249. //[fileProviderDomain removeAllDomains];
  250. //[fileProviderDomain registerDomains];
  251. [[NCCommunicationCommon shared] writeLog:@"initialize Main"];
  252. }
  253. #pragma --------------------------------------------------------------------------------------------
  254. #pragma mark ===== Login / checkErrorNetworking =====
  255. #pragma --------------------------------------------------------------------------------------------
  256. - (void)checkErrorNetworking
  257. {
  258. // test
  259. if (self.account.length == 0 || self.maintenanceMode)
  260. return;
  261. // check unauthorized server (401)
  262. if ([CCUtility getPassword:self.account].length == 0) {
  263. [self openLoginView:self.window.rootViewController selector:k_intro_login openLoginWeb:true];
  264. }
  265. // check certificate untrusted (-1202)
  266. if ([CCUtility getCertificateError:self.account]) {
  267. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_ssl_certificate_untrusted_", nil) message:NSLocalizedString(@"_connect_server_anyway_", nil) preferredStyle:UIAlertControllerStyleAlert];
  268. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_yes_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  269. [[NCNetworking shared] wrtiteCertificateWithDirectoryCertificate:[CCUtility getDirectoryCerificates]];
  270. [self startTimerErrorNetworking];
  271. }]];
  272. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_no_", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  273. [self startTimerErrorNetworking];
  274. }]];
  275. [self.window.rootViewController presentViewController:alertController animated:YES completion:^{
  276. // Stop timer error network
  277. [self.timerErrorNetworking invalidate];
  278. }];
  279. }
  280. }
  281. - (void)openLoginView:(UIViewController *)viewController selector:(NSInteger)selector openLoginWeb:(BOOL)openLoginWeb
  282. {
  283. // use appConfig [MDM]
  284. if ([NCBrandOptions sharedInstance].use_configuration) {
  285. if (!(_appConfigView.isViewLoaded && _appConfigView.view.window)) {
  286. self.appConfigView = [[UIStoryboard storyboardWithName:@"CCLogin" bundle:nil] instantiateViewControllerWithIdentifier:@"NCAppConfigView"];
  287. [self showLoginViewController:self.appConfigView forContext:viewController];
  288. }
  289. return;
  290. }
  291. // only for personalized LoginWeb [customer]
  292. if ([NCBrandOptions sharedInstance].use_login_web_personalized) {
  293. if (!(_activeLoginWeb.isViewLoaded && _activeLoginWeb.view.window)) {
  294. self.activeLoginWeb = [[UIStoryboard storyboardWithName:@"CCLogin" bundle:nil] instantiateViewControllerWithIdentifier:@"NCLoginWeb"];
  295. self.activeLoginWeb.urlBase = [[NCBrandOptions sharedInstance] loginBaseUrl];
  296. [self showLoginViewController:self.activeLoginWeb forContext:viewController];
  297. }
  298. return;
  299. }
  300. // normal login
  301. if (selector == k_intro_signup) {
  302. if (!(_activeLoginWeb.isViewLoaded && _activeLoginWeb.view.window)) {
  303. self.activeLoginWeb = [[UIStoryboard storyboardWithName:@"CCLogin" bundle:nil] instantiateViewControllerWithIdentifier:@"NCLoginWeb"];
  304. if (selector == k_intro_signup) {
  305. self.activeLoginWeb.urlBase = [[NCBrandOptions sharedInstance] linkloginPreferredProviders];
  306. } else {
  307. self.activeLoginWeb.urlBase = self.urlBase;
  308. }
  309. [self showLoginViewController:self.activeLoginWeb forContext:viewController];
  310. }
  311. } else if ([NCBrandOptions sharedInstance].disable_intro && [NCBrandOptions sharedInstance].disable_request_login_url) {
  312. self.activeLoginWeb = [[UIStoryboard storyboardWithName:@"CCLogin" bundle:nil] instantiateViewControllerWithIdentifier:@"NCLoginWeb"];
  313. self.activeLoginWeb.urlBase = [[NCBrandOptions sharedInstance] loginBaseUrl];
  314. [self showLoginViewController:self.activeLoginWeb forContext:viewController];
  315. } else if (openLoginWeb) {
  316. if (!(_activeLoginWeb.isViewLoaded && _activeLoginWeb.view.window)) {
  317. self.activeLoginWeb = [[UIStoryboard storyboardWithName:@"CCLogin" bundle:nil] instantiateViewControllerWithIdentifier:@"NCLoginWeb"];
  318. self.activeLoginWeb.urlBase = self.urlBase;
  319. [self showLoginViewController:self.activeLoginWeb forContext:viewController];
  320. }
  321. } else {
  322. if (!(_activeLogin.isViewLoaded && _activeLogin.view.window)) {
  323. _activeLogin = [[UIStoryboard storyboardWithName:@"CCLogin" bundle:nil] instantiateViewControllerWithIdentifier:@"CCLoginNextcloud"];
  324. [self showLoginViewController:_activeLogin forContext:viewController];
  325. }
  326. }
  327. }
  328. -(void)showLoginViewController:(UIViewController *)viewController forContext:(UIViewController *)contextViewController
  329. {
  330. if (contextViewController == NULL) {
  331. UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:viewController];
  332. navController.navigationBar.barStyle = UIBarStyleBlack;
  333. navController.navigationBar.tintColor = NCBrandColor.sharedInstance.customerText;
  334. navController.navigationBar.barTintColor = NCBrandColor.sharedInstance.customer;
  335. [navController.navigationBar setTranslucent:false];
  336. self.window.rootViewController = navController;
  337. [self.window makeKeyAndVisible];
  338. } else if ([contextViewController isKindOfClass:[UINavigationController class]]) {
  339. UINavigationController *navController = ((UINavigationController *)contextViewController);
  340. [navController pushViewController:viewController animated:true];
  341. } else {
  342. UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:viewController];
  343. navController.modalPresentationStyle = UIModalPresentationFullScreen;
  344. navController.navigationBar.barStyle = UIBarStyleBlack;
  345. navController.navigationBar.tintColor = NCBrandColor.sharedInstance.customerText;
  346. navController.navigationBar.barTintColor = NCBrandColor.sharedInstance.customer;
  347. [navController.navigationBar setTranslucent:false];
  348. [contextViewController presentViewController:navController animated:true completion:nil];
  349. }
  350. }
  351. - (void)startTimerErrorNetworking
  352. {
  353. self.timerErrorNetworking = [NSTimer scheduledTimerWithTimeInterval:k_timerErrorNetworking target:self selector:@selector(checkErrorNetworking) userInfo:nil repeats:YES];
  354. }
  355. #pragma --------------------------------------------------------------------------------------------
  356. #pragma mark ===== Account & Communication =====
  357. #pragma --------------------------------------------------------------------------------------------
  358. - (void)settingAccount:(NSString *)account urlBase:(NSString *)urlBase user:(NSString *)user userID:(NSString *)userID password:(NSString *)password
  359. {
  360. self.account = account;
  361. self.urlBase = urlBase;
  362. self.user = user;
  363. self.userID = userID;
  364. self.password = password;
  365. (void)[NCNetworkingNotificationCenter shared];
  366. [[NCCommunicationCommon shared] setupWithAccount:account user:user userId:userID password:password urlBase:urlBase];
  367. [self settingSetupCommunication:account];
  368. }
  369. - (void)deleteAccount:(NSString *)account wipe:(BOOL)wipe
  370. {
  371. // Push Notification
  372. tableAccount *accountPN = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  373. [self unsubscribingNextcloudServerPushNotification:accountPN.account urlBase:accountPN.urlBase user:accountPN.user withSubscribing:false];
  374. [self settingAccount:nil urlBase:nil user:nil userID:nil password:nil];
  375. /* DELETE ALL FILES LOCAL FS */
  376. NSArray *results = [[NCManageDatabase sharedInstance] getTableLocalFilesWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account] sorted:@"ocId" ascending:NO];
  377. for (tableLocalFile *result in results) {
  378. [CCUtility removeFileAtPath:[CCUtility getDirectoryProviderStorageOcId:result.ocId]];
  379. }
  380. // Clear database
  381. [[NCManageDatabase sharedInstance] clearDatabaseWithAccount:account removeAccount:true];
  382. [CCUtility clearAllKeysEndToEnd:account];
  383. [CCUtility clearAllKeysPushNotification:account];
  384. [CCUtility setCertificateError:account error:false];
  385. [CCUtility setPassword:account password:nil];
  386. if (wipe) {
  387. NSArray *listAccount = [[NCManageDatabase sharedInstance] getAccounts];
  388. if ([listAccount count] > 0) {
  389. NSString *newAccount = listAccount[0];
  390. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] setAccountActive:newAccount];
  391. [self settingAccount:newAccount urlBase:tableAccount.urlBase user:tableAccount.user userID:tableAccount.userID password:[CCUtility getPassword:tableAccount.account]];
  392. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_initializeMain object:nil userInfo:nil];
  393. } else {
  394. [self openLoginView:self.window.rootViewController selector:k_intro_login openLoginWeb:false];
  395. }
  396. }
  397. }
  398. - (void)settingSetupCommunication:(NSString *)account
  399. {
  400. NSInteger serverVersionMajor = [[NCManageDatabase sharedInstance] getCapabilitiesServerIntWithAccount:account elements:NCElementsJSON.shared.capabilitiesVersionMajor];
  401. if (serverVersionMajor > 0) {
  402. [[NCCommunicationCommon shared] setupWithNextcloudVersion:serverVersionMajor];
  403. }
  404. [[NCCommunicationCommon shared] setupWithWebDav:[[NCUtility shared] getWebDAVWithAccount:account]];
  405. [[NCCommunicationCommon shared] setupWithDav:[[NCUtility shared] getDAV]];
  406. }
  407. #pragma --------------------------------------------------------------------------------------------
  408. #pragma mark ===== Push Notifications =====
  409. #pragma --------------------------------------------------------------------------------------------
  410. - (void)pushNotification
  411. {
  412. // test
  413. if (self.account.length == 0 || self.maintenanceMode || self.pushKitToken.length == 0)
  414. return;
  415. for (tableAccount *result in [[NCManageDatabase sharedInstance] getAllAccount]) {
  416. NSString *token = [CCUtility getPushNotificationToken:result.account];
  417. if (![token isEqualToString:self.pushKitToken]) {
  418. if (token != nil) {
  419. // unsubscribing + subscribing
  420. [self unsubscribingNextcloudServerPushNotification:result.account urlBase:result.urlBase user:result.user withSubscribing:true];
  421. } else {
  422. [self subscribingNextcloudServerPushNotification:result.account urlBase:result.urlBase user:result.user];
  423. }
  424. }
  425. }
  426. }
  427. - (void)subscribingNextcloudServerPushNotification:(NSString *)account urlBase:(NSString *)urlBase user:(NSString *)user
  428. {
  429. // test
  430. if (self.account.length == 0 || self.maintenanceMode || self.pushKitToken.length == 0)
  431. return;
  432. [[NCPushNotificationEncryption sharedInstance] generatePushNotificationsKeyPair:account];
  433. NSString *pushTokenHash = [[NCEndToEndEncryption sharedManager] createSHA512:self.pushKitToken];
  434. NSData *pushPublicKey = [CCUtility getPushNotificationPublicKey:account];
  435. NSString *pushDevicePublicKey = [[NSString alloc] initWithData:pushPublicKey encoding:NSUTF8StringEncoding];
  436. NSString *proxyServerPath = [NCBrandOptions sharedInstance].pushNotificationServerProxy;
  437. [[NCCommunication shared] subscribingPushNotificationWithServerUrl:urlBase account:account user:user password:[CCUtility getPassword:account] pushTokenHash:pushTokenHash devicePublicKey:pushDevicePublicKey proxyServerUrl:proxyServerPath customUserAgent:nil addCustomHeaders:nil completionHandler:^(NSString *account, NSString *deviceIdentifier, NSString *signature, NSString *publicKey, NSInteger errorCode, NSString *errorDescription) {
  438. if (errorCode == 0) {
  439. NSString *userAgent = [NSString stringWithFormat:@"%@ (Strict VoIP)", [CCUtility getUserAgent]];
  440. [[NCCommunication shared] subscribingPushProxyWithProxyServerUrl:proxyServerPath pushToken:self.pushKitToken deviceIdentifier:deviceIdentifier signature:signature publicKey:publicKey userAgent:userAgent completionHandler:^(NSInteger errorCode, NSString *errorDescription) {
  441. if (errorCode == 0) {
  442. [[NCCommunicationCommon shared] writeLog:@"Subscribed to Push Notification server & proxy successfully"];
  443. [CCUtility setPushNotificationToken:account token:self.pushKitToken];
  444. [CCUtility setPushNotificationDeviceIdentifier:account deviceIdentifier:deviceIdentifier];
  445. [CCUtility setPushNotificationDeviceIdentifierSignature:account deviceIdentifierSignature:signature];
  446. [CCUtility setPushNotificationSubscribingPublicKey:account publicKey:publicKey];
  447. }
  448. }];
  449. }
  450. }];
  451. }
  452. - (void)unsubscribingNextcloudServerPushNotification:(NSString *)account urlBase:(NSString *)urlBase user:(NSString *)user withSubscribing:(BOOL)subscribing
  453. {
  454. // test
  455. if (self.account.length == 0 || self.maintenanceMode)
  456. return;
  457. NSString *deviceIdentifier = [CCUtility getPushNotificationDeviceIdentifier:account];
  458. NSString *signature = [CCUtility getPushNotificationDeviceIdentifierSignature:account];
  459. NSString *publicKey = [CCUtility getPushNotificationSubscribingPublicKey:account];
  460. [[NCCommunication shared] unsubscribingPushNotificationWithServerUrl:urlBase account:account user:user password:[CCUtility getPassword:account] customUserAgent:nil addCustomHeaders:nil completionHandler:^(NSString *account, NSInteger errorCode, NSString *errorDescription) {
  461. if (errorCode == 0) {
  462. NSString *userAgent = [NSString stringWithFormat:@"%@ (Strict VoIP)", [CCUtility getUserAgent]];
  463. NSString *proxyServerPath = [NCBrandOptions sharedInstance].pushNotificationServerProxy;
  464. [[NCCommunication shared] unsubscribingPushProxyWithProxyServerUrl:proxyServerPath deviceIdentifier:deviceIdentifier signature:signature publicKey:publicKey userAgent:userAgent completionHandler:^(NSInteger errorCode, NSString *errorDescription) {
  465. if (errorCode == 0) {
  466. [[NCCommunicationCommon shared] writeLog:@"Unsubscribed to Push Notification server & proxy successfully."];
  467. [CCUtility setPushNotificationPublicKey:account data:nil];
  468. [CCUtility setPushNotificationSubscribingPublicKey:account publicKey:nil];
  469. [CCUtility setPushNotificationPrivateKey:account data:nil];
  470. [CCUtility setPushNotificationToken:account token:nil];
  471. [CCUtility setPushNotificationDeviceIdentifier:account deviceIdentifier:nil];
  472. [CCUtility setPushNotificationDeviceIdentifierSignature:account deviceIdentifierSignature:nil];
  473. if (self.pushKitToken != nil && subscribing) {
  474. [self subscribingNextcloudServerPushNotification:account urlBase:urlBase user:user];
  475. }
  476. }
  477. }];
  478. }
  479. }];
  480. }
  481. -(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler
  482. {
  483. //Called when a notification is delivered to a foreground app.
  484. completionHandler(UNNotificationPresentationOptionAlert);
  485. }
  486. -(void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(nonnull UNNotificationResponse *)response withCompletionHandler:(nonnull void (^)(void))completionHandler
  487. {
  488. completionHandler();
  489. }
  490. - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
  491. {
  492. self.pushKitToken = [self stringWithDeviceToken:deviceToken];
  493. [self pushNotification];
  494. }
  495. - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
  496. {
  497. NSString *message = [userInfo objectForKey:@"subject"];
  498. if (message) {
  499. NSArray *results = [[NCManageDatabase sharedInstance] getAllAccount];
  500. for (tableAccount *result in results) {
  501. if ([CCUtility getPushNotificationPrivateKey:result.account]) {
  502. NSData *decryptionKey = [CCUtility getPushNotificationPrivateKey:result.account];
  503. NSString *decryptedMessage = [[NCPushNotificationEncryption sharedInstance] decryptPushNotification:message withDevicePrivateKey:decryptionKey];
  504. if (decryptedMessage) {
  505. NSData *data = [decryptedMessage dataUsingEncoding:NSUTF8StringEncoding];
  506. NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
  507. NSInteger nid = [[json objectForKey:@"nid"] integerValue];
  508. BOOL delete = [[json objectForKey:@"delete"] boolValue];
  509. BOOL deleteAll = [[json objectForKey:@"delete-all"] boolValue];
  510. if (delete) {
  511. [self removeNotificationWithNotificationId:nid usingDecryptionKey:decryptionKey];
  512. } else if (deleteAll) {
  513. [self cleanAllNotifications];
  514. }
  515. }
  516. }
  517. }
  518. }
  519. completionHandler(UIBackgroundFetchResultNoData);
  520. }
  521. - (void)cleanAllNotifications
  522. {
  523. [[UNUserNotificationCenter currentNotificationCenter] removeAllDeliveredNotifications];
  524. }
  525. - (void)removeNotificationWithNotificationId:(NSInteger)notificationId usingDecryptionKey:(NSData *)key
  526. {
  527. // Check in pending notifications
  528. [[UNUserNotificationCenter currentNotificationCenter] getPendingNotificationRequestsWithCompletionHandler:^(NSArray<UNNotificationRequest *> * _Nonnull requests) {
  529. for (UNNotificationRequest *notificationRequest in requests) {
  530. NSString *message = [notificationRequest.content.userInfo objectForKey:@"subject"];
  531. NSString *decryptedMessage = [[NCPushNotificationEncryption sharedInstance] decryptPushNotification:message withDevicePrivateKey:key];
  532. if (decryptedMessage) {
  533. NSData *data = [decryptedMessage dataUsingEncoding:NSUTF8StringEncoding];
  534. NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
  535. NSInteger nid = [[json objectForKey:@"nid"] integerValue];
  536. if (nid == notificationId) {
  537. [[UNUserNotificationCenter currentNotificationCenter] removePendingNotificationRequestsWithIdentifiers:@[notificationRequest.identifier]];
  538. }
  539. }
  540. }
  541. }];
  542. // Check in delivered notifications
  543. [[UNUserNotificationCenter currentNotificationCenter] getDeliveredNotificationsWithCompletionHandler:^(NSArray<UNNotification *> * _Nonnull notifications) {
  544. for (UNNotification *notification in notifications) {
  545. NSString *message = [notification.request.content.userInfo objectForKey:@"subject"];
  546. NSString *decryptedMessage = [[NCPushNotificationEncryption sharedInstance] decryptPushNotification:message withDevicePrivateKey:key];
  547. if (decryptedMessage) {
  548. NSData *data = [decryptedMessage dataUsingEncoding:NSUTF8StringEncoding];
  549. NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
  550. NSInteger nid = [[json objectForKey:@"nid"] integerValue];
  551. if (nid == notificationId) {
  552. [[UNUserNotificationCenter currentNotificationCenter] removeDeliveredNotificationsWithIdentifiers:@[notification.request.identifier]];
  553. }
  554. }
  555. }
  556. }];
  557. }
  558. - (NSString *)stringWithDeviceToken:(NSData *)deviceToken
  559. {
  560. const char *data = [deviceToken bytes];
  561. NSMutableString *token = [NSMutableString string];
  562. for (NSUInteger i = 0; i < [deviceToken length]; i++) {
  563. [token appendFormat:@"%02.2hhX", data[i]];
  564. }
  565. return [token copy];
  566. }
  567. #pragma --------------------------------------------------------------------------------------------
  568. #pragma mark ===== Quick Actions - ShotcutItem =====
  569. #pragma --------------------------------------------------------------------------------------------
  570. - (void)configDynamicShortcutItems
  571. {
  572. NSString *bundleId = [NSBundle mainBundle].bundleIdentifier;
  573. UIApplicationShortcutIcon *shortcutMediaIcon = [UIApplicationShortcutIcon iconWithTemplateImageName:@"media"];
  574. UIApplicationShortcutItem *shortcutMedia = [[UIApplicationShortcutItem alloc] initWithType:[NSString stringWithFormat:@"%@.media", bundleId] localizedTitle:NSLocalizedString(@"_media_", nil) localizedSubtitle:nil icon:shortcutMediaIcon userInfo:nil];
  575. // add the array to our app
  576. if (shortcutMedia)
  577. [UIApplication sharedApplication].shortcutItems = @[shortcutMedia];
  578. }
  579. - (void)application:(UIApplication *)application performActionForShortcutItem:(UIApplicationShortcutItem *)shortcutItem completionHandler:(void (^)(BOOL))completionHandler
  580. {
  581. BOOL handledShortCutItem = [self handleShortCutItem:shortcutItem];
  582. completionHandler(handledShortCutItem);
  583. }
  584. - (BOOL)handleShortCutItem:(UIApplicationShortcutItem *)shortcutItem
  585. {
  586. BOOL handled = NO;
  587. NSString *bundleId = [NSBundle mainBundle].bundleIdentifier;
  588. NSString *shortcutMedia = [NSString stringWithFormat:@"%@.media", bundleId];
  589. if ([shortcutItem.type isEqualToString:shortcutMedia] && self.account) {
  590. dispatch_async(dispatch_get_main_queue(), ^{
  591. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  592. if ([splitViewController isKindOfClass:[UISplitViewController class]]) {
  593. UINavigationController *navigationControllerMaster = (UINavigationController *)splitViewController.viewControllers.firstObject;
  594. if ([navigationControllerMaster isKindOfClass:[UINavigationController class]]) {
  595. UITabBarController *tabBarController = (UITabBarController *)navigationControllerMaster.topViewController;
  596. if ([tabBarController isKindOfClass:[UITabBarController class]]) {
  597. if (splitViewController.isCollapsed) {
  598. [navigationControllerMaster popToRootViewControllerAnimated:false];
  599. UINavigationController *navigationControllerMaster = (UINavigationController *)splitViewController.viewControllers.firstObject;
  600. if ([navigationControllerMaster isKindOfClass:[UINavigationController class]]) {
  601. UITabBarController *tabBarController = (UITabBarController *)navigationControllerMaster.topViewController;
  602. if ([tabBarController isKindOfClass:[UITabBarController class]]) {
  603. [tabBarController setSelectedIndex: k_tabBarApplicationIndexMedia];
  604. }
  605. }
  606. } else {
  607. if ([tabBarController isKindOfClass:[UITabBarController class]]) {
  608. [tabBarController setSelectedIndex: k_tabBarApplicationIndexMedia];
  609. }
  610. }
  611. }
  612. }
  613. }
  614. });
  615. handled = YES;
  616. }
  617. return handled;
  618. }
  619. #pragma --------------------------------------------------------------------------------------------
  620. #pragma mark ===== ApplicationIconBadgeNumber =====
  621. #pragma --------------------------------------------------------------------------------------------
  622. - (void)updateApplicationIconBadgeNumber
  623. {
  624. if (self.account.length == 0 || self.maintenanceMode) return;
  625. NSInteger counterDownload = [[NCOperationQueue shared] downloadCount];
  626. NSInteger counterUpload = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"status == %d OR status == %d OR status == %d", k_metadataStatusWaitUpload, k_metadataStatusInUpload, k_metadataStatusUploading]].count;
  627. NSInteger total = counterDownload + counterUpload;
  628. [UIApplication sharedApplication].applicationIconBadgeNumber = total;
  629. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  630. if ([splitViewController isKindOfClass:[UISplitViewController class]]) {
  631. UINavigationController *navigationController = (UINavigationController *)[splitViewController.viewControllers firstObject];
  632. if ([navigationController isKindOfClass:[UINavigationController class]]) {
  633. UITabBarController *tabBarController = (UITabBarController *)navigationController.topViewController;
  634. if ([tabBarController isKindOfClass:[UITabBarController class]]) {
  635. UITabBarItem *tabBarItem = [tabBarController.tabBar.items objectAtIndex:0];
  636. if (total > 0) {
  637. [tabBarItem setBadgeValue:[NSString stringWithFormat:@"%li", (unsigned long)total]];
  638. } else {
  639. [tabBarItem setBadgeValue:nil];
  640. }
  641. }
  642. }
  643. }
  644. }
  645. #pragma --------------------------------------------------------------------------------------------
  646. #pragma mark ===== TabBarController =====
  647. #pragma --------------------------------------------------------------------------------------------
  648. - (void)createTabBarController:(UITabBarController *)tabBarController
  649. {
  650. UITabBarItem *item;
  651. NSLayoutConstraint *constraint;
  652. CGFloat safeAreaBottom = safeAreaBottom = [UIApplication sharedApplication].delegate.window.safeAreaInsets.bottom;
  653. // File
  654. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexFile];
  655. [item setTitle:NSLocalizedString(@"_home_", nil)];
  656. item.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarFiles"] width:50 height:50 color:NCBrandColor.sharedInstance.brandElement];
  657. item.selectedImage = item.image;
  658. // Favorites
  659. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexFavorite];
  660. [item setTitle:NSLocalizedString(@"_favorites_", nil)];
  661. item.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"favorite"] width:50 height:50 color:NCBrandColor.sharedInstance.brandElement];
  662. item.selectedImage = item.image;
  663. // (PLUS INVISIBLE)
  664. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexPlusHide];
  665. item.title = @"";
  666. item.image = nil;
  667. item.enabled = false;
  668. // Media
  669. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexMedia];
  670. [item setTitle:NSLocalizedString(@"_media_", nil)];
  671. item.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"media"] width:50 height:50 color:NCBrandColor.sharedInstance.brandElement];
  672. item.selectedImage = item.image;
  673. // More
  674. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexMore];
  675. [item setTitle:NSLocalizedString(@"_more_", nil)];
  676. item.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarMore"] width:50 height:50 color:NCBrandColor.sharedInstance.brandElement];
  677. item.selectedImage = item.image;
  678. // Plus Button
  679. int buttonSize = 57;
  680. UIImage *buttonImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarPlus"] width:120 height:120 color:UIColor.whiteColor];
  681. UIButton *buttonPlus = [UIButton buttonWithType:UIButtonTypeCustom];
  682. buttonPlus.tag = 99;
  683. buttonPlus.accessibilityLabel = NSLocalizedString(@"_accessibility_add_upload_", nil);
  684. [buttonPlus setImage:buttonImage forState:UIControlStateNormal];
  685. buttonPlus.backgroundColor = NCBrandColor.sharedInstance.brandElement;
  686. buttonPlus.layer.cornerRadius = buttonSize / 2;
  687. buttonPlus.layer.masksToBounds = NO;
  688. buttonPlus.layer.shadowOffset = CGSizeMake(0, 0);
  689. buttonPlus.layer.shadowRadius = 3.0f;
  690. buttonPlus.layer.shadowOpacity = 0.5;
  691. [buttonPlus addTarget:self action:@selector(handleTouchTabbarCenter:) forControlEvents:UIControlEventTouchUpInside];
  692. [buttonPlus setTranslatesAutoresizingMaskIntoConstraints:NO];
  693. [tabBarController.tabBar addSubview:buttonPlus];
  694. if (safeAreaBottom > 0) {
  695. // X
  696. constraint = [NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:tabBarController.tabBar attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0];
  697. [tabBarController.view addConstraint:constraint];
  698. // Y
  699. constraint = [NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:tabBarController.tabBar attribute:NSLayoutAttributeTop multiplier:1.0 constant:-(buttonSize / 2)];
  700. [tabBarController.view addConstraint:constraint];
  701. // Width
  702. constraint = [NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:0 multiplier:1.0 constant:buttonSize];
  703. [tabBarController.view addConstraint:constraint];
  704. // Height
  705. constraint = [NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:0 multiplier:1.0 constant:buttonSize];
  706. [tabBarController.view addConstraint:constraint];
  707. } else {
  708. // X
  709. constraint = [NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:tabBarController.tabBar attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0];
  710. [tabBarController.view addConstraint:constraint];
  711. // Y
  712. constraint = [NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:tabBarController.tabBar attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:-(buttonSize / 2)];
  713. [tabBarController.view addConstraint:constraint];
  714. // Width
  715. constraint = [NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:0 multiplier:1.0 constant:buttonSize];
  716. [tabBarController.view addConstraint:constraint];
  717. // Height
  718. constraint = [NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:0 multiplier:1.0 constant:buttonSize];
  719. [tabBarController.view addConstraint:constraint];
  720. }
  721. }
  722. - (void)handleTouchTabbarCenter:(id)sender
  723. {
  724. // Test Maintenance
  725. if (self.maintenanceMode)
  726. return;
  727. tableDirectory *tableDirectory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", self.account, self.activeServerUrl]];
  728. if ([tableDirectory.permissions containsString:@"CK"]) {
  729. [self showMenuInViewController:self.window.rootViewController];
  730. } else {
  731. [[NCContentPresenter shared] messageNotification:@"_warning_" description:@"_no_permission_add_file_" delay:k_dismissAfterSecond type:messageTypeInfo errorCode:k_CCErrorInternalError forced:false];
  732. }
  733. }
  734. #pragma --------------------------------------------------------------------------------------------
  735. #pragma mark ===== Theming Color =====
  736. #pragma --------------------------------------------------------------------------------------------
  737. - (void)settingThemingColorBrand
  738. {
  739. if (self.account.length == 0 || self.maintenanceMode)
  740. return;
  741. if ([NCBrandOptions sharedInstance].use_themingColor) {
  742. NSString *themingColor = [[NCManageDatabase sharedInstance] getCapabilitiesServerStringWithAccount:self.account elements:NCElementsJSON.shared.capabilitiesThemingColor];
  743. NSString *themingColorElement = [[NCManageDatabase sharedInstance] getCapabilitiesServerStringWithAccount:self.account elements:NCElementsJSON.shared.capabilitiesThemingColorElement];
  744. NSString *themingColorText = [[NCManageDatabase sharedInstance] getCapabilitiesServerStringWithAccount:self.account elements:NCElementsJSON.shared.capabilitiesThemingColorText];
  745. [CCGraphics settingThemingColor:themingColor themingColorElement:themingColorElement themingColorText:themingColorText];
  746. BOOL isTooLight = NCBrandColor.sharedInstance.brandElement.isTooLight;
  747. BOOL isTooDark = NCBrandColor.sharedInstance.brandElement.isTooDark;
  748. if (isTooLight) {
  749. NCBrandColor.sharedInstance.brandElement = [NCBrandColor.sharedInstance.brandElement darkerBy:30];
  750. } else if (isTooDark) {
  751. NCBrandColor.sharedInstance.brandElement = [NCBrandColor.sharedInstance.brandElement lighterBy:30];
  752. }
  753. } else {
  754. BOOL isTooLight = NCBrandColor.sharedInstance.customer.isTooLight;
  755. BOOL isTooDark = NCBrandColor.sharedInstance.customer.isTooDark;
  756. if (isTooLight) {
  757. NCBrandColor.sharedInstance.brandElement = [NCBrandColor.sharedInstance.customer darkerBy:30];
  758. } else if (isTooDark) {
  759. NCBrandColor.sharedInstance.brandElement = [NCBrandColor.sharedInstance.customer lighterBy:30];
  760. } else {
  761. NCBrandColor.sharedInstance.brandElement = NCBrandColor.sharedInstance.customer;
  762. }
  763. NCBrandColor.sharedInstance.brand = NCBrandColor.sharedInstance.customer;
  764. NCBrandColor.sharedInstance.brandText = NCBrandColor.sharedInstance.customerText;
  765. }
  766. [NCBrandColor.sharedInstance setDarkMode];
  767. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  768. [[NCCollectionCommon shared] createImagesThemingColor];
  769. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_changeTheming object:nil];
  770. });
  771. }
  772. - (void)changeTheming:(UIViewController *)viewController tableView:(UITableView *)tableView collectionView:(UICollectionView *)collectionView form:(BOOL)form
  773. {
  774. [NCBrandColor.sharedInstance setDarkMode];
  775. [self.window setTintColor:NCBrandColor.sharedInstance.textView];
  776. //Tab bar
  777. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  778. if ([splitViewController isKindOfClass:[UISplitViewController class]]) {
  779. UINavigationController *masterNavigationController = [splitViewController.viewControllers firstObject];
  780. if ([masterNavigationController isKindOfClass:[UINavigationController class]]) {
  781. UITabBarController *tabBarController = [masterNavigationController.viewControllers firstObject];
  782. if ([tabBarController isKindOfClass:[UITabBarController class]]) {
  783. tabBarController.tabBar.barTintColor = NCBrandColor.sharedInstance.backgroundView;
  784. tabBarController.tabBar.backgroundColor = NCBrandColor.sharedInstance.tabBar;
  785. tabBarController.tabBar.tintColor = NCBrandColor.sharedInstance.brandElement;
  786. [tabBarController.tabBar viewWithTag:99].backgroundColor = NCBrandColor.sharedInstance.brandElement;
  787. }
  788. }
  789. }
  790. // Nav bar
  791. [self configureNavBarForViewController:viewController];
  792. // View
  793. if (form) viewController.view.backgroundColor = NCBrandColor.sharedInstance.backgroundForm;
  794. else viewController.view.backgroundColor = NCBrandColor.sharedInstance.backgroundView;
  795. // TableView
  796. if (tableView) {
  797. if (form) tableView.backgroundColor = NCBrandColor.sharedInstance.backgroundForm;
  798. else tableView.backgroundColor = NCBrandColor.sharedInstance.backgroundView;
  799. tableView.separatorColor = NCBrandColor.sharedInstance.separator;
  800. [tableView reloadData];
  801. }
  802. // CollectionView
  803. if (collectionView) {
  804. if (form) collectionView.backgroundColor = NCBrandColor.sharedInstance.backgroundForm;
  805. else collectionView.backgroundColor = NCBrandColor.sharedInstance.backgroundView;
  806. [collectionView reloadData];
  807. }
  808. }
  809. #pragma --------------------------------------------------------------------------------------------
  810. #pragma mark ===== Fetch =====
  811. #pragma --------------------------------------------------------------------------------------------
  812. - (void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
  813. {
  814. // Test Maintenance
  815. if (self.account.length == 0 || self.maintenanceMode) {
  816. completionHandler(UIBackgroundFetchResultNoData);
  817. return;
  818. }
  819. [[NCCommunicationCommon shared] writeLog:@"Start perform Fetch With Completion Handler"];
  820. // Verify new photo
  821. [[NCAutoUpload sharedInstance] initStateAutoUpload];
  822. // after 20 sec
  823. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 20 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  824. [[NCCommunicationCommon shared] writeLog:@"End 20 sec. perform Fetch With Completion Handler"];
  825. completionHandler(UIBackgroundFetchResultNoData);
  826. });
  827. }
  828. #pragma --------------------------------------------------------------------------------------------
  829. #pragma mark ===== Operation Networking & Session =====
  830. #pragma --------------------------------------------------------------------------------------------
  831. //
  832. // Method called by the system when all the background task has end
  833. //
  834. - (void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)(void))completionHandler
  835. {
  836. [[NCCommunicationCommon shared] writeLog:[NSString stringWithFormat:@"Start handle Events For Background URLSession: %@", identifier]];
  837. [self updateApplicationIconBadgeNumber];
  838. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 20 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  839. self.backgroundSessionCompletionHandler = completionHandler;
  840. void (^completionHandler)() = self.backgroundSessionCompletionHandler;
  841. self.backgroundSessionCompletionHandler = nil;
  842. completionHandler();
  843. });
  844. }
  845. #pragma --------------------------------------------------------------------------------------------
  846. #pragma mark ===== OpenURL =====
  847. #pragma --------------------------------------------------------------------------------------------
  848. // Method called from iOS system to send a file from other app.
  849. - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url options:(NSDictionary<NSString *,id> *)options
  850. {
  851. if (self.account.length == 0 || self.maintenanceMode)
  852. return YES;
  853. NSString *scheme = url.scheme;
  854. NSString *fileName;
  855. NSString *serverUrl;
  856. if ([scheme isEqualToString:@"nextcloud"]) {
  857. NSString *action = url.host;
  858. if ([action isEqualToString:@"open-file"]) {
  859. NSURLComponents *urlComponents = [NSURLComponents componentsWithURL:url resolvingAgainstBaseURL:NO];
  860. NSArray *queryItems = urlComponents.queryItems;
  861. NSString *user = [CCUtility valueForKey:@"user" fromQueryItems:queryItems];
  862. NSString *path = [CCUtility valueForKey:@"path" fromQueryItems:queryItems];
  863. NSString *link = [CCUtility valueForKey:@"link" fromQueryItems:queryItems];
  864. tableAccount *matchedAccount = nil;
  865. // verify parameter
  866. if (user.length == 0 || path.length == 0 || [[NSURL URLWithString:link] host].length == 0) {
  867. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_error_parameter_schema_", nil) preferredStyle:UIAlertControllerStyleAlert];
  868. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  869. [alertController addAction:okAction];
  870. [self.window.rootViewController presentViewController:alertController animated:YES completion:nil];
  871. } else {
  872. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  873. if (account) {
  874. NSURL *accountURL = [NSURL URLWithString:account.urlBase];
  875. NSString *accountUser = account.user;
  876. if ([link containsString:accountURL.host] && [user isEqualToString:accountUser]) {
  877. matchedAccount = account;
  878. } else {
  879. NSArray *accounts = [[NCManageDatabase sharedInstance] getAllAccount];
  880. for (tableAccount *account in accounts) {
  881. NSURL *accountURL = [NSURL URLWithString:account.urlBase];
  882. NSString *accountUser = account.user;
  883. if ([link containsString:accountURL.host] && [user isEqualToString:accountUser]) {
  884. matchedAccount = [[NCManageDatabase sharedInstance] setAccountActive:account.account];
  885. [self settingAccount:matchedAccount.account urlBase:matchedAccount.urlBase user:matchedAccount.user userID:matchedAccount.userID password:[CCUtility getPassword:matchedAccount.account]];
  886. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_initializeMain object:nil userInfo:nil];
  887. }
  888. }
  889. }
  890. if (matchedAccount) {
  891. NSString *webDAV = [[NCUtility shared] getWebDAVWithAccount:self.account];
  892. if ([path containsString:@"/"]) {
  893. fileName = [path lastPathComponent];
  894. serverUrl = [NSString stringWithFormat:@"%@/%@/%@", matchedAccount.urlBase, webDAV, [path stringByDeletingLastPathComponent]];
  895. } else {
  896. fileName = path;
  897. serverUrl = [NSString stringWithFormat:@"%@/%@", matchedAccount.urlBase, webDAV];
  898. }
  899. [[NCCollectionCommon shared] openFileViewInFolderWithServerUrl:serverUrl fileName:fileName];
  900. } else {
  901. NSString *domain = [[NSURL URLWithString:link] host];
  902. NSString *fileName = [path lastPathComponent];
  903. NSString *message = [NSString stringWithFormat:NSLocalizedString(@"_account_not_available_", nil), user, domain, fileName];
  904. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_info_", nil) message:message preferredStyle:UIAlertControllerStyleAlert];
  905. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  906. [alertController addAction:okAction];
  907. [self.window.rootViewController presentViewController:alertController animated:YES completion:nil];
  908. }
  909. }
  910. }
  911. }
  912. return YES;
  913. }
  914. NSError *error;
  915. NSLog(@"[LOG] the path is: %@", url.path);
  916. NSArray *splitedUrl = [url.path componentsSeparatedByString:@"/"];
  917. self.fileNameUpload = [NSString stringWithFormat:@"%@",[splitedUrl objectAtIndex:([splitedUrl count]-1)]];
  918. if (self.account) {
  919. [[NSFileManager defaultManager]removeItemAtPath:[NSTemporaryDirectory() stringByAppendingString:self.fileNameUpload] error:nil];
  920. [[NSFileManager defaultManager]moveItemAtPath:url.path toPath:[NSTemporaryDirectory() stringByAppendingString:self.fileNameUpload] error:&error];
  921. if (error == nil) {
  922. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  923. if ([splitViewController isKindOfClass:[UISplitViewController class]]) {
  924. UINavigationController *navigationControllerMaster = (UINavigationController *)splitViewController.viewControllers.firstObject;
  925. if ([navigationControllerMaster isKindOfClass:[UINavigationController class]]) {
  926. UIViewController *uploadNavigationViewController = [[UIStoryboard storyboardWithName:@"CCUploadFromOtherUpp" bundle:nil] instantiateViewControllerWithIdentifier:@"CCUploadNavigationViewController"];
  927. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  928. [navigationControllerMaster presentViewController:uploadNavigationViewController animated:YES completion:nil];
  929. });
  930. }
  931. }
  932. }
  933. }
  934. return YES;
  935. }
  936. #pragma --------------------------------------------------------------------------------------------
  937. #pragma mark ===== Passcode + Delegate =====
  938. #pragma --------------------------------------------------------------------------------------------
  939. - (void)passcodeWithAutomaticallyPromptForBiometricValidation:(BOOL)automaticallyPromptForBiometricValidation
  940. {
  941. LAContext *laContext = [LAContext new];
  942. NSError *error;
  943. BOOL isBiometryAvailable = false;
  944. if ([[CCUtility getPasscode] length] == 0 || [self.account length] == 0 || [CCUtility getNotPasscodeAtStart]) return;
  945. if (self.passcodeViewController == nil) {
  946. self.passcodeViewController = [[TOPasscodeViewController alloc] initWithStyle:TOPasscodeViewStyleTranslucentLight passcodeType:TOPasscodeTypeSixDigits];
  947. if (@available(iOS 13.0, *)) {
  948. if ([[UITraitCollection currentTraitCollection] userInterfaceStyle] == UIUserInterfaceStyleDark) {
  949. self.passcodeViewController.style = TOPasscodeViewStyleTranslucentDark;
  950. }
  951. }
  952. self.passcodeViewController.delegate = self;
  953. self.passcodeViewController.keypadButtonShowLettering = false;
  954. if (CCUtility.getEnableTouchFaceID && [laContext canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:&error]) {
  955. if (error == NULL) {
  956. if (laContext.biometryType == LABiometryTypeFaceID) {
  957. self.passcodeViewController.biometryType = TOPasscodeBiometryTypeFaceID;
  958. self.passcodeViewController.allowBiometricValidation = true;
  959. isBiometryAvailable = true;
  960. } else if (laContext.biometryType == LABiometryTypeTouchID) {
  961. self.passcodeViewController.biometryType = TOPasscodeBiometryTypeTouchID;
  962. self.passcodeViewController.allowBiometricValidation = true;
  963. isBiometryAvailable = true;
  964. } else {
  965. isBiometryAvailable = false;
  966. NSLog(@"No Biometric support");
  967. }
  968. }
  969. }
  970. [self.window.rootViewController presentViewController:self.passcodeViewController animated:YES completion:^{
  971. [self enableTouchFaceID:automaticallyPromptForBiometricValidation];
  972. }];
  973. } else {
  974. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  975. [self enableTouchFaceID:automaticallyPromptForBiometricValidation];
  976. });
  977. }
  978. }
  979. - (void)didInputCorrectPasscodeInPasscodeViewController:(TOPasscodeViewController *)passcodeViewController
  980. {
  981. [passcodeViewController dismissViewControllerAnimated:YES completion:^{
  982. self.passcodeViewController = nil;
  983. }];
  984. }
  985. - (BOOL)passcodeViewController:(TOPasscodeViewController *)passcodeViewController isCorrectCode:(NSString *)code
  986. {
  987. return [code isEqualToString:[CCUtility getPasscode]];
  988. }
  989. - (void)didPerformBiometricValidationRequestInPasscodeViewController:(TOPasscodeViewController *)passcodeViewController
  990. {
  991. [[LAContext new] evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics localizedReason:[[NCBrandOptions sharedInstance] brand] reply:^(BOOL success, NSError * _Nullable error) {
  992. if (success) {
  993. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  994. [passcodeViewController dismissViewControllerAnimated:YES completion:^{
  995. self.passcodeViewController = nil;
  996. }];
  997. });
  998. }
  999. }];
  1000. }
  1001. - (void)enableTouchFaceID:(BOOL)automaticallyPromptForBiometricValidation
  1002. {
  1003. if (CCUtility.getEnableTouchFaceID && automaticallyPromptForBiometricValidation && self.passcodeViewController.view.window) {
  1004. [[LAContext new] evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics localizedReason:[[NCBrandOptions sharedInstance] brand] reply:^(BOOL success, NSError * _Nullable error) {
  1005. if (success) {
  1006. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1007. [self.passcodeViewController dismissViewControllerAnimated:YES completion:^{
  1008. self.passcodeViewController = nil;
  1009. }];
  1010. });
  1011. }
  1012. }];
  1013. }
  1014. }
  1015. #pragma --------------------------------------------------------------------------------------------
  1016. #pragma mark ===== Maintenance Mode =====
  1017. #pragma --------------------------------------------------------------------------------------------
  1018. - (void)maintenanceMode:(BOOL)mode
  1019. {
  1020. self.maintenanceMode = mode;
  1021. }
  1022. @end