AppDelegate.swift 28 KB

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