AppDelegate.swift 37 KB

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