AppDelegate.swift 52 KB

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