* feat: add shared SwiftUI passcode component Support passcode authentication, creation, changes and removal with biometrics and shared lockout protection. Keep the existing passcode flow active until callers are migrated. Signed-off-by: Marino Faggiana <[email protected]> * feat: migrate settings to SwiftUI passcode flow Update lock settings after passcode completion and handle reset results. Add toolbar dismissal and require the current passcode when changing it. Signed-off-by: Marino Faggiana <[email protected]> * fix: authenticate E2EE actions with the shared passcode view Require authentication in Debug builds and verify the account before executing E2EE actions. Present cancellable passcode flows as sheets and handle completion during dismissal. Signed-off-by: Marino Faggiana <[email protected]> * refactor: migrate app passcode flows to NCPasscodeView Use the shared passcode view for app unlock and enforced setup. Scope lifecycle handling to the presenting window scene and cancel optional operations when backgrounded. Signed-off-by: Marino Faggiana <[email protected]> * refactor: migrate passcode flows to shared SwiftUI components Replace TOPasscode in the main app and Share Extension, remove the legacy implementation, and add passcode UI tests. Signed-off-by: Marino Faggiana <[email protected]> * Acknowledgements update Signed-off-by: Marino Faggiana <[email protected]> * fix Signed-off-by: Marino Faggiana <[email protected]> * fix: preserve passcode reset threshold across lockouts Clear only the retry counter and lockout deadline when the delay expires. Add UI coverage verifying app reset after ten failures across lockouts. Signed-off-by: Marino Faggiana <[email protected]> * fix: keep app passcode lock above sheets and alerts Present the mandatory lock in a dedicated window per scene and preserve underlying UI after unlocking. Add UI regression coverage, improve authentication test handling, and enforce CI test timeouts with retained diagnostics. Signed-off-by: Marino Faggiana <[email protected]> * fix: wait for HTTP fallback in UI test login Allow the initial HTTPS request to time out before expecting the localhost authentication page, and skip UI queries against authentication services that are not running. Signed-off-by: Marino Faggiana <[email protected]> Assisted-by: Codex:GPT-6 * CI Signed-off-by: Marino Faggiana <[email protected]> * CI Signed-off-by: Marino Faggiana <[email protected]> * CI Signed-off-by: Marino Faggiana <[email protected]> * CI Signed-off-by: Marino Faggiana <[email protected]> * size button Signed-off-by: Marino Faggiana <[email protected]> * fix: avoid redundant transfer and auto-upload state updates Preserve the auto-upload suspension message until all reads finish, and discard cancelled or stale refreshes. Signed-off-by: Marino Faggiana <[email protected]> * added NCPasscodeView.embed Signed-off-by: Marino Faggiana <[email protected]> * fix: correct share extension passcode layout Embed the passcode view in the content controller while hiding the enclosing navigation bar, and constrain its width to the available space. Signed-off-by: Marino Faggiana <[email protected]> * fix: enforce app lock after failed passcode attempts Preserve mandatory authentication across scenes and relaunches after lockout. Require biometric authorization before enabling Touch ID or Face ID, add passcode error feedback, and update lockout UI tests. Signed-off-by: Marino Faggiana <[email protected]> * fix: stabilize passcode UI tests and run them for relevant changes Shorten reset-test lockouts and let XCTest terminate the app after observing completed cleanup to avoid TSan exit issues. Run passcode UI tests when related files change and increase CI test timeouts. Signed-off-by: Marino Faggiana <[email protected]> --------- Signed-off-by: Marino Faggiana <[email protected]>
795 lines
35 KiB
Swift
795 lines
35 KiB
Swift
// SPDX-FileCopyrightText: Nextcloud GmbH
|
|
// SPDX-FileCopyrightText: 2024 Marino Faggiana
|
|
// SPDX-License-Identifier: GPL-3.0-or-later
|
|
|
|
import Foundation
|
|
import UIKit
|
|
import NextcloudKit
|
|
import WidgetKit
|
|
import SwiftUI
|
|
import CoreLocation
|
|
import LucidBanner
|
|
|
|
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
|
|
var window: UIWindow?
|
|
var lucidBanner: LucidBanner?
|
|
|
|
private let appDelegate = UIApplication.shared.delegate as? AppDelegate
|
|
private var privacyProtectionWindow: UIWindow?
|
|
private var passcodeWindow: NCPasscodeWindow?
|
|
private let global = NCGlobal.shared
|
|
private let alreadyMigratedMultiDomains = UserDefaults.standard.bool(forKey: NCGlobal.shared.udMigrationMultiDomains)
|
|
|
|
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
|
|
guard let windowScene = (scene as? UIWindowScene) else {
|
|
return
|
|
}
|
|
NotificationCenter.default.removeObserver(self, name: NCPasscodeModel.lockoutNotification, object: nil)
|
|
NotificationCenter.default.addObserver(self, selector: #selector(passcodeLockoutStarted),
|
|
name: NCPasscodeModel.lockoutNotification, object: nil)
|
|
let versionApp = NCUtility().getVersionMaintenance()
|
|
var lastVersion: String?
|
|
|
|
lucidBanner = LucidBannerRegistry.shared.banner(for: windowScene)
|
|
|
|
if let groupDefaults = UserDefaults(suiteName: NCBrandOptions.shared.capabilitiesGroup) {
|
|
lastVersion = groupDefaults.string(forKey: NCGlobal.shared.udLastVersion)
|
|
groupDefaults.set(versionApp, forKey: global.udLastVersion)
|
|
}
|
|
UserDefaults.standard.set(true, forKey: global.udMigrationMultiDomains)
|
|
|
|
self.window = UIWindow(windowScene: windowScene)
|
|
if !NCPreferences().appearanceAutomatic {
|
|
self.window?.overrideUserInterfaceStyle = NCPreferences().appearanceInterfaceStyle
|
|
}
|
|
|
|
// in Debug write all UserDefaults.standard
|
|
#if DEBUG
|
|
print("UserDefaults: ---------------------------")
|
|
for (key, value) in UserDefaults.standard.dictionaryRepresentation() {
|
|
print("\(key) = \(value)")
|
|
}
|
|
print("UserDefaults Group: ---------------------")
|
|
if let groupDefaults = UserDefaults(suiteName: NCBrandOptions.shared.capabilitiesGroup) {
|
|
for (key, value) in groupDefaults.dictionaryRepresentation() {
|
|
print("\(key) = \(value)")
|
|
}
|
|
}
|
|
print("-----------------------------------------")
|
|
#endif
|
|
|
|
if lastVersion != versionApp {
|
|
// Suspending Database for blocked the realm access (better be sure 100%)
|
|
isSuspendingDatabaseOperation = true
|
|
maintenanceMode = true
|
|
window?.rootViewController = UIHostingController(rootView: Maintenance(onCompleted: {
|
|
isSuspendingDatabaseOperation = false
|
|
maintenanceMode = false
|
|
// Start App
|
|
self.startNextcloud(scene: scene, withActivateSceneForAccount: true)
|
|
}))
|
|
window?.makeKeyAndVisible()
|
|
} else {
|
|
self.startNextcloud(scene: scene, withActivateSceneForAccount: false)
|
|
}
|
|
}
|
|
|
|
private func startNextcloud(scene: UIScene, withActivateSceneForAccount activateSceneForAccount: Bool) {
|
|
// App not in background
|
|
isAppInBackground = false
|
|
// Open Realm
|
|
NCManageDatabase.shared.openRealm()
|
|
// Table account
|
|
var activeTblAccount = NCManageDatabase.shared.getActiveTableAccount()
|
|
|
|
// Try to restore accounts
|
|
if activeTblAccount == nil {
|
|
NCManageDatabase.shared.restoreTableAccountFromFile()
|
|
activeTblAccount = NCManageDatabase.shared.getActiveTableAccount()
|
|
}
|
|
|
|
// Activation singleton
|
|
_ = NCAppStateManager.shared
|
|
_ = NCNetworking.shared
|
|
_ = NCNetworkingProcess.shared
|
|
|
|
if let activeTblAccount, !alreadyMigratedMultiDomains {
|
|
//
|
|
// Migration Multi Domains
|
|
//
|
|
window?.rootViewController = UIHostingController(rootView: MigrationMultiDomains(onCompleted: {
|
|
//
|
|
// Start Main
|
|
//
|
|
self.launchMainInterface(scene: scene, activeTblAccount: activeTblAccount, withActivateSceneForAccount: activateSceneForAccount)
|
|
}))
|
|
window?.makeKeyAndVisible()
|
|
|
|
} else if let activeTblAccount {
|
|
//
|
|
// Start Main
|
|
//
|
|
self.launchMainInterface(scene: scene, activeTblAccount: activeTblAccount, withActivateSceneForAccount: activateSceneForAccount)
|
|
|
|
} else {
|
|
//
|
|
// NO account found, start with the Login
|
|
//
|
|
NCPreferences().removeAll()
|
|
passcodeWindow?.hide()
|
|
passcodeWindow = nil
|
|
|
|
if let bundleID = Bundle.main.bundleIdentifier {
|
|
UserDefaults.standard.removePersistentDomain(forName: bundleID)
|
|
}
|
|
|
|
if NCBrandOptions.shared.disable_intro {
|
|
if let viewController = UIStoryboard(name: "NCLogin", bundle: nil).instantiateViewController(withIdentifier: "NCLogin") as? NCLogin {
|
|
let navigationController = UINavigationController(rootViewController: viewController)
|
|
window?.rootViewController = navigationController
|
|
window?.makeKeyAndVisible()
|
|
}
|
|
} else {
|
|
if let navigationController = UIStoryboard(name: "NCIntro", bundle: nil).instantiateInitialViewController() as? UINavigationController {
|
|
window?.rootViewController = navigationController
|
|
window?.makeKeyAndVisible()
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
private func launchMainInterface(scene: UIScene,
|
|
activeTblAccount: tableAccount,
|
|
withActivateSceneForAccount activateSceneForAccount: Bool) {
|
|
nkLog(debug: "Account active \(activeTblAccount.account)")
|
|
|
|
// Networking Certificate
|
|
NCNetworking.shared.activeAccountCertificate(account: activeTblAccount.account)
|
|
|
|
Task {
|
|
if let capabilities = await NCManageDatabase.shared.getCapabilities(account: activeTblAccount.account) {
|
|
// set theming color
|
|
NCBrandColor.shared.settingThemingColor(account: activeTblAccount.account, capabilities: capabilities)
|
|
NotificationCenter.default.postOnMainThread(name: self.global.notificationCenterChangeTheming, userInfo: ["account": activeTblAccount.account])
|
|
}
|
|
|
|
// Start Networking Process
|
|
await NCNetworkingProcess.shared.setCurrentAccount(activeTblAccount.account)
|
|
await NCNetworkingProcess.shared.startTimer(interval: NCNetworkingProcess.shared.maxInterval)
|
|
}
|
|
|
|
// Set up networking session for all configured accounts
|
|
for tblAccount in NCManageDatabase.shared.getAllTableAccount() {
|
|
// Append account to NextcloudKit shared session
|
|
NextcloudKit.shared.appendSession(account: tblAccount.account,
|
|
urlBase: tblAccount.urlBase,
|
|
user: tblAccount.user,
|
|
userId: tblAccount.userId,
|
|
password: NCPreferences().getPassword(account: tblAccount.account),
|
|
userAgent: userAgent,
|
|
httpMaximumConnectionsPerHost: NCBrandOptions.shared.httpMaximumConnectionsPerHost,
|
|
httpMaximumConnectionsPerHostInDownload: NCBrandOptions.shared.httpMaximumConnectionsPerHostInDownload,
|
|
httpMaximumConnectionsPerHostInUpload: NCBrandOptions.shared.httpMaximumConnectionsPerHostInUpload,
|
|
groupIdentifier: NCBrandOptions.shared.capabilitiesGroup)
|
|
|
|
// Perform async setup: restore capabilities and ensure file provider domain
|
|
Task {
|
|
await NCManageDatabase.shared.getCapabilities(account: tblAccount.account)
|
|
try? await FileProviderDomain().ensureDomainRegistered(userId: tblAccount.userId, user: tblAccount.user, urlBase: tblAccount.urlBase)
|
|
}
|
|
|
|
// Append session to internal session manager
|
|
NCSession.shared.appendSession(account: tblAccount.account, urlBase: tblAccount.urlBase, user: tblAccount.user, userId: tblAccount.userId)
|
|
}
|
|
|
|
// Load Main.storyboard
|
|
if let controller = UIStoryboard(name: "Main", bundle: nil).instantiateInitialViewController() as? NCMainTabBarController {
|
|
SceneManager.shared.register(scene: scene, withRootViewController: controller)
|
|
// Set the ACCOUNT
|
|
controller.account = activeTblAccount.account
|
|
//
|
|
window?.rootViewController = controller
|
|
window?.makeKeyAndVisible()
|
|
// Also protect interfaces created after an asynchronous maintenance or migration.
|
|
requestPasscodeIfNeeded(controller: controller)
|
|
//
|
|
if activateSceneForAccount {
|
|
self.activateSceneForAccount(scene, account: activeTblAccount.account, controller: controller)
|
|
}
|
|
}
|
|
|
|
// Clean orphaned FP Domains
|
|
Task {
|
|
await FileProviderDomain().cleanOrphanedFileProviderDomains()
|
|
}
|
|
}
|
|
|
|
func sceneDidDisconnect(_ scene: UIScene) {
|
|
guard let windowScene = scene as? UIWindowScene else { return }
|
|
|
|
passcodeWindow?.hide()
|
|
passcodeWindow = nil
|
|
hidePrivacyProtectionWindow()
|
|
LucidBannerRegistry.shared.remove(for: windowScene)
|
|
lucidBanner = nil
|
|
|
|
print("[DEBUG] Scene did disconnect")
|
|
}
|
|
|
|
func sceneWillEnterForeground(_ scene: UIScene) {
|
|
hidePrivacyProtectionWindow()
|
|
|
|
guard let controller = window?.rootViewController as? NCMainTabBarController else {
|
|
return
|
|
}
|
|
|
|
activateSceneForAccount(scene, account: controller.account, controller: controller)
|
|
}
|
|
|
|
func sceneDidBecomeActive(_ scene: UIScene) {
|
|
hidePrivacyProtectionWindow()
|
|
|
|
if !NextcloudKit.shared.isNetworkReachable(),
|
|
let windowScenee = SceneManager.shared.getWindow(scene: scene)?.windowScene {
|
|
Task {
|
|
await showWarningBanner(windowScene: windowScenee,
|
|
subtitle: "_network_not_available_",
|
|
systemImage: "wifi.exclamationmark.circle",
|
|
imageAnimation: .bounce,
|
|
errorCode: NSURLErrorNotConnectedToInternet)
|
|
}
|
|
}
|
|
}
|
|
|
|
func sceneWillResignActive(_ scene: UIScene) {
|
|
nkLog(debug: "Scene will resign active")
|
|
|
|
let session = SceneManager.shared.getSession(scene: scene)
|
|
guard !session.account.isEmpty else {
|
|
return
|
|
}
|
|
|
|
if NCPreferences().privacyScreenEnabled {
|
|
showPrivacyProtectionWindow()
|
|
}
|
|
}
|
|
|
|
func sceneDidEnterBackground(_ scene: UIScene) {
|
|
let app = UIApplication.shared
|
|
var bgID: UIBackgroundTaskIdentifier = .invalid
|
|
let isBackgroundRefreshStatus = (UIApplication.shared.backgroundRefreshStatus == .available)
|
|
let session = SceneManager.shared.getSession(scene: scene)
|
|
guard let tblAccount = NCManageDatabase.shared.getTableAccount(predicate: NSPredicate(format: "account == %@", session.account)) else {
|
|
return
|
|
}
|
|
if NCPreferences().presentPasscode {
|
|
showPrivacyProtectionWindow()
|
|
}
|
|
bgID = app.beginBackgroundTask(withName: "FlushBeforeSuspend") {
|
|
app.endBackgroundTask(bgID); bgID = .invalid
|
|
}
|
|
|
|
Task {
|
|
defer {
|
|
app.endBackgroundTask(bgID); bgID = .invalid
|
|
}
|
|
// Timeout auto
|
|
let didFinish = await withTaskGroup(of: Bool.self) { group -> Bool in
|
|
group.addTask {
|
|
// TransferCoordinator
|
|
await NCTransferCoordinator.shared.cancelAll()
|
|
// FLUSH TRANSFERS SUCCESS
|
|
await NCNetworking.shared.metadataDownloadTranfersSuccess.flush()
|
|
await NCNetworking.shared.metadataUploadTranfersSuccess.flush()
|
|
// BACKUP
|
|
await NCManageDatabase.shared.backupTableAccountToFileAsync()
|
|
// LOG
|
|
nkLog(info: "Auto upload in background: \(tblAccount.autoUploadStart)")
|
|
nkLog(info: "Update in background: \(isBackgroundRefreshStatus)")
|
|
// LOCATION MANAGER
|
|
if CLLocationManager().authorizationStatus == .authorizedAlways && NCPreferences().location && tblAccount.autoUploadStart {
|
|
NCBackgroundLocationUploadManager.shared.start()
|
|
} else {
|
|
NCBackgroundLocationUploadManager.shared.stop()
|
|
}
|
|
// UPDATE SHARE GROUP ACCOUNTS
|
|
if let error = await NCAccount().updateAppsShareAccounts() {
|
|
nkLog(error: "Create Apps share accounts \(error.localizedDescription)")
|
|
}
|
|
return true
|
|
}
|
|
group.addTask {
|
|
try? await Task.sleep(for: .seconds(25))
|
|
return false
|
|
}
|
|
return await group.next() ?? false
|
|
}
|
|
|
|
if !didFinish {
|
|
nkLog(debug: "Flush timed out, will continue next launch")
|
|
}
|
|
}
|
|
}
|
|
|
|
func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
|
|
guard let controller = SceneManager.shared.getController(scene: scene),
|
|
let url = URLContexts.first?.url else { return }
|
|
let scheme = url.scheme
|
|
let action = url.host
|
|
let versionApp = NCUtility().getVersionMaintenance()
|
|
|
|
// Test version
|
|
guard let groupDefaults = UserDefaults(suiteName: NCBrandOptions.shared.capabilitiesGroup),
|
|
let lastVersion = groupDefaults.string(forKey: NCGlobal.shared.udLastVersion),
|
|
lastVersion == versionApp else {
|
|
return
|
|
}
|
|
|
|
func getMatchedAccount(user: String, url: String, account: String? = nil) async -> tableAccount? {
|
|
let tblAccounts = await NCManageDatabase.shared.getAllTableAccountAsync()
|
|
|
|
for tblAccount in tblAccounts {
|
|
let host = URL(string: tblAccount.urlBase)?.host() ?? ""
|
|
|
|
if (account == tblAccount.account) || (url.contains(host) && user == tblAccount.userId) {
|
|
await NCAccount().changeAccount(tblAccount.account, userProfile: nil, controller: controller)
|
|
// wait switch account
|
|
try? await Task.sleep(for: .seconds(1))
|
|
return tblAccount
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
/*
|
|
Example: nextcloud://assistant/shared-text
|
|
*/
|
|
|
|
if scheme == global.appScheme, action == "assistant", url.path == "/shared-text" {
|
|
guard let text = NCAssistantSharedTextStore.loadAndClear() else {
|
|
return
|
|
}
|
|
|
|
Task { @MainActor in
|
|
let capabilities = await NKCapabilities.shared.getCapabilities(for: controller.account)
|
|
if capabilities.assistantEnabled {
|
|
let inputModel = NCAssistantInputModel(initialText: text)
|
|
let assistant = NCAssistant(assistantModel: NCAssistantModel(controller: controller, inputModel: inputModel), chatModel: NCAssistantChatModel(controller: controller, inputModel: inputModel), conversationsModel: NCAssistantChatConversationsModel(controller: controller))
|
|
let hostingController = UIHostingController(rootView: assistant)
|
|
controller.present(hostingController, animated: true, completion: nil)
|
|
} else {
|
|
try? await Task.sleep(for: .seconds(1))
|
|
await showBanner(windowScene: scene as? UIWindowScene,
|
|
title: "_info_",
|
|
subtitle: "_no_assistant_installed_",
|
|
systemImage: "sparkles",
|
|
imageAnimation: .none,
|
|
imageColor: .systemBlue
|
|
)
|
|
}
|
|
}
|
|
|
|
return
|
|
}
|
|
|
|
/*
|
|
Example: nextcloud://open-action?action=create-voice-memo&&user=marinofaggiana&url=https://cloud.nextcloud.com
|
|
*/
|
|
|
|
if scheme == global.appScheme && action == "open-action" {
|
|
if let urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false) {
|
|
let queryItems = urlComponents.queryItems
|
|
guard let actionScheme = queryItems?.filter({ $0.name == "action" }).first?.value,
|
|
let userScheme = queryItems?.filter({ $0.name == "user" }).first?.value,
|
|
let urlScheme = queryItems?.filter({ $0.name == "url" }).first?.value else {
|
|
return
|
|
}
|
|
|
|
Task {
|
|
if await getMatchedAccount(user: userScheme, url: urlScheme) == nil {
|
|
let message = String(
|
|
format: NSLocalizedString("account_does_not_exist", comment: ""),
|
|
userScheme,
|
|
)
|
|
|
|
let alertController = UIAlertController(title: NSLocalizedString("_info_", comment: ""), message: message, preferredStyle: .alert)
|
|
alertController.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { _ in }))
|
|
|
|
controller.present(alertController, animated: true, completion: { })
|
|
return
|
|
}
|
|
|
|
switch actionScheme {
|
|
case self.global.actionUploadAsset:
|
|
NCAskAuthorization().askAuthorizationPhotoLibrary(controller: controller) { hasPermission in
|
|
if hasPermission {
|
|
NCPhotosPickerViewController(controller: controller, maxSelectedAssets: 0, singleSelectedMode: false)
|
|
}
|
|
}
|
|
case self.global.actionScanDocument:
|
|
NCDocumentCamera.shared.openScannerDocument(viewController: controller)
|
|
case self.global.actionTextDocument:
|
|
let session = SceneManager.shared.getSession(scene: scene)
|
|
let capabilities = await NKCapabilities.shared.getCapabilities(for: session.account)
|
|
guard let creator = capabilities.directEditingCreators.first(where: { $0.editor == global.editorText }) else {
|
|
return
|
|
}
|
|
let serverUrl = controller.currentServerUrl()
|
|
let fileName = await NCNetworking.shared.createFileName(fileNameBase: NSLocalizedString("_untitled_", comment: "") + "." + creator.ext, account: session.account, serverUrl: serverUrl)
|
|
|
|
await NCCreate().createDocument(controller: controller,
|
|
serverUrl: serverUrl,
|
|
fileName: fileName,
|
|
editorId: global.editorText,
|
|
creatorId: creator.identifier,
|
|
templateId: "document",
|
|
session: session)
|
|
case self.global.actionVoiceMemo:
|
|
NCAskAuthorization().askAuthorizationAudioRecord(controller: controller) { hasPermission in
|
|
if hasPermission {
|
|
if let viewController = UIStoryboard(name: "NCAudioRecorderViewController", bundle: nil).instantiateInitialViewController() as? NCAudioRecorderViewController {
|
|
viewController.controller = controller
|
|
viewController.modalTransitionStyle = .crossDissolve
|
|
viewController.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext
|
|
controller.present(viewController, animated: true, completion: nil)
|
|
}
|
|
}
|
|
}
|
|
default:
|
|
print("No action")
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
/*
|
|
Example: nextcloud://open-file?path=Talk/IMG_0000123.jpg&user=marinofaggiana&link=https://cloud.nextcloud.com/f/123
|
|
*/
|
|
|
|
else if scheme == self.global.appScheme && action == "open-file" {
|
|
if let urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false) {
|
|
let queryItems = urlComponents.queryItems
|
|
guard let userScheme = queryItems?.filter({ $0.name == "user" }).first?.value,
|
|
// let pathScheme = queryItems?.filter({ $0.name == "path" }).first?.value,
|
|
let linkScheme = queryItems?.filter({ $0.name == "link" }).first?.value else {
|
|
return
|
|
}
|
|
let domain = URL(string: linkScheme)?.host ?? ""
|
|
let accountScheme = queryItems?.filter({ $0.name == "account" }).first?.value
|
|
|
|
Task {
|
|
guard let tblAccount = await getMatchedAccount(user: userScheme, url: linkScheme, account: accountScheme) else {
|
|
|
|
let message = String(format: NSLocalizedString("_account_not_available_", comment: ""), userScheme, domain)
|
|
let alertController = UIAlertController(title: NSLocalizedString("_info_", comment: ""), message: message, preferredStyle: .alert)
|
|
alertController.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { _ in }))
|
|
|
|
controller.present(alertController, animated: true)
|
|
return
|
|
}
|
|
|
|
let results = await NextcloudKit.shared.getFileFromFileIdAsync(link: linkScheme,
|
|
account: tblAccount.account)
|
|
if results.error == .success, let file = results.file {
|
|
let metadata = await NCManageDatabaseCreateMetadata().convertFileToMetadataAsync(file)
|
|
await NCManageDatabase.shared.addMetadataAsync(metadata)
|
|
if metadata.hasPreview {
|
|
let results = await NextcloudKit.shared.downloadPreviewAsync(fileId: metadata.fileId, etag: metadata.etag, account: metadata.account)
|
|
if results.error == .success,
|
|
let data = results.responseData?.data {
|
|
NCUtility().createImageFileFrom(data: data, metadata: metadata)
|
|
}
|
|
}
|
|
await NCNetworking.shared.openFileView(serverUrl: metadata.serverUrl,
|
|
metadata: metadata,
|
|
sceneIdentifier: controller.sceneIdentifier)
|
|
}
|
|
}
|
|
}
|
|
|
|
/*
|
|
Example: nextcloud://open-and-switch-account?user=marinofaggiana&url=https://cloud.nextcloud.com
|
|
*/
|
|
|
|
} else if scheme == self.global.appScheme && action == "open-and-switch-account" {
|
|
guard let urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false) else {
|
|
return
|
|
}
|
|
let queryItems = urlComponents.queryItems
|
|
guard let userScheme = queryItems?.filter({ $0.name == "user" }).first?.value,
|
|
let urlScheme = queryItems?.filter({ $0.name == "url" }).first?.value else {
|
|
return
|
|
}
|
|
|
|
Task {
|
|
_ = await getMatchedAccount(user: userScheme, url: urlScheme)
|
|
}
|
|
} else if let action {
|
|
if DeepLink(rawValue: action) != nil {
|
|
NCDeepLinkHandler().parseDeepLink(url, controller: controller)
|
|
}
|
|
} else {
|
|
scene.open(url, options: nil)
|
|
}
|
|
}
|
|
|
|
private func showPrivacyProtectionWindow() {
|
|
guard privacyProtectionWindow == nil,
|
|
let windowScene = self.window?.windowScene else {
|
|
return
|
|
}
|
|
|
|
self.privacyProtectionWindow = UIWindow(windowScene: windowScene)
|
|
self.privacyProtectionWindow?.rootViewController = UIStoryboard(name: "LaunchScreen", bundle: nil).instantiateInitialViewController()
|
|
self.privacyProtectionWindow?.windowLevel = .alert + 1
|
|
self.privacyProtectionWindow?.isHidden = false
|
|
}
|
|
|
|
private func hidePrivacyProtectionWindow() {
|
|
privacyProtectionWindow?.isHidden = true
|
|
privacyProtectionWindow = nil
|
|
}
|
|
|
|
/// A failed settings authentication must protect every scene, independently of modal transitions.
|
|
@objc private func passcodeLockoutStarted() {
|
|
guard let controller = window?.rootViewController as? NCMainTabBarController else { return }
|
|
requestPasscodeIfNeeded(controller: controller)
|
|
}
|
|
|
|
/// Request the mandatory lock; return whether authentication is required, including while the UI is not ready.
|
|
@discardableResult
|
|
private func requestPasscodeIfNeeded(controller: NCMainTabBarController) -> Bool {
|
|
guard NCPreferences().presentPasscode else {
|
|
passcodeWindow?.hide()
|
|
passcodeWindow = nil
|
|
return false
|
|
}
|
|
guard !controller.account.isEmpty,
|
|
NCManageDatabase.shared.getTableAccount(account: controller.account) != nil,
|
|
let window,
|
|
window.rootViewController === controller,
|
|
let windowScene = window.windowScene else {
|
|
return true
|
|
}
|
|
if passcodeWindow == nil {
|
|
passcodeWindow = NCPasscodeWindow(mainWindow: window, windowScene: windowScene) { [weak self, weak controller] result in
|
|
guard let self else { return }
|
|
self.passcodeWindow = nil
|
|
switch result {
|
|
case .authenticated:
|
|
if NCPreferences().accountRequest,
|
|
let controller,
|
|
self.window?.rootViewController === controller,
|
|
NCManageDatabase.shared.getTableAccount(account: controller.account) != nil {
|
|
self.requestedAccount(controller: controller)
|
|
}
|
|
case .reset:
|
|
self.appDelegate?.resetApplication()
|
|
case .cancelled, .configured, .disabled:
|
|
break
|
|
}
|
|
}
|
|
}
|
|
passcodeWindow?.show()
|
|
return true
|
|
}
|
|
|
|
private func activateSceneForAccount(_ scene: UIScene,
|
|
account: String,
|
|
controller: NCMainTabBarController?) {
|
|
guard !account.isEmpty,
|
|
let controller,
|
|
controller.account == account,
|
|
NCManageDatabase.shared.getTableAccount(account: account) != nil,
|
|
let window,
|
|
window.rootViewController === controller,
|
|
let windowScene = scene as? UIWindowScene,
|
|
window.windowScene === windowScene else {
|
|
return
|
|
}
|
|
|
|
if !requestPasscodeIfNeeded(controller: controller), NCPreferences().accountRequest {
|
|
requestedAccount(controller: controller)
|
|
}
|
|
|
|
Task {
|
|
try? await Task.sleep(for: .seconds(1))
|
|
|
|
let num = await NCAutoUpload.shared.initAutoUpload()
|
|
nkLog(start: "Auto upload with \(num) photo")
|
|
|
|
try? await Task.sleep(for: .seconds(1.5))
|
|
await NCService().startRequestServicesServer(account: account, controller: controller)
|
|
|
|
try? await Task.sleep(for: .seconds(2))
|
|
await NCNetworking.shared.verifyZombie()
|
|
}
|
|
|
|
NotificationCenter.default.postOnMainThread(name: global.notificationCenterRichdocumentGrabFocus)
|
|
}
|
|
}
|
|
|
|
// MARK: - Extension
|
|
|
|
extension SceneDelegate {
|
|
func requestedAccount(controller: UIViewController?) {
|
|
guard var presenter = controller else { return }
|
|
while let presented = presenter.presentedViewController {
|
|
if let popup = presented as? NCPopupViewController, popup.contentController is NCAccountRequest {
|
|
return
|
|
}
|
|
presenter = presented
|
|
}
|
|
let tblAccounts = NCManageDatabase.shared.getAllTableAccount()
|
|
if tblAccounts.count > 1, let accountRequestVC = UIStoryboard(name: "NCAccountRequest", bundle: nil).instantiateInitialViewController() as? NCAccountRequest {
|
|
accountRequestVC.controller = controller
|
|
accountRequestVC.activeAccount = (controller as? NCMainTabBarController)?.account
|
|
accountRequestVC.accounts = tblAccounts
|
|
accountRequestVC.enableTimerProgress = true
|
|
accountRequestVC.enableAddAccount = false
|
|
accountRequestVC.dismissDidEnterBackground = false
|
|
accountRequestVC.delegate = self
|
|
accountRequestVC.startTimer(nil)
|
|
|
|
let availableHeight = presenter.view.safeAreaLayoutGuide.layoutFrame.height
|
|
let maximumHeight = availableHeight * 0.8
|
|
let numberCell = tblAccounts.count
|
|
let height = min(CGFloat(numberCell * Int(accountRequestVC.heightCell) + 45), maximumHeight)
|
|
|
|
let popup = NCPopupViewController(contentController: accountRequestVC, popupWidth: 300, popupHeight: height + 20)
|
|
popup.backgroundAlpha = 0.8
|
|
|
|
presenter.present(popup, animated: true)
|
|
}
|
|
}
|
|
}
|
|
|
|
extension SceneDelegate: NCAccountRequestDelegate {
|
|
func accountRequestAddAccount() { }
|
|
|
|
func accountRequestChangeAccount(account: String, controller: UIViewController?) {
|
|
Task {
|
|
await NCAccount().changeAccount(account, userProfile: nil, controller: controller as? NCMainTabBarController)
|
|
}
|
|
}
|
|
}
|
|
|
|
// MARK: - Scene Manager
|
|
|
|
@MainActor
|
|
final class SceneManager {
|
|
static let shared = SceneManager()
|
|
private var sceneController: [NCMainTabBarController: UIScene] = [:]
|
|
|
|
func register(scene: UIScene, withRootViewController rootViewController: NCMainTabBarController) {
|
|
sceneController[rootViewController] = scene
|
|
}
|
|
|
|
/// Returns the main tab controller, or nil when the window displays another root,
|
|
/// such as the login screen.
|
|
func getController(window: UIWindow?) -> NCMainTabBarController? {
|
|
window?.rootViewController as? NCMainTabBarController
|
|
}
|
|
|
|
func getController(scene: UIScene?) -> NCMainTabBarController? {
|
|
for controller in sceneController.keys {
|
|
if sceneController[controller] == scene {
|
|
return controller
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func getController(sceneIdentifier: String?) -> NCMainTabBarController? {
|
|
if let sceneIdentifier {
|
|
for controller in sceneController.keys {
|
|
if sceneIdentifier == controller.sceneIdentifier {
|
|
return controller
|
|
}
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func getController(account: String?) -> NCMainTabBarController? {
|
|
if let account {
|
|
for controller in sceneController.keys {
|
|
if account == controller.account {
|
|
return controller
|
|
}
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func getControllers() -> [NCMainTabBarController] {
|
|
return Array(sceneController.keys)
|
|
}
|
|
|
|
func getWindow(scene: UIScene?) -> UIWindow? {
|
|
guard let windowScene = scene as? UIWindowScene else { return nil }
|
|
|
|
return windowScene.keyWindow
|
|
}
|
|
|
|
func getWindow(controller: UITabBarController?) -> UIWindow? {
|
|
guard let controller = controller as? NCMainTabBarController,
|
|
let scene = sceneController[controller] else { return nil }
|
|
return getWindow(scene: scene)
|
|
}
|
|
|
|
func getWindowScene(controller: UIViewController?) -> UIWindowScene? {
|
|
if let windowScene = controller?.viewIfLoaded?.window?.windowScene {
|
|
return windowScene
|
|
}
|
|
|
|
// Fallback: if the controller is a registered NCMainTabBarController.
|
|
if let mainTabBarController = controller as? NCMainTabBarController,
|
|
let scene = sceneController[mainTabBarController] as? UIWindowScene {
|
|
return scene
|
|
}
|
|
|
|
// Fallback: any foregroundActive scene.
|
|
if let active = UIApplication.shared.connectedScenes
|
|
.compactMap({ $0 as? UIWindowScene })
|
|
.first(where: { $0.activationState == .foregroundActive }) {
|
|
return active
|
|
}
|
|
|
|
// Last resort: literally the first connected window scene.
|
|
return UIApplication.shared.connectedScenes
|
|
.compactMap { $0 as? UIWindowScene }
|
|
.first
|
|
}
|
|
|
|
func getWindow(sceneIdentifier: String?) -> UIWindow? {
|
|
// Try exact match via your registry
|
|
if let sceneIdentifier,
|
|
let controller = sceneController.keys.first(where: { $0.sceneIdentifier == sceneIdentifier }),
|
|
let scene = sceneController[controller],
|
|
let window = getWindow(scene: scene)?.windowScene?.resolvedWindow {
|
|
return window
|
|
}
|
|
|
|
let windowScenes = UIApplication.shared.connectedScenes
|
|
.compactMap { $0 as? UIWindowScene }
|
|
|
|
// Fallback: prefer a foregroundActive window scene
|
|
if let window = windowScenes
|
|
.first(where: { $0.activationState == .foregroundActive })?
|
|
.resolvedWindow {
|
|
return window
|
|
}
|
|
|
|
// Fallback: foregroundInactive window scene
|
|
if let window = windowScenes
|
|
.first(where: { $0.activationState == .foregroundInactive })?
|
|
.resolvedWindow {
|
|
return window
|
|
}
|
|
|
|
// Last resort: first connected window scene with a resolved window
|
|
if let window = windowScenes
|
|
.compactMap({ $0.resolvedWindow })
|
|
.first {
|
|
return window
|
|
}
|
|
|
|
// Absolute last resort
|
|
return UIApplication.shared.mainAppWindow
|
|
}
|
|
|
|
func getSceneIdentifier() -> [String] {
|
|
var results: [String] = []
|
|
for controller in sceneController.keys {
|
|
results.append(controller.sceneIdentifier)
|
|
}
|
|
return results
|
|
}
|
|
|
|
func getSession(scene: UIScene?) -> NCSession.Session {
|
|
let controller = SceneManager.shared.getController(scene: scene)
|
|
return NCSession.shared.getSession(controller: controller)
|
|
}
|
|
}
|