NCAccount.swift 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  1. //
  2. // NCAccount.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 03/08/24.
  6. // Copyright © 2024 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 Foundation
  24. import UIKit
  25. import NextcloudKit
  26. class NCAccount: NSObject {
  27. let database = NCManageDatabase.shared
  28. func createAccount(urlBase: String,
  29. user: String,
  30. password: String,
  31. controller: NCMainTabBarController?,
  32. completion: @escaping (_ account: String, _ error: NKError) -> Void) {
  33. var urlBase = urlBase
  34. if urlBase.last == "/" { urlBase = String(urlBase.dropLast()) }
  35. let account: String = "\(user) \(urlBase)"
  36. NextcloudKit.shared.appendSession(account: account,
  37. urlBase: urlBase,
  38. user: user,
  39. userId: user,
  40. password: password,
  41. userAgent: userAgent,
  42. nextcloudVersion: NCCapabilities.shared.getCapabilities(account: account).capabilityServerVersionMajor,
  43. groupIdentifier: NCBrandOptions.shared.capabilitiesGroup)
  44. NextcloudKit.shared.getUserProfile(account: account) { account, userProfile, _, error in
  45. if error == .success, let userProfile {
  46. NextcloudKit.shared.updateSession(account: account, userId: userProfile.userId)
  47. NCSession.shared.appendSession(account: account, urlBase: urlBase, user: user, userId: userProfile.userId)
  48. self.database.addAccount(account, urlBase: urlBase, user: user, userId: userProfile.userId, password: password)
  49. self.changeAccount(account, userProfile: userProfile, controller: controller) {
  50. NCKeychain().setClientCertificate(account: account, p12Data: NCNetworking.shared.p12Data, p12Password: NCNetworking.shared.p12Password)
  51. completion(account, error)
  52. }
  53. } else {
  54. NextcloudKit.shared.removeSession(account: account)
  55. let alertController = UIAlertController(title: NSLocalizedString("_error_", comment: ""), message: error.errorDescription, preferredStyle: .alert)
  56. alertController.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { _ in }))
  57. UIApplication.shared.firstWindow?.rootViewController?.present(alertController, animated: true)
  58. completion(account, error)
  59. }
  60. }
  61. }
  62. func changeAccount(_ account: String,
  63. userProfile: NKUserProfile?,
  64. controller: NCMainTabBarController?,
  65. completion: () -> Void) {
  66. /// Set account
  67. controller?.account = account
  68. database.setAccountActive(account)
  69. /// Set capabilities
  70. database.setCapabilities(account: account)
  71. /// Set User Profile
  72. if let userProfile {
  73. database.setAccountUserProfile(account: account, userProfile: userProfile)
  74. }
  75. /// Start Push Notification
  76. NCPushNotification.shared.pushNotification()
  77. /// Start the service
  78. NCService().startRequestServicesServer(account: account, controller: controller)
  79. /// Start the auto upload
  80. NCAutoUpload.shared.initAutoUpload(controller: nil, account: account) { num in
  81. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Initialize Auto upload with \(num) uploads")
  82. }
  83. /// Color
  84. NCBrandColor.shared.settingThemingColor(account: account)
  85. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterChangeTheming, userInfo: ["account": account])
  86. /// Notification
  87. if let controller {
  88. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterChangeUser, userInfo: ["account": account, "controller": controller])
  89. } else {
  90. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterChangeUser, userInfo: ["account": account])
  91. }
  92. completion()
  93. }
  94. func deleteAccount(_ account: String, wipe: Bool = true) {
  95. UIApplication.shared.allSceneSessionDestructionExceptFirst()
  96. /// Unsubscribing Push Notification
  97. if let tableAccount = database.getTableAccount(predicate: NSPredicate(format: "account == %@", account)) {
  98. NCPushNotification.shared.unsubscribingNextcloudServerPushNotification(account: tableAccount.account, urlBase: tableAccount.urlBase, user: tableAccount.user, withSubscribing: false)
  99. }
  100. /// Remove al local files
  101. if wipe {
  102. let results = database.getTableLocalFiles(predicate: NSPredicate(format: "account == %@", account), sorted: "ocId", ascending: false)
  103. let utilityFileSystem = NCUtilityFileSystem()
  104. for result in results {
  105. utilityFileSystem.removeFile(atPath: utilityFileSystem.getDirectoryProviderStorageOcId(result.ocId))
  106. }
  107. /// Remove account in all database
  108. database.clearDatabase(account: account, removeAccount: true)
  109. } else {
  110. /// Remove account
  111. database.clearTable(tableAccount.self, account: account)
  112. }
  113. /// Remove session in NextcloudKit
  114. NextcloudKit.shared.removeSession(account: account)
  115. /// Remove session
  116. NCSession.shared.removeSession(account: account)
  117. /// Remove keychain security
  118. NCKeychain().setPassword(account: account, password: nil)
  119. NCKeychain().clearAllKeysEndToEnd(account: account)
  120. NCKeychain().clearAllKeysPushNotification(account: account)
  121. /// Remove User Default Data
  122. NCNetworking.shared.removeAllKeyUserDefaultsData(account: account)
  123. }
  124. func deleteAllAccounts() {
  125. let accounts = database.getAccounts()
  126. accounts?.forEach({ account in
  127. deleteAccount(account)
  128. })
  129. }
  130. func updateAppsShareAccounts() -> Error? {
  131. guard let dirGroupApps = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: NCBrandOptions.shared.capabilitiesGroupApps) else { return nil }
  132. var accounts = [NKShareAccounts.DataAccounts]()
  133. for account in database.getAllTableAccount() {
  134. let name = account.alias.isEmpty ? account.displayName : account.alias
  135. let fileName = NCSession.shared.getFileName(urlBase: account.urlBase, user: account.user)
  136. let fileNamePath = NCUtilityFileSystem().directoryUserData + "/" + fileName
  137. let image = UIImage(contentsOfFile: fileNamePath)
  138. accounts.append(NKShareAccounts.DataAccounts(withUrl: account.urlBase, user: account.user, name: name, image: image))
  139. }
  140. return NKShareAccounts().putShareAccounts(at: dirGroupApps, app: NCGlobal.shared.appScheme, dataAccounts: accounts)
  141. }
  142. }