SceneDelegate.swift 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  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)
  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. NCService().startRequestServicesServer(account: session.account, controller: controller)
  109. NCAutoUpload.shared.initAutoUpload(controller: nil, account: session.account) { num in
  110. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Initialize Auto upload with \(num) uploads")
  111. }
  112. DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
  113. Task {
  114. await NCNetworking.shared.verifyZombie()
  115. }
  116. }
  117. }
  118. func sceneWillResignActive(_ scene: UIScene) {
  119. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Scene will resign active")
  120. NSFileProviderManager.removeAllDomains { _ in
  121. /*
  122. if !NCKeychain().disableFilesApp,
  123. self.database.getAllTableAccount().count > 1 {
  124. FileProviderDomain().registerDomains()
  125. }
  126. */
  127. }
  128. ///
  129. let session = SceneManager.shared.getSession(scene: scene)
  130. guard !session.account.isEmpty else { return }
  131. if NCKeychain().privacyScreenEnabled {
  132. if SwiftEntryKit.isCurrentlyDisplaying {
  133. SwiftEntryKit.dismiss {
  134. self.showPrivacyProtectionWindow()
  135. }
  136. } else {
  137. showPrivacyProtectionWindow()
  138. }
  139. }
  140. // Clear older files
  141. let days = NCKeychain().cleanUpDay
  142. let utilityFileSystem = NCUtilityFileSystem()
  143. utilityFileSystem.cleanUp(directory: utilityFileSystem.directoryProviderStorage, days: TimeInterval(days))
  144. }
  145. func sceneDidEnterBackground(_ scene: UIScene) {
  146. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Scene did enter in background")
  147. let session = SceneManager.shared.getSession(scene: scene)
  148. guard let tableAccount = self.database.getTableAccount(predicate: NSPredicate(format: "account == %@", session.account)) else {
  149. return
  150. }
  151. if tableAccount.autoUpload {
  152. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Auto upload: true")
  153. if UIApplication.shared.backgroundRefreshStatus == .available {
  154. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Auto upload in background: true")
  155. } else {
  156. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Auto upload in background: false")
  157. }
  158. } else {
  159. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Auto upload: false")
  160. }
  161. if let error = NCAccount().updateAppsShareAccounts() {
  162. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] Create Apps share accounts \(error.localizedDescription)")
  163. }
  164. appDelegate?.scheduleAppRefresh()
  165. appDelegate?.scheduleAppProcessing()
  166. NCNetworking.shared.cancelAllQueue()
  167. if NCKeychain().presentPasscode {
  168. showPrivacyProtectionWindow()
  169. }
  170. }
  171. func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
  172. guard let controller = SceneManager.shared.getController(scene: scene),
  173. let url = URLContexts.first?.url else { return }
  174. let scheme = url.scheme
  175. let action = url.host
  176. let session = SceneManager.shared.getSession(scene: scene)
  177. guard !session.account.isEmpty else { return }
  178. func getMatchedAccount(userId: String, url: String) -> tableAccount? {
  179. if let activeTableAccount = self.database.getActiveTableAccount() {
  180. let urlBase = URL(string: activeTableAccount.urlBase)
  181. if url.contains(urlBase?.host ?? "") && userId == activeTableAccount.userId {
  182. return activeTableAccount
  183. } else {
  184. for tableAccount in self.database.getAllTableAccount() {
  185. let urlBase = URL(string: tableAccount.urlBase)
  186. if url.contains(urlBase?.host ?? "") && userId == tableAccount.userId {
  187. NCAccount().changeAccount(tableAccount.account, userProfile: nil, controller: controller) { }
  188. return tableAccount
  189. }
  190. }
  191. }
  192. }
  193. return nil
  194. }
  195. /*
  196. Example: nextcloud://open-action?action=create-voice-memo&&user=marinofaggiana&url=https://cloud.nextcloud.com
  197. */
  198. if scheme == NCGlobal.shared.appScheme && action == "open-action" {
  199. if let urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false) {
  200. let queryItems = urlComponents.queryItems
  201. guard let actionScheme = queryItems?.filter({ $0.name == "action" }).first?.value,
  202. let userScheme = queryItems?.filter({ $0.name == "user" }).first?.value,
  203. let urlScheme = queryItems?.filter({ $0.name == "url" }).first?.value else { return }
  204. if getMatchedAccount(userId: userScheme, url: urlScheme) == nil {
  205. let message = NSLocalizedString("_the_account_", comment: "") + " " + userScheme + NSLocalizedString("_of_", comment: "") + " " + urlScheme + " " + NSLocalizedString("_does_not_exist_", comment: "")
  206. let alertController = UIAlertController(title: NSLocalizedString("_info_", comment: ""), message: message, preferredStyle: .alert)
  207. alertController.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { _ in }))
  208. controller.present(alertController, animated: true, completion: { })
  209. return
  210. }
  211. switch actionScheme {
  212. case NCGlobal.shared.actionUploadAsset:
  213. NCAskAuthorization().askAuthorizationPhotoLibrary(controller: controller) { hasPermission in
  214. if hasPermission {
  215. NCPhotosPickerViewController(controller: controller, maxSelectedAssets: 0, singleSelectedMode: false)
  216. }
  217. }
  218. case NCGlobal.shared.actionScanDocument:
  219. NCDocumentCamera.shared.openScannerDocument(viewController: controller)
  220. case NCGlobal.shared.actionTextDocument:
  221. let directEditingCreators = self.database.getDirectEditingCreators(account: session.account)
  222. let directEditingCreator = directEditingCreators!.first(where: { $0.editor == NCGlobal.shared.editorText})!
  223. let serverUrl = controller.currentServerUrl()
  224. Task {
  225. let fileName = await NCNetworking.shared.createFileName(fileNameBase: NSLocalizedString("_untitled_", comment: "") + ".md", account: session.account, serverUrl: serverUrl)
  226. let fileNamePath = NCUtilityFileSystem().getFileNamePath(String(describing: fileName), serverUrl: serverUrl, session: session)
  227. NCCreateDocument().createDocument(controller: controller, fileNamePath: fileNamePath, fileName: String(describing: fileName), editorId: NCGlobal.shared.editorText, creatorId: directEditingCreator.identifier, templateId: NCGlobal.shared.templateDocument, account: session.account)
  228. }
  229. case NCGlobal.shared.actionVoiceMemo:
  230. NCAskAuthorization().askAuthorizationAudioRecord(viewController: controller) { hasPermission in
  231. if hasPermission {
  232. if let viewController = UIStoryboard(name: "NCAudioRecorderViewController", bundle: nil).instantiateInitialViewController() as? NCAudioRecorderViewController {
  233. viewController.controller = controller
  234. viewController.modalTransitionStyle = .crossDissolve
  235. viewController.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext
  236. controller.present(viewController, animated: true, completion: nil)
  237. }
  238. }
  239. }
  240. default:
  241. print("No action")
  242. }
  243. }
  244. return
  245. }
  246. /*
  247. Example: nextcloud://open-file?path=Talk/IMG_0000123.jpg&user=marinofaggiana&link=https://cloud.nextcloud.com/f/123
  248. */
  249. else if scheme == NCGlobal.shared.appScheme && action == "open-file" {
  250. if let urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false) {
  251. var serverUrl: String = ""
  252. var fileName: String = ""
  253. let queryItems = urlComponents.queryItems
  254. guard let userScheme = queryItems?.filter({ $0.name == "user" }).first?.value,
  255. let pathScheme = queryItems?.filter({ $0.name == "path" }).first?.value,
  256. let linkScheme = queryItems?.filter({ $0.name == "link" }).first?.value else { return}
  257. guard let matchedAccount = getMatchedAccount(userId: userScheme, url: linkScheme) else {
  258. guard let domain = URL(string: linkScheme)?.host else { return }
  259. fileName = (pathScheme as NSString).lastPathComponent
  260. let message = String(format: NSLocalizedString("_account_not_available_", comment: ""), userScheme, domain, fileName)
  261. let alertController = UIAlertController(title: NSLocalizedString("_info_", comment: ""), message: message, preferredStyle: .alert)
  262. alertController.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { _ in }))
  263. controller.present(alertController, animated: true, completion: { })
  264. return
  265. }
  266. let davFiles = "remote.php/dav/files/" + session.userId
  267. if pathScheme.contains("/") {
  268. fileName = (pathScheme as NSString).lastPathComponent
  269. serverUrl = matchedAccount.urlBase + "/" + davFiles + "/" + (pathScheme as NSString).deletingLastPathComponent
  270. } else {
  271. fileName = pathScheme
  272. serverUrl = matchedAccount.urlBase + "/" + davFiles
  273. }
  274. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  275. NCActionCenter.shared.openFileViewInFolder(serverUrl: serverUrl, fileNameBlink: nil, fileNameOpen: fileName, sceneIdentifier: controller.sceneIdentifier)
  276. }
  277. }
  278. return
  279. /*
  280. Example: nextcloud://open-and-switch-account?user=marinofaggiana&url=https://cloud.nextcloud.com
  281. */
  282. } else if scheme == NCGlobal.shared.appScheme && action == "open-and-switch-account" {
  283. guard let urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false) else { return }
  284. let queryItems = urlComponents.queryItems
  285. guard let userScheme = queryItems?.filter({ $0.name == "user" }).first?.value,
  286. let urlScheme = queryItems?.filter({ $0.name == "url" }).first?.value else { return }
  287. // If the account doesn't exist, return false which will open the app without switching
  288. if getMatchedAccount(userId: userScheme, url: urlScheme) == nil {
  289. return
  290. }
  291. // Otherwise open the app and switch accounts
  292. return
  293. } else if let action {
  294. if DeepLink(rawValue: action) != nil {
  295. NCDeepLinkHandler().parseDeepLink(url, controller: controller)
  296. }
  297. return
  298. } else {
  299. let applicationHandle = NCApplicationHandle()
  300. let isHandled = applicationHandle.applicationOpenURL(url)
  301. if isHandled {
  302. return
  303. } else {
  304. scene.open(url, options: nil)
  305. }
  306. }
  307. }
  308. private func showPrivacyProtectionWindow() {
  309. guard let windowScene = self.window?.windowScene else {
  310. return
  311. }
  312. privacyProtectionWindow = UIWindow(windowScene: windowScene)
  313. privacyProtectionWindow?.rootViewController = UIStoryboard(name: "LaunchScreen", bundle: nil).instantiateInitialViewController()
  314. privacyProtectionWindow?.windowLevel = .alert + 1
  315. privacyProtectionWindow?.makeKeyAndVisible()
  316. }
  317. private func hidePrivacyProtectionWindow() {
  318. privacyProtectionWindow?.isHidden = true
  319. privacyProtectionWindow = nil
  320. }
  321. }
  322. // MARK: - Extension
  323. extension SceneDelegate: NCPasscodeDelegate {
  324. func requestedAccount(controller: UIViewController?) {
  325. let tableAccounts = self.database.getAllTableAccount()
  326. if tableAccounts.count > 1, let accountRequestVC = UIStoryboard(name: "NCAccountRequest", bundle: nil).instantiateInitialViewController() as? NCAccountRequest {
  327. accountRequestVC.controller = controller
  328. accountRequestVC.activeAccount = (controller as? NCMainTabBarController)?.account
  329. accountRequestVC.accounts = tableAccounts
  330. accountRequestVC.enableTimerProgress = true
  331. accountRequestVC.enableAddAccount = false
  332. accountRequestVC.dismissDidEnterBackground = false
  333. accountRequestVC.delegate = self
  334. accountRequestVC.startTimer()
  335. let screenHeighMax = UIScreen.main.bounds.height - (UIScreen.main.bounds.height / 5)
  336. let numberCell = tableAccounts.count
  337. let height = min(CGFloat(numberCell * Int(accountRequestVC.heightCell) + 45), screenHeighMax)
  338. let popup = NCPopupViewController(contentController: accountRequestVC, popupWidth: 300, popupHeight: height + 20)
  339. popup.backgroundAlpha = 0.8
  340. controller?.present(popup, animated: true)
  341. }
  342. }
  343. func passcodeReset(_ passcodeViewController: TOPasscodeViewController) {
  344. appDelegate?.resetApplication()
  345. }
  346. }
  347. extension SceneDelegate: NCAccountRequestDelegate {
  348. func accountRequestAddAccount() { }
  349. func accountRequestChangeAccount(account: String, controller: UIViewController?) {
  350. NCAccount().changeAccount(account, userProfile: nil, controller: controller as? NCMainTabBarController) { }
  351. }
  352. }
  353. // MARK: - Scene Manager
  354. class SceneManager {
  355. static let shared = SceneManager()
  356. private var sceneController: [NCMainTabBarController: UIScene] = [:]
  357. func register(scene: UIScene, withRootViewController rootViewController: NCMainTabBarController) {
  358. sceneController[rootViewController] = scene
  359. }
  360. func getController(scene: UIScene?) -> NCMainTabBarController? {
  361. for controller in sceneController.keys {
  362. if sceneController[controller] == scene {
  363. return controller
  364. }
  365. }
  366. return nil
  367. }
  368. func getController(sceneIdentifier: String?) -> NCMainTabBarController? {
  369. if let sceneIdentifier {
  370. for controller in sceneController.keys {
  371. if sceneIdentifier == controller.sceneIdentifier {
  372. return controller
  373. }
  374. }
  375. }
  376. return nil
  377. }
  378. func getControllers() -> [NCMainTabBarController] {
  379. return Array(sceneController.keys)
  380. }
  381. func getWindow(scene: UIScene?) -> UIWindow? {
  382. return (scene as? UIWindowScene)?.keyWindow
  383. }
  384. func getWindow(controller: NCMainTabBarController?) -> UIWindow? {
  385. guard let controller,
  386. let scene = sceneController[controller] else { return nil }
  387. return getWindow(scene: scene)
  388. }
  389. func getSceneIdentifier() -> [String] {
  390. var results: [String] = []
  391. for controller in sceneController.keys {
  392. results.append(controller.sceneIdentifier)
  393. }
  394. return results
  395. }
  396. func getSession(scene: UIScene?) -> NCSession.Session {
  397. let controller = SceneManager.shared.getController(scene: scene)
  398. return NCSession.shared.getSession(controller: controller)
  399. }
  400. }