AppDelegate.swift 38 KB

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