SceneDelegate.swift 20 KB

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