1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051 |
- import UIKit
- import BackgroundTasks
- import NextcloudKit
- import TOPasscodeViewController
- import LocalAuthentication
- import Firebase
- import WidgetKit
- @UIApplicationMain
- class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, TOPasscodeViewControllerDelegate, NCAccountRequestDelegate, NCViewCertificateDetailsDelegate, NCUserBaseUrl {
- var backgroundSessionCompletionHandler: (() -> Void)?
- var window: UIWindow?
- @objc var account: String = ""
- @objc var urlBase: String = ""
- @objc var user: String = ""
- @objc var userId: String = ""
- @objc var password: String = ""
- var activeLogin: NCLogin?
- var activeLoginWeb: NCLoginWeb?
- var activeServerUrl: String = ""
- @objc var activeViewController: UIViewController?
- var mainTabBar: NCMainTabBar?
- var activeMetadata: tableMetadata?
- let listFilesVC = ThreadSafeDictionary<String, NCFiles>()
- let listFavoriteVC = ThreadSafeDictionary<String, NCFavorite>()
- let listOfflineVC = ThreadSafeDictionary<String, NCOffline>()
- let listGroupfoldersVC = ThreadSafeDictionary<String, NCGroupfolders>()
- var disableSharesView: Bool = false
- var documentPickerViewController: NCDocumentPickerViewController?
- var timerErrorNetworking: Timer?
- private var privacyProtectionWindow: UIWindow?
- var isUiTestingEnabled: Bool {
- get {
- return ProcessInfo.processInfo.arguments.contains("UI_TESTING")
- }
- }
- func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
- if isUiTestingEnabled {
- deleteAllAccounts()
- }
- NCSettingsBundleHelper.checkAndExecuteSettings(delay: 0)
- let versionNextcloudiOS = String(format: NCBrandOptions.shared.textCopyrightNextcloudiOS, NCUtility.shared.getVersionApp())
-
- NotificationCenter.default.addObserver(self, selector: #selector(initialize), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterInitialize), object: nil)
- UserDefaults.standard.register(defaults: ["UserAgent": userAgent])
- if !CCUtility.getDisableCrashservice() && !NCBrandOptions.shared.disable_crash_service {
- FirebaseApp.configure()
- }
- CCUtility.createDirectoryStandard()
- CCUtility.emptyTemporaryDirectory()
- NextcloudKit.shared.setup(delegate: NCNetworking.shared)
- NextcloudKit.shared.setup(userAgent: userAgent)
- startTimerErrorNetworking()
-
- var levelLog = 0
- if let pathDirectoryGroup = CCUtility.getDirectoryGroup()?.path {
- NextcloudKit.shared.nkCommonInstance.pathLog = pathDirectoryGroup
- }
- if NCBrandOptions.shared.disable_log {
- NCUtilityFileSystem.shared.deleteFile(filePath: NextcloudKit.shared.nkCommonInstance.filenamePathLog)
- NCUtilityFileSystem.shared.deleteFile(filePath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! + "/" + NextcloudKit.shared.nkCommonInstance.filenameLog)
- } else {
- levelLog = CCUtility.getLogLevel()
- NextcloudKit.shared.nkCommonInstance.levelLog = levelLog
- NextcloudKit.shared.nkCommonInstance.copyLogToDocumentDirectory = true
- NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Start session with level \(levelLog) " + versionNextcloudiOS + " in state \(UIApplication.shared.applicationState.rawValue) where (0 active, 1 inactive, 2 background).")
- }
-
- if let account = NCManageDatabase.shared.getActiveAccount() {
- NextcloudKit.shared.nkCommonInstance.writeLog("Account active \(account.account)")
- if CCUtility.getPassword(account.account).isEmpty {
- NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] PASSWORD NOT FOUND for \(account.account)")
- }
- }
-
- if let activeAccount = NCManageDatabase.shared.getActiveAccount() {
- settingAccount(activeAccount.account, urlBase: activeAccount.urlBase, user: activeAccount.user, userId: activeAccount.userId, password: CCUtility.getPassword(activeAccount.account), initialize: false)
- NCBrandColor.shared.settingThemingColor(account: activeAccount.account)
- initialize()
- } else {
- CCUtility.deleteAllChainStore()
- if let bundleID = Bundle.main.bundleIdentifier {
- UserDefaults.standard.removePersistentDomain(forName: bundleID)
- }
- NCBrandColor.shared.createImagesThemingColor()
- }
-
- NCBrandColor.shared.createUserColors()
-
- application.registerForRemoteNotifications()
- UNUserNotificationCenter.current().delegate = self
- UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { _, _ in }
-
- if !NCUtility.shared.isSimulatorOrTestFlight() {
- let review = NCStoreReview()
- review.incrementAppRuns()
- review.showStoreReview()
- }
-
- BGTaskScheduler.shared.register(forTaskWithIdentifier: NCGlobal.shared.refreshTask, using: nil) { task in
- self.handleRefreshTask(task)
- }
- BGTaskScheduler.shared.register(forTaskWithIdentifier: NCGlobal.shared.processingTask, using: nil) { task in
- self.handleProcessingTask(task)
- }
-
- if NCBrandOptions.shared.disable_intro {
- CCUtility.setIntro(true)
- if account.isEmpty {
- openLogin(viewController: nil, selector: NCGlobal.shared.introLogin, openLoginWeb: false)
- }
- } else {
- if !CCUtility.getIntro() {
- if let viewController = UIStoryboard(name: "NCIntro", bundle: nil).instantiateInitialViewController() {
- let navigationController = NCLoginNavigationController(rootViewController: viewController)
- window?.rootViewController = navigationController
- window?.makeKeyAndVisible()
- }
- }
- }
-
- self.presentPasscode {
- self.enableTouchFaceID()
- }
- return true
- }
-
-
- func applicationDidBecomeActive(_ application: UIApplication) {
- NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Application did become active")
- NCSettingsBundleHelper.setVersionAndBuildNumber()
- NCSettingsBundleHelper.checkAndExecuteSettings(delay: 0.5)
-
- NCNetworkingProcessUpload.shared.observeTableMetadata()
- NCNetworkingProcessUpload.shared.startTimer()
- if !NCAskAuthorization.shared.isRequesting {
- hidePrivacyProtectionWindow()
- }
- if !account.isEmpty {
- NCNetworkingProcessUpload.shared.verifyUploadZombie()
- }
-
- NCAutoUpload.shared.initAutoUpload(viewController: nil) { items in
- NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Initialize Auto upload with \(items) uploads")
- }
- NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterApplicationDidBecomeActive)
- }
-
- func applicationWillEnterForeground(_ application: UIApplication) {
- guard !account.isEmpty, let activeAccount = NCManageDatabase.shared.getActiveAccount() else { return }
- NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Application will enter in foreground")
- if activeAccount.account != account {
- settingAccount(activeAccount.account, urlBase: activeAccount.urlBase, user: activeAccount.user, userId: activeAccount.userId, password: CCUtility.getPassword(activeAccount.account))
- } else {
-
- NCService.shared.startRequestServicesServer()
- }
-
- NCPushNotification.shared().pushNotification()
-
- enableTouchFaceID()
- NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterRichdocumentGrabFocus)
- NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterReloadDataSourceNetwork, second: 2)
- }
-
- func applicationWillResignActive(_ application: UIApplication) {
-
- if let error = updateShareAccounts() {
- NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] Create share accounts \(error.localizedDescription)")
- }
- NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Application will resign active")
- guard !account.isEmpty else { return }
-
- NCNetworkingProcessUpload.shared.invalidateObserveTableMetadata()
- NCNetworkingProcessUpload.shared.stopTimer()
- if CCUtility.getPrivacyScreenEnabled() {
-
- showPrivacyProtectionWindow()
- }
-
- WidgetCenter.shared.reloadAllTimelines()
-
- NCOperationQueue.shared.cancelAllQueue()
-
- NCNetworking.shared.cancelAllDownloadTransfer()
-
- let days = CCUtility.getCleanUpDay()
- if let directory = CCUtility.getDirectoryProviderStorage() {
- NCUtilityFileSystem.shared.cleanUp(directory: directory, days: TimeInterval(days))
- }
- NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterApplicationWillResignActive)
- }
-
- func applicationDidEnterBackground(_ application: UIApplication) {
- guard !account.isEmpty else { return }
- NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Application did enter in background")
- scheduleAppRefresh()
- scheduleAppProcessing()
-
- presentPasscode { }
- NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterApplicationDidEnterBackground)
- }
-
- func applicationWillTerminate(_ application: UIApplication) {
- NCNetworking.shared.cancelAllDownloadTransfer()
- if UIApplication.shared.backgroundRefreshStatus == .available {
- let content = UNMutableNotificationContent()
- content.title = NCBrandOptions.shared.brand
- content.body = NSLocalizedString("_keep_running_", comment: "")
- let req = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: nil)
- let notificationCenter = UNUserNotificationCenter.current()
- notificationCenter.add(req)
- }
- NextcloudKit.shared.nkCommonInstance.writeLog("bye bye")
- }
-
- @objc private func initialize() {
- guard !account.isEmpty else { return }
- NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] initialize Main")
-
- NCPushNotification.shared().pushNotification()
-
- NCNetworkingE2EE().unlockAll(account: account)
-
- NCService.shared.startRequestServicesServer()
-
- NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterMenuDetailClose)
-
- WidgetCenter.shared.reloadAllTimelines()
-
-
-
-
- }
-
-
- func scheduleAppRefresh() {
- let request = BGAppRefreshTaskRequest(identifier: NCGlobal.shared.refreshTask)
- request.earliestBeginDate = Date(timeIntervalSinceNow: 60)
- do {
- try BGTaskScheduler.shared.submit(request)
- NextcloudKit.shared.nkCommonInstance.writeLog("[SUCCESS] Refresh task success submit request 60 seconds \(request)")
- } catch {
- NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] Refresh task failed to submit request: \(error)")
- }
- }
-
- func scheduleAppProcessing() {
- let request = BGProcessingTaskRequest(identifier: NCGlobal.shared.processingTask)
- request.earliestBeginDate = Date(timeIntervalSinceNow: 5 * 60)
- request.requiresNetworkConnectivity = false
- request.requiresExternalPower = false
- do {
- try BGTaskScheduler.shared.submit(request)
- NextcloudKit.shared.nkCommonInstance.writeLog("[SUCCESS] Background Processing task success submit request 5 minutes \(request)")
- } catch {
- NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] Background Processing task failed to submit request: \(error)")
- }
- }
- func handleRefreshTask(_ task: BGTask) {
- scheduleAppRefresh()
- guard !account.isEmpty else {
- task.setTaskCompleted(success: true)
- return
- }
- NextcloudKit.shared.setup(delegate: NCNetworking.shared)
- NCAutoUpload.shared.initAutoUpload(viewController: nil) { items in
- NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Refresh task auto upload with \(items) uploads")
- NCNetworkingProcessUpload.shared.start { items in
- NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Refresh task upload process with \(items) uploads")
- task.setTaskCompleted(success: true)
- }
- }
- }
- func handleProcessingTask(_ task: BGTask) {
- scheduleAppProcessing()
- guard !account.isEmpty else {
- task.setTaskCompleted(success: true)
- return
- }
- NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Processing task")
- task.setTaskCompleted(success: true)
- }
-
- func application(_ application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: @escaping () -> Void) {
- NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Start handle Events For Background URLSession: \(identifier)")
-
- WidgetCenter.shared.reloadAllTimelines()
- backgroundSessionCompletionHandler = completionHandler
- }
-
- func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
- completionHandler([.list, .banner, .sound])
- }
- func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
- if let pref = UserDefaults(suiteName: NCBrandOptions.shared.capabilitiesGroups),
- let data = pref.object(forKey: "NOTIFICATION_DATA") as? [String: AnyObject] {
- nextcloudPushNotificationAction(data: data)
- pref.set(nil, forKey: "NOTIFICATION_DATA")
- }
- completionHandler()
- }
- func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
- NCNetworking.shared.checkPushNotificationServerProxyCertificateUntrusted(viewController: self.window?.rootViewController) { error in
- if error == .success {
- NCPushNotification.shared().registerForRemoteNotifications(withDeviceToken: deviceToken)
- }
- }
- }
- func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
- NCPushNotification.shared().applicationdidReceiveRemoteNotification(userInfo) { result in
- completionHandler(result)
- }
- }
- func nextcloudPushNotificationAction(data: [String: AnyObject]) {
- guard let data = NCApplicationHandle().nextcloudPushNotificationAction(data: data) else { return }
- var findAccount: Bool = false
- if let accountPush = data["account"] as? String {
- if accountPush == self.account {
- findAccount = true
- } else {
- let accounts = NCManageDatabase.shared.getAllAccount()
- for account in accounts {
- if account.account == accountPush {
- self.changeAccount(account.account)
- findAccount = true
- }
- }
- }
- if findAccount, let viewController = UIStoryboard(name: "NCNotification", bundle: nil).instantiateInitialViewController() as? NCNotification {
- DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
- let navigationController = UINavigationController(rootViewController: viewController)
- navigationController.modalPresentationStyle = .fullScreen
- self.window?.rootViewController?.present(navigationController, animated: true)
- }
- } else if !findAccount {
- let message = NSLocalizedString("_the_account_", comment: "") + " " + accountPush + " " + NSLocalizedString("_does_not_exist_", comment: "")
- let alertController = UIAlertController(title: NSLocalizedString("_info_", comment: ""), message: message, preferredStyle: .alert)
- alertController.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { _ in }))
- self.window?.rootViewController?.present(alertController, animated: true, completion: { })
- }
- }
- }
-
- @objc func openLogin(viewController: UIViewController?, selector: Int, openLoginWeb: Bool) {
-
- if NCBrandOptions.shared.use_login_web_personalized || NCBrandOptions.shared.use_AppConfig {
- if activeLoginWeb?.view.window == nil {
- activeLoginWeb = UIStoryboard(name: "NCLogin", bundle: nil).instantiateViewController(withIdentifier: "NCLoginWeb") as? NCLoginWeb
- activeLoginWeb?.urlBase = NCBrandOptions.shared.loginBaseUrl
- showLoginViewController(activeLoginWeb, contextViewController: viewController)
- }
- return
- }
-
- if selector == NCGlobal.shared.introSignup {
- if activeLoginWeb?.view.window == nil {
- activeLoginWeb = UIStoryboard(name: "NCLogin", bundle: nil).instantiateViewController(withIdentifier: "NCLoginWeb") as? NCLoginWeb
- if selector == NCGlobal.shared.introSignup {
- activeLoginWeb?.urlBase = NCBrandOptions.shared.linkloginPreferredProviders
- } else {
- activeLoginWeb?.urlBase = self.urlBase
- }
- showLoginViewController(activeLoginWeb, contextViewController: viewController)
- }
- } else if NCBrandOptions.shared.disable_intro && NCBrandOptions.shared.disable_request_login_url {
- if activeLoginWeb?.view.window == nil {
- activeLoginWeb = UIStoryboard(name: "NCLogin", bundle: nil).instantiateViewController(withIdentifier: "NCLoginWeb") as? NCLoginWeb
- activeLoginWeb?.urlBase = NCBrandOptions.shared.loginBaseUrl
- showLoginViewController(activeLoginWeb, contextViewController: viewController)
- }
- } else if openLoginWeb {
-
- if activeLoginWeb?.view.window == nil {
- activeLoginWeb = UIStoryboard(name: "NCLogin", bundle: nil).instantiateViewController(withIdentifier: "NCLoginWeb") as? NCLoginWeb
- activeLoginWeb?.urlBase = urlBase
- activeLoginWeb?.user = user
- showLoginViewController(activeLoginWeb, contextViewController: viewController)
- }
- } else {
- if activeLogin?.view.window == nil {
- activeLogin = UIStoryboard(name: "NCLogin", bundle: nil).instantiateViewController(withIdentifier: "NCLogin") as? NCLogin
- showLoginViewController(activeLogin, contextViewController: viewController)
- }
- }
- }
- func showLoginViewController(_ viewController: UIViewController?, contextViewController: UIViewController?) {
- if contextViewController == nil {
- if let viewController = viewController {
- let navigationController = NCLoginNavigationController(rootViewController: viewController)
- navigationController.navigationBar.barStyle = .black
- navigationController.navigationBar.tintColor = NCBrandColor.shared.customerText
- navigationController.navigationBar.barTintColor = NCBrandColor.shared.customer
- navigationController.navigationBar.isTranslucent = false
- window?.rootViewController = navigationController
- window?.makeKeyAndVisible()
- }
- } else if contextViewController is UINavigationController {
- if let contextViewController = contextViewController, let viewController = viewController {
- (contextViewController as! UINavigationController).pushViewController(viewController, animated: true)
- }
- } else {
- if let viewController = viewController, let contextViewController = contextViewController {
- let navigationController = NCLoginNavigationController(rootViewController: viewController)
- navigationController.modalPresentationStyle = .fullScreen
- navigationController.navigationBar.barStyle = .black
- navigationController.navigationBar.tintColor = NCBrandColor.shared.customerText
- navigationController.navigationBar.barTintColor = NCBrandColor.shared.customer
- navigationController.navigationBar.isTranslucent = false
- contextViewController.present(navigationController, animated: true) { }
- }
- }
- }
- @objc func startTimerErrorNetworking() {
- timerErrorNetworking = Timer.scheduledTimer(timeInterval: 3, target: self, selector: #selector(checkErrorNetworking), userInfo: nil, repeats: true)
- }
- @objc private func checkErrorNetworking() {
- if account != "" && CCUtility.getPassword(account)!.count == 0 {
- openLogin(viewController: window?.rootViewController, selector: NCGlobal.shared.introLogin, openLoginWeb: true)
- }
- }
- func trustCertificateError(host: String) {
- guard let currentHost = URL(string: self.urlBase)?.host,
- let pushNotificationServerProxyHost = URL(string: NCBrandOptions.shared.pushNotificationServerProxy)?.host,
- host != pushNotificationServerProxyHost,
- host == currentHost
- else { return }
- let certificateHostSavedPath = CCUtility.getDirectoryCerificates()! + "/" + host + ".der"
- var title = NSLocalizedString("_ssl_certificate_changed_", comment: "")
- if !FileManager.default.fileExists(atPath: certificateHostSavedPath) {
- title = NSLocalizedString("_connect_server_anyway_", comment: "")
- }
- let alertController = UIAlertController(title: title, message: NSLocalizedString("_server_is_trusted_", comment: ""), preferredStyle: .alert)
- alertController.addAction(UIAlertAction(title: NSLocalizedString("_yes_", comment: ""), style: .default, handler: { _ in
- NCNetworking.shared.writeCertificate(host: host)
- }))
- alertController.addAction(UIAlertAction(title: NSLocalizedString("_no_", comment: ""), style: .default, handler: { _ in }))
- alertController.addAction(UIAlertAction(title: NSLocalizedString("_certificate_details_", comment: ""), style: .default, handler: { _ in
- if let navigationController = UIStoryboard(name: "NCViewCertificateDetails", bundle: nil).instantiateInitialViewController() as? UINavigationController {
- let viewController = navigationController.topViewController as! NCViewCertificateDetails
- viewController.delegate = self
- viewController.host = host
- self.window?.rootViewController?.present(navigationController, animated: true)
- }
- }))
- window?.rootViewController?.present(alertController, animated: true)
- }
- func viewCertificateDetailsDismiss(host: String) {
- trustCertificateError(host: host)
- }
-
- @objc func settingAccount(_ account: String, urlBase: String, user: String, userId: String, password: String, initialize: Bool = true) {
- let currentAccount = self.account + "/" + self.userId
- let newAccount = account + "/" + userId
- self.account = account
- self.urlBase = urlBase
- self.user = user
- self.userId = userId
- self.password = password
- _ = NCActionCenter.shared
- NextcloudKit.shared.setup(account: account, user: user, userId: userId, password: password, urlBase: urlBase)
- NCManageDatabase.shared.setCapabilities(account: account)
- if NCGlobal.shared.capabilityServerVersionMajor > 0 {
- NextcloudKit.shared.setup(nextcloudVersion: NCGlobal.shared.capabilityServerVersionMajor)
- }
- DispatchQueue.main.async {
- if initialize, UIApplication.shared.applicationState != .background && currentAccount != newAccount && newAccount != "/" {
- NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterInitialize, second: 0.2)
- }
- }
- }
- @objc func deleteAccount(_ account: String, wipe: Bool) {
- if let account = NCManageDatabase.shared.getAccount(predicate: NSPredicate(format: "account == %@", account)) {
- NCPushNotification.shared().unsubscribingNextcloudServerPushNotification(account.account, urlBase: account.urlBase, user: account.user, withSubscribing: false)
- }
- let results = NCManageDatabase.shared.getTableLocalFiles(predicate: NSPredicate(format: "account == %@", account), sorted: "ocId", ascending: false)
- for result in results {
- CCUtility.removeFile(atPath: CCUtility.getDirectoryProviderStorageOcId(result.ocId))
- }
- NCManageDatabase.shared.clearDatabase(account: account, removeAccount: true)
- CCUtility.clearAllKeysEnd(toEnd: account)
- CCUtility.clearAllKeysPushNotification(account)
- CCUtility.setPassword(account, password: nil)
- settingAccount("", urlBase: "", user: "", userId: "", password: "")
- if wipe {
- let accounts = NCManageDatabase.shared.getAccounts()
- if accounts?.count ?? 0 > 0 {
- if let newAccount = accounts?.first {
- self.changeAccount(newAccount)
- }
- } else {
- openLogin(viewController: window?.rootViewController, selector: NCGlobal.shared.introLogin, openLoginWeb: false)
- }
- }
- }
- @objc func deleteAllAccounts() {
- let accounts = NCManageDatabase.shared.getAccounts()
- accounts?.forEach({ account in
- deleteAccount(account, wipe: true)
- })
- }
- @objc func changeAccount(_ account: String) {
- NCManageDatabase.shared.setAccountActive(account)
- if let tableAccount = NCManageDatabase.shared.getActiveAccount() {
- NCOperationQueue.shared.cancelAllQueue()
- NCNetworking.shared.cancelAllTask()
- settingAccount(tableAccount.account, urlBase: tableAccount.urlBase, user: tableAccount.user, userId: tableAccount.userId, password: CCUtility.getPassword(tableAccount.account))
- }
- }
- func updateShareAccounts() -> Error? {
- guard let dirGroupApps = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: NCBrandOptions.shared.capabilitiesGroupApps) else { return nil }
- let tableAccount = NCManageDatabase.shared.getAllAccount()
- var accounts = [NKShareAccounts.DataAccounts]()
- for account in tableAccount {
- let name = account.alias.isEmpty ? account.displayName : account.alias
- let userBaseUrl = account.user + "-" + (URL(string: account.urlBase)?.host ?? "")
- let avatarFileName = userBaseUrl + "-\(account.user).png"
- let pathAvatarFileName = String(CCUtility.getDirectoryUserData()) + "/" + avatarFileName
- let image = UIImage(contentsOfFile: pathAvatarFileName)
- accounts.append(NKShareAccounts.DataAccounts(withUrl: account.urlBase, user: account.user, name: name, image: image))
- }
- return NKShareAccounts().putShareAccounts(at: dirGroupApps, app: NCGlobal.shared.appScheme, dataAccounts: accounts)
- }
-
- func accountRequestChangeAccount(account: String) {
- changeAccount(account)
- }
- func requestAccount() {
- if isPasscodePresented() { return }
- if !CCUtility.getAccountRequest() { return }
- let accounts = NCManageDatabase.shared.getAllAccount()
- if accounts.count > 1 {
- if let vcAccountRequest = UIStoryboard(name: "NCAccountRequest", bundle: nil).instantiateInitialViewController() as? NCAccountRequest {
- vcAccountRequest.activeAccount = NCManageDatabase.shared.getActiveAccount()
- vcAccountRequest.accounts = accounts
- vcAccountRequest.enableTimerProgress = true
- vcAccountRequest.enableAddAccount = false
- vcAccountRequest.dismissDidEnterBackground = false
- vcAccountRequest.delegate = self
- let screenHeighMax = UIScreen.main.bounds.height - (UIScreen.main.bounds.height / 5)
- let numberCell = accounts.count
- let height = min(CGFloat(numberCell * Int(vcAccountRequest.heightCell) + 45), screenHeighMax)
- let popup = NCPopupViewController(contentController: vcAccountRequest, popupWidth: 300, popupHeight: height + 20)
- popup.backgroundAlpha = 0.8
- window?.rootViewController?.present(popup, animated: true)
- vcAccountRequest.startTimer()
- }
- }
- }
-
- func presentPasscode(completion: @escaping () -> Void) {
- let laContext = LAContext()
- var error: NSError?
- defer { self.requestAccount() }
- let presentedViewController = window?.rootViewController?.presentedViewController
- guard !account.isEmpty, CCUtility.isPasscodeAtStartEnabled(), !(presentedViewController is NCLoginNavigationController) else { return }
-
- showPrivacyProtectionWindow()
- let passcodeViewController = TOPasscodeViewController(passcodeType: .sixDigits, allowCancel: false)
- passcodeViewController.delegate = self
- passcodeViewController.keypadButtonShowLettering = false
- if CCUtility.getEnableTouchFaceID() && laContext.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error) {
- if error == nil {
- if laContext.biometryType == .faceID {
- passcodeViewController.biometryType = .faceID
- } else if laContext.biometryType == .touchID {
- passcodeViewController.biometryType = .touchID
- }
- passcodeViewController.allowBiometricValidation = true
- passcodeViewController.automaticallyPromptForBiometricValidation = false
- }
- }
-
- privacyProtectionWindow?.rootViewController?.present(passcodeViewController, animated: true, completion: {
- completion()
- })
- }
- func isPasscodePresented() -> Bool {
- return privacyProtectionWindow?.rootViewController?.presentedViewController is TOPasscodeViewController
- }
- func enableTouchFaceID() {
- guard !account.isEmpty,
- CCUtility.getEnableTouchFaceID(),
- CCUtility.isPasscodeAtStartEnabled(),
- let passcodeViewController = privacyProtectionWindow?.rootViewController?.presentedViewController as? TOPasscodeViewController
- else { return }
- DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
- LAContext().evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: NCBrandOptions.shared.brand) { success, _ in
- if success {
- DispatchQueue.main.async {
- passcodeViewController.dismiss(animated: true) {
- self.hidePrivacyProtectionWindow()
- self.requestAccount()
- }
- }
- }
- }
- }
- }
- func didInputCorrectPasscode(in passcodeViewController: TOPasscodeViewController) {
- DispatchQueue.main.async {
- passcodeViewController.dismiss(animated: true) {
- self.hidePrivacyProtectionWindow()
- self.requestAccount()
- }
- }
- }
- func passcodeViewController(_ passcodeViewController: TOPasscodeViewController, isCorrectCode code: String) -> Bool {
- return code == CCUtility.getPasscode()
- }
- func didPerformBiometricValidationRequest(in passcodeViewController: TOPasscodeViewController) {
- enableTouchFaceID()
- }
-
- private func showPrivacyProtectionWindow() {
- guard privacyProtectionWindow == nil else {
- privacyProtectionWindow?.isHidden = false
- return
- }
- privacyProtectionWindow = UIWindow(frame: UIScreen.main.bounds)
- let storyboard = UIStoryboard(name: "LaunchScreen", bundle: nil)
- let initialViewController = storyboard.instantiateInitialViewController()
- self.privacyProtectionWindow?.rootViewController = initialViewController
- privacyProtectionWindow?.windowLevel = .alert + 1
- privacyProtectionWindow?.makeKeyAndVisible()
- }
- func hidePrivacyProtectionWindow() {
- guard !(privacyProtectionWindow?.rootViewController?.presentedViewController is TOPasscodeViewController) else { return }
- UIWindow.animate(withDuration: 0.25) {
- self.privacyProtectionWindow?.alpha = 0
- } completion: { _ in
- self.privacyProtectionWindow?.isHidden = true
- self.privacyProtectionWindow = nil
- }
- }
-
- func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
- let applicationHandle = NCApplicationHandle()
- return applicationHandle.applicationOpenUserActivity(userActivity)
- }
-
- func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool {
- let scheme = url.scheme
- let action = url.host
- var fileName: String = ""
- var serverUrl: String = ""
-
- if !account.isEmpty && scheme == NCGlobal.shared.appScheme && action == "open-action" {
- if let urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false) {
- let queryItems = urlComponents.queryItems
- guard let actionScheme = CCUtility.value(forKey: "action", fromQueryItems: queryItems), let rootViewController = window?.rootViewController else { return false }
- guard let userScheme = CCUtility.value(forKey: "user", fromQueryItems: queryItems) else { return false }
- guard let urlScheme = CCUtility.value(forKey: "url", fromQueryItems: queryItems) else { return false }
- if getMatchedAccount(userId: userScheme, url: urlScheme) == nil {
- let message = NSLocalizedString("_the_account_", comment: "") + " " + userScheme + NSLocalizedString("_of_", comment: "") + " " + urlScheme + " " + NSLocalizedString("_does_not_exist_", comment: "")
- let alertController = UIAlertController(title: NSLocalizedString("_info_", comment: ""), message: message, preferredStyle: .alert)
- alertController.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { _ in }))
- window?.rootViewController?.present(alertController, animated: true, completion: { })
- return false
- }
- switch actionScheme {
- case NCGlobal.shared.actionUploadAsset:
- NCAskAuthorization.shared.askAuthorizationPhotoLibrary(viewController: rootViewController) { hasPermission in
- if hasPermission {NCPhotosPickerViewController(viewController: rootViewController, maxSelectedAssets: 0, singleSelectedMode: false)
- }
- }
- case NCGlobal.shared.actionScanDocument:
- NCDocumentCamera.shared.openScannerDocument(viewController: rootViewController)
- case NCGlobal.shared.actionTextDocument:
- guard let navigationController = UIStoryboard(name: "NCCreateFormUploadDocuments", bundle: nil).instantiateInitialViewController(), let directEditingCreators = NCManageDatabase.shared.getDirectEditingCreators(account: account), let directEditingCreator = directEditingCreators.first(where: { $0.editor == NCGlobal.shared.editorText}) else { return false }
- navigationController.modalPresentationStyle = UIModalPresentationStyle.formSheet
- let viewController = (navigationController as! UINavigationController).topViewController as! NCCreateFormUploadDocuments
- viewController.editorId = NCGlobal.shared.editorText
- viewController.creatorId = directEditingCreator.identifier
- viewController.typeTemplate = NCGlobal.shared.templateDocument
- viewController.serverUrl = activeServerUrl
- viewController.titleForm = NSLocalizedString("_create_nextcloudtext_document_", comment: "")
- rootViewController.present(navigationController, animated: true, completion: nil)
- case NCGlobal.shared.actionVoiceMemo:
- NCAskAuthorization.shared.askAuthorizationAudioRecord(viewController: rootViewController) { hasPermission in
- if hasPermission {
- let fileName = CCUtility.createFileNameDate(NSLocalizedString("_voice_memo_filename_", comment: ""), extension: "m4a")!
- let viewController = UIStoryboard(name: "NCAudioRecorderViewController", bundle: nil).instantiateInitialViewController() as! NCAudioRecorderViewController
- viewController.delegate = self
- viewController.createRecorder(fileName: fileName)
- viewController.modalTransitionStyle = .crossDissolve
- viewController.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext
- rootViewController.present(viewController, animated: true, completion: nil)
- }
- }
- default:
- print("No action")
- }
- }
- return true
- }
- /*
- Example:
- nextcloud://open-file?path=Talk/IMG_0000123.jpg&user=marinofaggiana&link=https://cloud.nextcloud.com/f/123
- */
- else if !account.isEmpty && scheme == NCGlobal.shared.appScheme && action == "open-file" {
- if let urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false) {
- let queryItems = urlComponents.queryItems
- guard let userScheme = CCUtility.value(forKey: "user", fromQueryItems: queryItems) else { return false }
- guard let pathScheme = CCUtility.value(forKey: "path", fromQueryItems: queryItems) else { return false }
- guard let linkScheme = CCUtility.value(forKey: "link", fromQueryItems: queryItems) else { return false }
- guard let matchedAccount = getMatchedAccount(userId: userScheme, url: linkScheme) else {
- guard let domain = URL(string: linkScheme)?.host else { return true }
- fileName = (pathScheme as NSString).lastPathComponent
- let message = String(format: NSLocalizedString("_account_not_available_", comment: ""), userScheme, domain, fileName)
- let alertController = UIAlertController(title: NSLocalizedString("_info_", comment: ""), message: message, preferredStyle: .alert)
- alertController.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { _ in }))
- window?.rootViewController?.present(alertController, animated: true, completion: { })
- return false
- }
- let davFiles = NextcloudKit.shared.nkCommonInstance.dav + "/files/" + self.userId
- if pathScheme.contains("/") {
- fileName = (pathScheme as NSString).lastPathComponent
- serverUrl = matchedAccount.urlBase + "/" + davFiles + "/" + (pathScheme as NSString).deletingLastPathComponent
- } else {
- fileName = pathScheme
- serverUrl = matchedAccount.urlBase + "/" + davFiles
- }
- DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
- NCActionCenter.shared.openFileViewInFolder(serverUrl: serverUrl, fileNameBlink: nil, fileNameOpen: fileName)
- }
- }
- return true
-
- } else if !account.isEmpty && scheme == NCGlobal.shared.appScheme && action == "open-and-switch-account" {
- guard let urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false) else { return false }
- let queryItems = urlComponents.queryItems
- guard let userScheme = CCUtility.value(forKey: "user", fromQueryItems: queryItems) else { return false }
- guard let urlScheme = CCUtility.value(forKey: "url", fromQueryItems: queryItems) else { return false }
-
- if getMatchedAccount(userId: userScheme, url: urlScheme) == nil {
- return false
- }
-
- return true
- } else {
- let applicationHandle = NCApplicationHandle()
- let isHandled = applicationHandle.applicationOpenURL(url)
- if isHandled {
- return true
- } else {
- app.open(url)
- return true
- }
- }
- }
- func getMatchedAccount(userId: String, url: String) -> tableAccount? {
- if let activeAccount = NCManageDatabase.shared.getActiveAccount() {
- let urlBase = URL(string: activeAccount.urlBase)
- if url.contains(urlBase?.host ?? "") && userId == activeAccount.userId {
- return activeAccount
- } else {
- let accounts = NCManageDatabase.shared.getAllAccount()
- for account in accounts {
- let urlBase = URL(string: account.urlBase)
- if url.contains(urlBase?.host ?? "") && userId == account.userId {
- changeAccount(account.account)
- return account
- }
- }
- }
- }
- return nil
- }
- }
- extension AppDelegate: NCAudioRecorderViewControllerDelegate {
- func didFinishRecording(_ viewController: NCAudioRecorderViewController, fileName: String) {
- guard
- let navigationController = UIStoryboard(name: "NCCreateFormUploadVoiceNote", bundle: nil).instantiateInitialViewController() as? UINavigationController,
- let viewController = navigationController.topViewController as? NCCreateFormUploadVoiceNote
- else { return }
- navigationController.modalPresentationStyle = .formSheet
- viewController.setup(serverUrl: activeServerUrl, fileNamePath: NSTemporaryDirectory() + fileName, fileName: fileName)
- window?.rootViewController?.present(navigationController, animated: true)
- }
- func didFinishWithoutRecording(_ viewController: NCAudioRecorderViewController, fileName: String) {
- }
- }
- extension AppDelegate: NCCreateFormUploadConflictDelegate {
- func dismissCreateFormUploadConflict(metadatas: [tableMetadata]?) {
- guard let metadatas = metadatas, !metadatas.isEmpty else { return }
- NCNetworkingProcessUpload.shared.createProcessUploads(metadatas: metadatas) { _ in }
- }
- }
|