AppDelegate.m 63 KB

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