SceneDelegate.swift 20 KB

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