AppDelegate.swift 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047
  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. NCNetworking.shared.cancelUploadTasks()
  222. presentPasscode { }
  223. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterApplicationDidEnterBackground)
  224. }
  225. // L'applicazione terminerà
  226. func applicationWillTerminate(_ application: UIApplication) {
  227. if UIApplication.shared.backgroundRefreshStatus == .available {
  228. let content = UNMutableNotificationContent()
  229. content.title = NCBrandOptions.shared.brand
  230. content.body = NSLocalizedString("_keep_running_", comment: "")
  231. let req = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: nil)
  232. let notificationCenter = UNUserNotificationCenter.current()
  233. notificationCenter.add(req)
  234. }
  235. NextcloudKit.shared.nkCommonInstance.writeLog("bye bye")
  236. }
  237. // MARK: - Background Task
  238. /*
  239. @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.
  240. < MAX 30 seconds >
  241. */
  242. func scheduleAppRefresh() {
  243. let request = BGAppRefreshTaskRequest(identifier: NCGlobal.shared.refreshTask)
  244. request.earliestBeginDate = Date(timeIntervalSinceNow: 60) // Refresh after 60 seconds.
  245. do {
  246. try BGTaskScheduler.shared.submit(request)
  247. NextcloudKit.shared.nkCommonInstance.writeLog("- Refresh task: ok")
  248. } catch {
  249. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] Refresh task failed to submit request: \(error)")
  250. }
  251. }
  252. /*
  253. @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.
  254. < MAX over 1 minute >
  255. */
  256. func scheduleAppProcessing() {
  257. let request = BGProcessingTaskRequest(identifier: NCGlobal.shared.processingTask)
  258. request.earliestBeginDate = Date(timeIntervalSinceNow: 5 * 60) // Refresh after 5 minutes.
  259. request.requiresNetworkConnectivity = false
  260. request.requiresExternalPower = false
  261. do {
  262. try BGTaskScheduler.shared.submit(request)
  263. NextcloudKit.shared.nkCommonInstance.writeLog("- Processing task: ok")
  264. } catch {
  265. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] Background Processing task failed to submit request: \(error)")
  266. }
  267. }
  268. func handleAppRefresh(_ task: BGTask) {
  269. scheduleAppRefresh()
  270. if isAppProcessing {
  271. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Processing task already in progress, abort.")
  272. task.setTaskCompleted(success: true)
  273. return
  274. }
  275. isAppRefresh = true
  276. NCAutoUpload.shared.initAutoUpload(viewController: nil) { items in
  277. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Refresh task auto upload with \(items) uploads")
  278. NCNetworkingProcessUpload.shared.start { items in
  279. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Refresh task upload process with \(items) uploads")
  280. task.setTaskCompleted(success: true)
  281. self.isAppRefresh = false
  282. }
  283. }
  284. }
  285. func handleProcessingTask(_ task: BGTask) {
  286. scheduleAppProcessing()
  287. if isAppRefresh {
  288. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Refresh task already in progress, abort.")
  289. task.setTaskCompleted(success: true)
  290. return
  291. }
  292. isAppProcessing = true
  293. NCAutoUpload.shared.initAutoUpload(viewController: nil) { items in
  294. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Processing task auto upload with \(items) uploads")
  295. NCNetworkingProcessUpload.shared.start { items in
  296. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Processing task upload process with \(items) uploads")
  297. task.setTaskCompleted(success: true)
  298. self.isAppProcessing = false
  299. }
  300. }
  301. }
  302. // MARK: - Background Networking Session
  303. func application(_ application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: @escaping () -> Void) {
  304. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Start handle Events For Background URLSession: \(identifier)")
  305. WidgetCenter.shared.reloadAllTimelines()
  306. backgroundSessionCompletionHandler = completionHandler
  307. }
  308. // MARK: - Push Notifications
  309. func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
  310. completionHandler([.list, .banner, .sound])
  311. }
  312. func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
  313. if let pref = UserDefaults(suiteName: NCBrandOptions.shared.capabilitiesGroups),
  314. let data = pref.object(forKey: "NOTIFICATION_DATA") as? [String: AnyObject] {
  315. nextcloudPushNotificationAction(data: data)
  316. pref.set(nil, forKey: "NOTIFICATION_DATA")
  317. }
  318. completionHandler()
  319. }
  320. func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
  321. NCNetworking.shared.checkPushNotificationServerProxyCertificateUntrusted(viewController: self.window?.rootViewController) { error in
  322. if error == .success {
  323. NCPushNotification.shared().registerForRemoteNotifications(withDeviceToken: deviceToken)
  324. }
  325. }
  326. }
  327. func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
  328. NCPushNotification.shared().applicationdidReceiveRemoteNotification(userInfo) { result in
  329. completionHandler(result)
  330. }
  331. }
  332. func nextcloudPushNotificationAction(data: [String: AnyObject]) {
  333. guard let data = NCApplicationHandle().nextcloudPushNotificationAction(data: data) else { return }
  334. var findAccount: Bool = false
  335. if let accountPush = data["account"] as? String {
  336. if accountPush == self.account {
  337. findAccount = true
  338. } else {
  339. let accounts = NCManageDatabase.shared.getAllAccount()
  340. for account in accounts {
  341. if account.account == accountPush {
  342. self.changeAccount(account.account, userProfile: nil)
  343. findAccount = true
  344. }
  345. }
  346. }
  347. if findAccount, let viewController = UIStoryboard(name: "NCNotification", bundle: nil).instantiateInitialViewController() as? NCNotification {
  348. DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
  349. let navigationController = UINavigationController(rootViewController: viewController)
  350. navigationController.modalPresentationStyle = .fullScreen
  351. self.window?.rootViewController?.present(navigationController, animated: true)
  352. }
  353. } else if !findAccount {
  354. let message = NSLocalizedString("_the_account_", comment: "") + " " + accountPush + " " + NSLocalizedString("_does_not_exist_", comment: "")
  355. let alertController = UIAlertController(title: NSLocalizedString("_info_", comment: ""), message: message, preferredStyle: .alert)
  356. alertController.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { _ in }))
  357. self.window?.rootViewController?.present(alertController, animated: true, completion: { })
  358. }
  359. }
  360. }
  361. // MARK: - Login & checkErrorNetworking
  362. @objc func openLogin(viewController: UIViewController?, selector: Int, openLoginWeb: Bool) {
  363. // [WEBPersonalized] [AppConfig]
  364. if NCBrandOptions.shared.use_login_web_personalized || NCBrandOptions.shared.use_AppConfig {
  365. if activeLoginWeb?.view.window == nil {
  366. activeLoginWeb = UIStoryboard(name: "NCLogin", bundle: nil).instantiateViewController(withIdentifier: "NCLoginWeb") as? NCLoginWeb
  367. activeLoginWeb?.urlBase = NCBrandOptions.shared.loginBaseUrl
  368. showLoginViewController(activeLoginWeb, contextViewController: viewController)
  369. }
  370. return
  371. }
  372. // Nextcloud standard login
  373. if selector == NCGlobal.shared.introSignup {
  374. if activeLoginWeb?.view.window == nil {
  375. activeLoginWeb = UIStoryboard(name: "NCLogin", bundle: nil).instantiateViewController(withIdentifier: "NCLoginWeb") as? NCLoginWeb
  376. if selector == NCGlobal.shared.introSignup {
  377. activeLoginWeb?.urlBase = NCBrandOptions.shared.linkloginPreferredProviders
  378. } else {
  379. activeLoginWeb?.urlBase = self.urlBase
  380. }
  381. showLoginViewController(activeLoginWeb, contextViewController: viewController)
  382. }
  383. } else if NCBrandOptions.shared.disable_intro && NCBrandOptions.shared.disable_request_login_url {
  384. if activeLoginWeb?.view.window == nil {
  385. activeLoginWeb = UIStoryboard(name: "NCLogin", bundle: nil).instantiateViewController(withIdentifier: "NCLoginWeb") as? NCLoginWeb
  386. activeLoginWeb?.urlBase = NCBrandOptions.shared.loginBaseUrl
  387. showLoginViewController(activeLoginWeb, contextViewController: viewController)
  388. }
  389. } else if openLoginWeb {
  390. // Used also for reinsert the account (change passwd)
  391. if activeLoginWeb?.view.window == nil {
  392. activeLoginWeb = UIStoryboard(name: "NCLogin", bundle: nil).instantiateViewController(withIdentifier: "NCLoginWeb") as? NCLoginWeb
  393. activeLoginWeb?.urlBase = urlBase
  394. activeLoginWeb?.user = user
  395. showLoginViewController(activeLoginWeb, contextViewController: viewController)
  396. }
  397. } else {
  398. if activeLogin?.view.window == nil {
  399. activeLogin = UIStoryboard(name: "NCLogin", bundle: nil).instantiateViewController(withIdentifier: "NCLogin") as? NCLogin
  400. showLoginViewController(activeLogin, contextViewController: viewController)
  401. }
  402. }
  403. }
  404. func showLoginViewController(_ viewController: UIViewController?, contextViewController: UIViewController?) {
  405. if contextViewController == nil {
  406. if let viewController = viewController {
  407. let navigationController = NCLoginNavigationController(rootViewController: viewController)
  408. navigationController.navigationBar.barStyle = .black
  409. navigationController.navigationBar.tintColor = NCBrandColor.shared.customerText
  410. navigationController.navigationBar.barTintColor = NCBrandColor.shared.customer
  411. navigationController.navigationBar.isTranslucent = false
  412. window?.rootViewController = navigationController
  413. window?.makeKeyAndVisible()
  414. }
  415. } else if contextViewController is UINavigationController {
  416. if let contextViewController = contextViewController, let viewController = viewController {
  417. (contextViewController as? UINavigationController)?.pushViewController(viewController, animated: true)
  418. }
  419. } else {
  420. if let viewController = viewController, let contextViewController = contextViewController {
  421. let navigationController = NCLoginNavigationController(rootViewController: viewController)
  422. navigationController.modalPresentationStyle = .fullScreen
  423. navigationController.navigationBar.barStyle = .black
  424. navigationController.navigationBar.tintColor = NCBrandColor.shared.customerText
  425. navigationController.navigationBar.barTintColor = NCBrandColor.shared.customer
  426. navigationController.navigationBar.isTranslucent = false
  427. contextViewController.present(navigationController, animated: true) { }
  428. }
  429. }
  430. }
  431. @objc func startTimerErrorNetworking() {
  432. timerErrorNetworking = Timer.scheduledTimer(timeInterval: 3, target: self, selector: #selector(checkErrorNetworking), userInfo: nil, repeats: true)
  433. }
  434. @objc private func checkErrorNetworking() {
  435. guard !account.isEmpty, NCKeychain().getPassword(account: account).isEmpty else { return }
  436. openLogin(viewController: window?.rootViewController, selector: NCGlobal.shared.introLogin, openLoginWeb: true)
  437. }
  438. func trustCertificateError(host: String) {
  439. guard let currentHost = URL(string: self.urlBase)?.host,
  440. let pushNotificationServerProxyHost = URL(string: NCBrandOptions.shared.pushNotificationServerProxy)?.host,
  441. host != pushNotificationServerProxyHost,
  442. host == currentHost
  443. else { return }
  444. let certificateHostSavedPath = NCUtilityFileSystem().directoryCertificates + "/" + host + ".der"
  445. var title = NSLocalizedString("_ssl_certificate_changed_", comment: "")
  446. if !FileManager.default.fileExists(atPath: certificateHostSavedPath) {
  447. title = NSLocalizedString("_connect_server_anyway_", comment: "")
  448. }
  449. let alertController = UIAlertController(title: title, message: NSLocalizedString("_server_is_trusted_", comment: ""), preferredStyle: .alert)
  450. alertController.addAction(UIAlertAction(title: NSLocalizedString("_yes_", comment: ""), style: .default, handler: { _ in
  451. NCNetworking.shared.writeCertificate(host: host)
  452. }))
  453. alertController.addAction(UIAlertAction(title: NSLocalizedString("_no_", comment: ""), style: .default, handler: { _ in }))
  454. alertController.addAction(UIAlertAction(title: NSLocalizedString("_certificate_details_", comment: ""), style: .default, handler: { _ in
  455. if let navigationController = UIStoryboard(name: "NCViewCertificateDetails", bundle: nil).instantiateInitialViewController() as? UINavigationController,
  456. let viewController = navigationController.topViewController as? NCViewCertificateDetails {
  457. viewController.delegate = self
  458. viewController.host = host
  459. self.window?.rootViewController?.present(navigationController, animated: true)
  460. }
  461. }))
  462. window?.rootViewController?.present(alertController, animated: true)
  463. }
  464. func viewCertificateDetailsDismiss(host: String) {
  465. trustCertificateError(host: host)
  466. }
  467. // MARK: - Account
  468. @objc func changeAccount(_ account: String, userProfile: NKUserProfile?) {
  469. NCNetworking.shared.cancelDataTask()
  470. NCNetworking.shared.cancelDownloadTasks()
  471. NCNetworking.shared.cancelUploadTasks()
  472. guard let tableAccount = NCManageDatabase.shared.setAccountActive(account) else { return }
  473. self.account = tableAccount.account
  474. self.urlBase = tableAccount.urlBase
  475. self.user = tableAccount.user
  476. self.userId = tableAccount.userId
  477. self.password = NCKeychain().getPassword(account: tableAccount.account)
  478. NextcloudKit.shared.setup(account: account, user: user, userId: userId, password: password, urlBase: urlBase)
  479. NCManageDatabase.shared.setCapabilities(account: account)
  480. if let userProfile {
  481. NCManageDatabase.shared.setAccountUserProfile(account: account, userProfile: userProfile)
  482. }
  483. if NCGlobal.shared.capabilityServerVersionMajor > 0 {
  484. NextcloudKit.shared.setup(nextcloudVersion: NCGlobal.shared.capabilityServerVersionMajor)
  485. }
  486. NCPushNotification.shared().pushNotification()
  487. NCService().startRequestServicesServer()
  488. NCAutoUpload.shared.initAutoUpload(viewController: nil) { items in
  489. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Initialize Auto upload with \(items) uploads")
  490. }
  491. DispatchQueue.global().async { NCImageCache.shared.createMediaCache(account: self.account) }
  492. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterChangeUser)
  493. }
  494. @objc func deleteAccount(_ account: String, wipe: Bool) {
  495. if let account = NCManageDatabase.shared.getAccount(predicate: NSPredicate(format: "account == %@", account)) {
  496. NCPushNotification.shared().unsubscribingNextcloudServerPushNotification(account.account, urlBase: account.urlBase, user: account.user, withSubscribing: false)
  497. }
  498. let results = NCManageDatabase.shared.getTableLocalFiles(predicate: NSPredicate(format: "account == %@", account), sorted: "ocId", ascending: false)
  499. let utilityFileSystem = NCUtilityFileSystem()
  500. for result in results {
  501. utilityFileSystem.removeFile(atPath: utilityFileSystem.getDirectoryProviderStorageOcId(result.ocId))
  502. }
  503. NCManageDatabase.shared.clearDatabase(account: account, removeAccount: true)
  504. NCKeychain().clearAllKeysEndToEnd(account: account)
  505. NCKeychain().clearAllKeysPushNotification(account: account)
  506. NCKeychain().setPassword(account: account, password: nil)
  507. self.account = ""
  508. self.urlBase = ""
  509. self.user = ""
  510. self.userId = ""
  511. self.password = ""
  512. if wipe {
  513. let accounts = NCManageDatabase.shared.getAccounts()
  514. if accounts?.count ?? 0 > 0 {
  515. if let newAccount = accounts?.first {
  516. self.changeAccount(newAccount, userProfile: nil)
  517. }
  518. } else {
  519. openLogin(viewController: window?.rootViewController, selector: NCGlobal.shared.introLogin, openLoginWeb: false)
  520. }
  521. }
  522. }
  523. func deleteAllAccounts() {
  524. let accounts = NCManageDatabase.shared.getAccounts()
  525. accounts?.forEach({ account in
  526. deleteAccount(account, wipe: true)
  527. })
  528. }
  529. func updateShareAccounts() -> Error? {
  530. guard let dirGroupApps = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: NCBrandOptions.shared.capabilitiesGroupApps) else { return nil }
  531. let tableAccount = NCManageDatabase.shared.getAllAccount()
  532. var accounts = [NKShareAccounts.DataAccounts]()
  533. for account in tableAccount {
  534. let name = account.alias.isEmpty ? account.displayName : account.alias
  535. let userBaseUrl = account.user + "-" + (URL(string: account.urlBase)?.host ?? "")
  536. let avatarFileName = userBaseUrl + "-\(account.user).png"
  537. let pathAvatarFileName = NCUtilityFileSystem().directoryUserData + "/" + avatarFileName
  538. let image = UIImage(contentsOfFile: pathAvatarFileName)
  539. accounts.append(NKShareAccounts.DataAccounts(withUrl: account.urlBase, user: account.user, name: name, image: image))
  540. }
  541. return NKShareAccounts().putShareAccounts(at: dirGroupApps, app: NCGlobal.shared.appScheme, dataAccounts: accounts)
  542. }
  543. // MARK: - Account Request
  544. func accountRequestChangeAccount(account: String) {
  545. changeAccount(account, userProfile: nil)
  546. }
  547. func requestAccount() {
  548. if isPasscodePresented() { return }
  549. if !NCKeychain().accountRequest { return }
  550. let accounts = NCManageDatabase.shared.getAllAccount()
  551. if accounts.count > 1 {
  552. if let vcAccountRequest = UIStoryboard(name: "NCAccountRequest", bundle: nil).instantiateInitialViewController() as? NCAccountRequest {
  553. vcAccountRequest.activeAccount = NCManageDatabase.shared.getActiveAccount()
  554. vcAccountRequest.accounts = accounts
  555. vcAccountRequest.enableTimerProgress = true
  556. vcAccountRequest.enableAddAccount = false
  557. vcAccountRequest.dismissDidEnterBackground = false
  558. vcAccountRequest.delegate = self
  559. let screenHeighMax = UIScreen.main.bounds.height - (UIScreen.main.bounds.height / 5)
  560. let numberCell = accounts.count
  561. let height = min(CGFloat(numberCell * Int(vcAccountRequest.heightCell) + 45), screenHeighMax)
  562. let popup = NCPopupViewController(contentController: vcAccountRequest, popupWidth: 300, popupHeight: height + 20)
  563. popup.backgroundAlpha = 0.8
  564. window?.rootViewController?.present(popup, animated: true)
  565. vcAccountRequest.startTimer()
  566. }
  567. }
  568. }
  569. // MARK: - Passcode
  570. func presentPasscode(completion: @escaping () -> Void) {
  571. let laContext = LAContext()
  572. var error: NSError?
  573. defer { self.requestAccount() }
  574. let presentedViewController = window?.rootViewController?.presentedViewController
  575. guard !account.isEmpty, NCKeychain().passcode != nil, NCKeychain().requestPasscodeAtStart, !(presentedViewController is NCLoginNavigationController) else { return }
  576. // Make sure we have a privacy window (in case it's not enabled)
  577. showPrivacyProtectionWindow()
  578. let passcodeViewController = TOPasscodeViewController(passcodeType: .sixDigits, allowCancel: false)
  579. passcodeViewController.delegate = self
  580. passcodeViewController.keypadButtonShowLettering = false
  581. if NCKeychain().touchFaceID, laContext.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error) {
  582. if error == nil {
  583. if laContext.biometryType == .faceID {
  584. passcodeViewController.biometryType = .faceID
  585. } else if laContext.biometryType == .touchID {
  586. passcodeViewController.biometryType = .touchID
  587. }
  588. passcodeViewController.allowBiometricValidation = true
  589. passcodeViewController.automaticallyPromptForBiometricValidation = false
  590. }
  591. }
  592. // show passcode on top of privacy window
  593. privacyProtectionWindow?.rootViewController?.present(passcodeViewController, animated: true, completion: {
  594. completion()
  595. })
  596. }
  597. func isPasscodePresented() -> Bool {
  598. return privacyProtectionWindow?.rootViewController?.presentedViewController is TOPasscodeViewController
  599. }
  600. func enableTouchFaceID() {
  601. guard !account.isEmpty,
  602. NCKeychain().touchFaceID,
  603. NCKeychain().passcode != nil,
  604. NCKeychain().requestPasscodeAtStart,
  605. let passcodeViewController = privacyProtectionWindow?.rootViewController?.presentedViewController as? TOPasscodeViewController
  606. else { return }
  607. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  608. LAContext().evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: NCBrandOptions.shared.brand) { success, _ in
  609. if success {
  610. DispatchQueue.main.async {
  611. passcodeViewController.dismiss(animated: true) {
  612. self.hidePrivacyProtectionWindow()
  613. self.requestAccount()
  614. }
  615. }
  616. }
  617. }
  618. }
  619. }
  620. func didInputCorrectPasscode(in passcodeViewController: TOPasscodeViewController) {
  621. DispatchQueue.main.async {
  622. passcodeViewController.dismiss(animated: true) {
  623. self.hidePrivacyProtectionWindow()
  624. self.requestAccount()
  625. }
  626. }
  627. }
  628. func passcodeViewController(_ passcodeViewController: TOPasscodeViewController, isCorrectCode code: String) -> Bool {
  629. return code == NCKeychain().passcode
  630. }
  631. func didPerformBiometricValidationRequest(in passcodeViewController: TOPasscodeViewController) {
  632. enableTouchFaceID()
  633. }
  634. // MARK: - Privacy Protection
  635. private func showPrivacyProtectionWindow() {
  636. guard privacyProtectionWindow == nil else {
  637. privacyProtectionWindow?.isHidden = false
  638. return
  639. }
  640. privacyProtectionWindow = UIWindow(frame: UIScreen.main.bounds)
  641. let storyboard = UIStoryboard(name: "LaunchScreen", bundle: nil)
  642. let initialViewController = storyboard.instantiateInitialViewController()
  643. self.privacyProtectionWindow?.rootViewController = initialViewController
  644. privacyProtectionWindow?.windowLevel = .alert + 1
  645. privacyProtectionWindow?.makeKeyAndVisible()
  646. }
  647. func hidePrivacyProtectionWindow() {
  648. guard !(privacyProtectionWindow?.rootViewController?.presentedViewController is TOPasscodeViewController) else { return }
  649. UIWindow.animate(withDuration: 0.25) {
  650. self.privacyProtectionWindow?.alpha = 0
  651. } completion: { _ in
  652. self.privacyProtectionWindow?.isHidden = true
  653. self.privacyProtectionWindow = nil
  654. }
  655. }
  656. // MARK: - Queue
  657. @objc func cancelAllQueue() {
  658. downloadQueue.cancelAll()
  659. downloadThumbnailQueue.cancelAll()
  660. downloadThumbnailActivityQueue.cancelAll()
  661. downloadAvatarQueue.cancelAll()
  662. unifiedSearchQueue.cancelAll()
  663. saveLivePhotoQueue.cancelAll()
  664. }
  665. // MARK: - Universal Links
  666. func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
  667. let applicationHandle = NCApplicationHandle()
  668. return applicationHandle.applicationOpenUserActivity(userActivity)
  669. }
  670. // MARK: - Scheme URL
  671. func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool {
  672. let scheme = url.scheme
  673. let action = url.host
  674. var fileName: String = ""
  675. var serverUrl: String = ""
  676. /*
  677. Example: nextcloud://open-action?action=create-voice-memo&&user=marinofaggiana&url=https://cloud.nextcloud.com
  678. */
  679. if !account.isEmpty && scheme == NCGlobal.shared.appScheme && action == "open-action" {
  680. if let urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false) {
  681. let queryItems = urlComponents.queryItems
  682. guard let actionScheme = queryItems?.filter({ $0.name == "action" }).first?.value,
  683. let userScheme = queryItems?.filter({ $0.name == "user" }).first?.value,
  684. let urlScheme = queryItems?.filter({ $0.name == "url" }).first?.value,
  685. let rootViewController = window?.rootViewController else { return false }
  686. if getMatchedAccount(userId: userScheme, url: urlScheme) == nil {
  687. let message = NSLocalizedString("_the_account_", comment: "") + " " + userScheme + NSLocalizedString("_of_", comment: "") + " " + urlScheme + " " + NSLocalizedString("_does_not_exist_", comment: "")
  688. let alertController = UIAlertController(title: NSLocalizedString("_info_", comment: ""), message: message, preferredStyle: .alert)
  689. alertController.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { _ in }))
  690. window?.rootViewController?.present(alertController, animated: true, completion: { })
  691. return false
  692. }
  693. switch actionScheme {
  694. case NCGlobal.shared.actionUploadAsset:
  695. NCAskAuthorization().askAuthorizationPhotoLibrary(viewController: rootViewController) { hasPermission in
  696. if hasPermission {
  697. NCPhotosPickerViewController(viewController: rootViewController, maxSelectedAssets: 0, singleSelectedMode: false)
  698. }
  699. }
  700. case NCGlobal.shared.actionScanDocument:
  701. NCDocumentCamera.shared.openScannerDocument(viewController: rootViewController)
  702. case NCGlobal.shared.actionTextDocument:
  703. guard let navigationController = UIStoryboard(name: "NCCreateFormUploadDocuments", bundle: nil).instantiateInitialViewController(),
  704. let directEditingCreators = NCManageDatabase.shared.getDirectEditingCreators(account: account),
  705. let directEditingCreator = directEditingCreators.first(where: { $0.editor == NCGlobal.shared.editorText}),
  706. let viewController = (navigationController as? UINavigationController)?.topViewController as? NCCreateFormUploadDocuments else { return false }
  707. navigationController.modalPresentationStyle = UIModalPresentationStyle.formSheet
  708. viewController.editorId = NCGlobal.shared.editorText
  709. viewController.creatorId = directEditingCreator.identifier
  710. viewController.typeTemplate = NCGlobal.shared.templateDocument
  711. viewController.serverUrl = activeServerUrl
  712. viewController.titleForm = NSLocalizedString("_create_nextcloudtext_document_", comment: "")
  713. rootViewController.present(navigationController, animated: true, completion: nil)
  714. case NCGlobal.shared.actionVoiceMemo:
  715. NCAskAuthorization().askAuthorizationAudioRecord(viewController: rootViewController) { hasPermission in
  716. if hasPermission {
  717. let fileName = NCUtilityFileSystem().createFileNameDate(NSLocalizedString("_voice_memo_filename_", comment: ""), ext: "m4a")
  718. if let viewController = UIStoryboard(name: "NCAudioRecorderViewController", bundle: nil).instantiateInitialViewController() as? NCAudioRecorderViewController {
  719. viewController.delegate = self
  720. viewController.createRecorder(fileName: fileName)
  721. viewController.modalTransitionStyle = .crossDissolve
  722. viewController.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext
  723. rootViewController.present(viewController, animated: true, completion: nil)
  724. }
  725. }
  726. }
  727. default:
  728. print("No action")
  729. }
  730. }
  731. return true
  732. }
  733. /*
  734. Example: nextcloud://open-file?path=Talk/IMG_0000123.jpg&user=marinofaggiana&link=https://cloud.nextcloud.com/f/123
  735. */
  736. else if !account.isEmpty && scheme == NCGlobal.shared.appScheme && action == "open-file" {
  737. if let urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false) {
  738. let queryItems = urlComponents.queryItems
  739. guard let userScheme = queryItems?.filter({ $0.name == "user" }).first?.value,
  740. let pathScheme = queryItems?.filter({ $0.name == "path" }).first?.value,
  741. let linkScheme = queryItems?.filter({ $0.name == "link" }).first?.value else { return false}
  742. guard let matchedAccount = getMatchedAccount(userId: userScheme, url: linkScheme) else {
  743. guard let domain = URL(string: linkScheme)?.host else { return true }
  744. fileName = (pathScheme as NSString).lastPathComponent
  745. let message = String(format: NSLocalizedString("_account_not_available_", comment: ""), userScheme, domain, fileName)
  746. let alertController = UIAlertController(title: NSLocalizedString("_info_", comment: ""), message: message, preferredStyle: .alert)
  747. alertController.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { _ in }))
  748. window?.rootViewController?.present(alertController, animated: true, completion: { })
  749. return false
  750. }
  751. let davFiles = NextcloudKit.shared.nkCommonInstance.dav + "/files/" + self.userId
  752. if pathScheme.contains("/") {
  753. fileName = (pathScheme as NSString).lastPathComponent
  754. serverUrl = matchedAccount.urlBase + "/" + davFiles + "/" + (pathScheme as NSString).deletingLastPathComponent
  755. } else {
  756. fileName = pathScheme
  757. serverUrl = matchedAccount.urlBase + "/" + davFiles
  758. }
  759. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  760. NCActionCenter.shared.openFileViewInFolder(serverUrl: serverUrl, fileNameBlink: nil, fileNameOpen: fileName)
  761. }
  762. }
  763. return true
  764. /*
  765. Example: nextcloud://open-and-switch-account?user=marinofaggiana&url=https://cloud.nextcloud.com
  766. */
  767. } else if !account.isEmpty && scheme == NCGlobal.shared.appScheme && action == "open-and-switch-account" {
  768. guard let urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false) else { return false }
  769. let queryItems = urlComponents.queryItems
  770. guard let userScheme = queryItems?.filter({ $0.name == "user" }).first?.value,
  771. let urlScheme = queryItems?.filter({ $0.name == "url" }).first?.value else { return false}
  772. // If the account doesn't exist, return false which will open the app without switching
  773. if getMatchedAccount(userId: userScheme, url: urlScheme) == nil {
  774. return false
  775. }
  776. // Otherwise open the app and switch accounts
  777. return true
  778. } else {
  779. let applicationHandle = NCApplicationHandle()
  780. let isHandled = applicationHandle.applicationOpenURL(url)
  781. if isHandled {
  782. return true
  783. } else {
  784. app.open(url)
  785. return true
  786. }
  787. }
  788. }
  789. func getMatchedAccount(userId: String, url: String) -> tableAccount? {
  790. if let activeAccount = NCManageDatabase.shared.getActiveAccount() {
  791. let urlBase = URL(string: activeAccount.urlBase)
  792. if url.contains(urlBase?.host ?? "") && userId == activeAccount.userId {
  793. return activeAccount
  794. } else {
  795. let accounts = NCManageDatabase.shared.getAllAccount()
  796. for account in accounts {
  797. let urlBase = URL(string: account.urlBase)
  798. if url.contains(urlBase?.host ?? "") && userId == account.userId {
  799. changeAccount(account.account, userProfile: nil)
  800. return account
  801. }
  802. }
  803. }
  804. }
  805. return nil
  806. }
  807. }
  808. // MARK: - NCAudioRecorder ViewController Delegate
  809. extension AppDelegate: NCAudioRecorderViewControllerDelegate {
  810. func didFinishRecording(_ viewController: NCAudioRecorderViewController, fileName: String) {
  811. guard
  812. let navigationController = UIStoryboard(name: "NCCreateFormUploadVoiceNote", bundle: nil).instantiateInitialViewController() as? UINavigationController,
  813. let viewController = navigationController.topViewController as? NCCreateFormUploadVoiceNote
  814. else { return }
  815. navigationController.modalPresentationStyle = .formSheet
  816. viewController.setup(serverUrl: activeServerUrl, fileNamePath: NSTemporaryDirectory() + fileName, fileName: fileName)
  817. window?.rootViewController?.present(navigationController, animated: true)
  818. }
  819. func didFinishWithoutRecording(_ viewController: NCAudioRecorderViewController, fileName: String) {
  820. }
  821. }
  822. extension AppDelegate: NCCreateFormUploadConflictDelegate {
  823. func dismissCreateFormUploadConflict(metadatas: [tableMetadata]?) {
  824. guard let metadatas = metadatas, !metadatas.isEmpty else { return }
  825. NCNetworkingProcessUpload.shared.createProcessUploads(metadatas: metadatas) { _ in }
  826. }
  827. }