AppDelegate.swift 42 KB

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