AppDelegate.swift 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757
  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 activeFavorite: NCFavorite?
  40. var activeFiles: NCFiles?
  41. var activeFileViewInFolder: NCFileViewInFolder?
  42. @objc var activeLogin: CCLogin?
  43. var activeLoginWeb: NCLoginWeb?
  44. @objc var activeMedia: NCMedia?
  45. var activeMore: NCMore?
  46. var activeOffline: NCOffline?
  47. var activeRecent: NCRecent?
  48. var activeServerUrl: String = ""
  49. var activeShares: NCShares?
  50. var activeTransfers: NCTransfers?
  51. var activeTrash: NCTrash?
  52. var activeViewController: UIViewController?
  53. var activeViewerVideo: NCViewerVideo?
  54. var listFilesVC: [String:NCFiles] = [:]
  55. var listFavoriteVC: [String:NCFavorite] = [:]
  56. var listOfflineVC: [String:NCOffline] = [:]
  57. var listProgress: [String:NCGlobal.progressType] = [:]
  58. var disableSharesView: Bool = false
  59. var documentPickerViewController: NCDocumentPickerViewController?
  60. var networkingAutoUpload: NCNetworkingAutoUpload?
  61. var passcodeViewController: TOPasscodeViewController?
  62. var pasteboardOcIds: [String] = []
  63. var shares: [tableShare] = []
  64. @objc var timerErrorNetworking: Timer?
  65. func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
  66. let userAgent = CCUtility.getUserAgent() as String
  67. let isSimulatorOrTestFlight = NCUtility.shared.isSimulatorOrTestFlight()
  68. let versionNextcloudiOS = String(format: NCBrandOptions.shared.textCopyrightNextcloudiOS, NCUtility.shared.getVersionApp())
  69. UserDefaults.standard.register(defaults: ["UserAgent" : userAgent])
  70. if !CCUtility.getDisableCrashservice() && !NCBrandOptions.shared.disable_crash_service {
  71. FirebaseApp.configure()
  72. }
  73. CCUtility.createDirectoryStandard()
  74. CCUtility.emptyTemporaryDirectory()
  75. NCCommunicationCommon.shared.setup(delegate: NCNetworking.shared)
  76. NCCommunicationCommon.shared.setup(userAgent: userAgent)
  77. startTimerErrorNetworking()
  78. // LOG
  79. let levelLog = CCUtility.getLogLevel()
  80. NCCommunicationCommon.shared.levelLog = levelLog
  81. if let pathDirectoryGroup = CCUtility.getDirectoryGroup()?.path {
  82. NCCommunicationCommon.shared.pathLog = pathDirectoryGroup
  83. }
  84. NCCommunicationCommon.shared.copyLogToDocumentDirectory = true
  85. if isSimulatorOrTestFlight {
  86. NCCommunicationCommon.shared.writeLog("Start session with level \(levelLog) " + versionNextcloudiOS + " (Simulator / TestFlight)")
  87. } else {
  88. NCCommunicationCommon.shared.writeLog("Start session with level \(levelLog) " + versionNextcloudiOS)
  89. }
  90. if let resultActiveAccount = NCManageDatabase.shared.getAccountActive() {
  91. // FIX 3.0.5 lost urlbase
  92. if resultActiveAccount.urlBase.count == 0 {
  93. let user = resultActiveAccount.user + " "
  94. let urlBase = resultActiveAccount.account.replacingOccurrences(of: user, with: "")
  95. resultActiveAccount.urlBase = urlBase
  96. NCManageDatabase.shared.updateAccount(resultActiveAccount)
  97. }
  98. settingAccount(resultActiveAccount.account, urlBase: resultActiveAccount.urlBase, user: resultActiveAccount.user, userId: resultActiveAccount.userId, password: CCUtility.getPassword(resultActiveAccount.account))
  99. } else {
  100. CCUtility.deleteAllChainStore()
  101. if let bundleID = Bundle.main.bundleIdentifier {
  102. UserDefaults.standard.removePersistentDomain(forName: bundleID)
  103. }
  104. }
  105. // Push Notification & display notification
  106. application.registerForRemoteNotifications()
  107. UNUserNotificationCenter.current().delegate = self
  108. UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { (_, _) in }
  109. // AV
  110. do {
  111. try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default)
  112. try AVAudioSession.sharedInstance().setActive(true)
  113. } catch {
  114. print(error)
  115. }
  116. application.beginReceivingRemoteControlEvents()
  117. // Store review
  118. if !NCUtility.shared.isSimulatorOrTestFlight() {
  119. let review = NCStoreReview()
  120. review.incrementAppRuns()
  121. review.showStoreReview()
  122. }
  123. // Detect Dark mode
  124. if #available(iOS 13.0, *) {
  125. if CCUtility.getDarkModeDetect() {
  126. if UITraitCollection.current.userInterfaceStyle == .dark {
  127. CCUtility.setDarkMode(true)
  128. } else {
  129. CCUtility.setDarkMode(false)
  130. }
  131. }
  132. }
  133. if NCBrandOptions.shared.disable_intro {
  134. CCUtility.setIntro(true)
  135. if account == "" {
  136. openLogin(viewController: nil, selector: NCGlobal.shared.introLogin, openLoginWeb: false)
  137. }
  138. } else {
  139. if !CCUtility.getIntro() {
  140. if let viewController = UIStoryboard(name: "NCIntro", bundle: nil).instantiateInitialViewController() {
  141. let navigationController = UINavigationController(rootViewController: viewController)
  142. window?.rootViewController = navigationController
  143. window?.makeKeyAndVisible()
  144. }
  145. }
  146. }
  147. // init home
  148. NotificationCenter.default.addObserver(self, selector: #selector(initializeMain(notification:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterInitializeMain), object: nil)
  149. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterInitializeMain)
  150. // Passcode
  151. DispatchQueue.main.async {
  152. self.passcodeWithAutomaticallyPromptForBiometricValidation(true)
  153. }
  154. // Auto upload
  155. networkingAutoUpload = NCNetworkingAutoUpload.init()
  156. // Background task: register
  157. if #available(iOS 13.0, *) {
  158. BGTaskScheduler.shared.register(forTaskWithIdentifier: NCGlobal.shared.refreshTask, using: nil) { task in
  159. self.handleRefreshTask(task)
  160. }
  161. BGTaskScheduler.shared.register(forTaskWithIdentifier: NCGlobal.shared.processingTask, using: nil) { task in
  162. self.handleProcessingTask(task)
  163. }
  164. } else {
  165. application.setMinimumBackgroundFetchInterval(UIApplication.backgroundFetchIntervalMinimum)
  166. }
  167. return true
  168. }
  169. // MARK: - Life Cycle
  170. // L' applicazione entrerà in primo piano (attivo sempre)
  171. func applicationDidBecomeActive(_ application: UIApplication) {
  172. NCSettingsBundleHelper.setVersionAndBuildNumber()
  173. if account == "" { return}
  174. NCNetworking.shared.verifyUploadZombie()
  175. }
  176. // L' applicazione entrerà in primo piano (attivo solo dopo il background)
  177. func applicationWillEnterForeground(_ application: UIApplication) {
  178. if account == "" { return}
  179. NCCommunicationCommon.shared.writeLog("Application will enter in foreground")
  180. // Request Passcode
  181. passcodeWithAutomaticallyPromptForBiometricValidation(true)
  182. // Initialize Auto upload
  183. NCAutoUpload.shared.initAutoUpload(viewController: nil) { (_) in }
  184. // Required unsubscribing / subscribing
  185. NCPushNotification.shared().pushNotification()
  186. // Request Service Server Nextcloud
  187. NCService.shared.startRequestServicesServer()
  188. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterApplicationWillEnterForeground)
  189. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterRichdocumentGrabFocus)
  190. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterReloadDataSourceNetworkForced)
  191. }
  192. // L' applicazione si dimetterà dallo stato di attivo
  193. func applicationWillResignActive(_ application: UIApplication) {
  194. if account == "" { return}
  195. // Dismiss FileViewInFolder
  196. if activeFileViewInFolder != nil {
  197. activeFileViewInFolder?.dismiss(animated: false, completion: {
  198. self.activeFileViewInFolder = nil
  199. })
  200. }
  201. }
  202. // L' applicazione è entrata nello sfondo
  203. func applicationDidEnterBackground(_ application: UIApplication) {
  204. if account == "" { return}
  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 initializeMain(notification: NSNotification) {
  219. if account == "" { return}
  220. NCCommunicationCommon.shared.writeLog("initialize Main")
  221. // Clear error certificate
  222. CCUtility.setCertificateError(account, error: false)
  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: "CCLogin", 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: "CCLogin", 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: "CCLogin", 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: "CCLogin", 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: "CCLogin", 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: "CCLogin", bundle: nil).instantiateViewController(withIdentifier: "CCLogin") as? CCLogin
  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)
  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(directoryCertificate: CCUtility.getDirectoryCerificates())
  422. self.startTimerErrorNetworking()
  423. }))
  424. alertController.addAction(UIAlertAction(title: NSLocalizedString("_no_", comment: ""), style: .default, handler: { action in
  425. self.startTimerErrorNetworking()
  426. }))
  427. window?.rootViewController?.present(alertController, animated: true, completion: {
  428. self.timerErrorNetworking?.invalidate()
  429. })
  430. }
  431. }
  432. // MARK: - Account & Communication
  433. @objc func settingAccount(_ account: String, urlBase: String, user: String, userId: String, password: String) {
  434. self.account = account
  435. self.urlBase = urlBase
  436. self.user = user
  437. self.userId = userId
  438. self.password = password
  439. _ = NCNetworkingNotificationCenter.shared
  440. NCCommunicationCommon.shared.setup(account: account, user: user, userId: userId, password: password, urlBase: urlBase)
  441. NCCommunicationCommon.shared.setup(webDav: NCUtilityFileSystem.shared.getWebDAV(account: account))
  442. NCCommunicationCommon.shared.setup(dav: NCUtilityFileSystem.shared.getDAV())
  443. let serverVersionMajor = NCManageDatabase.shared.getCapabilitiesServerInt(account: account, elements: NCElementsJSON.shared.capabilitiesVersionMajor)
  444. if serverVersionMajor > 0 {
  445. NCCommunicationCommon.shared.setup(nextcloudVersion: serverVersionMajor)
  446. }
  447. }
  448. @objc func deleteAccount(_ account: String, wipe: Bool) {
  449. // Push Notification
  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.setCertificateError(account, error: false)
  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.notificationCenterInitializeMain)
  470. }
  471. }
  472. } else {
  473. openLogin(viewController: window?.rootViewController, selector: NCGlobal.shared.introLogin, openLoginWeb: false)
  474. }
  475. }
  476. }
  477. // MARK: - TOPasscodeViewController
  478. func passcodeWithAutomaticallyPromptForBiometricValidation(_ automaticallyPromptForBiometricValidation: Bool) {
  479. let laContext = LAContext()
  480. var error: NSError?
  481. guard let passcode = CCUtility.getPasscode() else { return }
  482. if passcode.count == 0 || account == "" || CCUtility.getNotPasscodeAtStart() { return }
  483. if passcodeViewController == nil {
  484. passcodeViewController = TOPasscodeViewController.init(style: .translucentLight, passcodeType: .sixDigits)
  485. if #available(iOS 13.0, *) {
  486. if UITraitCollection.current.userInterfaceStyle == .dark {
  487. passcodeViewController?.style = .translucentDark
  488. }
  489. }
  490. passcodeViewController?.delegate = self
  491. passcodeViewController?.keypadButtonShowLettering = false
  492. if CCUtility.getEnableTouchFaceID() && laContext.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error) {
  493. if error == nil {
  494. if laContext.biometryType == .faceID {
  495. passcodeViewController?.biometryType = .faceID
  496. passcodeViewController?.allowBiometricValidation = true
  497. } else if laContext.biometryType == .touchID {
  498. passcodeViewController?.biometryType = .touchID
  499. passcodeViewController?.allowBiometricValidation = true
  500. }
  501. }
  502. }
  503. if let passcodeViewController = self.passcodeViewController {
  504. window?.rootViewController?.present(passcodeViewController, animated: true, completion: {
  505. self.enableTouchFaceID(automaticallyPromptForBiometricValidation)
  506. })
  507. }
  508. } else {
  509. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  510. self.enableTouchFaceID(automaticallyPromptForBiometricValidation)
  511. }
  512. }
  513. }
  514. func didInputCorrectPasscode(in passcodeViewController: TOPasscodeViewController) {
  515. passcodeViewController.dismiss(animated: true) {
  516. self.passcodeViewController = nil
  517. }
  518. }
  519. func passcodeViewController(_ passcodeViewController: TOPasscodeViewController, isCorrectCode code: String) -> Bool {
  520. return code == CCUtility.getPasscode()
  521. }
  522. func didPerformBiometricValidationRequest(in passcodeViewController: TOPasscodeViewController) {
  523. LAContext().evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: NCBrandOptions.shared.brand) { (success, error) in
  524. if success {
  525. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  526. passcodeViewController.dismiss(animated: true) {
  527. self.passcodeViewController = nil
  528. }
  529. }
  530. }
  531. }
  532. }
  533. func enableTouchFaceID(_ automaticallyPromptForBiometricValidation: Bool) {
  534. if CCUtility.getEnableTouchFaceID() && automaticallyPromptForBiometricValidation && passcodeViewController?.view.window != nil {
  535. LAContext().evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: NCBrandOptions.shared.brand) { (success, error) in
  536. if success {
  537. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  538. self.passcodeViewController?.dismiss(animated: true) {
  539. self.passcodeViewController = nil
  540. }
  541. }
  542. }
  543. }
  544. }
  545. }
  546. // MARK: - OpenURL
  547. func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
  548. if account == "" { return false }
  549. let scheme = url.scheme
  550. let action = url.host
  551. var fileName: String = ""
  552. var serverUrl: String = ""
  553. var matchedAccount: tableAccount?
  554. if scheme == "nextcloud" && action == "open-file" {
  555. if let urlComponents = URLComponents.init(url: url, resolvingAgainstBaseURL: false) {
  556. let queryItems = urlComponents.queryItems
  557. guard let userScheme = CCUtility.value(forKey: "user", fromQueryItems: queryItems) else { return false }
  558. guard let pathScheme = CCUtility.value(forKey: "path", fromQueryItems: queryItems) else { return false }
  559. guard let linkScheme = CCUtility.value(forKey: "link", fromQueryItems: queryItems) else { return false }
  560. if let account = NCManageDatabase.shared.getAccountActive() {
  561. let urlBase = URL(string: account.urlBase)
  562. let user = account.user
  563. if linkScheme.contains(urlBase?.host ?? "") && userScheme == user {
  564. matchedAccount = account
  565. } else {
  566. let accounts = NCManageDatabase.shared.getAllAccount()
  567. for account in accounts {
  568. guard let accountURL = URL(string: account.urlBase) else { return false }
  569. if linkScheme.contains(accountURL.host ?? "") && userScheme == account.user {
  570. NCManageDatabase.shared.setAccountActive(account.account)
  571. settingAccount(account.account, urlBase: account.urlBase, user: account.user, userId: account.userId, password: CCUtility.getPassword(account.account))
  572. matchedAccount = account
  573. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterInitializeMain)
  574. break
  575. }
  576. }
  577. }
  578. if matchedAccount != nil {
  579. let webDAV = NCUtilityFileSystem.shared.getWebDAV(account: account.account)
  580. if pathScheme.contains("/") {
  581. fileName = (pathScheme as NSString).lastPathComponent
  582. serverUrl = matchedAccount!.urlBase + "/" + webDAV + "/" + (pathScheme as NSString).deletingLastPathComponent
  583. } else {
  584. fileName = pathScheme
  585. serverUrl = matchedAccount!.urlBase + "/" + webDAV
  586. }
  587. NCCollectionCommon.shared.openFileViewInFolder(serverUrl: serverUrl, fileName: fileName)
  588. } else {
  589. guard let domain = URL(string: linkScheme)?.host else { return true }
  590. fileName = (pathScheme as NSString).lastPathComponent
  591. let message = String(format: NSLocalizedString("_account_not_available_", comment: ""), userScheme, domain, fileName)
  592. let alertController = UIAlertController(title: NSLocalizedString("_info_", comment: ""), message: message, preferredStyle: .alert)
  593. alertController.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { _ in }))
  594. window?.rootViewController?.present(alertController, animated: true, completion: { })
  595. return false
  596. }
  597. }
  598. }
  599. }
  600. return true
  601. }
  602. }