AppDelegate.swift 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754
  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
  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 introViewController = UIStoryboard(name: "NCIntro", bundle: nil).instantiateInitialViewController() {
  141. let navController = UINavigationController(rootViewController: introViewController)
  142. window?.rootViewController = navController
  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. // L' applicazione entrerà in primo piano (attivo sempre)
  170. func applicationDidBecomeActive(_ application: UIApplication) {
  171. NCSettingsBundleHelper.setVersionAndBuildNumber()
  172. if account == "" { return}
  173. NCNetworking.shared.verifyUploadZombie()
  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(notification: NSNotification) {
  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: "CCLogin", 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: "CCLogin", 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: "CCLogin", 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: "CCLogin", 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: "CCLogin", 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: "CCLogin", bundle: nil).instantiateViewController(withIdentifier: "CCLogin") as? CCLogin
  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.getPasscode()?.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 & Communication
  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. _ = NCNetworkingNotificationCenter.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. // Push Notification
  449. if let account = NCManageDatabase.shared.getAccount(predicate: NSPredicate(format: "account == %@", account)) {
  450. NCPushNotification.shared().unsubscribingNextcloudServerPushNotification(account.account, urlBase: account.urlBase, user: account.user, withSubscribing: false)
  451. }
  452. settingAccount("", urlBase: "", user: "", userId: "", password: "")
  453. let results = NCManageDatabase.shared.getTableLocalFiles(predicate: NSPredicate(format: "account == %@", account), sorted: "ocId", ascending: false)
  454. for result in results {
  455. CCUtility.removeFile(atPath: CCUtility.getDirectoryProviderStorageOcId(result.ocId))
  456. }
  457. NCManageDatabase.shared.clearDatabase(account: account, removeAccount: true)
  458. CCUtility.clearAllKeysEnd(toEnd: account)
  459. CCUtility.clearAllKeysPushNotification(account)
  460. CCUtility.setCertificateError(account, error: false)
  461. CCUtility.setPassword(account, password: nil)
  462. if wipe {
  463. let accounts = NCManageDatabase.shared.getAccounts()
  464. if accounts?.count ?? 0 > 0 {
  465. if let newAccount = accounts?.first {
  466. if let account = NCManageDatabase.shared.setAccountActive(newAccount) {
  467. settingAccount(account.account, urlBase: account.urlBase, user: account.user, userId: account.userId, password: CCUtility.getPassword(account.account))
  468. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterInitializeMain)
  469. }
  470. }
  471. } else {
  472. openLogin(viewController: window?.rootViewController, selector: NCGlobal.shared.introLogin, openLoginWeb: false)
  473. }
  474. }
  475. }
  476. // MARK: - TOPasscodeViewController
  477. func passcodeWithAutomaticallyPromptForBiometricValidation(_ automaticallyPromptForBiometricValidation: Bool) {
  478. let laContext = LAContext()
  479. var error: NSError?
  480. guard let passcode = CCUtility.getPasscode() else { return }
  481. if passcode.count == 0 || account == "" || CCUtility.getNotPasscodeAtStart() { return }
  482. if passcodeViewController == nil {
  483. passcodeViewController = TOPasscodeViewController.init(style: .translucentLight, passcodeType: .sixDigits)
  484. if #available(iOS 13.0, *) {
  485. if UITraitCollection.current.userInterfaceStyle == .dark {
  486. passcodeViewController?.style = .translucentDark
  487. }
  488. }
  489. passcodeViewController?.delegate = self
  490. passcodeViewController?.keypadButtonShowLettering = false
  491. if CCUtility.getEnableTouchFaceID() && laContext.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error) {
  492. if error == nil {
  493. if laContext.biometryType == .faceID {
  494. passcodeViewController?.biometryType = .faceID
  495. passcodeViewController?.allowBiometricValidation = true
  496. } else if laContext.biometryType == .touchID {
  497. passcodeViewController?.biometryType = .touchID
  498. passcodeViewController?.allowBiometricValidation = true
  499. }
  500. }
  501. }
  502. if let passcodeViewController = self.passcodeViewController {
  503. window?.rootViewController?.present(passcodeViewController, animated: true, completion: {
  504. self.enableTouchFaceID(automaticallyPromptForBiometricValidation)
  505. })
  506. }
  507. } else {
  508. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  509. self.enableTouchFaceID(automaticallyPromptForBiometricValidation)
  510. }
  511. }
  512. }
  513. func didInputCorrectPasscode(in passcodeViewController: TOPasscodeViewController) {
  514. passcodeViewController.dismiss(animated: true) {
  515. self.passcodeViewController = nil
  516. }
  517. }
  518. func passcodeViewController(_ passcodeViewController: TOPasscodeViewController, isCorrectCode code: String) -> Bool {
  519. return code == CCUtility.getPasscode()
  520. }
  521. func didPerformBiometricValidationRequest(in passcodeViewController: TOPasscodeViewController) {
  522. LAContext().evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: NCBrandOptions.shared.brand) { (success, error) in
  523. if success {
  524. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  525. passcodeViewController.dismiss(animated: true) {
  526. self.passcodeViewController = nil
  527. }
  528. }
  529. }
  530. }
  531. }
  532. func enableTouchFaceID(_ automaticallyPromptForBiometricValidation: Bool) {
  533. if CCUtility.getEnableTouchFaceID() && automaticallyPromptForBiometricValidation && passcodeViewController?.view.window != nil {
  534. LAContext().evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: NCBrandOptions.shared.brand) { (success, error) in
  535. if success {
  536. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  537. self.passcodeViewController?.dismiss(animated: true) {
  538. self.passcodeViewController = nil
  539. }
  540. }
  541. }
  542. }
  543. }
  544. }
  545. // MARK: - OpenURL
  546. func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
  547. if account == "" { return false }
  548. let scheme = url.scheme
  549. let action = url.host
  550. var fileName: String = ""
  551. var serverUrl: String = ""
  552. var matchedAccount: tableAccount?
  553. if scheme == "nextcloud" && action == "open-file" {
  554. if let urlComponents = URLComponents.init(url: url, resolvingAgainstBaseURL: false) {
  555. let queryItems = urlComponents.queryItems
  556. guard let userScheme = CCUtility.value(forKey: "user", fromQueryItems: queryItems) else { return false }
  557. guard let pathScheme = CCUtility.value(forKey: "path", fromQueryItems: queryItems) else { return false }
  558. guard let linkScheme = CCUtility.value(forKey: "link", fromQueryItems: queryItems) else { return false }
  559. if let account = NCManageDatabase.shared.getAccountActive() {
  560. let urlBase = URL(string: account.urlBase)
  561. let user = account.user
  562. if linkScheme.contains(urlBase?.host ?? "") && userScheme == user {
  563. matchedAccount = account
  564. } else {
  565. let accounts = NCManageDatabase.shared.getAllAccount()
  566. for account in accounts {
  567. guard let accountURL = URL(string: account.urlBase) else { return false }
  568. if linkScheme.contains(accountURL.host ?? "") && userScheme == account.user {
  569. NCManageDatabase.shared.setAccountActive(account.account)
  570. guard let password = CCUtility.getPassword(account.account) else { return false }
  571. settingAccount(account.account, urlBase: account.urlBase, user: account.user, userId: account.userId, password: password)
  572. matchedAccount = account
  573. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterInitializeMain)
  574. }
  575. }
  576. }
  577. if matchedAccount != nil {
  578. let webDAV = NCUtilityFileSystem.shared.getWebDAV(account: account.account)
  579. if pathScheme.contains("/") {
  580. fileName = (pathScheme as NSString).lastPathComponent
  581. serverUrl = matchedAccount!.urlBase + "/" + webDAV + "/" + (pathScheme as NSString).deletingLastPathComponent
  582. } else {
  583. fileName = pathScheme
  584. serverUrl = matchedAccount!.urlBase + "/" + webDAV
  585. }
  586. NCCollectionCommon.shared.openFileViewInFolder(serverUrl: serverUrl, fileName: fileName)
  587. } else {
  588. guard let domain = URL(string: linkScheme)?.host else { return true }
  589. fileName = (pathScheme as NSString).lastPathComponent
  590. let message = String(format: NSLocalizedString("_account_not_available_", comment: ""), userScheme, domain, fileName)
  591. let alertController = UIAlertController(title: NSLocalizedString("_info_", comment: ""), message: message, preferredStyle: .alert)
  592. alertController.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { _ in }))
  593. window?.rootViewController?.present(alertController, animated: true, completion: { })
  594. return false
  595. }
  596. }
  597. }
  598. }
  599. return true
  600. }
  601. }