AppDelegate.m 67 KB

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