AppDelegate.swift 37 KB

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