SceneDelegate.swift 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  1. //
  2. // SceneDelegate.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 25/03/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. import WidgetKit
  27. import SwiftEntryKit
  28. class SceneDelegate: UIResponder, UIWindowSceneDelegate {
  29. var window: UIWindow?
  30. private let appDelegate = UIApplication.shared.delegate as? AppDelegate
  31. private var privacyProtectionWindow: UIWindow?
  32. private var isFirstScene: Bool = true
  33. private let database = NCManageDatabase.shared
  34. func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
  35. guard let windowScene = (scene as? UIWindowScene),
  36. let appDelegate else { return }
  37. self.window = UIWindow(windowScene: windowScene)
  38. if let activeTableAccount = self.database.getActiveTableAccount() {
  39. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Account active \(activeTableAccount.account)")
  40. let capability = self.database.setCapabilities(account: activeTableAccount.account)
  41. NCBrandColor.shared.settingThemingColor(account: activeTableAccount.account)
  42. for tableAccount in self.database.getAllTableAccount() {
  43. NextcloudKit.shared.appendSession(account: tableAccount.account,
  44. urlBase: tableAccount.urlBase,
  45. user: tableAccount.user,
  46. userId: tableAccount.userId,
  47. password: NCKeychain().getPassword(account: tableAccount.account),
  48. userAgent: userAgent,
  49. nextcloudVersion: capability?.capabilityServerVersionMajor ?? 0,
  50. groupIdentifier: NCBrandOptions.shared.capabilitiesGroup)
  51. NCSession.shared.appendSession(account: tableAccount.account, urlBase: tableAccount.urlBase, user: tableAccount.user, userId: tableAccount.userId)
  52. }
  53. /// Main.storyboard
  54. if let controller = UIStoryboard(name: "Main", bundle: nil).instantiateInitialViewController() as? NCMainTabBarController {
  55. SceneManager.shared.register(scene: scene, withRootViewController: controller)
  56. window?.rootViewController = controller
  57. window?.makeKeyAndVisible()
  58. /// Set the ACCOUNT
  59. controller.account = activeTableAccount.account
  60. }
  61. } else {
  62. NCKeychain().removeAll()
  63. if let bundleID = Bundle.main.bundleIdentifier {
  64. UserDefaults.standard.removePersistentDomain(forName: bundleID)
  65. }
  66. if NCBrandOptions.shared.disable_intro {
  67. appDelegate.openLogin(selector: NCGlobal.shared.introLogin, window: window)
  68. } else {
  69. if let viewController = UIStoryboard(name: "NCIntro", bundle: nil).instantiateInitialViewController() as? NCIntroViewController {
  70. let navigationController = NCLoginNavigationController(rootViewController: viewController)
  71. window?.rootViewController = navigationController
  72. window?.makeKeyAndVisible()
  73. }
  74. }
  75. }
  76. }
  77. func sceneDidDisconnect(_ scene: UIScene) {
  78. print("[DEBUG] Scene did disconnect")
  79. }
  80. func sceneWillEnterForeground(_ scene: UIScene) {
  81. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Scene will enter in foreground")
  82. let session = SceneManager.shared.getSession(scene: scene)
  83. // In Login mode is possible ONLY 1 window
  84. if (UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }).count > 1,
  85. (appDelegate?.activeLogin?.view.window != nil || appDelegate?.activeLoginWeb?.view.window != nil) || (UIApplication.shared.firstWindow?.rootViewController is NCLoginNavigationController) {
  86. UIApplication.shared.allSceneSessionDestructionExceptFirst()
  87. return
  88. }
  89. guard !session.account.isEmpty else { return }
  90. hidePrivacyProtectionWindow()
  91. if let window = SceneManager.shared.getWindow(scene: scene), let controller = SceneManager.shared.getController(scene: scene) {
  92. window.rootViewController = controller
  93. if NCKeychain().presentPasscode {
  94. NCPasscode.shared.presentPasscode(viewController: controller, delegate: self) {
  95. NCPasscode.shared.enableTouchFaceID()
  96. }
  97. } else if NCKeychain().accountRequest {
  98. requestedAccount(controller: controller)
  99. }
  100. }
  101. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterRichdocumentGrabFocus)
  102. }
  103. func sceneDidBecomeActive(_ scene: UIScene) {
  104. let session = SceneManager.shared.getSession(scene: scene)
  105. let controller = SceneManager.shared.getController(scene: scene)
  106. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Scene did become active")
  107. hidePrivacyProtectionWindow()
  108. NCAutoUpload.shared.initAutoUpload(controller: nil, account: session.account) { num in
  109. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Initialize Auto upload with \(num) uploads")
  110. }
  111. DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
  112. NCService().startRequestServicesServer(account: session.account, controller: controller)
  113. }
  114. DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
  115. Task {
  116. await NCNetworking.shared.verifyZombie()
  117. }
  118. }
  119. }
  120. func sceneWillResignActive(_ scene: UIScene) {
  121. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Scene will resign active")
  122. NSFileProviderManager.removeAllDomains { _ in
  123. /*
  124. if !NCKeychain().disableFilesApp,
  125. self.database.getAllTableAccount().count > 1 {
  126. FileProviderDomain().registerDomains()
  127. }
  128. */
  129. }
  130. ///
  131. let session = SceneManager.shared.getSession(scene: scene)
  132. guard !session.account.isEmpty else { return }
  133. if NCKeychain().privacyScreenEnabled {
  134. if SwiftEntryKit.isCurrentlyDisplaying {
  135. SwiftEntryKit.dismiss {
  136. self.showPrivacyProtectionWindow()
  137. }
  138. } else {
  139. showPrivacyProtectionWindow()
  140. }
  141. }
  142. // Clear older files
  143. let days = NCKeychain().cleanUpDay
  144. let utilityFileSystem = NCUtilityFileSystem()
  145. utilityFileSystem.cleanUp(directory: utilityFileSystem.directoryProviderStorage, days: TimeInterval(days))
  146. }
  147. func sceneDidEnterBackground(_ scene: UIScene) {
  148. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Scene did enter in background")
  149. let session = SceneManager.shared.getSession(scene: scene)
  150. guard let tableAccount = self.database.getTableAccount(predicate: NSPredicate(format: "account == %@", session.account)) else {
  151. return
  152. }
  153. if tableAccount.autoUpload {
  154. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Auto upload: true")
  155. if UIApplication.shared.backgroundRefreshStatus == .available {
  156. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Auto upload in background: true")
  157. } else {
  158. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Auto upload in background: false")
  159. }
  160. } else {
  161. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Auto upload: false")
  162. }
  163. if let error = NCAccount().updateAppsShareAccounts() {
  164. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] Create Apps share accounts \(error.localizedDescription)")
  165. }
  166. appDelegate?.scheduleAppRefresh()
  167. appDelegate?.scheduleAppProcessing()
  168. NCNetworking.shared.cancelAllQueue()
  169. if NCKeychain().presentPasscode {
  170. showPrivacyProtectionWindow()
  171. }
  172. }
  173. func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
  174. guard let controller = SceneManager.shared.getController(scene: scene),
  175. let url = URLContexts.first?.url else { return }
  176. let scheme = url.scheme
  177. let action = url.host
  178. let session = SceneManager.shared.getSession(scene: scene)
  179. guard !session.account.isEmpty else { return }
  180. func getMatchedAccount(userId: String, url: String) -> tableAccount? {
  181. if let activeTableAccount = self.database.getActiveTableAccount() {
  182. let urlBase = URL(string: activeTableAccount.urlBase)
  183. if url.contains(urlBase?.host ?? "") && userId == activeTableAccount.userId {
  184. return activeTableAccount
  185. } else {
  186. for tableAccount in self.database.getAllTableAccount() {
  187. let urlBase = URL(string: tableAccount.urlBase)
  188. if url.contains(urlBase?.host ?? "") && userId == tableAccount.userId {
  189. NCAccount().changeAccount(tableAccount.account, userProfile: nil, controller: controller) { }
  190. return tableAccount
  191. }
  192. }
  193. }
  194. }
  195. return nil
  196. }
  197. /*
  198. Example: nextcloud://open-action?action=create-voice-memo&&user=marinofaggiana&url=https://cloud.nextcloud.com
  199. */
  200. if scheme == NCGlobal.shared.appScheme && action == "open-action" {
  201. if let urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false) {
  202. let queryItems = urlComponents.queryItems
  203. guard let actionScheme = queryItems?.filter({ $0.name == "action" }).first?.value,
  204. let userScheme = queryItems?.filter({ $0.name == "user" }).first?.value,
  205. let urlScheme = queryItems?.filter({ $0.name == "url" }).first?.value else { return }
  206. if getMatchedAccount(userId: userScheme, url: urlScheme) == nil {
  207. let message = NSLocalizedString("_the_account_", comment: "") + " " + userScheme + NSLocalizedString("_of_", comment: "") + " " + urlScheme + " " + NSLocalizedString("_does_not_exist_", comment: "")
  208. let alertController = UIAlertController(title: NSLocalizedString("_info_", comment: ""), message: message, preferredStyle: .alert)
  209. alertController.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { _ in }))
  210. controller.present(alertController, animated: true, completion: { })
  211. return
  212. }
  213. switch actionScheme {
  214. case NCGlobal.shared.actionUploadAsset:
  215. NCAskAuthorization().askAuthorizationPhotoLibrary(controller: controller) { hasPermission in
  216. if hasPermission {
  217. NCPhotosPickerViewController(controller: controller, maxSelectedAssets: 0, singleSelectedMode: false)
  218. }
  219. }
  220. case NCGlobal.shared.actionScanDocument:
  221. NCDocumentCamera.shared.openScannerDocument(viewController: controller)
  222. case NCGlobal.shared.actionTextDocument:
  223. let directEditingCreators = self.database.getDirectEditingCreators(account: session.account)
  224. let directEditingCreator = directEditingCreators!.first(where: { $0.editor == NCGlobal.shared.editorText})!
  225. let serverUrl = controller.currentServerUrl()
  226. Task {
  227. let fileName = await NCNetworking.shared.createFileName(fileNameBase: NSLocalizedString("_untitled_", comment: "") + ".md", account: session.account, serverUrl: serverUrl)
  228. let fileNamePath = NCUtilityFileSystem().getFileNamePath(String(describing: fileName), serverUrl: serverUrl, session: session)
  229. NCCreateDocument().createDocument(controller: controller, fileNamePath: fileNamePath, fileName: String(describing: fileName), editorId: NCGlobal.shared.editorText, creatorId: directEditingCreator.identifier, templateId: NCGlobal.shared.templateDocument, account: session.account)
  230. }
  231. case NCGlobal.shared.actionVoiceMemo:
  232. NCAskAuthorization().askAuthorizationAudioRecord(viewController: controller) { hasPermission in
  233. if hasPermission {
  234. if let viewController = UIStoryboard(name: "NCAudioRecorderViewController", bundle: nil).instantiateInitialViewController() as? NCAudioRecorderViewController {
  235. viewController.controller = controller
  236. viewController.modalTransitionStyle = .crossDissolve
  237. viewController.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext
  238. controller.present(viewController, animated: true, completion: nil)
  239. }
  240. }
  241. }
  242. default:
  243. print("No action")
  244. }
  245. }
  246. return
  247. }
  248. /*
  249. Example: nextcloud://open-file?path=Talk/IMG_0000123.jpg&user=marinofaggiana&link=https://cloud.nextcloud.com/f/123
  250. */
  251. else if scheme == NCGlobal.shared.appScheme && action == "open-file" {
  252. if let urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false) {
  253. var serverUrl: String = ""
  254. var fileName: String = ""
  255. let queryItems = urlComponents.queryItems
  256. guard let userScheme = queryItems?.filter({ $0.name == "user" }).first?.value,
  257. let pathScheme = queryItems?.filter({ $0.name == "path" }).first?.value,
  258. let linkScheme = queryItems?.filter({ $0.name == "link" }).first?.value else { return}
  259. guard let matchedAccount = getMatchedAccount(userId: userScheme, url: linkScheme) else {
  260. guard let domain = URL(string: linkScheme)?.host else { return }
  261. fileName = (pathScheme as NSString).lastPathComponent
  262. let message = String(format: NSLocalizedString("_account_not_available_", comment: ""), userScheme, domain, fileName)
  263. let alertController = UIAlertController(title: NSLocalizedString("_info_", comment: ""), message: message, preferredStyle: .alert)
  264. alertController.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { _ in }))
  265. controller.present(alertController, animated: true, completion: { })
  266. return
  267. }
  268. let davFiles = "remote.php/dav/files/" + session.userId
  269. if pathScheme.contains("/") {
  270. fileName = (pathScheme as NSString).lastPathComponent
  271. serverUrl = matchedAccount.urlBase + "/" + davFiles + "/" + (pathScheme as NSString).deletingLastPathComponent
  272. } else {
  273. fileName = pathScheme
  274. serverUrl = matchedAccount.urlBase + "/" + davFiles
  275. }
  276. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  277. NCActionCenter.shared.openFileViewInFolder(serverUrl: serverUrl, fileNameBlink: nil, fileNameOpen: fileName, sceneIdentifier: controller.sceneIdentifier)
  278. }
  279. }
  280. return
  281. /*
  282. Example: nextcloud://open-and-switch-account?user=marinofaggiana&url=https://cloud.nextcloud.com
  283. */
  284. } else if scheme == NCGlobal.shared.appScheme && action == "open-and-switch-account" {
  285. guard let urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false) else { return }
  286. let queryItems = urlComponents.queryItems
  287. guard let userScheme = queryItems?.filter({ $0.name == "user" }).first?.value,
  288. let urlScheme = queryItems?.filter({ $0.name == "url" }).first?.value else { return }
  289. // If the account doesn't exist, return false which will open the app without switching
  290. if getMatchedAccount(userId: userScheme, url: urlScheme) == nil {
  291. return
  292. }
  293. // Otherwise open the app and switch accounts
  294. return
  295. } else if let action {
  296. if DeepLink(rawValue: action) != nil {
  297. NCDeepLinkHandler().parseDeepLink(url, controller: controller)
  298. }
  299. return
  300. } else {
  301. let applicationHandle = NCApplicationHandle()
  302. let isHandled = applicationHandle.applicationOpenURL(url)
  303. if isHandled {
  304. return
  305. } else {
  306. scene.open(url, options: nil)
  307. }
  308. }
  309. }
  310. private func showPrivacyProtectionWindow() {
  311. guard let windowScene = self.window?.windowScene else {
  312. return
  313. }
  314. privacyProtectionWindow = UIWindow(windowScene: windowScene)
  315. privacyProtectionWindow?.rootViewController = UIStoryboard(name: "LaunchScreen", bundle: nil).instantiateInitialViewController()
  316. privacyProtectionWindow?.windowLevel = .alert + 1
  317. privacyProtectionWindow?.makeKeyAndVisible()
  318. }
  319. private func hidePrivacyProtectionWindow() {
  320. privacyProtectionWindow?.isHidden = true
  321. privacyProtectionWindow = nil
  322. }
  323. }
  324. // MARK: - Extension
  325. extension SceneDelegate: NCPasscodeDelegate {
  326. func requestedAccount(controller: UIViewController?) {
  327. let tableAccounts = self.database.getAllTableAccount()
  328. if tableAccounts.count > 1, let accountRequestVC = UIStoryboard(name: "NCAccountRequest", bundle: nil).instantiateInitialViewController() as? NCAccountRequest {
  329. accountRequestVC.controller = controller
  330. accountRequestVC.activeAccount = (controller as? NCMainTabBarController)?.account
  331. accountRequestVC.accounts = tableAccounts
  332. accountRequestVC.enableTimerProgress = true
  333. accountRequestVC.enableAddAccount = false
  334. accountRequestVC.dismissDidEnterBackground = false
  335. accountRequestVC.delegate = self
  336. accountRequestVC.startTimer()
  337. let screenHeighMax = UIScreen.main.bounds.height - (UIScreen.main.bounds.height / 5)
  338. let numberCell = tableAccounts.count
  339. let height = min(CGFloat(numberCell * Int(accountRequestVC.heightCell) + 45), screenHeighMax)
  340. let popup = NCPopupViewController(contentController: accountRequestVC, popupWidth: 300, popupHeight: height + 20)
  341. popup.backgroundAlpha = 0.8
  342. controller?.present(popup, animated: true)
  343. }
  344. }
  345. func passcodeReset(_ passcodeViewController: TOPasscodeViewController) {
  346. appDelegate?.resetApplication()
  347. }
  348. }
  349. extension SceneDelegate: NCAccountRequestDelegate {
  350. func accountRequestAddAccount() { }
  351. func accountRequestChangeAccount(account: String, controller: UIViewController?) {
  352. NCAccount().changeAccount(account, userProfile: nil, controller: controller as? NCMainTabBarController) { }
  353. }
  354. }
  355. // MARK: - Scene Manager
  356. class SceneManager {
  357. static let shared = SceneManager()
  358. private var sceneController: [NCMainTabBarController: UIScene] = [:]
  359. func register(scene: UIScene, withRootViewController rootViewController: NCMainTabBarController) {
  360. sceneController[rootViewController] = scene
  361. }
  362. func getController(scene: UIScene?) -> NCMainTabBarController? {
  363. for controller in sceneController.keys {
  364. if sceneController[controller] == scene {
  365. return controller
  366. }
  367. }
  368. return nil
  369. }
  370. func getController(sceneIdentifier: String?) -> NCMainTabBarController? {
  371. if let sceneIdentifier {
  372. for controller in sceneController.keys {
  373. if sceneIdentifier == controller.sceneIdentifier {
  374. return controller
  375. }
  376. }
  377. }
  378. return nil
  379. }
  380. func getControllers() -> [NCMainTabBarController] {
  381. return Array(sceneController.keys)
  382. }
  383. func getWindow(scene: UIScene?) -> UIWindow? {
  384. return (scene as? UIWindowScene)?.keyWindow
  385. }
  386. func getWindow(controller: NCMainTabBarController?) -> UIWindow? {
  387. guard let controller,
  388. let scene = sceneController[controller] else { return nil }
  389. return getWindow(scene: scene)
  390. }
  391. func getSceneIdentifier() -> [String] {
  392. var results: [String] = []
  393. for controller in sceneController.keys {
  394. results.append(controller.sceneIdentifier)
  395. }
  396. return results
  397. }
  398. func getSession(scene: UIScene?) -> NCSession.Session {
  399. let controller = SceneManager.shared.getController(scene: scene)
  400. return NCSession.shared.getSession(controller: controller)
  401. }
  402. }