AppDelegate.swift 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941
  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 TOPasscodeViewController
  27. import LocalAuthentication
  28. import Firebase
  29. import WidgetKit
  30. import Queuer
  31. @UIApplicationMain
  32. class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, NCUserBaseUrl {
  33. var backgroundSessionCompletionHandler: (() -> Void)?
  34. var window: UIWindow?
  35. @objc var account: String = ""
  36. @objc var urlBase: String = ""
  37. @objc var user: String = ""
  38. @objc var userId: String = ""
  39. @objc var password: String = ""
  40. var activeLogin: NCLogin?
  41. var activeLoginWeb: NCLoginWeb?
  42. var activeServerUrl: String = ""
  43. @objc var activeViewController: UIViewController?
  44. var mainTabBar: NCMainTabBar?
  45. var activeMetadata: tableMetadata?
  46. let listFilesVC = ThreadSafeDictionary<String, NCFiles>()
  47. var disableSharesView: Bool = false
  48. var documentPickerViewController: NCDocumentPickerViewController?
  49. var timerErrorNetworking: Timer?
  50. var isAppRefresh: Bool = false
  51. var isProcessingTask: Bool = false
  52. var isUiTestingEnabled: Bool {
  53. return ProcessInfo.processInfo.arguments.contains("UI_TESTING")
  54. }
  55. func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
  56. if isUiTestingEnabled {
  57. deleteAllAccounts()
  58. }
  59. let utilityFileSystem = NCUtilityFileSystem()
  60. let utility = NCUtility()
  61. NCSettingsBundleHelper.checkAndExecuteSettings(delay: 0)
  62. let versionNextcloudiOS = String(format: NCBrandOptions.shared.textCopyrightNextcloudiOS, utility.getVersionApp())
  63. UserDefaults.standard.register(defaults: ["UserAgent": userAgent])
  64. if !NCKeychain().disableCrashservice, !NCBrandOptions.shared.disable_crash_service {
  65. FirebaseApp.configure()
  66. }
  67. utilityFileSystem.createDirectoryStandard()
  68. utilityFileSystem.emptyTemporaryDirectory()
  69. utilityFileSystem.clearCacheDirectory("com.limit-point.LivePhoto")
  70. // Activated singleton
  71. _ = NCActionCenter.shared
  72. _ = NCNetworking.shared
  73. NextcloudKit.shared.setup(delegate: NCNetworking.shared)
  74. NextcloudKit.shared.setup(userAgent: userAgent)
  75. startTimerErrorNetworking()
  76. var levelLog = 0
  77. NextcloudKit.shared.nkCommonInstance.pathLog = utilityFileSystem.directoryGroup
  78. if NCBrandOptions.shared.disable_log {
  79. utilityFileSystem.removeFile(atPath: NextcloudKit.shared.nkCommonInstance.filenamePathLog)
  80. utilityFileSystem.removeFile(atPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! + "/" + NextcloudKit.shared.nkCommonInstance.filenameLog)
  81. } else {
  82. levelLog = NCKeychain().logLevel
  83. NextcloudKit.shared.nkCommonInstance.levelLog = levelLog
  84. NextcloudKit.shared.nkCommonInstance.copyLogToDocumentDirectory = true
  85. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Start session with level \(levelLog) " + versionNextcloudiOS)
  86. }
  87. if let account = NCManageDatabase.shared.getActiveAccount() {
  88. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Account active \(account.account)")
  89. if NCKeychain().getPassword(account: account.account).isEmpty {
  90. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] PASSWORD NOT FOUND for \(account.account)")
  91. }
  92. }
  93. if let activeAccount = NCManageDatabase.shared.getActiveAccount() {
  94. account = activeAccount.account
  95. urlBase = activeAccount.urlBase
  96. user = activeAccount.user
  97. userId = activeAccount.userId
  98. password = NCKeychain().getPassword(account: account)
  99. NextcloudKit.shared.setup(account: account, user: user, userId: userId, password: password, urlBase: urlBase)
  100. NCManageDatabase.shared.setCapabilities(account: account)
  101. NCBrandColor.shared.settingThemingColor(account: activeAccount.account)
  102. DispatchQueue.global().async {
  103. NCImageCache.shared.createMediaCache(account: self.account, withCacheSize: true)
  104. }
  105. } else {
  106. NCKeychain().removeAll()
  107. if let bundleID = Bundle.main.bundleIdentifier {
  108. UserDefaults.standard.removePersistentDomain(forName: bundleID)
  109. }
  110. }
  111. NCBrandColor.shared.createUserColors()
  112. NCImageCache.shared.createImagesCache()
  113. // Push Notification & display notification
  114. application.registerForRemoteNotifications()
  115. UNUserNotificationCenter.current().delegate = self
  116. UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { _, _ in }
  117. if !utility.isSimulatorOrTestFlight() {
  118. let review = NCStoreReview()
  119. review.incrementAppRuns()
  120. review.showStoreReview()
  121. }
  122. // Background task register
  123. BGTaskScheduler.shared.register(forTaskWithIdentifier: NCGlobal.shared.refreshTask, using: nil) { task in
  124. self.handleAppRefresh(task)
  125. }
  126. BGTaskScheduler.shared.register(forTaskWithIdentifier: NCGlobal.shared.processingTask, using: nil) { task in
  127. self.handleProcessingTask(task)
  128. }
  129. if account.isEmpty {
  130. if NCBrandOptions.shared.disable_intro {
  131. openLogin(viewController: nil, selector: NCGlobal.shared.introLogin, openLoginWeb: false)
  132. } else {
  133. if let viewController = UIStoryboard(name: "NCIntro", bundle: nil).instantiateInitialViewController() {
  134. let navigationController = NCLoginNavigationController(rootViewController: viewController)
  135. window?.rootViewController = navigationController
  136. window?.makeKeyAndVisible()
  137. }
  138. }
  139. } else {
  140. NCPasscode.shared.presentPasscode(delegate: self) {
  141. NCPasscode.shared.enableTouchFaceID()
  142. }
  143. }
  144. return true
  145. }
  146. // MARK: - Life Cycle
  147. // L' applicazione entrerà in attivo (sempre)
  148. func applicationDidBecomeActive(_ application: UIApplication) {
  149. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Application did become active")
  150. NCSettingsBundleHelper.setVersionAndBuildNumber()
  151. NCSettingsBundleHelper.checkAndExecuteSettings(delay: 0.5)
  152. // START TIMER UPLOAD PROCESS
  153. NCNetworkingProcess.shared.startTimer()
  154. if !NCAskAuthorization().isRequesting {
  155. NCPasscode.shared.hidePrivacyProtectionWindow()
  156. }
  157. NCService().startRequestServicesServer()
  158. NCAutoUpload.shared.initAutoUpload(viewController: nil) { items in
  159. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Initialize Auto upload with \(items) uploads")
  160. }
  161. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterApplicationDidBecomeActive)
  162. }
  163. // L' applicazione si dimetterà dallo stato di attivo
  164. func applicationWillResignActive(_ application: UIApplication) {
  165. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Application will resign active")
  166. guard !account.isEmpty else { return }
  167. // STOP TIMER UPLOAD PROCESS
  168. NCNetworkingProcess.shared.stopTimer()
  169. if NCKeychain().privacyScreenEnabled {
  170. NCPasscode.shared.showPrivacyProtectionWindow()
  171. }
  172. // Reload Widget
  173. WidgetCenter.shared.reloadAllTimelines()
  174. // Clear older files
  175. let days = NCKeychain().cleanUpDay
  176. let utilityFileSystem = NCUtilityFileSystem()
  177. utilityFileSystem.cleanUp(directory: utilityFileSystem.directoryProviderStorage, days: TimeInterval(days))
  178. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterApplicationWillResignActive)
  179. }
  180. // L' applicazione entrerà in primo piano (dopo il background)
  181. func applicationWillEnterForeground(_ application: UIApplication) {
  182. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Application will enter in foreground")
  183. guard !account.isEmpty else { return }
  184. NCPasscode.shared.enableTouchFaceID()
  185. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterApplicationWillEnterForeground)
  186. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterRichdocumentGrabFocus)
  187. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterReloadDataSourceNetwork, second: 2)
  188. }
  189. // L' applicazione è entrata nello sfondo
  190. func applicationDidEnterBackground(_ application: UIApplication) {
  191. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Application did enter in background")
  192. guard !account.isEmpty else { return }
  193. let activeAccount = NCManageDatabase.shared.getActiveAccount()
  194. if let autoUpload = activeAccount?.autoUpload, autoUpload {
  195. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Auto upload: true")
  196. if UIApplication.shared.backgroundRefreshStatus == .available {
  197. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Auto upload in background: true")
  198. } else {
  199. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Auto upload in background: false")
  200. }
  201. } else {
  202. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Auto upload: false")
  203. }
  204. if let error = updateShareAccounts() {
  205. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] Create share accounts \(error.localizedDescription)")
  206. }
  207. scheduleAppRefresh()
  208. scheduleAppProcessing()
  209. NCNetworking.shared.cancelAllQueue()
  210. NCNetworking.shared.cancelDownloadTasks()
  211. NCNetworking.shared.cancelUploadTasks()
  212. NCPasscode.shared.presentPasscode(delegate: self) { }
  213. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterApplicationDidEnterBackground)
  214. }
  215. // L'applicazione terminerà
  216. func applicationWillTerminate(_ application: UIApplication) {
  217. if UIApplication.shared.backgroundRefreshStatus == .available {
  218. let content = UNMutableNotificationContent()
  219. content.title = NCBrandOptions.shared.brand
  220. content.body = NSLocalizedString("_keep_running_", comment: "")
  221. let req = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: nil)
  222. let notificationCenter = UNUserNotificationCenter.current()
  223. notificationCenter.add(req)
  224. }
  225. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] bye bye")
  226. }
  227. // MARK: - Background Task
  228. /*
  229. @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.
  230. < MAX 30 seconds >
  231. */
  232. func scheduleAppRefresh() {
  233. let request = BGAppRefreshTaskRequest(identifier: NCGlobal.shared.refreshTask)
  234. request.earliestBeginDate = Date(timeIntervalSinceNow: 60) // Refresh after 60 seconds.
  235. do {
  236. try BGTaskScheduler.shared.submit(request)
  237. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Refresh task: ok")
  238. } catch {
  239. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] Refresh task failed to submit request: \(error)")
  240. }
  241. }
  242. /*
  243. @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.
  244. < MAX over 1 minute >
  245. */
  246. func scheduleAppProcessing() {
  247. let request = BGProcessingTaskRequest(identifier: NCGlobal.shared.processingTask)
  248. request.earliestBeginDate = Date(timeIntervalSinceNow: 5 * 60) // Refresh after 5 minutes.
  249. request.requiresNetworkConnectivity = false
  250. request.requiresExternalPower = false
  251. do {
  252. try BGTaskScheduler.shared.submit(request)
  253. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Processing task: ok")
  254. } catch {
  255. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] Background Processing task failed to submit request: \(error)")
  256. }
  257. }
  258. func handleAppRefresh(_ task: BGTask) {
  259. scheduleAppRefresh()
  260. if isProcessingTask {
  261. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] ProcessingTask already in progress, abort.")
  262. return task.setTaskCompleted(success: true)
  263. }
  264. isAppRefresh = true
  265. handleAppRefreshProcessingTask(taskText: "AppRefresh") {
  266. task.setTaskCompleted(success: true)
  267. self.isAppRefresh = false
  268. }
  269. }
  270. func handleProcessingTask(_ task: BGTask) {
  271. scheduleAppProcessing()
  272. if isAppRefresh {
  273. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] AppRefresh already in progress, abort.")
  274. return task.setTaskCompleted(success: true)
  275. }
  276. isProcessingTask = true
  277. handleAppRefreshProcessingTask(taskText: "ProcessingTask") {
  278. task.setTaskCompleted(success: true)
  279. self.isProcessingTask = false
  280. }
  281. }
  282. func handleAppRefreshProcessingTask(taskText: String, completion: @escaping () -> Void = {}) {
  283. Task {
  284. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] \(taskText) start handle")
  285. let items = await NCAutoUpload.shared.initAutoUpload()
  286. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] \(taskText) auto upload with \(items) uploads")
  287. let results = await NCNetworkingProcess.shared.start()
  288. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] \(taskText) networking process with download: \(results.counterDownload) upload: \(results.counterUpload)")
  289. if taskText == "ProcessingTask",
  290. items == 0, results.counterDownload == 0, results.counterUpload == 0,
  291. let directories = NCManageDatabase.shared.getTablesDirectory(predicate: NSPredicate(format: "account == %@ AND offline == true", self.account), sorted: "offlineDate", ascending: true) {
  292. for directory: tableDirectory in directories {
  293. // only 3 time for day
  294. if let offlineDate = directory.offlineDate, offlineDate.addingTimeInterval(28800) > Date() {
  295. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] \(taskText) skip synchronization for \(directory.serverUrl) in date \(offlineDate)")
  296. continue
  297. }
  298. let results = await NCNetworking.shared.synchronization(account: self.account, serverUrl: directory.serverUrl, add: false)
  299. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] \(taskText) end synchronization for \(directory.serverUrl), errorCode: \(results.errorCode), item: \(results.items)")
  300. }
  301. }
  302. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] \(taskText) completion handle")
  303. completion()
  304. }
  305. }
  306. // MARK: - Background Networking Session
  307. func application(_ application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: @escaping () -> Void) {
  308. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Start handle Events For Background URLSession: \(identifier)")
  309. WidgetCenter.shared.reloadAllTimelines()
  310. backgroundSessionCompletionHandler = completionHandler
  311. }
  312. // MARK: - Push Notifications
  313. func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
  314. completionHandler([.list, .banner, .sound])
  315. }
  316. func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
  317. if let pref = UserDefaults(suiteName: NCBrandOptions.shared.capabilitiesGroups),
  318. let data = pref.object(forKey: "NOTIFICATION_DATA") as? [String: AnyObject] {
  319. nextcloudPushNotificationAction(data: data)
  320. pref.set(nil, forKey: "NOTIFICATION_DATA")
  321. }
  322. completionHandler()
  323. }
  324. func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
  325. NCNetworking.shared.checkPushNotificationServerProxyCertificateUntrusted(viewController: self.window?.rootViewController) { error in
  326. if error == .success {
  327. NCPushNotification.shared().registerForRemoteNotifications(withDeviceToken: deviceToken)
  328. }
  329. }
  330. }
  331. func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
  332. NCPushNotification.shared().applicationdidReceiveRemoteNotification(userInfo) { result in
  333. completionHandler(result)
  334. }
  335. }
  336. func nextcloudPushNotificationAction(data: [String: AnyObject]) {
  337. guard let data = NCApplicationHandle().nextcloudPushNotificationAction(data: data) else { return }
  338. var findAccount: Bool = false
  339. if let accountPush = data["account"] as? String {
  340. if accountPush == self.account {
  341. findAccount = true
  342. } else {
  343. let accounts = NCManageDatabase.shared.getAllAccount()
  344. for account in accounts {
  345. if account.account == accountPush {
  346. self.changeAccount(account.account, userProfile: nil)
  347. findAccount = true
  348. }
  349. }
  350. }
  351. if findAccount, let viewController = UIStoryboard(name: "NCNotification", bundle: nil).instantiateInitialViewController() as? NCNotification {
  352. DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
  353. let navigationController = UINavigationController(rootViewController: viewController)
  354. navigationController.modalPresentationStyle = .fullScreen
  355. self.window?.rootViewController?.present(navigationController, animated: true)
  356. }
  357. } else if !findAccount {
  358. let message = NSLocalizedString("_the_account_", comment: "") + " " + accountPush + " " + NSLocalizedString("_does_not_exist_", comment: "")
  359. let alertController = UIAlertController(title: NSLocalizedString("_info_", comment: ""), message: message, preferredStyle: .alert)
  360. alertController.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { _ in }))
  361. self.window?.rootViewController?.present(alertController, animated: true, completion: { })
  362. }
  363. }
  364. }
  365. // MARK: - Login & checkErrorNetworking
  366. @objc func openLogin(viewController: UIViewController?, selector: Int, openLoginWeb: Bool) {
  367. // [WEBPersonalized] [AppConfig]
  368. if NCBrandOptions.shared.use_login_web_personalized || NCBrandOptions.shared.use_AppConfig {
  369. if activeLoginWeb?.view.window == nil {
  370. activeLoginWeb = UIStoryboard(name: "NCLogin", bundle: nil).instantiateViewController(withIdentifier: "NCLoginWeb") as? NCLoginWeb
  371. activeLoginWeb?.urlBase = NCBrandOptions.shared.loginBaseUrl
  372. showLoginViewController(activeLoginWeb, contextViewController: viewController)
  373. }
  374. return
  375. }
  376. // Nextcloud standard login
  377. if selector == NCGlobal.shared.introSignup {
  378. if activeLoginWeb?.view.window == nil {
  379. activeLoginWeb = UIStoryboard(name: "NCLogin", bundle: nil).instantiateViewController(withIdentifier: "NCLoginWeb") as? NCLoginWeb
  380. if selector == NCGlobal.shared.introSignup {
  381. activeLoginWeb?.urlBase = NCBrandOptions.shared.linkloginPreferredProviders
  382. } else {
  383. activeLoginWeb?.urlBase = self.urlBase
  384. }
  385. showLoginViewController(activeLoginWeb, contextViewController: viewController)
  386. }
  387. } else if NCBrandOptions.shared.disable_intro && NCBrandOptions.shared.disable_request_login_url {
  388. if activeLoginWeb?.view.window == nil {
  389. activeLoginWeb = UIStoryboard(name: "NCLogin", bundle: nil).instantiateViewController(withIdentifier: "NCLoginWeb") as? NCLoginWeb
  390. activeLoginWeb?.urlBase = NCBrandOptions.shared.loginBaseUrl
  391. showLoginViewController(activeLoginWeb, contextViewController: viewController)
  392. }
  393. } else if openLoginWeb {
  394. // Used also for reinsert the account (change passwd)
  395. if activeLoginWeb?.view.window == nil {
  396. activeLoginWeb = UIStoryboard(name: "NCLogin", bundle: nil).instantiateViewController(withIdentifier: "NCLoginWeb") as? NCLoginWeb
  397. activeLoginWeb?.urlBase = urlBase
  398. activeLoginWeb?.user = user
  399. showLoginViewController(activeLoginWeb, contextViewController: viewController)
  400. }
  401. } else {
  402. if activeLogin?.view.window == nil {
  403. activeLogin = UIStoryboard(name: "NCLogin", bundle: nil).instantiateViewController(withIdentifier: "NCLogin") as? NCLogin
  404. showLoginViewController(activeLogin, contextViewController: viewController)
  405. }
  406. }
  407. }
  408. func showLoginViewController(_ viewController: UIViewController?, contextViewController: UIViewController?) {
  409. if contextViewController == nil {
  410. if let viewController = viewController {
  411. let navigationController = NCLoginNavigationController(rootViewController: viewController)
  412. navigationController.navigationBar.barStyle = .black
  413. navigationController.navigationBar.tintColor = NCBrandColor.shared.customerText
  414. navigationController.navigationBar.barTintColor = NCBrandColor.shared.customer
  415. navigationController.navigationBar.isTranslucent = false
  416. window?.rootViewController = navigationController
  417. window?.makeKeyAndVisible()
  418. }
  419. } else if contextViewController is UINavigationController {
  420. if let contextViewController = contextViewController, let viewController = viewController {
  421. (contextViewController as? UINavigationController)?.pushViewController(viewController, animated: true)
  422. }
  423. } else {
  424. if let viewController = viewController, let contextViewController = contextViewController {
  425. let navigationController = NCLoginNavigationController(rootViewController: viewController)
  426. navigationController.modalPresentationStyle = .fullScreen
  427. navigationController.navigationBar.barStyle = .black
  428. navigationController.navigationBar.tintColor = NCBrandColor.shared.customerText
  429. navigationController.navigationBar.barTintColor = NCBrandColor.shared.customer
  430. navigationController.navigationBar.isTranslucent = false
  431. contextViewController.present(navigationController, animated: true) { }
  432. }
  433. }
  434. }
  435. @objc func startTimerErrorNetworking() {
  436. timerErrorNetworking = Timer.scheduledTimer(timeInterval: 3, target: self, selector: #selector(checkErrorNetworking), userInfo: nil, repeats: true)
  437. }
  438. @objc private func checkErrorNetworking() {
  439. guard !account.isEmpty, NCKeychain().getPassword(account: account).isEmpty else { return }
  440. openLogin(viewController: window?.rootViewController, selector: NCGlobal.shared.introLogin, openLoginWeb: true)
  441. }
  442. func trustCertificateError(host: String) {
  443. guard let currentHost = URL(string: self.urlBase)?.host,
  444. let pushNotificationServerProxyHost = URL(string: NCBrandOptions.shared.pushNotificationServerProxy)?.host,
  445. host != pushNotificationServerProxyHost,
  446. host == currentHost
  447. else { return }
  448. let certificateHostSavedPath = NCUtilityFileSystem().directoryCertificates + "/" + host + ".der"
  449. var title = NSLocalizedString("_ssl_certificate_changed_", comment: "")
  450. if !FileManager.default.fileExists(atPath: certificateHostSavedPath) {
  451. title = NSLocalizedString("_connect_server_anyway_", comment: "")
  452. }
  453. let alertController = UIAlertController(title: title, message: NSLocalizedString("_server_is_trusted_", comment: ""), preferredStyle: .alert)
  454. alertController.addAction(UIAlertAction(title: NSLocalizedString("_yes_", comment: ""), style: .default, handler: { _ in
  455. NCNetworking.shared.writeCertificate(host: host)
  456. }))
  457. alertController.addAction(UIAlertAction(title: NSLocalizedString("_no_", comment: ""), style: .default, handler: { _ in }))
  458. alertController.addAction(UIAlertAction(title: NSLocalizedString("_certificate_details_", comment: ""), style: .default, handler: { _ in
  459. if let navigationController = UIStoryboard(name: "NCViewCertificateDetails", bundle: nil).instantiateInitialViewController() as? UINavigationController,
  460. let viewController = navigationController.topViewController as? NCViewCertificateDetails {
  461. viewController.delegate = self
  462. viewController.host = host
  463. self.window?.rootViewController?.present(navigationController, animated: true)
  464. }
  465. }))
  466. window?.rootViewController?.present(alertController, animated: true)
  467. }
  468. // MARK: - Account
  469. @objc func changeAccount(_ account: String, userProfile: NKUserProfile?) {
  470. NCNetworking.shared.cancelAllQueue()
  471. NCNetworking.shared.cancelDataTask()
  472. NCNetworking.shared.cancelDownloadTasks()
  473. NCNetworking.shared.cancelUploadTasks()
  474. guard let tableAccount = NCManageDatabase.shared.setAccountActive(account) else { return }
  475. if account != self.account {
  476. DispatchQueue.global().async {
  477. if NCManageDatabase.shared.getAccounts()?.count == 1 {
  478. NCImageCache.shared.createMediaCache(account: account, withCacheSize: true)
  479. } else {
  480. NCImageCache.shared.createMediaCache(account: account, withCacheSize: false)
  481. }
  482. }
  483. }
  484. self.account = tableAccount.account
  485. self.urlBase = tableAccount.urlBase
  486. self.user = tableAccount.user
  487. self.userId = tableAccount.userId
  488. self.password = NCKeychain().getPassword(account: tableAccount.account)
  489. NextcloudKit.shared.setup(account: account, user: user, userId: userId, password: password, urlBase: urlBase)
  490. NCManageDatabase.shared.setCapabilities(account: account)
  491. if let userProfile {
  492. NCManageDatabase.shared.setAccountUserProfile(account: account, userProfile: userProfile)
  493. }
  494. NCPushNotification.shared().pushNotification()
  495. NCService().startRequestServicesServer()
  496. NCAutoUpload.shared.initAutoUpload(viewController: nil) { items in
  497. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Initialize Auto upload with \(items) uploads")
  498. }
  499. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterChangeUser)
  500. }
  501. @objc func deleteAccount(_ account: String, wipe: Bool) {
  502. if let account = NCManageDatabase.shared.getAccount(predicate: NSPredicate(format: "account == %@", account)) {
  503. NCPushNotification.shared().unsubscribingNextcloudServerPushNotification(account.account, urlBase: account.urlBase, user: account.user, withSubscribing: false)
  504. }
  505. NextcloudKit.shared.deleteAppPassword(serverUrl: urlBase, username: userId, password: password) { _, error in
  506. print(error)
  507. }
  508. let results = NCManageDatabase.shared.getTableLocalFiles(predicate: NSPredicate(format: "account == %@", account), sorted: "ocId", ascending: false)
  509. let utilityFileSystem = NCUtilityFileSystem()
  510. for result in results {
  511. utilityFileSystem.removeFile(atPath: utilityFileSystem.getDirectoryProviderStorageOcId(result.ocId))
  512. }
  513. NCManageDatabase.shared.clearDatabase(account: account, removeAccount: true)
  514. NCKeychain().clearAllKeysEndToEnd(account: account)
  515. NCKeychain().clearAllKeysPushNotification(account: account)
  516. NCKeychain().setPassword(account: account, password: nil)
  517. self.account = ""
  518. self.urlBase = ""
  519. self.user = ""
  520. self.userId = ""
  521. self.password = ""
  522. if wipe {
  523. let accounts = NCManageDatabase.shared.getAccounts()
  524. if accounts?.count ?? 0 > 0 {
  525. if let newAccount = accounts?.first {
  526. self.changeAccount(newAccount, userProfile: nil)
  527. }
  528. } else {
  529. openLogin(viewController: window?.rootViewController, selector: NCGlobal.shared.introLogin, openLoginWeb: false)
  530. }
  531. }
  532. }
  533. func deleteAllAccounts() {
  534. let accounts = NCManageDatabase.shared.getAccounts()
  535. accounts?.forEach({ account in
  536. deleteAccount(account, wipe: true)
  537. })
  538. }
  539. func updateShareAccounts() -> Error? {
  540. guard let dirGroupApps = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: NCBrandOptions.shared.capabilitiesGroupApps) else { return nil }
  541. let tableAccount = NCManageDatabase.shared.getAllAccount()
  542. var accounts = [NKShareAccounts.DataAccounts]()
  543. for account in tableAccount {
  544. let name = account.alias.isEmpty ? account.displayName : account.alias
  545. let userBaseUrl = account.user + "-" + (URL(string: account.urlBase)?.host ?? "")
  546. let avatarFileName = userBaseUrl + "-\(account.user).png"
  547. let pathAvatarFileName = NCUtilityFileSystem().directoryUserData + "/" + avatarFileName
  548. let image = UIImage(contentsOfFile: pathAvatarFileName)
  549. accounts.append(NKShareAccounts.DataAccounts(withUrl: account.urlBase, user: account.user, name: name, image: image))
  550. }
  551. return NKShareAccounts().putShareAccounts(at: dirGroupApps, app: NCGlobal.shared.appScheme, dataAccounts: accounts)
  552. }
  553. // MARK: - Reset Application
  554. @objc func resetApplication() {
  555. let utilityFileSystem = NCUtilityFileSystem()
  556. NCNetworking.shared.cancelAllTask()
  557. URLCache.shared.memoryCapacity = 0
  558. URLCache.shared.diskCapacity = 0
  559. utilityFileSystem.removeGroupDirectoryProviderStorage()
  560. utilityFileSystem.removeGroupApplicationSupport()
  561. utilityFileSystem.removeDocumentsDirectory()
  562. utilityFileSystem.removeTemporaryDirectory()
  563. NCKeychain().removeAll()
  564. exit(0)
  565. }
  566. // MARK: - Universal Links
  567. func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
  568. let applicationHandle = NCApplicationHandle()
  569. return applicationHandle.applicationOpenUserActivity(userActivity)
  570. }
  571. // MARK: - Scheme URL
  572. func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool {
  573. let scheme = url.scheme
  574. let action = url.host
  575. var fileName: String = ""
  576. var serverUrl: String = ""
  577. /*
  578. Example: nextcloud://open-action?action=create-voice-memo&&user=marinofaggiana&url=https://cloud.nextcloud.com
  579. */
  580. if !account.isEmpty && scheme == NCGlobal.shared.appScheme && action == "open-action" {
  581. if let urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false) {
  582. let queryItems = urlComponents.queryItems
  583. guard let actionScheme = queryItems?.filter({ $0.name == "action" }).first?.value,
  584. let userScheme = queryItems?.filter({ $0.name == "user" }).first?.value,
  585. let urlScheme = queryItems?.filter({ $0.name == "url" }).first?.value,
  586. let rootViewController = window?.rootViewController else { return false }
  587. if getMatchedAccount(userId: userScheme, url: urlScheme) == nil {
  588. let message = NSLocalizedString("_the_account_", comment: "") + " " + userScheme + NSLocalizedString("_of_", comment: "") + " " + urlScheme + " " + NSLocalizedString("_does_not_exist_", comment: "")
  589. let alertController = UIAlertController(title: NSLocalizedString("_info_", comment: ""), message: message, preferredStyle: .alert)
  590. alertController.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { _ in }))
  591. window?.rootViewController?.present(alertController, animated: true, completion: { })
  592. return false
  593. }
  594. switch actionScheme {
  595. case NCGlobal.shared.actionUploadAsset:
  596. NCAskAuthorization().askAuthorizationPhotoLibrary(viewController: rootViewController) { hasPermission in
  597. if hasPermission {
  598. NCPhotosPickerViewController(viewController: rootViewController, maxSelectedAssets: 0, singleSelectedMode: false)
  599. }
  600. }
  601. case NCGlobal.shared.actionScanDocument:
  602. NCDocumentCamera.shared.openScannerDocument(viewController: rootViewController)
  603. case NCGlobal.shared.actionTextDocument:
  604. guard let navigationController = UIStoryboard(name: "NCCreateFormUploadDocuments", bundle: nil).instantiateInitialViewController(),
  605. let directEditingCreators = NCManageDatabase.shared.getDirectEditingCreators(account: account),
  606. let directEditingCreator = directEditingCreators.first(where: { $0.editor == NCGlobal.shared.editorText}),
  607. let viewController = (navigationController as? UINavigationController)?.topViewController as? NCCreateFormUploadDocuments else { return false }
  608. navigationController.modalPresentationStyle = UIModalPresentationStyle.formSheet
  609. viewController.editorId = NCGlobal.shared.editorText
  610. viewController.creatorId = directEditingCreator.identifier
  611. viewController.typeTemplate = NCGlobal.shared.templateDocument
  612. viewController.serverUrl = activeServerUrl
  613. viewController.titleForm = NSLocalizedString("_create_nextcloudtext_document_", comment: "")
  614. rootViewController.present(navigationController, animated: true, completion: nil)
  615. case NCGlobal.shared.actionVoiceMemo:
  616. NCAskAuthorization().askAuthorizationAudioRecord(viewController: rootViewController) { hasPermission in
  617. if hasPermission {
  618. if let viewController = UIStoryboard(name: "NCAudioRecorderViewController", bundle: nil).instantiateInitialViewController() as? NCAudioRecorderViewController {
  619. viewController.modalTransitionStyle = .crossDissolve
  620. viewController.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext
  621. rootViewController.present(viewController, animated: true, completion: nil)
  622. }
  623. }
  624. }
  625. default:
  626. print("No action")
  627. }
  628. }
  629. return true
  630. }
  631. /*
  632. Example: nextcloud://open-file?path=Talk/IMG_0000123.jpg&user=marinofaggiana&link=https://cloud.nextcloud.com/f/123
  633. */
  634. else if !account.isEmpty && scheme == NCGlobal.shared.appScheme && action == "open-file" {
  635. if let urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false) {
  636. let queryItems = urlComponents.queryItems
  637. guard let userScheme = queryItems?.filter({ $0.name == "user" }).first?.value,
  638. let pathScheme = queryItems?.filter({ $0.name == "path" }).first?.value,
  639. let linkScheme = queryItems?.filter({ $0.name == "link" }).first?.value else { return false}
  640. guard let matchedAccount = getMatchedAccount(userId: userScheme, url: linkScheme) else {
  641. guard let domain = URL(string: linkScheme)?.host else { return true }
  642. fileName = (pathScheme as NSString).lastPathComponent
  643. let message = String(format: NSLocalizedString("_account_not_available_", comment: ""), userScheme, domain, fileName)
  644. let alertController = UIAlertController(title: NSLocalizedString("_info_", comment: ""), message: message, preferredStyle: .alert)
  645. alertController.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { _ in }))
  646. window?.rootViewController?.present(alertController, animated: true, completion: { })
  647. return false
  648. }
  649. let davFiles = NextcloudKit.shared.nkCommonInstance.dav + "/files/" + self.userId
  650. if pathScheme.contains("/") {
  651. fileName = (pathScheme as NSString).lastPathComponent
  652. serverUrl = matchedAccount.urlBase + "/" + davFiles + "/" + (pathScheme as NSString).deletingLastPathComponent
  653. } else {
  654. fileName = pathScheme
  655. serverUrl = matchedAccount.urlBase + "/" + davFiles
  656. }
  657. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  658. NCActionCenter.shared.openFileViewInFolder(serverUrl: serverUrl, fileNameBlink: nil, fileNameOpen: fileName)
  659. }
  660. }
  661. return true
  662. /*
  663. Example: nextcloud://open-and-switch-account?user=marinofaggiana&url=https://cloud.nextcloud.com
  664. */
  665. } else if !account.isEmpty && scheme == NCGlobal.shared.appScheme && action == "open-and-switch-account" {
  666. guard let urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false) else { return false }
  667. let queryItems = urlComponents.queryItems
  668. guard let userScheme = queryItems?.filter({ $0.name == "user" }).first?.value,
  669. let urlScheme = queryItems?.filter({ $0.name == "url" }).first?.value else { return false}
  670. // If the account doesn't exist, return false which will open the app without switching
  671. if getMatchedAccount(userId: userScheme, url: urlScheme) == nil {
  672. return false
  673. }
  674. // Otherwise open the app and switch accounts
  675. return true
  676. } else {
  677. let applicationHandle = NCApplicationHandle()
  678. let isHandled = applicationHandle.applicationOpenURL(url)
  679. if isHandled {
  680. return true
  681. } else {
  682. app.open(url)
  683. return true
  684. }
  685. }
  686. }
  687. func getMatchedAccount(userId: String, url: String) -> tableAccount? {
  688. if let activeAccount = NCManageDatabase.shared.getActiveAccount() {
  689. let urlBase = URL(string: activeAccount.urlBase)
  690. if url.contains(urlBase?.host ?? "") && userId == activeAccount.userId {
  691. return activeAccount
  692. } else {
  693. let accounts = NCManageDatabase.shared.getAllAccount()
  694. for account in accounts {
  695. let urlBase = URL(string: account.urlBase)
  696. if url.contains(urlBase?.host ?? "") && userId == account.userId {
  697. changeAccount(account.account, userProfile: nil)
  698. return account
  699. }
  700. }
  701. }
  702. }
  703. return nil
  704. }
  705. }
  706. // MARK: -
  707. extension AppDelegate: NCViewCertificateDetailsDelegate {
  708. func viewCertificateDetailsDismiss(host: String) {
  709. trustCertificateError(host: host)
  710. }
  711. }
  712. extension AppDelegate: NCCreateFormUploadConflictDelegate {
  713. func dismissCreateFormUploadConflict(metadatas: [tableMetadata]?) {
  714. guard let metadatas = metadatas, !metadatas.isEmpty else { return }
  715. NCNetworkingProcess.shared.createProcessUploads(metadatas: metadatas)
  716. }
  717. }
  718. extension AppDelegate: NCPasscodeDelegate {
  719. func requestedAccount() {
  720. guard !NCPasscode.shared.isPasscodePresented, NCKeychain().accountRequest else {
  721. return
  722. }
  723. let accounts = NCManageDatabase.shared.getAllAccount()
  724. if accounts.count > 1 {
  725. if let viewController = UIStoryboard(name: "NCAccountRequest", bundle: nil).instantiateInitialViewController() as? NCAccountRequest {
  726. viewController.activeAccount = NCManageDatabase.shared.getActiveAccount()
  727. viewController.accounts = accounts
  728. viewController.enableTimerProgress = true
  729. viewController.enableAddAccount = false
  730. viewController.dismissDidEnterBackground = false
  731. viewController.delegate = self
  732. let screenHeighMax = UIScreen.main.bounds.height - (UIScreen.main.bounds.height / 5)
  733. let numberCell = accounts.count
  734. let height = min(CGFloat(numberCell * Int(viewController.heightCell) + 45), screenHeighMax)
  735. let popup = NCPopupViewController(contentController: viewController, popupWidth: 300, popupHeight: height + 20)
  736. popup.backgroundAlpha = 0.8
  737. window?.rootViewController?.present(popup, animated: true)
  738. viewController.startTimer()
  739. }
  740. }
  741. }
  742. func passcodeReset(_ passcodeViewController: TOPasscodeViewController) {
  743. resetApplication()
  744. }
  745. }
  746. extension AppDelegate: NCAccountRequestDelegate {
  747. func accountRequestChangeAccount(account: String) {
  748. changeAccount(account, userProfile: nil)
  749. }
  750. }