SceneDelegate.swift 20 KB

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