AppDelegate.swift 48 KB

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