AppDelegate.swift 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141
  1. //
  2. // AppDelegate.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 04/09/14 (19/02/21 swift).
  6. // Copyright (c) 2014 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 BackgroundTasks
  25. import NextcloudKit
  26. import TOPasscodeViewController
  27. import LocalAuthentication
  28. import Firebase
  29. import WidgetKit
  30. import Queuer
  31. @UIApplicationMain
  32. class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, TOPasscodeViewControllerDelegate, NCAccountRequestDelegate, NCViewCertificateDetailsDelegate, NCUserBaseUrl {
  33. var backgroundSessionCompletionHandler: (() -> Void)?
  34. var window: UIWindow?
  35. @objc var account: String = ""
  36. @objc var urlBase: String = ""
  37. @objc var user: String = ""
  38. @objc var userId: String = ""
  39. @objc var password: String = ""
  40. var activeLogin: NCLogin?
  41. var activeLoginWeb: NCLoginWeb?
  42. var activeServerUrl: String = ""
  43. @objc var activeViewController: UIViewController?
  44. var mainTabBar: NCMainTabBar?
  45. var activeMetadata: tableMetadata?
  46. let listFilesVC = ThreadSafeDictionary<String, NCFiles>()
  47. var disableSharesView: Bool = false
  48. var documentPickerViewController: NCDocumentPickerViewController?
  49. var timerErrorNetworking: Timer?
  50. private var privacyProtectionWindow: UIWindow?
  51. let downloadQueue = Queuer(name: "downloadQueue", maxConcurrentOperationCount: NCGlobal.shared.maxConcurrentOperationCountDownload, qualityOfService: .default)
  52. let downloadThumbnailQueue = Queuer(name: "downloadThumbnailQueue", maxConcurrentOperationCount: 10, qualityOfService: .default)
  53. let downloadThumbnailActivityQueue = Queuer(name: "downloadThumbnailActivityQueue", maxConcurrentOperationCount: 10, qualityOfService: .default)
  54. let downloadAvatarQueue = Queuer(name: "downloadAvatarQueue", maxConcurrentOperationCount: 10, qualityOfService: .default)
  55. let unifiedSearchQueue = Queuer(name: "unifiedSearchQueue", maxConcurrentOperationCount: 1, qualityOfService: .default)
  56. let saveLivePhotoQueue = Queuer(name: "saveLivePhotoQueue", maxConcurrentOperationCount: 1, qualityOfService: .default)
  57. var isAppRefresh: Bool = false
  58. var isAppProcessing: Bool = false
  59. var isUiTestingEnabled: Bool {
  60. return ProcessInfo.processInfo.arguments.contains("UI_TESTING")
  61. }
  62. func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
  63. if isUiTestingEnabled {
  64. deleteAllAccounts()
  65. }
  66. let utilityFileSystem = NCUtilityFileSystem()
  67. let utility = NCUtility()
  68. NCSettingsBundleHelper.checkAndExecuteSettings(delay: 0)
  69. let versionNextcloudiOS = String(format: NCBrandOptions.shared.textCopyrightNextcloudiOS, utility.getVersionApp())
  70. UserDefaults.standard.register(defaults: ["UserAgent": userAgent])
  71. if !NCKeychain().disableCrashservice, !NCBrandOptions.shared.disable_crash_service {
  72. FirebaseApp.configure()
  73. }
  74. utilityFileSystem.createDirectoryStandard()
  75. utilityFileSystem.emptyTemporaryDirectory()
  76. utilityFileSystem.clearCacheDirectory("com.limit-point.LivePhoto")
  77. // Activated singleton
  78. _ = NCActionCenter.shared
  79. _ = NCNetworking.shared
  80. NextcloudKit.shared.setup(delegate: NCNetworking.shared)
  81. NextcloudKit.shared.setup(userAgent: userAgent)
  82. startTimerErrorNetworking()
  83. var levelLog = 0
  84. NextcloudKit.shared.nkCommonInstance.pathLog = utilityFileSystem.directoryGroup
  85. if NCBrandOptions.shared.disable_log {
  86. utilityFileSystem.removeFile(atPath: NextcloudKit.shared.nkCommonInstance.filenamePathLog)
  87. utilityFileSystem.removeFile(atPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! + "/" + NextcloudKit.shared.nkCommonInstance.filenameLog)
  88. } else {
  89. levelLog = NCKeychain().logLevel
  90. NextcloudKit.shared.nkCommonInstance.levelLog = levelLog
  91. NextcloudKit.shared.nkCommonInstance.copyLogToDocumentDirectory = true
  92. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Start session with level \(levelLog) " + versionNextcloudiOS)
  93. }
  94. if let account = NCManageDatabase.shared.getActiveAccount() {
  95. NextcloudKit.shared.nkCommonInstance.writeLog("Account active \(account.account)")
  96. if NCKeychain().getPassword(account: account.account).isEmpty {
  97. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] PASSWORD NOT FOUND for \(account.account)")
  98. }
  99. }
  100. if let activeAccount = NCManageDatabase.shared.getActiveAccount() {
  101. account = activeAccount.account
  102. urlBase = activeAccount.urlBase
  103. user = activeAccount.user
  104. userId = activeAccount.userId
  105. password = NCKeychain().getPassword(account: account)
  106. NextcloudKit.shared.setup(account: account, user: user, userId: userId, password: password, urlBase: urlBase)
  107. NCManageDatabase.shared.setCapabilities(account: account)
  108. NCBrandColor.shared.settingThemingColor(account: activeAccount.account)
  109. NCImageCache.shared.createImagesCache()
  110. NCImageCache.shared.createMediaCache(account: activeAccount.account)
  111. } else {
  112. NCKeychain().removeAll()
  113. if let bundleID = Bundle.main.bundleIdentifier {
  114. UserDefaults.standard.removePersistentDomain(forName: bundleID)
  115. }
  116. NCImageCache.shared.createImagesCache()
  117. }
  118. NCBrandColor.shared.createUserColors()
  119. // Push Notification & display notification
  120. application.registerForRemoteNotifications()
  121. UNUserNotificationCenter.current().delegate = self
  122. UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { _, _ in }
  123. if !utility.isSimulatorOrTestFlight() {
  124. let review = NCStoreReview()
  125. review.incrementAppRuns()
  126. review.showStoreReview()
  127. }
  128. // Background task register
  129. BGTaskScheduler.shared.register(forTaskWithIdentifier: NCGlobal.shared.refreshTask, using: nil) { task in
  130. self.handleAppRefresh(task)
  131. }
  132. BGTaskScheduler.shared.register(forTaskWithIdentifier: NCGlobal.shared.processingTask, using: nil) { task in
  133. self.handleProcessingTask(task)
  134. }
  135. // Intro
  136. if NCBrandOptions.shared.disable_intro {
  137. NCKeychain().intro = true
  138. if account.isEmpty {
  139. openLogin(viewController: nil, selector: NCGlobal.shared.introLogin, openLoginWeb: false)
  140. }
  141. } else {
  142. if !NCKeychain().intro {
  143. if let viewController = UIStoryboard(name: "NCIntro", bundle: nil).instantiateInitialViewController() {
  144. let navigationController = NCLoginNavigationController(rootViewController: viewController)
  145. window?.rootViewController = navigationController
  146. window?.makeKeyAndVisible()
  147. }
  148. }
  149. }
  150. self.presentPasscode {
  151. self.enableTouchFaceID()
  152. }
  153. return true
  154. }
  155. // MARK: - Life Cycle
  156. // L' applicazione entrerà in attivo (sempre)
  157. func applicationDidBecomeActive(_ application: UIApplication) {
  158. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Application did become active")
  159. NCSettingsBundleHelper.setVersionAndBuildNumber()
  160. NCSettingsBundleHelper.checkAndExecuteSettings(delay: 0.5)
  161. // START OBSERVE/TIMER UPLOAD PROCESS
  162. NCNetworkingProcessUpload.shared.observeTableMetadata()
  163. NCNetworkingProcessUpload.shared.startTimer()
  164. if !NCAskAuthorization().isRequesting {
  165. hidePrivacyProtectionWindow()
  166. }
  167. NCService().startRequestServicesServer()
  168. NCAutoUpload.shared.initAutoUpload(viewController: nil) { items in
  169. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Initialize Auto upload with \(items) uploads")
  170. }
  171. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterApplicationDidBecomeActive)
  172. }
  173. // L' applicazione si dimetterà dallo stato di attivo
  174. func applicationWillResignActive(_ application: UIApplication) {
  175. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Application will resign active")
  176. guard !account.isEmpty else { return }
  177. // STOP OBSERVE/TIMER UPLOAD PROCESS
  178. NCNetworkingProcessUpload.shared.invalidateObserveTableMetadata()
  179. NCNetworkingProcessUpload.shared.stopTimer()
  180. if NCKeychain().privacyScreenEnabled {
  181. showPrivacyProtectionWindow()
  182. }
  183. // Reload Widget
  184. WidgetCenter.shared.reloadAllTimelines()
  185. // Clear older files
  186. let days = NCKeychain().cleanUpDay
  187. let utilityFileSystem = NCUtilityFileSystem()
  188. utilityFileSystem.cleanUp(directory: utilityFileSystem.directoryProviderStorage, days: TimeInterval(days))
  189. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterApplicationWillResignActive)
  190. }
  191. // L' applicazione entrerà in primo piano (dopo il background)
  192. func applicationWillEnterForeground(_ application: UIApplication) {
  193. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Application will enter in foreground")
  194. guard !account.isEmpty else { return }
  195. enableTouchFaceID()
  196. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterRichdocumentGrabFocus)
  197. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterReloadDataSourceNetwork, second: 2)
  198. }
  199. // L' applicazione è entrata nello sfondo
  200. func applicationDidEnterBackground(_ application: UIApplication) {
  201. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Application did enter in background")
  202. guard !account.isEmpty else { return }
  203. let activeAccount = NCManageDatabase.shared.getActiveAccount()
  204. if let autoUpload = activeAccount?.autoUpload, autoUpload {
  205. NextcloudKit.shared.nkCommonInstance.writeLog("- Auto upload: true")
  206. if UIApplication.shared.backgroundRefreshStatus == .available {
  207. NextcloudKit.shared.nkCommonInstance.writeLog("- Auto upload in background: true")
  208. } else {
  209. NextcloudKit.shared.nkCommonInstance.writeLog("- Auto upload in background: false")
  210. }
  211. } else {
  212. NextcloudKit.shared.nkCommonInstance.writeLog("- Auto upload: false")
  213. }
  214. if let error = updateShareAccounts() {
  215. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] Create share accounts \(error.localizedDescription)")
  216. }
  217. scheduleAppRefresh()
  218. scheduleAppProcessing()
  219. NCNetworking.shared.cancelDataTask()
  220. NCNetworking.shared.cancelDownloadTasks()
  221. presentPasscode { }
  222. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterApplicationDidEnterBackground)
  223. }
  224. // L'applicazione terminerà
  225. func applicationWillTerminate(_ application: UIApplication) {
  226. if UIApplication.shared.backgroundRefreshStatus == .available {
  227. let content = UNMutableNotificationContent()
  228. content.title = NCBrandOptions.shared.brand
  229. content.body = NSLocalizedString("_keep_running_", comment: "")
  230. let req = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: nil)
  231. let notificationCenter = UNUserNotificationCenter.current()
  232. notificationCenter.add(req)
  233. }
  234. NextcloudKit.shared.nkCommonInstance.writeLog("bye bye")
  235. }
  236. // MARK: - Background Task
  237. /*
  238. @discussion Schedule a refresh task request to ask that the system launch your app briefly so that you can download data and keep your app's contents up-to-date. The system will fulfill this request intelligently based on system conditions and app usage.
  239. < MAX 30 seconds >
  240. */
  241. func scheduleAppRefresh() {
  242. let request = BGAppRefreshTaskRequest(identifier: NCGlobal.shared.refreshTask)
  243. request.earliestBeginDate = Date(timeIntervalSinceNow: 60) // Refresh after 60 seconds.
  244. do {
  245. try BGTaskScheduler.shared.submit(request)
  246. NextcloudKit.shared.nkCommonInstance.writeLog("- Refresh task: ok")
  247. } catch {
  248. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] Refresh task failed to submit request: \(error)")
  249. }
  250. }
  251. /*
  252. @discussion Schedule a processing task request to ask that the system launch your app when conditions are favorable for battery life to handle deferrable, longer-running processing, such as syncing, database maintenance, or similar tasks. The system will attempt to fulfill this request to the best of its ability within the next two days as long as the user has used your app within the past week.
  253. < MAX over 1 minute >
  254. */
  255. func scheduleAppProcessing() {
  256. let request = BGProcessingTaskRequest(identifier: NCGlobal.shared.processingTask)
  257. request.earliestBeginDate = Date(timeIntervalSinceNow: 5 * 60) // Refresh after 5 minutes.
  258. request.requiresNetworkConnectivity = false
  259. request.requiresExternalPower = false
  260. do {
  261. try BGTaskScheduler.shared.submit(request)
  262. NextcloudKit.shared.nkCommonInstance.writeLog("- Processing task: ok")
  263. } catch {
  264. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] Background Processing task failed to submit request: \(error)")
  265. }
  266. }
  267. func handleAppRefresh(_ task: BGTask) {
  268. scheduleAppRefresh()
  269. if isAppProcessing {
  270. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Processing task already in progress, abort.")
  271. task.setTaskCompleted(success: true)
  272. return
  273. }
  274. isAppRefresh = true
  275. NCAutoUpload.shared.initAutoUpload(viewController: nil) { items in
  276. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Refresh task auto upload with \(items) uploads")
  277. NCNetworkingProcessUpload.shared.start { items in
  278. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Refresh task upload process with \(items) uploads")
  279. task.setTaskCompleted(success: true)
  280. self.isAppRefresh = false
  281. }
  282. }
  283. }
  284. func handleProcessingTask(_ task: BGTask) {
  285. scheduleAppProcessing()
  286. if isAppRefresh {
  287. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Refresh task already in progress, abort.")
  288. task.setTaskCompleted(success: true)
  289. return
  290. }
  291. isAppProcessing = true
  292. NCAutoUpload.shared.initAutoUpload(viewController: nil) { items in
  293. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Processing task auto upload with \(items) uploads")
  294. NCNetworkingProcessUpload.shared.start { items in
  295. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Processing task upload process with \(items) uploads")
  296. task.setTaskCompleted(success: true)
  297. self.isAppProcessing = false
  298. }
  299. }
  300. }
  301. // MARK: - Background Networking Session
  302. func application(_ application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: @escaping () -> Void) {
  303. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Start handle Events For Background URLSession: \(identifier)")
  304. WidgetCenter.shared.reloadAllTimelines()
  305. backgroundSessionCompletionHandler = completionHandler
  306. }
  307. // MARK: - Push Notifications
  308. func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
  309. completionHandler([.list, .banner, .sound])
  310. }
  311. func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
  312. if let pref = UserDefaults(suiteName: NCBrandOptions.shared.capabilitiesGroups),
  313. let data = pref.object(forKey: "NOTIFICATION_DATA") as? [String: AnyObject] {
  314. nextcloudPushNotificationAction(data: data)
  315. pref.set(nil, forKey: "NOTIFICATION_DATA")
  316. }
  317. completionHandler()
  318. }
  319. func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
  320. NCNetworking.shared.checkPushNotificationServerProxyCertificateUntrusted(viewController: self.window?.rootViewController) { error in
  321. if error == .success {
  322. NCPushNotification.shared().registerForRemoteNotifications(withDeviceToken: deviceToken)
  323. }
  324. }
  325. }
  326. func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
  327. NCPushNotification.shared().applicationdidReceiveRemoteNotification(userInfo) { result in
  328. completionHandler(result)
  329. }
  330. }
  331. func nextcloudPushNotificationAction(data: [String: AnyObject]) {
  332. guard let data = NCApplicationHandle().nextcloudPushNotificationAction(data: data) else { return }
  333. var findAccount: Bool = false
  334. if let accountPush = data["account"] as? String {
  335. if accountPush == self.account {
  336. findAccount = true
  337. } else {
  338. let accounts = NCManageDatabase.shared.getAllAccount()
  339. for account in accounts {
  340. if account.account == accountPush {
  341. self.changeAccount(account.account, userProfile: nil)
  342. findAccount = true
  343. }
  344. }
  345. }
  346. if findAccount, let viewController = UIStoryboard(name: "NCNotification", bundle: nil).instantiateInitialViewController() as? NCNotification {
  347. DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
  348. let navigationController = UINavigationController(rootViewController: viewController)
  349. navigationController.modalPresentationStyle = .fullScreen
  350. self.window?.rootViewController?.present(navigationController, animated: true)
  351. }
  352. } else if !findAccount {
  353. let message = NSLocalizedString("_the_account_", comment: "") + " " + accountPush + " " + NSLocalizedString("_does_not_exist_", comment: "")
  354. let alertController = UIAlertController(title: NSLocalizedString("_info_", comment: ""), message: message, preferredStyle: .alert)
  355. alertController.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { _ in }))
  356. self.window?.rootViewController?.present(alertController, animated: true, completion: { })
  357. }
  358. }
  359. }
  360. // MARK: - Login & checkErrorNetworking
  361. @objc func openLogin(viewController: UIViewController?, selector: Int, openLoginWeb: Bool) {
  362. // [WEBPersonalized] [AppConfig]
  363. if NCBrandOptions.shared.use_login_web_personalized || NCBrandOptions.shared.use_AppConfig {
  364. if activeLoginWeb?.view.window == nil {
  365. activeLoginWeb = UIStoryboard(name: "NCLogin", bundle: nil).instantiateViewController(withIdentifier: "NCLoginWeb") as? NCLoginWeb
  366. activeLoginWeb?.urlBase = NCBrandOptions.shared.loginBaseUrl
  367. showLoginViewController(activeLoginWeb, contextViewController: viewController)
  368. }
  369. return
  370. }
  371. // Nextcloud standard login
  372. if selector == NCGlobal.shared.introSignup {
  373. if activeLoginWeb?.view.window == nil {
  374. activeLoginWeb = UIStoryboard(name: "NCLogin", bundle: nil).instantiateViewController(withIdentifier: "NCLoginWeb") as? NCLoginWeb
  375. if selector == NCGlobal.shared.introSignup {
  376. activeLoginWeb?.urlBase = NCBrandOptions.shared.linkloginPreferredProviders
  377. } else {
  378. activeLoginWeb?.urlBase = self.urlBase
  379. }
  380. showLoginViewController(activeLoginWeb, contextViewController: viewController)
  381. }
  382. } else if NCBrandOptions.shared.disable_intro && NCBrandOptions.shared.disable_request_login_url {
  383. if activeLoginWeb?.view.window == nil {
  384. activeLoginWeb = UIStoryboard(name: "NCLogin", bundle: nil).instantiateViewController(withIdentifier: "NCLoginWeb") as? NCLoginWeb
  385. activeLoginWeb?.urlBase = NCBrandOptions.shared.loginBaseUrl
  386. showLoginViewController(activeLoginWeb, contextViewController: viewController)
  387. }
  388. } else if openLoginWeb {
  389. // Used also for reinsert the account (change passwd)
  390. if activeLoginWeb?.view.window == nil {
  391. activeLoginWeb = UIStoryboard(name: "NCLogin", bundle: nil).instantiateViewController(withIdentifier: "NCLoginWeb") as? NCLoginWeb
  392. activeLoginWeb?.urlBase = urlBase
  393. activeLoginWeb?.user = user
  394. showLoginViewController(activeLoginWeb, contextViewController: viewController)
  395. }
  396. } else {
  397. if activeLogin?.view.window == nil {
  398. activeLogin = UIStoryboard(name: "NCLogin", bundle: nil).instantiateViewController(withIdentifier: "NCLogin") as? NCLogin
  399. showLoginViewController(activeLogin, contextViewController: viewController)
  400. }
  401. }
  402. }
  403. func showLoginViewController(_ viewController: UIViewController?, contextViewController: UIViewController?) {
  404. if contextViewController == nil {
  405. if let viewController = viewController {
  406. let navigationController = NCLoginNavigationController(rootViewController: viewController)
  407. navigationController.navigationBar.barStyle = .black
  408. navigationController.navigationBar.tintColor = NCBrandColor.shared.customerText
  409. navigationController.navigationBar.barTintColor = NCBrandColor.shared.customer
  410. navigationController.navigationBar.isTranslucent = false
  411. window?.rootViewController = navigationController
  412. window?.makeKeyAndVisible()
  413. }
  414. } else if contextViewController is UINavigationController {
  415. if let contextViewController = contextViewController, let viewController = viewController {
  416. (contextViewController as? UINavigationController)?.pushViewController(viewController, animated: true)
  417. }
  418. } else {
  419. if let viewController = viewController, let contextViewController = contextViewController {
  420. let navigationController = NCLoginNavigationController(rootViewController: viewController)
  421. navigationController.modalPresentationStyle = .fullScreen
  422. navigationController.navigationBar.barStyle = .black
  423. navigationController.navigationBar.tintColor = NCBrandColor.shared.customerText
  424. navigationController.navigationBar.barTintColor = NCBrandColor.shared.customer
  425. navigationController.navigationBar.isTranslucent = false
  426. contextViewController.present(navigationController, animated: true) { }
  427. }
  428. }
  429. }
  430. @objc func startTimerErrorNetworking() {
  431. timerErrorNetworking = Timer.scheduledTimer(timeInterval: 3, target: self, selector: #selector(checkErrorNetworking), userInfo: nil, repeats: true)
  432. }
  433. @objc private func checkErrorNetworking() {
  434. guard !account.isEmpty, NCKeychain().getPassword(account: account).isEmpty else { return }
  435. openLogin(viewController: window?.rootViewController, selector: NCGlobal.shared.introLogin, openLoginWeb: true)
  436. }
  437. func trustCertificateError(host: String) {
  438. guard let currentHost = URL(string: self.urlBase)?.host,
  439. let pushNotificationServerProxyHost = URL(string: NCBrandOptions.shared.pushNotificationServerProxy)?.host,
  440. host != pushNotificationServerProxyHost,
  441. host == currentHost
  442. else { return }
  443. let certificateHostSavedPath = NCUtilityFileSystem().directoryCertificates + "/" + host + ".der"
  444. var title = NSLocalizedString("_ssl_certificate_changed_", comment: "")
  445. if !FileManager.default.fileExists(atPath: certificateHostSavedPath) {
  446. title = NSLocalizedString("_connect_server_anyway_", comment: "")
  447. }
  448. let alertController = UIAlertController(title: title, message: NSLocalizedString("_server_is_trusted_", comment: ""), preferredStyle: .alert)
  449. alertController.addAction(UIAlertAction(title: NSLocalizedString("_yes_", comment: ""), style: .default, handler: { _ in
  450. NCNetworking.shared.writeCertificate(host: host)
  451. }))
  452. alertController.addAction(UIAlertAction(title: NSLocalizedString("_no_", comment: ""), style: .default, handler: { _ in }))
  453. alertController.addAction(UIAlertAction(title: NSLocalizedString("_certificate_details_", comment: ""), style: .default, handler: { _ in
  454. if let navigationController = UIStoryboard(name: "NCViewCertificateDetails", bundle: nil).instantiateInitialViewController() as? UINavigationController,
  455. let viewController = navigationController.topViewController as? NCViewCertificateDetails {
  456. viewController.delegate = self
  457. viewController.host = host
  458. self.window?.rootViewController?.present(navigationController, animated: true)
  459. }
  460. }))
  461. window?.rootViewController?.present(alertController, animated: true)
  462. }
  463. func viewCertificateDetailsDismiss(host: String) {
  464. trustCertificateError(host: host)
  465. }
  466. // MARK: - Account
  467. @objc func changeAccount(_ account: String, userProfile: NKUserProfile?) {
  468. NCNetworking.shared.cancelDataTask()
  469. NCNetworking.shared.cancelDownloadTasks()
  470. NCNetworking.shared.cancelUploadTasks()
  471. guard let tableAccount = NCManageDatabase.shared.setAccountActive(account) else { return }
  472. self.account = tableAccount.account
  473. self.urlBase = tableAccount.urlBase
  474. self.user = tableAccount.user
  475. self.userId = tableAccount.userId
  476. self.password = NCKeychain().getPassword(account: tableAccount.account)
  477. NextcloudKit.shared.setup(account: account, user: user, userId: userId, password: password, urlBase: urlBase)
  478. NCManageDatabase.shared.setCapabilities(account: account)
  479. if let userProfile {
  480. NCManageDatabase.shared.setAccountUserProfile(account: account, userProfile: userProfile)
  481. }
  482. if NCGlobal.shared.capabilityServerVersionMajor > 0 {
  483. NextcloudKit.shared.setup(nextcloudVersion: NCGlobal.shared.capabilityServerVersionMajor)
  484. }
  485. NCPushNotification.shared().pushNotification()
  486. NCService().startRequestServicesServer()
  487. NCAutoUpload.shared.initAutoUpload(viewController: nil) { items in
  488. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Initialize Auto upload with \(items) uploads")
  489. }
  490. DispatchQueue.global().async { NCImageCache.shared.createMediaCache(account: self.account) }
  491. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterChangeUser)
  492. }
  493. @objc func deleteAccount(_ account: String, wipe: Bool) {
  494. if let account = NCManageDatabase.shared.getAccount(predicate: NSPredicate(format: "account == %@", account)) {
  495. NCPushNotification.shared().unsubscribingNextcloudServerPushNotification(account.account, urlBase: account.urlBase, user: account.user, withSubscribing: false)
  496. }
  497. let results = NCManageDatabase.shared.getTableLocalFiles(predicate: NSPredicate(format: "account == %@", account), sorted: "ocId", ascending: false)
  498. let utilityFileSystem = NCUtilityFileSystem()
  499. for result in results {
  500. utilityFileSystem.removeFile(atPath: utilityFileSystem.getDirectoryProviderStorageOcId(result.ocId))
  501. }
  502. NCManageDatabase.shared.clearDatabase(account: account, removeAccount: true)
  503. NCKeychain().clearAllKeysEndToEnd(account: account)
  504. NCKeychain().clearAllKeysPushNotification(account: account)
  505. NCKeychain().setPassword(account: account, password: nil)
  506. self.account = ""
  507. self.urlBase = ""
  508. self.user = ""
  509. self.userId = ""
  510. self.password = ""
  511. if wipe {
  512. let accounts = NCManageDatabase.shared.getAccounts()
  513. if accounts?.count ?? 0 > 0 {
  514. if let newAccount = accounts?.first {
  515. self.changeAccount(newAccount, userProfile: nil)
  516. }
  517. } else {
  518. openLogin(viewController: window?.rootViewController, selector: NCGlobal.shared.introLogin, openLoginWeb: false)
  519. }
  520. }
  521. }
  522. func deleteAllAccounts() {
  523. let accounts = NCManageDatabase.shared.getAccounts()
  524. accounts?.forEach({ account in
  525. deleteAccount(account, wipe: true)
  526. })
  527. }
  528. func updateShareAccounts() -> Error? {
  529. guard let dirGroupApps = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: NCBrandOptions.shared.capabilitiesGroupApps) else { return nil }
  530. let tableAccount = NCManageDatabase.shared.getAllAccount()
  531. var accounts = [NKShareAccounts.DataAccounts]()
  532. for account in tableAccount {
  533. let name = account.alias.isEmpty ? account.displayName : account.alias
  534. let userBaseUrl = account.user + "-" + (URL(string: account.urlBase)?.host ?? "")
  535. let avatarFileName = userBaseUrl + "-\(account.user).png"
  536. let pathAvatarFileName = NCUtilityFileSystem().directoryUserData + "/" + avatarFileName
  537. let image = UIImage(contentsOfFile: pathAvatarFileName)
  538. accounts.append(NKShareAccounts.DataAccounts(withUrl: account.urlBase, user: account.user, name: name, image: image))
  539. }
  540. return NKShareAccounts().putShareAccounts(at: dirGroupApps, app: NCGlobal.shared.appScheme, dataAccounts: accounts)
  541. }
  542. // MARK: - Account Request
  543. func accountRequestChangeAccount(account: String) {
  544. changeAccount(account, userProfile: nil)
  545. }
  546. func requestAccount() {
  547. if isPasscodePresented() { return }
  548. if !NCKeychain().accountRequest { return }
  549. let accounts = NCManageDatabase.shared.getAllAccount()
  550. if accounts.count > 1 {
  551. if let vcAccountRequest = UIStoryboard(name: "NCAccountRequest", bundle: nil).instantiateInitialViewController() as? NCAccountRequest {
  552. vcAccountRequest.activeAccount = NCManageDatabase.shared.getActiveAccount()
  553. vcAccountRequest.accounts = accounts
  554. vcAccountRequest.enableTimerProgress = true
  555. vcAccountRequest.enableAddAccount = false
  556. vcAccountRequest.dismissDidEnterBackground = false
  557. vcAccountRequest.delegate = self
  558. let screenHeighMax = UIScreen.main.bounds.height - (UIScreen.main.bounds.height / 5)
  559. let numberCell = accounts.count
  560. let height = min(CGFloat(numberCell * Int(vcAccountRequest.heightCell) + 45), screenHeighMax)
  561. let popup = NCPopupViewController(contentController: vcAccountRequest, popupWidth: 300, popupHeight: height + 20)
  562. popup.backgroundAlpha = 0.8
  563. window?.rootViewController?.present(popup, animated: true)
  564. vcAccountRequest.startTimer()
  565. }
  566. }
  567. }
  568. // MARK: - Passcode
  569. func presentPasscode(completion: @escaping () -> Void) {
  570. let laContext = LAContext()
  571. var error: NSError?
  572. defer { self.requestAccount() }
  573. let presentedViewController = window?.rootViewController?.presentedViewController
  574. guard !account.isEmpty, NCKeychain().passcode != nil, NCKeychain().requestPasscodeAtStart, !(presentedViewController is NCLoginNavigationController) else { return }
  575. // Make sure we have a privacy window (in case it's not enabled)
  576. showPrivacyProtectionWindow()
  577. let passcodeViewController = TOPasscodeViewController(passcodeType: .sixDigits, allowCancel: false)
  578. passcodeViewController.delegate = self
  579. passcodeViewController.keypadButtonShowLettering = false
  580. if NCKeychain().touchFaceID,
  581. laContext.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error),
  582. NCKeychain().passcodeCounterFail < 3 {
  583. if error == nil {
  584. if laContext.biometryType == .faceID {
  585. passcodeViewController.biometryType = .faceID
  586. } else if laContext.biometryType == .touchID {
  587. passcodeViewController.biometryType = .touchID
  588. }
  589. passcodeViewController.allowBiometricValidation = true
  590. passcodeViewController.automaticallyPromptForBiometricValidation = false
  591. }
  592. }
  593. // show passcode on top of privacy window
  594. privacyProtectionWindow?.rootViewController?.present(passcodeViewController, animated: true, completion: {
  595. let resetAppCounterFail = NCKeychain().resetAppCounterFail
  596. let passcodeCounterFail = NCKeychain().passcodeCounterFail
  597. if resetAppCounterFail > 0 && (passcodeCounterFail >= resetAppCounterFail) {
  598. self.passcodeResetApp(passcodeViewController)
  599. } else if passcodeCounterFail >= 3 {
  600. self.passcodeAlert(passcodeViewController)
  601. }
  602. completion()
  603. })
  604. }
  605. func isPasscodePresented() -> Bool {
  606. return privacyProtectionWindow?.rootViewController?.presentedViewController is TOPasscodeViewController
  607. }
  608. func enableTouchFaceID() {
  609. guard !account.isEmpty,
  610. NCKeychain().touchFaceID,
  611. NCKeychain().passcode != nil,
  612. NCKeychain().requestPasscodeAtStart,
  613. NCKeychain().passcodeCounterFail < 3,
  614. let passcodeViewController = privacyProtectionWindow?.rootViewController?.presentedViewController as? TOPasscodeViewController
  615. else { return }
  616. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  617. LAContext().evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: NCBrandOptions.shared.brand) { success, _ in
  618. if success {
  619. DispatchQueue.main.async {
  620. passcodeViewController.dismiss(animated: true) {
  621. NCKeychain().passcodeCounterFail = 0
  622. self.hidePrivacyProtectionWindow()
  623. self.requestAccount()
  624. }
  625. }
  626. }
  627. }
  628. }
  629. }
  630. func didInputCorrectPasscode(in passcodeViewController: TOPasscodeViewController) {
  631. DispatchQueue.main.async {
  632. passcodeViewController.dismiss(animated: true) {
  633. NCKeychain().passcodeCounterFail = 0
  634. self.hidePrivacyProtectionWindow()
  635. self.requestAccount()
  636. }
  637. }
  638. }
  639. func passcodeViewController(_ passcodeViewController: TOPasscodeViewController, isCorrectCode code: String) -> Bool {
  640. if code == NCKeychain().passcode {
  641. return true
  642. } else {
  643. NCKeychain().passcodeCounterFail += 1
  644. let resetAppCounterFail = NCKeychain().resetAppCounterFail
  645. let passcodeCounterFail = NCKeychain().passcodeCounterFail
  646. if resetAppCounterFail > 0 && (passcodeCounterFail >= resetAppCounterFail) {
  647. DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { self.passcodeResetApp(passcodeViewController) }
  648. } else if passcodeCounterFail >= 3 {
  649. DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { self.passcodeAlert(passcodeViewController) }
  650. }
  651. return false
  652. }
  653. }
  654. func didPerformBiometricValidationRequest(in passcodeViewController: TOPasscodeViewController) {
  655. enableTouchFaceID()
  656. }
  657. func passcodeAlert(_ passcodeViewController: TOPasscodeViewController) {
  658. passcodeViewController.biometricButton.isHidden = true
  659. let alertController = UIAlertController(title: NSLocalizedString("_passcode_counter_fail_", comment: ""), message: nil, preferredStyle: .alert)
  660. passcodeViewController.present(alertController, animated: true, completion: { })
  661. var seconds = NCKeychain().passcodeSecondsFail * 30
  662. _ = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { timer in
  663. alertController.message = "\(seconds) " + NSLocalizedString("_seconds_", comment: "")
  664. seconds -= 1
  665. if seconds < 0 {
  666. NCKeychain().passcodeSecondsFail += 1
  667. timer.invalidate()
  668. alertController.dismiss(animated: true)
  669. }
  670. }
  671. }
  672. func passcodeResetApp(_ passcodeViewController: TOPasscodeViewController) {
  673. let alertController = UIAlertController(title: NSLocalizedString("_failes_attemps_reset_", comment: ""), message: nil, preferredStyle: .alert)
  674. passcodeViewController.present(alertController, animated: true, completion: { })
  675. DispatchQueue.main.asyncAfter(deadline: .now() + 4) {
  676. self.resetApplication()
  677. }
  678. }
  679. // MARK: - Remove / Reset App
  680. @objc func removeAllSettings() {
  681. let utilityFileSystem = NCUtilityFileSystem()
  682. URLCache.shared.memoryCapacity = 0
  683. URLCache.shared.diskCapacity = 0
  684. utilityFileSystem.removeGroupDirectoryProviderStorage()
  685. utilityFileSystem.removeGroupLibraryDirectory()
  686. utilityFileSystem.removeDocumentsDirectory()
  687. utilityFileSystem.removeTemporaryDirectory()
  688. utilityFileSystem.createDirectoryStandard()
  689. NCKeychain().removeAll()
  690. NCManageDatabase.shared.clearDatabase(account: nil, removeAccount: true)
  691. }
  692. @objc func resetApplication() {
  693. let utilityFileSystem = NCUtilityFileSystem()
  694. NCNetworking.shared.cancelDataTask()
  695. NCNetworking.shared.cancelDownloadTasks()
  696. NCNetworking.shared.cancelUploadTasks()
  697. NCNetworking.shared.cancelUploadBackgroundTask()
  698. DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
  699. URLCache.shared.memoryCapacity = 0
  700. URLCache.shared.diskCapacity = 0
  701. utilityFileSystem.removeGroupDirectoryProviderStorage()
  702. utilityFileSystem.removeGroupApplicationSupport()
  703. utilityFileSystem.removeDocumentsDirectory()
  704. utilityFileSystem.removeTemporaryDirectory()
  705. NCKeychain().removeAll()
  706. NCManageDatabase.shared.removeDB()
  707. exit(0)
  708. }
  709. }
  710. // MARK: - Privacy Protection
  711. private func showPrivacyProtectionWindow() {
  712. guard privacyProtectionWindow == nil else {
  713. privacyProtectionWindow?.isHidden = false
  714. return
  715. }
  716. privacyProtectionWindow = UIWindow(frame: UIScreen.main.bounds)
  717. let storyboard = UIStoryboard(name: "LaunchScreen", bundle: nil)
  718. let initialViewController = storyboard.instantiateInitialViewController()
  719. self.privacyProtectionWindow?.rootViewController = initialViewController
  720. privacyProtectionWindow?.windowLevel = .alert + 1
  721. privacyProtectionWindow?.makeKeyAndVisible()
  722. }
  723. func hidePrivacyProtectionWindow() {
  724. guard !(privacyProtectionWindow?.rootViewController?.presentedViewController is TOPasscodeViewController) else { return }
  725. UIWindow.animate(withDuration: 0.25) {
  726. self.privacyProtectionWindow?.alpha = 0
  727. } completion: { _ in
  728. self.privacyProtectionWindow?.isHidden = true
  729. self.privacyProtectionWindow = nil
  730. }
  731. }
  732. // MARK: - Queue
  733. @objc func cancelAllQueue() {
  734. downloadQueue.cancelAll()
  735. downloadThumbnailQueue.cancelAll()
  736. downloadThumbnailActivityQueue.cancelAll()
  737. downloadAvatarQueue.cancelAll()
  738. unifiedSearchQueue.cancelAll()
  739. saveLivePhotoQueue.cancelAll()
  740. }
  741. // MARK: - Universal Links
  742. func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
  743. let applicationHandle = NCApplicationHandle()
  744. return applicationHandle.applicationOpenUserActivity(userActivity)
  745. }
  746. // MARK: - Scheme URL
  747. func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool {
  748. let scheme = url.scheme
  749. let action = url.host
  750. var fileName: String = ""
  751. var serverUrl: String = ""
  752. /*
  753. Example: nextcloud://open-action?action=create-voice-memo&&user=marinofaggiana&url=https://cloud.nextcloud.com
  754. */
  755. if !account.isEmpty && scheme == NCGlobal.shared.appScheme && action == "open-action" {
  756. if let urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false) {
  757. let queryItems = urlComponents.queryItems
  758. guard let actionScheme = queryItems?.filter({ $0.name == "action" }).first?.value,
  759. let userScheme = queryItems?.filter({ $0.name == "user" }).first?.value,
  760. let urlScheme = queryItems?.filter({ $0.name == "url" }).first?.value,
  761. let rootViewController = window?.rootViewController else { return false }
  762. if getMatchedAccount(userId: userScheme, url: urlScheme) == nil {
  763. let message = NSLocalizedString("_the_account_", comment: "") + " " + userScheme + NSLocalizedString("_of_", comment: "") + " " + urlScheme + " " + NSLocalizedString("_does_not_exist_", comment: "")
  764. let alertController = UIAlertController(title: NSLocalizedString("_info_", comment: ""), message: message, preferredStyle: .alert)
  765. alertController.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { _ in }))
  766. window?.rootViewController?.present(alertController, animated: true, completion: { })
  767. return false
  768. }
  769. switch actionScheme {
  770. case NCGlobal.shared.actionUploadAsset:
  771. NCAskAuthorization().askAuthorizationPhotoLibrary(viewController: rootViewController) { hasPermission in
  772. if hasPermission {
  773. NCPhotosPickerViewController(viewController: rootViewController, maxSelectedAssets: 0, singleSelectedMode: false)
  774. }
  775. }
  776. case NCGlobal.shared.actionScanDocument:
  777. NCDocumentCamera.shared.openScannerDocument(viewController: rootViewController)
  778. case NCGlobal.shared.actionTextDocument:
  779. guard let navigationController = UIStoryboard(name: "NCCreateFormUploadDocuments", bundle: nil).instantiateInitialViewController(),
  780. let directEditingCreators = NCManageDatabase.shared.getDirectEditingCreators(account: account),
  781. let directEditingCreator = directEditingCreators.first(where: { $0.editor == NCGlobal.shared.editorText}),
  782. let viewController = (navigationController as? UINavigationController)?.topViewController as? NCCreateFormUploadDocuments else { return false }
  783. navigationController.modalPresentationStyle = UIModalPresentationStyle.formSheet
  784. viewController.editorId = NCGlobal.shared.editorText
  785. viewController.creatorId = directEditingCreator.identifier
  786. viewController.typeTemplate = NCGlobal.shared.templateDocument
  787. viewController.serverUrl = activeServerUrl
  788. viewController.titleForm = NSLocalizedString("_create_nextcloudtext_document_", comment: "")
  789. rootViewController.present(navigationController, animated: true, completion: nil)
  790. case NCGlobal.shared.actionVoiceMemo:
  791. NCAskAuthorization().askAuthorizationAudioRecord(viewController: rootViewController) { hasPermission in
  792. if hasPermission {
  793. let fileName = NCUtilityFileSystem().createFileNameDate(NSLocalizedString("_voice_memo_filename_", comment: ""), ext: "m4a")
  794. if let viewController = UIStoryboard(name: "NCAudioRecorderViewController", bundle: nil).instantiateInitialViewController() as? NCAudioRecorderViewController {
  795. viewController.delegate = self
  796. viewController.createRecorder(fileName: fileName)
  797. viewController.modalTransitionStyle = .crossDissolve
  798. viewController.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext
  799. rootViewController.present(viewController, animated: true, completion: nil)
  800. }
  801. }
  802. }
  803. default:
  804. print("No action")
  805. }
  806. }
  807. return true
  808. }
  809. /*
  810. Example: nextcloud://open-file?path=Talk/IMG_0000123.jpg&user=marinofaggiana&link=https://cloud.nextcloud.com/f/123
  811. */
  812. else if !account.isEmpty && scheme == NCGlobal.shared.appScheme && action == "open-file" {
  813. if let urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false) {
  814. let queryItems = urlComponents.queryItems
  815. guard let userScheme = queryItems?.filter({ $0.name == "user" }).first?.value,
  816. let pathScheme = queryItems?.filter({ $0.name == "path" }).first?.value,
  817. let linkScheme = queryItems?.filter({ $0.name == "link" }).first?.value else { return false}
  818. guard let matchedAccount = getMatchedAccount(userId: userScheme, url: linkScheme) else {
  819. guard let domain = URL(string: linkScheme)?.host else { return true }
  820. fileName = (pathScheme as NSString).lastPathComponent
  821. let message = String(format: NSLocalizedString("_account_not_available_", comment: ""), userScheme, domain, fileName)
  822. let alertController = UIAlertController(title: NSLocalizedString("_info_", comment: ""), message: message, preferredStyle: .alert)
  823. alertController.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { _ in }))
  824. window?.rootViewController?.present(alertController, animated: true, completion: { })
  825. return false
  826. }
  827. let davFiles = NextcloudKit.shared.nkCommonInstance.dav + "/files/" + self.userId
  828. if pathScheme.contains("/") {
  829. fileName = (pathScheme as NSString).lastPathComponent
  830. serverUrl = matchedAccount.urlBase + "/" + davFiles + "/" + (pathScheme as NSString).deletingLastPathComponent
  831. } else {
  832. fileName = pathScheme
  833. serverUrl = matchedAccount.urlBase + "/" + davFiles
  834. }
  835. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  836. NCActionCenter.shared.openFileViewInFolder(serverUrl: serverUrl, fileNameBlink: nil, fileNameOpen: fileName)
  837. }
  838. }
  839. return true
  840. /*
  841. Example: nextcloud://open-and-switch-account?user=marinofaggiana&url=https://cloud.nextcloud.com
  842. */
  843. } else if !account.isEmpty && scheme == NCGlobal.shared.appScheme && action == "open-and-switch-account" {
  844. guard let urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false) else { return false }
  845. let queryItems = urlComponents.queryItems
  846. guard let userScheme = queryItems?.filter({ $0.name == "user" }).first?.value,
  847. let urlScheme = queryItems?.filter({ $0.name == "url" }).first?.value else { return false}
  848. // If the account doesn't exist, return false which will open the app without switching
  849. if getMatchedAccount(userId: userScheme, url: urlScheme) == nil {
  850. return false
  851. }
  852. // Otherwise open the app and switch accounts
  853. return true
  854. } else {
  855. let applicationHandle = NCApplicationHandle()
  856. let isHandled = applicationHandle.applicationOpenURL(url)
  857. if isHandled {
  858. return true
  859. } else {
  860. app.open(url)
  861. return true
  862. }
  863. }
  864. }
  865. func getMatchedAccount(userId: String, url: String) -> tableAccount? {
  866. if let activeAccount = NCManageDatabase.shared.getActiveAccount() {
  867. let urlBase = URL(string: activeAccount.urlBase)
  868. if url.contains(urlBase?.host ?? "") && userId == activeAccount.userId {
  869. return activeAccount
  870. } else {
  871. let accounts = NCManageDatabase.shared.getAllAccount()
  872. for account in accounts {
  873. let urlBase = URL(string: account.urlBase)
  874. if url.contains(urlBase?.host ?? "") && userId == account.userId {
  875. changeAccount(account.account, userProfile: nil)
  876. return account
  877. }
  878. }
  879. }
  880. }
  881. return nil
  882. }
  883. }
  884. // MARK: - NCAudioRecorder ViewController Delegate
  885. extension AppDelegate: NCAudioRecorderViewControllerDelegate {
  886. func didFinishRecording(_ viewController: NCAudioRecorderViewController, fileName: String) {
  887. guard let navigationController = UIStoryboard(name: "NCCreateFormUploadVoiceNote", bundle: nil).instantiateInitialViewController() as? UINavigationController,
  888. let viewController = navigationController.topViewController as? NCCreateFormUploadVoiceNote else { return }
  889. navigationController.modalPresentationStyle = .formSheet
  890. viewController.setup(serverUrl: activeServerUrl, fileNamePath: NSTemporaryDirectory() + fileName, fileName: fileName)
  891. window?.rootViewController?.present(navigationController, animated: true)
  892. }
  893. func didFinishWithoutRecording(_ viewController: NCAudioRecorderViewController, fileName: String) { }
  894. }
  895. extension AppDelegate: NCCreateFormUploadConflictDelegate {
  896. func dismissCreateFormUploadConflict(metadatas: [tableMetadata]?) {
  897. guard let metadatas = metadatas, !metadatas.isEmpty else { return }
  898. NCNetworkingProcessUpload.shared.createProcessUploads(metadatas: metadatas) { _ in }
  899. }
  900. }