AppDelegate.swift 34 KB

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