AppDelegate.swift 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632
  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 NextcloudKit
  26. import LocalAuthentication
  27. import Firebase
  28. import WidgetKit
  29. import Queuer
  30. import EasyTipView
  31. import SwiftUI
  32. @UIApplicationMain
  33. class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, NCUserBaseUrl {
  34. var account: String = ""
  35. var urlBase: String = ""
  36. var user: String = ""
  37. var userId: String = ""
  38. var password: String = ""
  39. var tipView: EasyTipView?
  40. var backgroundSessionCompletionHandler: (() -> Void)?
  41. var activeLogin: NCLogin?
  42. var activeLoginWeb: NCLoginProvider?
  43. var timerErrorNetworking: Timer?
  44. var timerErrorNetworkingDisabled: Bool = false
  45. var taskAutoUploadDate: Date = Date()
  46. var isUiTestingEnabled: Bool {
  47. return ProcessInfo.processInfo.arguments.contains("UI_TESTING")
  48. }
  49. var notificationSettings: UNNotificationSettings?
  50. var loginFlowV2Token = ""
  51. var loginFlowV2Endpoint = ""
  52. var loginFlowV2Login = ""
  53. func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
  54. if isUiTestingEnabled {
  55. deleteAllAccounts()
  56. }
  57. let utilityFileSystem = NCUtilityFileSystem()
  58. let utility = NCUtility()
  59. NCSettingsBundleHelper.checkAndExecuteSettings(delay: 0)
  60. let versionNextcloudiOS = String(format: NCBrandOptions.shared.textCopyrightNextcloudiOS, utility.getVersionApp())
  61. UserDefaults.standard.register(defaults: ["UserAgent": userAgent])
  62. if !NCKeychain().disableCrashservice, !NCBrandOptions.shared.disable_crash_service {
  63. FirebaseApp.configure()
  64. }
  65. utilityFileSystem.createDirectoryStandard()
  66. utilityFileSystem.emptyTemporaryDirectory()
  67. utilityFileSystem.clearCacheDirectory("com.limit-point.LivePhoto")
  68. // Activated singleton
  69. _ = NCActionCenter.shared
  70. _ = NCNetworking.shared
  71. NextcloudKit.shared.setup(delegate: NCNetworking.shared)
  72. NextcloudKit.shared.setup(userAgent: userAgent)
  73. var levelLog = 0
  74. NextcloudKit.shared.nkCommonInstance.pathLog = utilityFileSystem.directoryGroup
  75. if NCBrandOptions.shared.disable_log {
  76. utilityFileSystem.removeFile(atPath: NextcloudKit.shared.nkCommonInstance.filenamePathLog)
  77. utilityFileSystem.removeFile(atPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! + "/" + NextcloudKit.shared.nkCommonInstance.filenameLog)
  78. } else {
  79. levelLog = NCKeychain().logLevel
  80. NextcloudKit.shared.nkCommonInstance.levelLog = levelLog
  81. NextcloudKit.shared.nkCommonInstance.copyLogToDocumentDirectory = true
  82. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Start session with level \(levelLog) " + versionNextcloudiOS)
  83. }
  84. if let activeAccount = NCManageDatabase.shared.getActiveAccount() {
  85. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Account active \(activeAccount.account)")
  86. if NCKeychain().getPassword(account: activeAccount.account).isEmpty {
  87. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] PASSWORD NOT FOUND for \(activeAccount.account)")
  88. }
  89. account = activeAccount.account
  90. urlBase = activeAccount.urlBase
  91. user = activeAccount.user
  92. userId = activeAccount.userId
  93. password = NCKeychain().getPassword(account: account)
  94. NextcloudKit.shared.setup(account: account, user: user, userId: userId, password: password, urlBase: urlBase)
  95. NCManageDatabase.shared.setCapabilities(account: account)
  96. NCBrandColor.shared.settingThemingColor(account: activeAccount.account)
  97. DispatchQueue.global().async {
  98. NCImageCache.shared.createMediaCache(account: self.account, withCacheSize: true)
  99. }
  100. } else {
  101. NCKeychain().removeAll()
  102. if let bundleID = Bundle.main.bundleIdentifier {
  103. UserDefaults.standard.removePersistentDomain(forName: bundleID)
  104. }
  105. }
  106. NCBrandColor.shared.createUserColors()
  107. NCImageCache.shared.createImagesCache()
  108. // Push Notification & display notification
  109. UNUserNotificationCenter.current().getNotificationSettings { settings in
  110. self.notificationSettings = settings
  111. }
  112. application.registerForRemoteNotifications()
  113. UNUserNotificationCenter.current().delegate = self
  114. UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { _, _ in }
  115. if !utility.isSimulatorOrTestFlight() {
  116. let review = NCStoreReview()
  117. review.incrementAppRuns()
  118. review.showStoreReview()
  119. }
  120. // Background task register
  121. BGTaskScheduler.shared.register(forTaskWithIdentifier: NCGlobal.shared.refreshTask, using: nil) { task in
  122. self.handleAppRefresh(task)
  123. }
  124. BGTaskScheduler.shared.register(forTaskWithIdentifier: NCGlobal.shared.processingTask, using: nil) { task in
  125. self.handleProcessingTask(task)
  126. }
  127. FileNameValidator.shared.setup(
  128. forbiddenFileNames: NCGlobal.shared.capabilityForbiddenFileNames,
  129. forbiddenFileNameBasenames: NCGlobal.shared.capabilityForbiddenFileNameBasenames,
  130. forbiddenFileNameCharacters: NCGlobal.shared.capabilityForbiddenFileNameCharacters,
  131. forbiddenFileNameExtensions: NCGlobal.shared.capabilityForbiddenFileNameExtensions
  132. )
  133. return true
  134. }
  135. func applicationWillTerminate(_ application: UIApplication) {
  136. if self.notificationSettings?.authorizationStatus != .denied && UIApplication.shared.backgroundRefreshStatus == .available {
  137. let content = UNMutableNotificationContent()
  138. content.title = NCBrandOptions.shared.brand
  139. content.body = NSLocalizedString("_keep_running_", comment: "")
  140. let req = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: nil)
  141. let notificationCenter = UNUserNotificationCenter.current()
  142. notificationCenter.add(req)
  143. }
  144. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] bye bye")
  145. }
  146. // MARK: - UISceneSession Lifecycle
  147. func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
  148. // Called when a new scene session is being created.
  149. // Use this method to select a configuration to create the new scene with.
  150. return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
  151. }
  152. func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
  153. // Called when the user discards a scene session.
  154. // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
  155. // Use this method to release any resources that were specific to the discarded scenes, as they will not return.
  156. }
  157. // MARK: - Background Task
  158. /*
  159. @discussion Schedule a refresh task request to ask that the system launch your app briefly so that you can download data and keep your app's contents up-to-date. The system will fulfill this request intelligently based on system conditions and app usage.
  160. */
  161. func scheduleAppRefresh() {
  162. let request = BGAppRefreshTaskRequest(identifier: NCGlobal.shared.refreshTask)
  163. request.earliestBeginDate = Date(timeIntervalSinceNow: 60) // Refresh after 60 seconds.
  164. do {
  165. try BGTaskScheduler.shared.submit(request)
  166. } catch {
  167. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] Refresh task failed to submit request: \(error)")
  168. }
  169. }
  170. /*
  171. @discussion Schedule a processing task request to ask that the system launch your app when conditions are favorable for battery life to handle deferrable, longer-running processing, such as syncing, database maintenance, or similar tasks. The system will attempt to fulfill this request to the best of its ability within the next two days as long as the user has used your app within the past week.
  172. */
  173. func scheduleAppProcessing() {
  174. let request = BGProcessingTaskRequest(identifier: NCGlobal.shared.processingTask)
  175. request.earliestBeginDate = Date(timeIntervalSinceNow: 5 * 60) // Refresh after 5 minutes.
  176. request.requiresNetworkConnectivity = false
  177. request.requiresExternalPower = false
  178. do {
  179. try BGTaskScheduler.shared.submit(request)
  180. } catch {
  181. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] Background Processing task failed to submit request: \(error)")
  182. }
  183. }
  184. func handleAppRefresh(_ task: BGTask) {
  185. scheduleAppRefresh()
  186. handleAppRefreshProcessingTask(taskText: "AppRefresh") {
  187. task.setTaskCompleted(success: true)
  188. }
  189. }
  190. func handleProcessingTask(_ task: BGTask) {
  191. scheduleAppProcessing()
  192. handleAppRefreshProcessingTask(taskText: "ProcessingTask") {
  193. task.setTaskCompleted(success: true)
  194. }
  195. }
  196. func handleAppRefreshProcessingTask(taskText: String, completion: @escaping () -> Void = {}) {
  197. Task {
  198. var itemsAutoUpload = 0
  199. NextcloudKit.shared.nkCommonInstance.writeLog("[DEBUG] \(taskText) start handle")
  200. // Test every > 1 min
  201. if Date() > self.taskAutoUploadDate.addingTimeInterval(60) {
  202. self.taskAutoUploadDate = Date()
  203. itemsAutoUpload = await NCAutoUpload.shared.initAutoUpload()
  204. NextcloudKit.shared.nkCommonInstance.writeLog("[DEBUG] \(taskText) auto upload with \(itemsAutoUpload) uploads")
  205. } else {
  206. NextcloudKit.shared.nkCommonInstance.writeLog("[DEBUG] \(taskText) disabled auto upload")
  207. }
  208. let results = await NCNetworkingProcess.shared.start(scene: nil)
  209. NextcloudKit.shared.nkCommonInstance.writeLog("[DEBUG] \(taskText) networking process with download: \(results.counterDownloading) upload: \(results.counterUploading)")
  210. if taskText == "ProcessingTask",
  211. itemsAutoUpload == 0,
  212. results.counterDownloading == 0,
  213. results.counterUploading == 0,
  214. let directories = NCManageDatabase.shared.getTablesDirectory(predicate: NSPredicate(format: "account == %@ AND offline == true", self.account), sorted: "offlineDate", ascending: true) {
  215. for directory: tableDirectory in directories {
  216. // test only 3 time for day (every 8 h.)
  217. if let offlineDate = directory.offlineDate, offlineDate.addingTimeInterval(28800) > Date() {
  218. NextcloudKit.shared.nkCommonInstance.writeLog("[DEBUG] \(taskText) skip synchronization for \(directory.serverUrl) in date \(offlineDate)")
  219. continue
  220. }
  221. let results = await NCNetworking.shared.synchronization(account: self.account, serverUrl: directory.serverUrl, add: false)
  222. NextcloudKit.shared.nkCommonInstance.writeLog("[DEBUG] \(taskText) end synchronization for \(directory.serverUrl), errorCode: \(results.errorCode), item: \(results.items)")
  223. }
  224. }
  225. let counter = NCManageDatabase.shared.getResultsMetadatas(predicate: NSPredicate(format: "account == %@ AND (session == %@ || session == %@) AND status != %d", self.account, NCNetworking.shared.sessionDownloadBackground, NCNetworking.shared.sessionUploadBackground, NCGlobal.shared.metadataStatusNormal))?.count ?? 0
  226. UIApplication.shared.applicationIconBadgeNumber = counter
  227. NextcloudKit.shared.nkCommonInstance.writeLog("[DEBUG] \(taskText) completion handle")
  228. completion()
  229. }
  230. }
  231. // MARK: - Background Networking Session
  232. func application(_ application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: @escaping () -> Void) {
  233. NextcloudKit.shared.nkCommonInstance.writeLog("[DEBUG] Start handle Events For Background URLSession: \(identifier)")
  234. WidgetCenter.shared.reloadAllTimelines()
  235. backgroundSessionCompletionHandler = completionHandler
  236. }
  237. // MARK: - Push Notifications
  238. func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
  239. completionHandler([.list, .banner, .sound])
  240. }
  241. func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
  242. if let pref = UserDefaults(suiteName: NCBrandOptions.shared.capabilitiesGroup),
  243. let data = pref.object(forKey: "NOTIFICATION_DATA") as? [String: AnyObject] {
  244. nextcloudPushNotificationAction(data: data)
  245. pref.set(nil, forKey: "NOTIFICATION_DATA")
  246. }
  247. completionHandler()
  248. }
  249. func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
  250. NCNetworking.shared.checkPushNotificationServerProxyCertificateUntrusted(viewController: UIApplication.shared.firstWindow?.rootViewController) { error in
  251. if error == .success {
  252. NCPushNotification.shared.registerForRemoteNotificationsWithDeviceToken(deviceToken)
  253. }
  254. }
  255. }
  256. func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
  257. NCPushNotification.shared.applicationdidReceiveRemoteNotification(userInfo: userInfo) { result in
  258. completionHandler(result)
  259. }
  260. }
  261. func nextcloudPushNotificationAction(data: [String: AnyObject]) {
  262. guard let data = NCApplicationHandle().nextcloudPushNotificationAction(data: data) else { return }
  263. var findAccount: Bool = false
  264. if let accountPush = data["account"] as? String {
  265. if accountPush == self.account {
  266. findAccount = true
  267. } else {
  268. let accounts = NCManageDatabase.shared.getAllAccount()
  269. for account in accounts {
  270. if account.account == accountPush {
  271. self.changeAccount(account.account, userProfile: nil) {
  272. findAccount = true
  273. }
  274. }
  275. }
  276. }
  277. if findAccount, let viewController = UIStoryboard(name: "NCNotification", bundle: nil).instantiateInitialViewController() as? NCNotification {
  278. DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
  279. let navigationController = UINavigationController(rootViewController: viewController)
  280. navigationController.modalPresentationStyle = .fullScreen
  281. UIApplication.shared.firstWindow?.rootViewController?.present(navigationController, animated: true)
  282. }
  283. } else if !findAccount {
  284. let message = NSLocalizedString("_the_account_", comment: "") + " " + accountPush + " " + NSLocalizedString("_does_not_exist_", comment: "")
  285. let alertController = UIAlertController(title: NSLocalizedString("_info_", comment: ""), message: message, preferredStyle: .alert)
  286. alertController.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { _ in }))
  287. UIApplication.shared.firstWindow?.rootViewController?.present(alertController, animated: true, completion: { })
  288. }
  289. }
  290. }
  291. // MARK: - Login
  292. func openLogin(selector: Int, openLoginWeb: Bool, windowForRootViewController: UIWindow? = nil) {
  293. func showLoginViewController(_ viewController: UIViewController?) {
  294. guard let viewController else { return }
  295. let navigationController = NCLoginNavigationController(rootViewController: viewController)
  296. navigationController.modalPresentationStyle = .fullScreen
  297. navigationController.navigationBar.barStyle = .black
  298. navigationController.navigationBar.tintColor = NCBrandColor.shared.customerText
  299. navigationController.navigationBar.barTintColor = NCBrandColor.shared.customer
  300. navigationController.navigationBar.isTranslucent = false
  301. if let window = windowForRootViewController {
  302. window.rootViewController = navigationController
  303. window.makeKeyAndVisible()
  304. } else {
  305. UIApplication.shared.allSceneSessionDestructionExceptFirst()
  306. if let rootVC = UIApplication.shared.firstWindow?.rootViewController {
  307. if let presentedVC = rootVC.presentedViewController, !(presentedVC is NCLoginNavigationController) {
  308. presentedVC.dismiss(animated: false) {
  309. rootVC.present(navigationController, animated: true)
  310. }
  311. } else {
  312. rootVC.present(navigationController, animated: true)
  313. }
  314. }
  315. }
  316. }
  317. // Nextcloud standard login
  318. if selector == NCGlobal.shared.introSignup {
  319. if activeLogin?.view.window == nil {
  320. activeLogin = UIStoryboard(name: "NCLogin", bundle: nil).instantiateViewController(withIdentifier: "NCLogin") as? NCLogin
  321. if selector == NCGlobal.shared.introSignup {
  322. activeLogin?.urlBase = NCBrandOptions.shared.linkloginPreferredProviders
  323. let web = UIStoryboard(name: "NCLogin", bundle: nil).instantiateViewController(withIdentifier: "NCLoginProvider") as? NCLoginProvider
  324. web?.urlBase = NCBrandOptions.shared.linkloginPreferredProviders
  325. showLoginViewController(web)
  326. } else {
  327. activeLogin?.urlBase = self.urlBase
  328. showLoginViewController(activeLogin)
  329. }
  330. }
  331. } else {
  332. if activeLogin?.view.window == nil {
  333. activeLogin = UIStoryboard(name: "NCLogin", bundle: nil).instantiateViewController(withIdentifier: "NCLogin") as? NCLogin
  334. activeLogin?.urlBase = NCBrandOptions.shared.disable_request_login_url ? NCBrandOptions.shared.loginBaseUrl : ""
  335. showLoginViewController(activeLogin)
  336. }
  337. }
  338. }
  339. // MARK: - Error Networking
  340. func startTimerErrorNetworking(scene: UIScene) {
  341. timerErrorNetworkingDisabled = false
  342. timerErrorNetworking = Timer.scheduledTimer(timeInterval: 3, target: self, selector: #selector(checkErrorNetworking(_:)), userInfo: nil, repeats: true)
  343. }
  344. @objc private func checkErrorNetworking(_ notification: NSNotification) {
  345. guard !self.timerErrorNetworkingDisabled,
  346. !account.isEmpty,
  347. NCKeychain().getPassword(account: account).isEmpty else { return }
  348. let description = String.localizedStringWithFormat(NSLocalizedString("_error_check_remote_user_", comment: ""))
  349. let error = NKError(errorCode: NCKeychain().getPassword(account: account).isEmpty ? NCGlobal.shared.errorUnauthorized997 : NCGlobal.shared.errorInternalServerError, errorDescription: description)
  350. NCContentPresenter().showError(error: error, priority: .max)
  351. deleteAccount(account)
  352. let accounts = NCManageDatabase.shared.getAccounts()
  353. if accounts?.count ?? 0 > 0, let newAccount = accounts?.first {
  354. changeAccount(newAccount, userProfile: nil) { }
  355. } else {
  356. openLogin(selector: NCGlobal.shared.introLogin, openLoginWeb: false)
  357. }
  358. }
  359. func trustCertificateError(host: String) {
  360. guard let currentHost = URL(string: self.urlBase)?.host,
  361. let pushNotificationServerProxyHost = URL(string: NCBrandOptions.shared.pushNotificationServerProxy)?.host,
  362. host != pushNotificationServerProxyHost,
  363. host == currentHost
  364. else { return }
  365. let certificateHostSavedPath = NCUtilityFileSystem().directoryCertificates + "/" + host + ".der"
  366. var title = NSLocalizedString("_ssl_certificate_changed_", comment: "")
  367. if !FileManager.default.fileExists(atPath: certificateHostSavedPath) {
  368. title = NSLocalizedString("_connect_server_anyway_", comment: "")
  369. }
  370. let alertController = UIAlertController(title: title, message: NSLocalizedString("_server_is_trusted_", comment: ""), preferredStyle: .alert)
  371. alertController.addAction(UIAlertAction(title: NSLocalizedString("_yes_", comment: ""), style: .default, handler: { _ in
  372. NCNetworking.shared.writeCertificate(host: host)
  373. }))
  374. alertController.addAction(UIAlertAction(title: NSLocalizedString("_no_", comment: ""), style: .default, handler: { _ in }))
  375. alertController.addAction(UIAlertAction(title: NSLocalizedString("_certificate_details_", comment: ""), style: .default, handler: { _ in
  376. if let navigationController = UIStoryboard(name: "NCViewCertificateDetails", bundle: nil).instantiateInitialViewController() as? UINavigationController,
  377. let viewController = navigationController.topViewController as? NCViewCertificateDetails {
  378. viewController.delegate = self
  379. viewController.host = host
  380. UIApplication.shared.firstWindow?.rootViewController?.present(navigationController, animated: true)
  381. }
  382. }))
  383. UIApplication.shared.firstWindow?.rootViewController?.present(alertController, animated: true)
  384. }
  385. // MARK: - Account
  386. func createAccount(urlBase: String,
  387. user: String,
  388. password: String,
  389. completion: @escaping (_ error: NKError) -> Void) {
  390. var urlBase = urlBase
  391. if urlBase.last == "/" { urlBase = String(urlBase.dropLast()) }
  392. let account: String = "\(user) \(urlBase)"
  393. NextcloudKit.shared.setup(account: account, user: user, userId: user, password: password, urlBase: urlBase)
  394. NextcloudKit.shared.getUserProfile(account: account) { account, userProfile, _, error in
  395. if error == .success, let userProfile {
  396. NCManageDatabase.shared.deleteAccount(account)
  397. NCManageDatabase.shared.addAccount(account, urlBase: urlBase, user: user, userId: userProfile.userId, password: password)
  398. NCKeychain().setClientCertificate(account: account, p12Data: NCNetworking.shared.p12Data, p12Password: NCNetworking.shared.p12Password)
  399. self.changeAccount(account, userProfile: userProfile) {
  400. completion(error)
  401. }
  402. } else {
  403. NextcloudKit.shared.setup(account: self.account, user: self.user, userId: self.userId, password: self.password, urlBase: self.urlBase)
  404. let alertController = UIAlertController(title: NSLocalizedString("_error_", comment: ""), message: error.errorDescription, preferredStyle: .alert)
  405. alertController.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { _ in }))
  406. UIApplication.shared.firstWindow?.rootViewController?.present(alertController, animated: true)
  407. completion(error)
  408. }
  409. }
  410. }
  411. func changeAccount(_ account: String,
  412. userProfile: NKUserProfile?,
  413. completion: () -> Void) {
  414. guard let tableAccount = NCManageDatabase.shared.setAccountActive(account) else {
  415. return completion()
  416. }
  417. NCNetworking.shared.cancelAllQueue()
  418. NCNetworking.shared.cancelDataTask()
  419. NCNetworking.shared.cancelDownloadTasks()
  420. NCNetworking.shared.cancelUploadTasks()
  421. if account != self.account {
  422. DispatchQueue.global().async {
  423. if NCManageDatabase.shared.getAccounts()?.count == 1 {
  424. NCImageCache.shared.createMediaCache(account: account, withCacheSize: true)
  425. } else {
  426. NCImageCache.shared.createMediaCache(account: account, withCacheSize: false)
  427. }
  428. }
  429. }
  430. self.account = tableAccount.account
  431. self.urlBase = tableAccount.urlBase
  432. self.user = tableAccount.user
  433. self.userId = tableAccount.userId
  434. self.password = NCKeychain().getPassword(account: tableAccount.account)
  435. NextcloudKit.shared.setup(account: account, user: user, userId: userId, password: password, urlBase: urlBase)
  436. NCManageDatabase.shared.setCapabilities(account: account)
  437. if let userProfile {
  438. NCManageDatabase.shared.setAccountUserProfile(account: account, userProfile: userProfile)
  439. }
  440. NCPushNotification.shared.pushNotification()
  441. NCService().startRequestServicesServer(account: self.account, user: self.user, userId: self.userId)
  442. NCAutoUpload.shared.initAutoUpload(viewController: nil) { items in
  443. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Initialize Auto upload with \(items) uploads")
  444. }
  445. FileNameValidator.shared.setup(
  446. forbiddenFileNames: NCGlobal.shared.capabilityForbiddenFileNames,
  447. forbiddenFileNameBasenames: NCGlobal.shared.capabilityForbiddenFileNameBasenames,
  448. forbiddenFileNameCharacters: NCGlobal.shared.capabilityForbiddenFileNameCharacters,
  449. forbiddenFileNameExtensions: NCGlobal.shared.capabilityForbiddenFileNameExtensions
  450. )
  451. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterChangeUser)
  452. completion()
  453. }
  454. func deleteAccount(_ account: String) {
  455. UIApplication.shared.allSceneSessionDestructionExceptFirst()
  456. if let account = NCManageDatabase.shared.getAccount(predicate: NSPredicate(format: "account == %@", account)) {
  457. NCPushNotification.shared.unsubscribingNextcloudServerPushNotification(account: account.account, urlBase: account.urlBase, user: account.user, withSubscribing: false)
  458. }
  459. let results = NCManageDatabase.shared.getTableLocalFiles(predicate: NSPredicate(format: "account == %@", account), sorted: "ocId", ascending: false)
  460. let utilityFileSystem = NCUtilityFileSystem()
  461. for result in results {
  462. utilityFileSystem.removeFile(atPath: utilityFileSystem.getDirectoryProviderStorageOcId(result.ocId))
  463. }
  464. NCManageDatabase.shared.clearDatabase(account: account, removeAccount: true)
  465. NCKeychain().clearAllKeysEndToEnd(account: account)
  466. NCKeychain().clearAllKeysPushNotification(account: account)
  467. NCKeychain().setPassword(account: account, password: nil)
  468. self.account = ""
  469. self.urlBase = ""
  470. self.user = ""
  471. self.userId = ""
  472. self.password = ""
  473. }
  474. func deleteAllAccounts() {
  475. let accounts = NCManageDatabase.shared.getAccounts()
  476. accounts?.forEach({ account in
  477. deleteAccount(account)
  478. })
  479. }
  480. func updateShareAccounts() -> Error? {
  481. guard let dirGroupApps = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: NCBrandOptions.shared.capabilitiesGroupApps) else { return nil }
  482. let tableAccount = NCManageDatabase.shared.getAllAccount()
  483. var accounts = [NKShareAccounts.DataAccounts]()
  484. for account in tableAccount {
  485. let name = account.alias.isEmpty ? account.displayName : account.alias
  486. let userBaseUrl = account.user + "-" + (URL(string: account.urlBase)?.host ?? "")
  487. let avatarFileName = userBaseUrl + "-\(account.user).png"
  488. let pathAvatarFileName = NCUtilityFileSystem().directoryUserData + "/" + avatarFileName
  489. let image = UIImage(contentsOfFile: pathAvatarFileName)
  490. accounts.append(NKShareAccounts.DataAccounts(withUrl: account.urlBase, user: account.user, name: name, image: image))
  491. }
  492. return NKShareAccounts().putShareAccounts(at: dirGroupApps, app: NCGlobal.shared.appScheme, dataAccounts: accounts)
  493. }
  494. // MARK: - Reset Application
  495. func resetApplication() {
  496. let utilityFileSystem = NCUtilityFileSystem()
  497. NCNetworking.shared.cancelAllTask()
  498. URLCache.shared.memoryCapacity = 0
  499. URLCache.shared.diskCapacity = 0
  500. utilityFileSystem.removeGroupDirectoryProviderStorage()
  501. utilityFileSystem.removeGroupApplicationSupport()
  502. utilityFileSystem.removeDocumentsDirectory()
  503. utilityFileSystem.removeTemporaryDirectory()
  504. NCKeychain().removeAll()
  505. exit(0)
  506. }
  507. // MARK: - Universal Links
  508. func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
  509. let applicationHandle = NCApplicationHandle()
  510. return applicationHandle.applicationOpenUserActivity(userActivity)
  511. }
  512. }
  513. // MARK: - Extension
  514. extension AppDelegate: NCViewCertificateDetailsDelegate {
  515. func viewCertificateDetailsDismiss(host: String) {
  516. trustCertificateError(host: host)
  517. }
  518. }
  519. extension AppDelegate: NCCreateFormUploadConflictDelegate {
  520. func dismissCreateFormUploadConflict(metadatas: [tableMetadata]?) {
  521. guard let metadatas = metadatas, !metadatas.isEmpty else { return }
  522. NCNetworkingProcess.shared.createProcessUploads(metadatas: metadatas)
  523. }
  524. }