AppDelegate.swift 53 KB

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