AppDelegate.swift 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917
  1. //
  2. // AppDelegate.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 04/09/14 (19/02/21 swift).
  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 UIKit
  24. import BackgroundTasks
  25. import NCCommunication
  26. import TOPasscodeViewController
  27. import LocalAuthentication
  28. import Firebase
  29. @UIApplicationMain
  30. class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, TOPasscodeViewControllerDelegate, NCAccountRequestDelegate, NCViewCertificateDetailsDelegate, NCUserBaseUrl {
  31. var backgroundSessionCompletionHandler: (() -> Void)?
  32. var window: UIWindow?
  33. @objc var account: String = ""
  34. @objc var urlBase: String = ""
  35. @objc var user: String = ""
  36. @objc var userId: String = ""
  37. @objc var password: String = ""
  38. var deletePasswordSession: Bool = false
  39. var activeAppConfigView: NCAppConfigView?
  40. var activeLogin: NCLogin?
  41. var activeLoginWeb: NCLoginWeb?
  42. @objc var activeMedia: NCMedia?
  43. var activeServerUrl: String = ""
  44. @objc var activeViewController: UIViewController?
  45. var mainTabBar: NCMainTabBar?
  46. var activeMetadata: tableMetadata?
  47. var listFilesVC: [String: NCFiles] = [:]
  48. var listFavoriteVC: [String: NCFavorite] = [:]
  49. var listOfflineVC: [String: NCOffline] = [:]
  50. var disableSharesView: Bool = false
  51. var documentPickerViewController: NCDocumentPickerViewController?
  52. var networkingProcessUpload: NCNetworkingProcessUpload?
  53. var shares: [tableShare] = []
  54. var timerErrorNetworking: Timer?
  55. var errorITMS90076: Bool = false
  56. private var privacyProtectionWindow: UIWindow?
  57. func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
  58. let userAgent = CCUtility.getUserAgent() as String
  59. let isSimulatorOrTestFlight = NCUtility.shared.isSimulatorOrTestFlight()
  60. let versionNextcloudiOS = String(format: NCBrandOptions.shared.textCopyrightNextcloudiOS, NCUtility.shared.getVersionApp())
  61. UserDefaults.standard.register(defaults: ["UserAgent": userAgent])
  62. if !CCUtility.getDisableCrashservice() && !NCBrandOptions.shared.disable_crash_service {
  63. FirebaseApp.configure()
  64. }
  65. CCUtility.createDirectoryStandard()
  66. CCUtility.emptyTemporaryDirectory()
  67. NCCommunicationCommon.shared.setup(delegate: NCNetworking.shared)
  68. NCCommunicationCommon.shared.setup(userAgent: userAgent)
  69. startTimerErrorNetworking()
  70. // LOG
  71. var levelLog = 0
  72. if let pathDirectoryGroup = CCUtility.getDirectoryGroup()?.path {
  73. NCCommunicationCommon.shared.pathLog = pathDirectoryGroup
  74. }
  75. if NCBrandOptions.shared.disable_log {
  76. NCUtilityFileSystem.shared.deleteFile(filePath: NCCommunicationCommon.shared.filenamePathLog)
  77. NCUtilityFileSystem.shared.deleteFile(filePath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! + "/" + NCCommunicationCommon.shared.filenameLog)
  78. } else {
  79. levelLog = CCUtility.getLogLevel()
  80. NCCommunicationCommon.shared.levelLog = levelLog
  81. NCCommunicationCommon.shared.copyLogToDocumentDirectory = true
  82. if isSimulatorOrTestFlight {
  83. NCCommunicationCommon.shared.writeLog("Start session with level \(levelLog) " + versionNextcloudiOS + " (Simulator / TestFlight)")
  84. } else {
  85. NCCommunicationCommon.shared.writeLog("Start session with level \(levelLog) " + versionNextcloudiOS)
  86. }
  87. }
  88. // LOG Account
  89. if let account = NCManageDatabase.shared.getActiveAccount() {
  90. NCCommunicationCommon.shared.writeLog("Account active \(account.account)")
  91. if CCUtility.getPassword(account.account).isEmpty {
  92. NCCommunicationCommon.shared.writeLog("PASSWORD NOT FOUND for \(account.account)")
  93. }
  94. }
  95. // ITMS-90076: Potential Loss of Keychain Access
  96. if let account = NCManageDatabase.shared.getActiveAccount(), CCUtility.getPassword(account.account).isEmpty, NCUtility.shared.getVersionApp(withBuild: false).starts(with: "4.4") {
  97. errorITMS90076 = true
  98. }
  99. // Activate user account
  100. if let activeAccount = NCManageDatabase.shared.getActiveAccount() {
  101. // FIX 3.0.5 lost urlbase
  102. if activeAccount.urlBase.count == 0 {
  103. let user = activeAccount.user + " "
  104. let urlBase = activeAccount.account.replacingOccurrences(of: user, with: "")
  105. activeAccount.urlBase = urlBase
  106. NCManageDatabase.shared.updateAccount(activeAccount)
  107. }
  108. settingAccount(activeAccount.account, urlBase: activeAccount.urlBase, user: activeAccount.user, userId: activeAccount.userId, password: CCUtility.getPassword(activeAccount.account))
  109. NCBrandColor.shared.settingThemingColor(account: activeAccount.account)
  110. } else {
  111. CCUtility.deleteAllChainStore()
  112. if let bundleID = Bundle.main.bundleIdentifier {
  113. UserDefaults.standard.removePersistentDomain(forName: bundleID)
  114. }
  115. NCBrandColor.shared.createImagesThemingColor()
  116. }
  117. // Create user color
  118. NCBrandColor.shared.createUserColors()
  119. // initialize
  120. NotificationCenter.default.addObserver(self, selector: #selector(initialize), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterInitialize), object: nil)
  121. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterInitialize, userInfo:["atStart":1])
  122. // Process upload
  123. networkingProcessUpload = NCNetworkingProcessUpload()
  124. // Push Notification & display notification
  125. application.registerForRemoteNotifications()
  126. UNUserNotificationCenter.current().delegate = self
  127. UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { _, _ in }
  128. // Store review
  129. if !NCUtility.shared.isSimulatorOrTestFlight() {
  130. let review = NCStoreReview()
  131. review.incrementAppRuns()
  132. review.showStoreReview()
  133. }
  134. // Background task: register
  135. if #available(iOS 13.0, *) {
  136. BGTaskScheduler.shared.register(forTaskWithIdentifier: NCGlobal.shared.refreshTask, using: nil) { task in
  137. self.handleRefreshTask(task)
  138. }
  139. BGTaskScheduler.shared.register(forTaskWithIdentifier: NCGlobal.shared.processingTask, using: nil) { task in
  140. self.handleProcessingTask(task)
  141. }
  142. } else {
  143. application.setMinimumBackgroundFetchInterval(UIApplication.backgroundFetchIntervalMinimum)
  144. }
  145. // Intro
  146. if NCBrandOptions.shared.disable_intro {
  147. CCUtility.setIntro(true)
  148. if account == "" {
  149. openLogin(viewController: nil, selector: NCGlobal.shared.introLogin, openLoginWeb: false)
  150. }
  151. } else {
  152. if !CCUtility.getIntro() {
  153. if let viewController = UIStoryboard(name: "NCIntro", bundle: nil).instantiateInitialViewController() {
  154. let navigationController = NCLoginNavigationController.init(rootViewController: viewController)
  155. window?.rootViewController = navigationController
  156. window?.makeKeyAndVisible()
  157. }
  158. }
  159. }
  160. // Passcode
  161. DispatchQueue.main.async {
  162. self.presentPasscode {
  163. self.enableTouchFaceID()
  164. }
  165. }
  166. return true
  167. }
  168. // MARK: - Life Cycle
  169. // L' applicazione entrerà in primo piano (attivo sempre)
  170. func applicationDidBecomeActive(_ application: UIApplication) {
  171. self.deletePasswordSession = false
  172. if !NCAskAuthorization.shared.isRequesting {
  173. // Privacy
  174. hidePrivacyProtectionWindow()
  175. }
  176. NCSettingsBundleHelper.setVersionAndBuildNumber()
  177. if account == "" { return }
  178. networkingProcessUpload?.verifyUploadZombie()
  179. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterApplicationDidBecomeActive)
  180. }
  181. // L' applicazione entrerà in primo piano (attivo solo dopo il background)
  182. func applicationWillEnterForeground(_ application: UIApplication) {
  183. if account == "" { return }
  184. guard let activeAccount = NCManageDatabase.shared.getActiveAccount() else { return }
  185. // Account changed ??
  186. if activeAccount.account != account {
  187. settingAccount(activeAccount.account, urlBase: activeAccount.urlBase, user: activeAccount.user, userId: activeAccount.userId, password: CCUtility.getPassword(activeAccount.account))
  188. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterInitialize)
  189. }
  190. NCCommunicationCommon.shared.writeLog("Application will enter in foreground")
  191. // START TIMER UPLOAD PROCESS
  192. if NCUtility.shared.isSimulator() {
  193. networkingProcessUpload?.startTimer()
  194. }
  195. // Initialize Auto upload
  196. NCAutoUpload.shared.initAutoUpload(viewController: nil) { _ in }
  197. // Required unsubscribing / subscribing
  198. NCPushNotification.shared().pushNotification()
  199. // Request Service Server Nextcloud
  200. NCService.shared.startRequestServicesServer()
  201. // Request TouchID, FaceID
  202. enableTouchFaceID()
  203. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterApplicationWillEnterForeground)
  204. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterRichdocumentGrabFocus)
  205. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterReloadDataSourceNetworkForced)
  206. }
  207. // L' applicazione si dimetterà dallo stato di attivo
  208. func applicationWillResignActive(_ application: UIApplication) {
  209. if account == "" { return }
  210. if CCUtility.getPrivacyScreenEnabled() {
  211. // Privacy
  212. showPrivacyProtectionWindow()
  213. }
  214. // Clear operation queue
  215. NCOperationQueue.shared.cancelAllQueue()
  216. // Clear download
  217. NCNetworking.shared.cancelAllDownloadTransfer()
  218. // Clear older files
  219. let days = CCUtility.getCleanUpDay()
  220. if let directory = CCUtility.getDirectoryProviderStorage() {
  221. NCUtilityFileSystem.shared.cleanUp(directory: directory, days: TimeInterval(days))
  222. }
  223. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterApplicationWillResignActive)
  224. }
  225. // L' applicazione è entrata nello sfondo
  226. func applicationDidEnterBackground(_ application: UIApplication) {
  227. if account == "" { return }
  228. // STOP TIMER UPLOAD PROCESS
  229. if NCUtility.shared.isSimulator() {
  230. networkingProcessUpload?.stopTimer()
  231. }
  232. if #available(iOS 13.0, *) {
  233. scheduleAppRefresh()
  234. scheduleBackgroundProcessing()
  235. }
  236. // Passcode
  237. presentPasscode { }
  238. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterApplicationDidEnterBackground)
  239. }
  240. // L'applicazione terminerà
  241. func applicationWillTerminate(_ application: UIApplication) {
  242. NCNetworking.shared.cancelAllDownloadTransfer()
  243. NCCommunicationCommon.shared.writeLog("bye bye")
  244. }
  245. // MARK: -
  246. @objc private func initialize() {
  247. guard !account.isEmpty else { return }
  248. NCCommunicationCommon.shared.writeLog("initialize Main")
  249. // Registeration push notification
  250. NCPushNotification.shared().pushNotification()
  251. // Start Auto Upload
  252. NCAutoUpload.shared.initAutoUpload(viewController: nil) { _ in }
  253. // Start services
  254. NCService.shared.startRequestServicesServer()
  255. // close detail
  256. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterMenuDetailClose)
  257. // Registeration domain File Provider
  258. // FileProviderDomain *fileProviderDomain = [FileProviderDomain new];
  259. // [fileProviderDomain removeAllDomains];
  260. // [fileProviderDomain registerDomains];
  261. }
  262. // MARK: - Background Task
  263. @available(iOS 13.0, *)
  264. func scheduleAppRefresh() {
  265. let request = BGAppRefreshTaskRequest(identifier: NCGlobal.shared.refreshTask)
  266. request.earliestBeginDate = Date(timeIntervalSinceNow: 5 * 60) // Refresh after 5 minutes.
  267. do {
  268. try BGTaskScheduler.shared.submit(request)
  269. NCCommunicationCommon.shared.writeLog("Refresh task success submit request \(request)")
  270. } catch {
  271. NCCommunicationCommon.shared.writeLog("Refresh task failed to submit request: \(error)")
  272. }
  273. }
  274. @available(iOS 13.0, *)
  275. func scheduleBackgroundProcessing() {
  276. let request = BGProcessingTaskRequest(identifier: NCGlobal.shared.processingTask)
  277. request.earliestBeginDate = Date(timeIntervalSinceNow: 5 * 60) // Refresh after 5 minutes.
  278. request.requiresNetworkConnectivity = true
  279. request.requiresExternalPower = false
  280. do {
  281. try BGTaskScheduler.shared.submit(request)
  282. NCCommunicationCommon.shared.writeLog("Background Processing task success submit request \(request)")
  283. } catch {
  284. NCCommunicationCommon.shared.writeLog("Background Processing task failed to submit request: \(error)")
  285. }
  286. }
  287. @available(iOS 13.0, *)
  288. func handleRefreshTask(_ task: BGTask) {
  289. if account == "" {
  290. task.setTaskCompleted(success: true)
  291. return
  292. }
  293. NCCommunicationCommon.shared.writeLog("Start handler refresh task [Auto upload]")
  294. NCAutoUpload.shared.initAutoUpload(viewController: nil) { _ in
  295. DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
  296. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterUpdateBadgeNumber)
  297. NCCommunicationCommon.shared.writeLog("Completition handler refresh task with [Auto upload]")
  298. task.setTaskCompleted(success: true)
  299. }
  300. }
  301. }
  302. @available(iOS 13.0, *)
  303. func handleProcessingTask(_ task: BGTask) {
  304. if account == "" {
  305. task.setTaskCompleted(success: true)
  306. return
  307. }
  308. NCCommunicationCommon.shared.writeLog("Start handler processing task [Synchronize Favorite & Offline]")
  309. NCNetworking.shared.listingFavoritescompletion(selector: NCGlobal.shared.selectorReadFile) { _, _, errorCode, _ in
  310. NCCommunicationCommon.shared.writeLog("Completition listing favorite with error: \(errorCode)")
  311. }
  312. NCService.shared.synchronizeOffline(account: account)
  313. DispatchQueue.main.asyncAfter(deadline: .now() + 25) {
  314. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterUpdateBadgeNumber)
  315. NCCommunicationCommon.shared.writeLog("Completition handler processing task [Synchronize Favorite & Offline]")
  316. task.setTaskCompleted(success: true)
  317. }
  318. }
  319. // MARK: - Fetch
  320. func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
  321. if account == "" {
  322. completionHandler(UIBackgroundFetchResult.noData)
  323. return
  324. }
  325. NCCommunicationCommon.shared.writeLog("Start perform Fetch [Auto upload]")
  326. NCAutoUpload.shared.initAutoUpload(viewController: nil) { items in
  327. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterUpdateBadgeNumber)
  328. NCCommunicationCommon.shared.writeLog("Completition perform Fetch with \(items) uploads [Auto upload]")
  329. if items == 0 {
  330. completionHandler(UIBackgroundFetchResult.noData)
  331. } else {
  332. completionHandler(UIBackgroundFetchResult.newData)
  333. }
  334. }
  335. }
  336. // MARK: - Background Networking Session
  337. func application(_ application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: @escaping () -> Void) {
  338. NCCommunicationCommon.shared.writeLog("Start handle Events For Background URLSession: \(identifier)")
  339. backgroundSessionCompletionHandler = completionHandler
  340. }
  341. // MARK: - Push Notifications
  342. func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
  343. completionHandler(UNNotificationPresentationOptions.alert)
  344. }
  345. func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
  346. completionHandler()
  347. }
  348. func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
  349. NCNetworking.shared.checkPushNotificationServerProxyCertificateUntrusted(viewController: self.window?.rootViewController) { errorCode in
  350. if errorCode == 0 {
  351. NCPushNotification.shared().registerForRemoteNotifications(withDeviceToken: deviceToken)
  352. }
  353. }
  354. }
  355. func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
  356. NCPushNotification.shared().applicationdidReceiveRemoteNotification(userInfo) { result in
  357. completionHandler(result)
  358. }
  359. }
  360. // MARK: - Login & checkErrorNetworking
  361. @objc func openLogin(viewController: UIViewController?, selector: Int, openLoginWeb: Bool) {
  362. // use appConfig [MDM]
  363. if NCBrandOptions.shared.use_configuration {
  364. if activeAppConfigView?.view.window == nil {
  365. activeAppConfigView = UIStoryboard(name: "NCLogin", bundle: nil).instantiateViewController(withIdentifier: "NCAppConfigView") as? NCAppConfigView
  366. showLoginViewController(activeAppConfigView, contextViewController: viewController)
  367. }
  368. return
  369. }
  370. // only for personalized LoginWeb [customer]
  371. if NCBrandOptions.shared.use_login_web_personalized {
  372. if activeLoginWeb?.view.window == nil {
  373. activeLoginWeb = UIStoryboard(name: "NCLogin", bundle: nil).instantiateViewController(withIdentifier: "NCLoginWeb") as? NCLoginWeb
  374. activeLoginWeb?.urlBase = NCBrandOptions.shared.loginBaseUrl
  375. showLoginViewController(activeLoginWeb, contextViewController: viewController)
  376. }
  377. return
  378. }
  379. // Nextcloud standard login
  380. if selector == NCGlobal.shared.introSignup {
  381. if activeLoginWeb?.view.window == nil {
  382. activeLoginWeb = UIStoryboard(name: "NCLogin", bundle: nil).instantiateViewController(withIdentifier: "NCLoginWeb") as? NCLoginWeb
  383. if selector == NCGlobal.shared.introSignup {
  384. activeLoginWeb?.urlBase = NCBrandOptions.shared.linkloginPreferredProviders
  385. } else {
  386. activeLoginWeb?.urlBase = self.urlBase
  387. }
  388. showLoginViewController(activeLoginWeb, contextViewController: viewController)
  389. }
  390. } else if NCBrandOptions.shared.disable_intro && NCBrandOptions.shared.disable_request_login_url {
  391. if activeLoginWeb?.view.window == nil {
  392. activeLoginWeb = UIStoryboard(name: "NCLogin", bundle: nil).instantiateViewController(withIdentifier: "NCLoginWeb") as? NCLoginWeb
  393. activeLoginWeb?.urlBase = NCBrandOptions.shared.loginBaseUrl
  394. showLoginViewController(activeLoginWeb, contextViewController: viewController)
  395. }
  396. } else if openLoginWeb {
  397. if activeLoginWeb?.view.window == nil {
  398. activeLoginWeb = UIStoryboard(name: "NCLogin", bundle: nil).instantiateViewController(withIdentifier: "NCLoginWeb") as? NCLoginWeb
  399. activeLoginWeb?.urlBase = urlBase
  400. showLoginViewController(activeLoginWeb, contextViewController: viewController)
  401. }
  402. } else {
  403. if activeLogin?.view.window == nil {
  404. activeLogin = UIStoryboard(name: "NCLogin", bundle: nil).instantiateViewController(withIdentifier: "NCLogin") as? NCLogin
  405. showLoginViewController(activeLogin, contextViewController: viewController)
  406. }
  407. }
  408. }
  409. func showLoginViewController(_ viewController: UIViewController?, contextViewController: UIViewController?) {
  410. if contextViewController == nil {
  411. if let viewController = viewController {
  412. let navigationController = NCLoginNavigationController.init(rootViewController: viewController)
  413. navigationController.navigationBar.barStyle = .black
  414. navigationController.navigationBar.tintColor = NCBrandColor.shared.customerText
  415. navigationController.navigationBar.barTintColor = NCBrandColor.shared.customer
  416. navigationController.navigationBar.isTranslucent = false
  417. window?.rootViewController = navigationController
  418. window?.makeKeyAndVisible()
  419. }
  420. } else if contextViewController is UINavigationController {
  421. if let contextViewController = contextViewController, let viewController = viewController {
  422. (contextViewController as! UINavigationController).pushViewController(viewController, animated: true)
  423. }
  424. } else {
  425. if let viewController = viewController, let contextViewController = contextViewController {
  426. let navigationController = NCLoginNavigationController.init(rootViewController: viewController)
  427. navigationController.modalPresentationStyle = .fullScreen
  428. navigationController.navigationBar.barStyle = .black
  429. navigationController.navigationBar.tintColor = NCBrandColor.shared.customerText
  430. navigationController.navigationBar.barTintColor = NCBrandColor.shared.customer
  431. navigationController.navigationBar.isTranslucent = false
  432. contextViewController.present(navigationController, animated: true) { }
  433. }
  434. }
  435. }
  436. @objc func startTimerErrorNetworking() {
  437. timerErrorNetworking = Timer.scheduledTimer(timeInterval: 3, target: self, selector: #selector(checkErrorNetworking), userInfo: nil, repeats: true)
  438. }
  439. @objc private func checkErrorNetworking() {
  440. // check unauthorized server (401/403)
  441. if account != "" && CCUtility.getPassword(account)!.count == 0 {
  442. openLogin(viewController: window?.rootViewController, selector: NCGlobal.shared.introLogin, openLoginWeb: true)
  443. }
  444. }
  445. func trustCertificateError(host: String) {
  446. guard let currentHost = URL(string: self.urlBase)?.host,
  447. let pushNotificationServerProxyHost = URL(string: NCBrandOptions.shared.pushNotificationServerProxy)?.host,
  448. host != pushNotificationServerProxyHost,
  449. host == currentHost
  450. else { return }
  451. let certificateHostSavedPath = CCUtility.getDirectoryCerificates()! + "/" + host + ".der"
  452. var title = NSLocalizedString("_ssl_certificate_changed_", comment: "")
  453. if !FileManager.default.fileExists(atPath: certificateHostSavedPath) {
  454. title = NSLocalizedString("_connect_server_anyway_", comment: "")
  455. }
  456. let alertController = UIAlertController(title: title, message: NSLocalizedString("_server_is_trusted_", comment: ""), preferredStyle: .alert)
  457. alertController.addAction(UIAlertAction(title: NSLocalizedString("_yes_", comment: ""), style: .default, handler: { action in
  458. NCNetworking.shared.writeCertificate(host: host)
  459. }))
  460. alertController.addAction(UIAlertAction(title: NSLocalizedString("_no_", comment: ""), style: .default, handler: { action in }))
  461. alertController.addAction(UIAlertAction(title: NSLocalizedString("_certificate_details_", comment: ""), style: .default, handler: { action in
  462. if let navigationController = UIStoryboard(name: "NCViewCertificateDetails", bundle: nil).instantiateInitialViewController() as? UINavigationController {
  463. let viewController = navigationController.topViewController as! NCViewCertificateDetails
  464. viewController.delegate = self
  465. viewController.host = host
  466. self.window?.rootViewController?.present(navigationController, animated: true)
  467. }
  468. }))
  469. window?.rootViewController?.present(alertController, animated: true)
  470. }
  471. func viewCertificateDetailsDismiss(host: String) {
  472. trustCertificateError(host: host)
  473. }
  474. // MARK: - Account
  475. @objc func settingAccount(_ account: String, urlBase: String, user: String, userId: String, password: String) {
  476. self.account = account
  477. self.urlBase = urlBase
  478. self.user = user
  479. self.userId = userId
  480. self.password = password
  481. _ = NCFunctionCenter.shared
  482. NCCommunicationCommon.shared.setup(account: account, user: user, userId: userId, password: password, urlBase: urlBase)
  483. NCCommunicationCommon.shared.setup(webDav: NCUtilityFileSystem.shared.getWebDAV(account: account))
  484. let serverVersionMajor = NCManageDatabase.shared.getCapabilitiesServerInt(account: account, elements: NCElementsJSON.shared.capabilitiesVersionMajor)
  485. if serverVersionMajor > 0 {
  486. NCCommunicationCommon.shared.setup(nextcloudVersion: serverVersionMajor)
  487. }
  488. NCKTVHTTPCache.shared.restartProxy(user: user, password: password)
  489. }
  490. @objc func deleteAccount(_ account: String, wipe: Bool) {
  491. if let account = NCManageDatabase.shared.getAccount(predicate: NSPredicate(format: "account == %@", account)) {
  492. NCPushNotification.shared().unsubscribingNextcloudServerPushNotification(account.account, urlBase: account.urlBase, user: account.user, withSubscribing: false)
  493. }
  494. let results = NCManageDatabase.shared.getTableLocalFiles(predicate: NSPredicate(format: "account == %@", account), sorted: "ocId", ascending: false)
  495. for result in results {
  496. CCUtility.removeFile(atPath: CCUtility.getDirectoryProviderStorageOcId(result.ocId))
  497. }
  498. NCManageDatabase.shared.clearDatabase(account: account, removeAccount: true)
  499. CCUtility.clearAllKeysEnd(toEnd: account)
  500. CCUtility.clearAllKeysPushNotification(account)
  501. CCUtility.setPassword(account, password: nil)
  502. if wipe {
  503. settingAccount("", urlBase: "", user: "", userId: "", password: "")
  504. let accounts = NCManageDatabase.shared.getAccounts()
  505. if accounts?.count ?? 0 > 0 {
  506. if let newAccount = accounts?.first {
  507. self.changeAccount(newAccount)
  508. }
  509. } else {
  510. openLogin(viewController: window?.rootViewController, selector: NCGlobal.shared.introLogin, openLoginWeb: false)
  511. }
  512. }
  513. }
  514. @objc func changeAccount(_ account: String) {
  515. NCManageDatabase.shared.setAccountActive(account)
  516. if let tableAccount = NCManageDatabase.shared.getActiveAccount() {
  517. NCOperationQueue.shared.cancelAllQueue()
  518. NCNetworking.shared.cancelAllTask()
  519. settingAccount(tableAccount.account, urlBase: tableAccount.urlBase, user: tableAccount.user, userId: tableAccount.userId, password: CCUtility.getPassword(tableAccount.account))
  520. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterInitialize)
  521. }
  522. }
  523. // MARK: - Account Request
  524. func accountRequestChangeAccount(account: String) {
  525. changeAccount(account)
  526. }
  527. func requestAccount() {
  528. if isPasscodePresented() { return }
  529. if !CCUtility.getAccountRequest() { return }
  530. let accounts = NCManageDatabase.shared.getAllAccount()
  531. if accounts.count > 1 {
  532. if let vcAccountRequest = UIStoryboard(name: "NCAccountRequest", bundle: nil).instantiateInitialViewController() as? NCAccountRequest {
  533. vcAccountRequest.activeAccount = NCManageDatabase.shared.getActiveAccount()
  534. vcAccountRequest.accounts = accounts
  535. vcAccountRequest.enableTimerProgress = true
  536. vcAccountRequest.enableAddAccount = false
  537. vcAccountRequest.dismissDidEnterBackground = false
  538. vcAccountRequest.delegate = self
  539. let screenHeighMax = UIScreen.main.bounds.height - (UIScreen.main.bounds.height/5)
  540. let numberCell = accounts.count
  541. let height = min(CGFloat(numberCell * Int(vcAccountRequest.heightCell) + 45), screenHeighMax)
  542. let popup = NCPopupViewController(contentController: vcAccountRequest, popupWidth: 300, popupHeight: height+20)
  543. popup.backgroundAlpha = 0.8
  544. UIApplication.shared.keyWindow?.rootViewController?.present(popup, animated: true)
  545. vcAccountRequest.startTimer()
  546. }
  547. }
  548. }
  549. // MARK: - Passcode
  550. func presentPasscode(completion: @escaping () -> ()) {
  551. let laContext = LAContext()
  552. var error: NSError?
  553. defer { self.requestAccount() }
  554. let presentedViewController = window?.rootViewController?.presentedViewController
  555. guard !account.isEmpty, CCUtility.isPasscodeAtStartEnabled(), !(presentedViewController is NCLoginNavigationController) else { return }
  556. // Make sure we have a privacy window (in case it's not enabled)
  557. showPrivacyProtectionWindow()
  558. let passcodeViewController = TOPasscodeViewController(passcodeType: .sixDigits, allowCancel: false)
  559. passcodeViewController.delegate = self
  560. passcodeViewController.keypadButtonShowLettering = false
  561. if CCUtility.getEnableTouchFaceID() && laContext.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error) {
  562. if error == nil {
  563. if laContext.biometryType == .faceID {
  564. passcodeViewController.biometryType = .faceID
  565. } else if laContext.biometryType == .touchID {
  566. passcodeViewController.biometryType = .touchID
  567. }
  568. passcodeViewController.allowBiometricValidation = true
  569. passcodeViewController.automaticallyPromptForBiometricValidation = false
  570. }
  571. }
  572. // show passcode on top of privacy window
  573. privacyProtectionWindow?.rootViewController?.present(passcodeViewController, animated: true, completion: {
  574. completion()
  575. })
  576. }
  577. func isPasscodePresented() -> Bool {
  578. return privacyProtectionWindow?.rootViewController?.presentedViewController is TOPasscodeViewController
  579. }
  580. func enableTouchFaceID() {
  581. guard !account.isEmpty,
  582. CCUtility.getEnableTouchFaceID(),
  583. CCUtility.isPasscodeAtStartEnabled(),
  584. let passcodeViewController = privacyProtectionWindow?.rootViewController?.presentedViewController as? TOPasscodeViewController
  585. else { return }
  586. LAContext().evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: NCBrandOptions.shared.brand) { (success, error) in
  587. if success {
  588. DispatchQueue.main.async {
  589. passcodeViewController.dismiss(animated: true) {
  590. self.hidePrivacyProtectionWindow()
  591. self.requestAccount()
  592. }
  593. }
  594. }
  595. }
  596. }
  597. func didInputCorrectPasscode(in passcodeViewController: TOPasscodeViewController) {
  598. DispatchQueue.main.async {
  599. passcodeViewController.dismiss(animated: true) {
  600. self.hidePrivacyProtectionWindow()
  601. self.requestAccount()
  602. }
  603. }
  604. }
  605. func passcodeViewController(_ passcodeViewController: TOPasscodeViewController, isCorrectCode code: String) -> Bool {
  606. return code == CCUtility.getPasscode()
  607. }
  608. func didPerformBiometricValidationRequest(in passcodeViewController: TOPasscodeViewController) {
  609. enableTouchFaceID()
  610. }
  611. // MARK: - Privacy Protection
  612. private func showPrivacyProtectionWindow() {
  613. guard privacyProtectionWindow == nil else {
  614. privacyProtectionWindow?.isHidden = false
  615. return
  616. }
  617. privacyProtectionWindow = UIWindow(frame: UIScreen.main.bounds)
  618. let storyboard = UIStoryboard(name: "LaunchScreen", bundle: nil)
  619. let initialViewController = storyboard.instantiateInitialViewController()
  620. self.privacyProtectionWindow?.rootViewController = initialViewController
  621. privacyProtectionWindow?.windowLevel = .alert + 1
  622. privacyProtectionWindow?.makeKeyAndVisible()
  623. }
  624. func hidePrivacyProtectionWindow() {
  625. guard !(privacyProtectionWindow?.rootViewController?.presentedViewController is TOPasscodeViewController) else { return }
  626. UIWindow.animate(withDuration: 0.25) {
  627. self.privacyProtectionWindow?.alpha = 0
  628. } completion: { _ in
  629. self.privacyProtectionWindow?.isHidden = true
  630. self.privacyProtectionWindow = nil
  631. }
  632. }
  633. // MARK: - Open URL
  634. func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool {
  635. if account == "" { return false }
  636. let scheme = url.scheme
  637. let action = url.host
  638. var fileName: String = ""
  639. var serverUrl: String = ""
  640. var matchedAccount: tableAccount?
  641. if scheme == "nextcloud" && action == "open-file" {
  642. if let urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false) {
  643. let queryItems = urlComponents.queryItems
  644. guard let userScheme = CCUtility.value(forKey: "user", fromQueryItems: queryItems) else { return false }
  645. guard let pathScheme = CCUtility.value(forKey: "path", fromQueryItems: queryItems) else { return false }
  646. guard let linkScheme = CCUtility.value(forKey: "link", fromQueryItems: queryItems) else { return false }
  647. if let activeAccount = NCManageDatabase.shared.getActiveAccount() {
  648. let urlBase = URL(string: activeAccount.urlBase)
  649. let user = activeAccount.user
  650. if linkScheme.contains(urlBase?.host ?? "") && userScheme == user {
  651. matchedAccount = activeAccount
  652. } else {
  653. let accounts = NCManageDatabase.shared.getAllAccount()
  654. for account in accounts {
  655. guard let accountURL = URL(string: account.urlBase) else { return false }
  656. if linkScheme.contains(accountURL.host ?? "") && userScheme == account.user {
  657. changeAccount(account.account)
  658. matchedAccount = account
  659. break
  660. }
  661. }
  662. }
  663. if matchedAccount != nil {
  664. let webDAV = NCUtilityFileSystem.shared.getWebDAV(account: self.account) + "/files/" + self.userId
  665. if pathScheme.contains("/") {
  666. fileName = (pathScheme as NSString).lastPathComponent
  667. serverUrl = matchedAccount!.urlBase + "/" + webDAV + "/" + (pathScheme as NSString).deletingLastPathComponent
  668. } else {
  669. fileName = pathScheme
  670. serverUrl = matchedAccount!.urlBase + "/" + webDAV
  671. }
  672. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  673. NCFunctionCenter.shared.openFileViewInFolder(viewController: self.activeViewController, serverUrl: serverUrl, fileNameBlink: fileName)
  674. }
  675. } else {
  676. guard let domain = URL(string: linkScheme)?.host else { return true }
  677. fileName = (pathScheme as NSString).lastPathComponent
  678. let message = String(format: NSLocalizedString("_account_not_available_", comment: ""), userScheme, domain, fileName)
  679. let alertController = UIAlertController(title: NSLocalizedString("_info_", comment: ""), message: message, preferredStyle: .alert)
  680. alertController.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { _ in }))
  681. window?.rootViewController?.present(alertController, animated: true, completion: { })
  682. return false
  683. }
  684. }
  685. }
  686. }
  687. return true
  688. }
  689. }
  690. // MARK: - NCAudioRecorder ViewController Delegate
  691. extension AppDelegate: NCAudioRecorderViewControllerDelegate {
  692. func didFinishRecording(_ viewController: NCAudioRecorderViewController, fileName: String) {
  693. guard
  694. let navigationController = UIStoryboard(name: "NCCreateFormUploadVoiceNote", bundle: nil).instantiateInitialViewController() as? UINavigationController,
  695. let viewController = navigationController.topViewController as? NCCreateFormUploadVoiceNote
  696. else { return }
  697. navigationController.modalPresentationStyle = .formSheet
  698. viewController.setup(serverUrl: activeServerUrl, fileNamePath: NSTemporaryDirectory() + fileName, fileName: fileName)
  699. window?.rootViewController?.present(navigationController, animated: true)
  700. }
  701. func didFinishWithoutRecording(_ viewController: NCAudioRecorderViewController, fileName: String) {
  702. }
  703. }
  704. extension AppDelegate: NCCreateFormUploadConflictDelegate {
  705. func dismissCreateFormUploadConflict(metadatas: [tableMetadata]?) {
  706. guard let metadatas = metadatas, !metadatas.isEmpty else { return }
  707. networkingProcessUpload?.createProcessUploads(metadatas: metadatas)
  708. }
  709. }