AppDelegate.swift 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619
  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, groupIdentifier: NCBrandOptions.shared.capabilitiesGroup)
  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. return true
  128. }
  129. func applicationWillTerminate(_ application: UIApplication) {
  130. if self.notificationSettings?.authorizationStatus != .denied && UIApplication.shared.backgroundRefreshStatus == .available {
  131. let content = UNMutableNotificationContent()
  132. content.title = NCBrandOptions.shared.brand
  133. content.body = NSLocalizedString("_keep_running_", comment: "")
  134. let req = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: nil)
  135. let notificationCenter = UNUserNotificationCenter.current()
  136. notificationCenter.add(req)
  137. }
  138. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] bye bye")
  139. }
  140. // MARK: - UISceneSession Lifecycle
  141. func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
  142. // Called when a new scene session is being created.
  143. // Use this method to select a configuration to create the new scene with.
  144. return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
  145. }
  146. func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
  147. // Called when the user discards a scene session.
  148. // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
  149. // Use this method to release any resources that were specific to the discarded scenes, as they will not return.
  150. }
  151. // MARK: - Background Task
  152. /*
  153. @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.
  154. */
  155. func scheduleAppRefresh() {
  156. let request = BGAppRefreshTaskRequest(identifier: NCGlobal.shared.refreshTask)
  157. request.earliestBeginDate = Date(timeIntervalSinceNow: 60) // Refresh after 60 seconds.
  158. do {
  159. try BGTaskScheduler.shared.submit(request)
  160. } catch {
  161. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] Refresh task failed to submit request: \(error)")
  162. }
  163. }
  164. /*
  165. @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.
  166. */
  167. func scheduleAppProcessing() {
  168. let request = BGProcessingTaskRequest(identifier: NCGlobal.shared.processingTask)
  169. request.earliestBeginDate = Date(timeIntervalSinceNow: 5 * 60) // Refresh after 5 minutes.
  170. request.requiresNetworkConnectivity = false
  171. request.requiresExternalPower = false
  172. do {
  173. try BGTaskScheduler.shared.submit(request)
  174. } catch {
  175. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] Background Processing task failed to submit request: \(error)")
  176. }
  177. }
  178. func handleAppRefresh(_ task: BGTask) {
  179. scheduleAppRefresh()
  180. handleAppRefreshProcessingTask(taskText: "AppRefresh") {
  181. task.setTaskCompleted(success: true)
  182. }
  183. }
  184. func handleProcessingTask(_ task: BGTask) {
  185. scheduleAppProcessing()
  186. handleAppRefreshProcessingTask(taskText: "ProcessingTask") {
  187. task.setTaskCompleted(success: true)
  188. }
  189. }
  190. func handleAppRefreshProcessingTask(taskText: String, completion: @escaping () -> Void = {}) {
  191. Task {
  192. var itemsAutoUpload = 0
  193. NextcloudKit.shared.nkCommonInstance.writeLog("[DEBUG] \(taskText) start handle")
  194. // Test every > 1 min
  195. if Date() > self.taskAutoUploadDate.addingTimeInterval(60) {
  196. self.taskAutoUploadDate = Date()
  197. itemsAutoUpload = await NCAutoUpload.shared.initAutoUpload()
  198. NextcloudKit.shared.nkCommonInstance.writeLog("[DEBUG] \(taskText) auto upload with \(itemsAutoUpload) uploads")
  199. } else {
  200. NextcloudKit.shared.nkCommonInstance.writeLog("[DEBUG] \(taskText) disabled auto upload")
  201. }
  202. let results = await NCNetworkingProcess.shared.start(scene: nil)
  203. NextcloudKit.shared.nkCommonInstance.writeLog("[DEBUG] \(taskText) networking process with download: \(results.counterDownloading) upload: \(results.counterUploading)")
  204. if taskText == "ProcessingTask",
  205. itemsAutoUpload == 0,
  206. results.counterDownloading == 0,
  207. results.counterUploading == 0,
  208. let directories = NCManageDatabase.shared.getTablesDirectory(predicate: NSPredicate(format: "account == %@ AND offline == true", self.account), sorted: "offlineDate", ascending: true) {
  209. for directory: tableDirectory in directories {
  210. // test only 3 time for day (every 8 h.)
  211. if let offlineDate = directory.offlineDate, offlineDate.addingTimeInterval(28800) > Date() {
  212. NextcloudKit.shared.nkCommonInstance.writeLog("[DEBUG] \(taskText) skip synchronization for \(directory.serverUrl) in date \(offlineDate)")
  213. continue
  214. }
  215. let results = await NCNetworking.shared.synchronization(account: self.account, serverUrl: directory.serverUrl, add: false)
  216. NextcloudKit.shared.nkCommonInstance.writeLog("[DEBUG] \(taskText) end synchronization for \(directory.serverUrl), errorCode: \(results.errorCode), item: \(results.items)")
  217. }
  218. }
  219. 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
  220. UIApplication.shared.applicationIconBadgeNumber = counter
  221. NextcloudKit.shared.nkCommonInstance.writeLog("[DEBUG] \(taskText) completion handle")
  222. completion()
  223. }
  224. }
  225. // MARK: - Background Networking Session
  226. func application(_ application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: @escaping () -> Void) {
  227. NextcloudKit.shared.nkCommonInstance.writeLog("[DEBUG] Start handle Events For Background URLSession: \(identifier)")
  228. WidgetCenter.shared.reloadAllTimelines()
  229. backgroundSessionCompletionHandler = completionHandler
  230. }
  231. // MARK: - Push Notifications
  232. func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
  233. completionHandler([.list, .banner, .sound])
  234. }
  235. func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
  236. if let pref = UserDefaults(suiteName: NCBrandOptions.shared.capabilitiesGroup),
  237. let data = pref.object(forKey: "NOTIFICATION_DATA") as? [String: AnyObject] {
  238. nextcloudPushNotificationAction(data: data)
  239. pref.set(nil, forKey: "NOTIFICATION_DATA")
  240. }
  241. completionHandler()
  242. }
  243. func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
  244. NCNetworking.shared.checkPushNotificationServerProxyCertificateUntrusted(viewController: UIApplication.shared.firstWindow?.rootViewController) { error in
  245. if error == .success {
  246. NCPushNotification.shared.registerForRemoteNotificationsWithDeviceToken(deviceToken)
  247. }
  248. }
  249. }
  250. func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
  251. NCPushNotification.shared.applicationdidReceiveRemoteNotification(userInfo: userInfo) { result in
  252. completionHandler(result)
  253. }
  254. }
  255. func nextcloudPushNotificationAction(data: [String: AnyObject]) {
  256. guard let data = NCApplicationHandle().nextcloudPushNotificationAction(data: data) else { return }
  257. var findAccount: Bool = false
  258. if let accountPush = data["account"] as? String {
  259. if accountPush == self.account {
  260. findAccount = true
  261. } else {
  262. let accounts = NCManageDatabase.shared.getAllAccount()
  263. for account in accounts {
  264. if account.account == accountPush {
  265. self.changeAccount(account.account, userProfile: nil) {
  266. findAccount = true
  267. }
  268. }
  269. }
  270. }
  271. if findAccount, let viewController = UIStoryboard(name: "NCNotification", bundle: nil).instantiateInitialViewController() as? NCNotification {
  272. DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
  273. let navigationController = UINavigationController(rootViewController: viewController)
  274. navigationController.modalPresentationStyle = .fullScreen
  275. UIApplication.shared.firstWindow?.rootViewController?.present(navigationController, animated: true)
  276. }
  277. } else if !findAccount {
  278. let message = NSLocalizedString("_the_account_", comment: "") + " " + accountPush + " " + NSLocalizedString("_does_not_exist_", comment: "")
  279. let alertController = UIAlertController(title: NSLocalizedString("_info_", comment: ""), message: message, preferredStyle: .alert)
  280. alertController.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { _ in }))
  281. UIApplication.shared.firstWindow?.rootViewController?.present(alertController, animated: true, completion: { })
  282. }
  283. }
  284. }
  285. // MARK: - Login
  286. func openLogin(selector: Int, openLoginWeb: Bool, windowForRootViewController: UIWindow? = nil) {
  287. func showLoginViewController(_ viewController: UIViewController?) {
  288. guard let viewController else { return }
  289. let navigationController = NCLoginNavigationController(rootViewController: viewController)
  290. navigationController.modalPresentationStyle = .fullScreen
  291. navigationController.navigationBar.barStyle = .black
  292. navigationController.navigationBar.tintColor = NCBrandColor.shared.customerText
  293. navigationController.navigationBar.barTintColor = NCBrandColor.shared.customer
  294. navigationController.navigationBar.isTranslucent = false
  295. if let window = windowForRootViewController {
  296. window.rootViewController = navigationController
  297. window.makeKeyAndVisible()
  298. } else {
  299. UIApplication.shared.allSceneSessionDestructionExceptFirst()
  300. UIApplication.shared.firstWindow?.rootViewController?.present(navigationController, animated: true)
  301. }
  302. }
  303. // Nextcloud standard login
  304. if selector == NCGlobal.shared.introSignup {
  305. if activeLogin?.view.window == nil {
  306. activeLogin = UIStoryboard(name: "NCLogin", bundle: nil).instantiateViewController(withIdentifier: "NCLogin") as? NCLogin
  307. if selector == NCGlobal.shared.introSignup {
  308. activeLogin?.urlBase = NCBrandOptions.shared.linkloginPreferredProviders
  309. let web = UIStoryboard(name: "NCLogin", bundle: nil).instantiateViewController(withIdentifier: "NCLoginProvider") as? NCLoginProvider
  310. web?.urlBase = NCBrandOptions.shared.linkloginPreferredProviders
  311. showLoginViewController(web)
  312. } else {
  313. activeLogin?.urlBase = self.urlBase
  314. showLoginViewController(activeLogin)
  315. }
  316. }
  317. } else if NCBrandOptions.shared.disable_request_login_url {
  318. if activeLogin?.view.window == nil {
  319. activeLogin = UIStoryboard(name: "NCLogin", bundle: nil).instantiateViewController(withIdentifier: "NCLogin") as? NCLogin
  320. activeLogin?.urlBase = NCBrandOptions.shared.loginBaseUrl
  321. showLoginViewController(activeLogin)
  322. }
  323. } else if openLoginWeb {
  324. // Used also for reinsert the account (change passwd)
  325. if activeLogin?.view.window == nil {
  326. activeLogin = UIStoryboard(name: "NCLogin", bundle: nil).instantiateViewController(withIdentifier: "NCLogin") as? NCLogin
  327. activeLogin?.urlBase = urlBase
  328. activeLogin?.disableUrlField = true
  329. activeLogin?.disableCloseButton = true
  330. showLoginViewController(activeLogin)
  331. }
  332. } else {
  333. if activeLogin?.view.window == nil {
  334. activeLogin?.disableCloseButton = true
  335. activeLogin = UIStoryboard(name: "NCLogin", bundle: nil).instantiateViewController(withIdentifier: "NCLogin") as? NCLogin
  336. showLoginViewController(activeLogin)
  337. }
  338. }
  339. }
  340. // MARK: - Error Networking
  341. func startTimerErrorNetworking(scene: UIScene) {
  342. timerErrorNetworkingDisabled = false
  343. timerErrorNetworking = Timer.scheduledTimer(timeInterval: 3, target: self, selector: #selector(checkErrorNetworking(_:)), userInfo: nil, repeats: true)
  344. }
  345. @objc private func checkErrorNetworking(_ notification: NSNotification) {
  346. guard !self.timerErrorNetworkingDisabled,
  347. !account.isEmpty,
  348. NCKeychain().getPassword(account: account).isEmpty else { return }
  349. openLogin(selector: NCGlobal.shared.introLogin, openLoginWeb: true)
  350. }
  351. func trustCertificateError(host: String) {
  352. guard let currentHost = URL(string: self.urlBase)?.host,
  353. let pushNotificationServerProxyHost = URL(string: NCBrandOptions.shared.pushNotificationServerProxy)?.host,
  354. host != pushNotificationServerProxyHost,
  355. host == currentHost
  356. else { return }
  357. let certificateHostSavedPath = NCUtilityFileSystem().directoryCertificates + "/" + host + ".der"
  358. var title = NSLocalizedString("_ssl_certificate_changed_", comment: "")
  359. if !FileManager.default.fileExists(atPath: certificateHostSavedPath) {
  360. title = NSLocalizedString("_connect_server_anyway_", comment: "")
  361. }
  362. let alertController = UIAlertController(title: title, message: NSLocalizedString("_server_is_trusted_", comment: ""), preferredStyle: .alert)
  363. alertController.addAction(UIAlertAction(title: NSLocalizedString("_yes_", comment: ""), style: .default, handler: { _ in
  364. NCNetworking.shared.writeCertificate(host: host)
  365. }))
  366. alertController.addAction(UIAlertAction(title: NSLocalizedString("_no_", comment: ""), style: .default, handler: { _ in }))
  367. alertController.addAction(UIAlertAction(title: NSLocalizedString("_certificate_details_", comment: ""), style: .default, handler: { _ in
  368. if let navigationController = UIStoryboard(name: "NCViewCertificateDetails", bundle: nil).instantiateInitialViewController() as? UINavigationController,
  369. let viewController = navigationController.topViewController as? NCViewCertificateDetails {
  370. viewController.delegate = self
  371. viewController.host = host
  372. UIApplication.shared.firstWindow?.rootViewController?.present(navigationController, animated: true)
  373. }
  374. }))
  375. UIApplication.shared.firstWindow?.rootViewController?.present(alertController, animated: true)
  376. }
  377. // MARK: - Account
  378. func createAccount(urlBase: String,
  379. user: String,
  380. password: String,
  381. completion: @escaping (_ error: NKError) -> Void) {
  382. var urlBase = urlBase
  383. if urlBase.last == "/" { urlBase = String(urlBase.dropLast()) }
  384. let account: String = "\(user) \(urlBase)"
  385. NextcloudKit.shared.setup(account: account, user: user, userId: user, password: password, urlBase: urlBase, groupIdentifier: NCBrandOptions.shared.capabilitiesGroup)
  386. NextcloudKit.shared.getUserProfile { _, userProfile, _, error in
  387. if error == .success, let userProfile {
  388. NCManageDatabase.shared.deleteAccount(account)
  389. NCManageDatabase.shared.addAccount(account, urlBase: urlBase, user: user, userId: userProfile.userId, password: password)
  390. NCKeychain().setClientCertificate(account: account, p12Data: NCNetworking.shared.p12Data, p12Password: NCNetworking.shared.p12Password)
  391. self.changeAccount(account, userProfile: userProfile) {
  392. completion(error)
  393. }
  394. } else {
  395. NextcloudKit.shared.setup(account: self.account, user: self.user, userId: self.userId, password: self.password, urlBase: self.urlBase, groupIdentifier: NCBrandOptions.shared.capabilitiesGroup)
  396. let alertController = UIAlertController(title: NSLocalizedString("_error_", comment: ""), message: error.errorDescription, preferredStyle: .alert)
  397. alertController.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { _ in }))
  398. UIApplication.shared.firstWindow?.rootViewController?.present(alertController, animated: true)
  399. completion(error)
  400. }
  401. }
  402. }
  403. func changeAccount(_ account: String,
  404. userProfile: NKUserProfile?,
  405. completion: () -> Void) {
  406. guard let tableAccount = NCManageDatabase.shared.setAccountActive(account) else {
  407. return completion()
  408. }
  409. NCNetworking.shared.cancelAllQueue()
  410. NCNetworking.shared.cancelDataTask()
  411. NCNetworking.shared.cancelDownloadTasks()
  412. NCNetworking.shared.cancelUploadTasks()
  413. if account != self.account {
  414. DispatchQueue.global().async {
  415. if NCManageDatabase.shared.getAccounts()?.count == 1 {
  416. NCImageCache.shared.createMediaCache(account: account, withCacheSize: true)
  417. } else {
  418. NCImageCache.shared.createMediaCache(account: account, withCacheSize: false)
  419. }
  420. }
  421. }
  422. self.account = tableAccount.account
  423. self.urlBase = tableAccount.urlBase
  424. self.user = tableAccount.user
  425. self.userId = tableAccount.userId
  426. self.password = NCKeychain().getPassword(account: tableAccount.account)
  427. NextcloudKit.shared.setup(account: account, user: user, userId: userId, password: password, urlBase: urlBase, groupIdentifier: NCBrandOptions.shared.capabilitiesGroup)
  428. NCManageDatabase.shared.setCapabilities(account: account)
  429. if let userProfile {
  430. NCManageDatabase.shared.setAccountUserProfile(account: account, userProfile: userProfile)
  431. }
  432. NCPushNotification.shared.pushNotification()
  433. NCService().startRequestServicesServer()
  434. NCAutoUpload.shared.initAutoUpload(viewController: nil) { items in
  435. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Initialize Auto upload with \(items) uploads")
  436. }
  437. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterChangeUser)
  438. completion()
  439. }
  440. func deleteAccount(_ account: String) {
  441. UIApplication.shared.allSceneSessionDestructionExceptFirst()
  442. if let account = NCManageDatabase.shared.getAccount(predicate: NSPredicate(format: "account == %@", account)) {
  443. NCPushNotification.shared.unsubscribingNextcloudServerPushNotification(account: account.account, urlBase: account.urlBase, user: account.user, withSubscribing: false)
  444. }
  445. let results = NCManageDatabase.shared.getTableLocalFiles(predicate: NSPredicate(format: "account == %@", account), sorted: "ocId", ascending: false)
  446. let utilityFileSystem = NCUtilityFileSystem()
  447. for result in results {
  448. utilityFileSystem.removeFile(atPath: utilityFileSystem.getDirectoryProviderStorageOcId(result.ocId))
  449. }
  450. NCManageDatabase.shared.clearDatabase(account: account, removeAccount: true)
  451. NCKeychain().clearAllKeysEndToEnd(account: account)
  452. NCKeychain().clearAllKeysPushNotification(account: account)
  453. NCKeychain().setPassword(account: account, password: nil)
  454. self.account = ""
  455. self.urlBase = ""
  456. self.user = ""
  457. self.userId = ""
  458. self.password = ""
  459. /*
  460. NextcloudKit.shared.deleteAppPassword(serverUrl: urlBase, username: userId, password: password) { _, error in
  461. print(error)
  462. }
  463. */
  464. }
  465. func deleteAllAccounts() {
  466. let accounts = NCManageDatabase.shared.getAccounts()
  467. accounts?.forEach({ account in
  468. deleteAccount(account)
  469. })
  470. }
  471. func updateShareAccounts() -> Error? {
  472. guard let dirGroupApps = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: NCBrandOptions.shared.capabilitiesGroupApps) else { return nil }
  473. let tableAccount = NCManageDatabase.shared.getAllAccount()
  474. var accounts = [NKShareAccounts.DataAccounts]()
  475. for account in tableAccount {
  476. let name = account.alias.isEmpty ? account.displayName : account.alias
  477. let userBaseUrl = account.user + "-" + (URL(string: account.urlBase)?.host ?? "")
  478. let avatarFileName = userBaseUrl + "-\(account.user).png"
  479. let pathAvatarFileName = NCUtilityFileSystem().directoryUserData + "/" + avatarFileName
  480. let image = UIImage(contentsOfFile: pathAvatarFileName)
  481. accounts.append(NKShareAccounts.DataAccounts(withUrl: account.urlBase, user: account.user, name: name, image: image))
  482. }
  483. return NKShareAccounts().putShareAccounts(at: dirGroupApps, app: NCGlobal.shared.appScheme, dataAccounts: accounts)
  484. }
  485. // MARK: - Reset Application
  486. func resetApplication() {
  487. let utilityFileSystem = NCUtilityFileSystem()
  488. NCNetworking.shared.cancelAllTask()
  489. URLCache.shared.memoryCapacity = 0
  490. URLCache.shared.diskCapacity = 0
  491. utilityFileSystem.removeGroupDirectoryProviderStorage()
  492. utilityFileSystem.removeGroupApplicationSupport()
  493. utilityFileSystem.removeDocumentsDirectory()
  494. utilityFileSystem.removeTemporaryDirectory()
  495. NCKeychain().removeAll()
  496. exit(0)
  497. }
  498. // MARK: - Universal Links
  499. func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
  500. let applicationHandle = NCApplicationHandle()
  501. return applicationHandle.applicationOpenUserActivity(userActivity)
  502. }
  503. }
  504. // MARK: - Extension
  505. extension AppDelegate: NCViewCertificateDetailsDelegate {
  506. func viewCertificateDetailsDismiss(host: String) {
  507. trustCertificateError(host: host)
  508. }
  509. }
  510. extension AppDelegate: NCCreateFormUploadConflictDelegate {
  511. func dismissCreateFormUploadConflict(metadatas: [tableMetadata]?) {
  512. guard let metadatas = metadatas, !metadatas.isEmpty else { return }
  513. NCNetworkingProcess.shared.createProcessUploads(metadatas: metadatas)
  514. }
  515. }