AppDelegate.m 68 KB

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