AppDelegate.swift 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152
  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. 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. NCPushNotification.shared().pushNotification()
  483. NCService().startRequestServicesServer()
  484. NCAutoUpload.shared.initAutoUpload(viewController: nil) { items in
  485. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Initialize Auto upload with \(items) uploads")
  486. }
  487. DispatchQueue.global().async {
  488. NCImageCache.shared.createMediaCache(account: self.account)
  489. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterChangeUser)
  490. }
  491. }
  492. @objc func deleteAccount(_ account: String, wipe: Bool) {
  493. if let account = NCManageDatabase.shared.getAccount(predicate: NSPredicate(format: "account == %@", account)) {
  494. NCPushNotification.shared().unsubscribingNextcloudServerPushNotification(account.account, urlBase: account.urlBase, user: account.user, withSubscribing: false)
  495. }
  496. let results = NCManageDatabase.shared.getTableLocalFiles(predicate: NSPredicate(format: "account == %@", account), sorted: "ocId", ascending: false)
  497. let utilityFileSystem = NCUtilityFileSystem()
  498. for result in results {
  499. utilityFileSystem.removeFile(atPath: utilityFileSystem.getDirectoryProviderStorageOcId(result.ocId))
  500. }
  501. NCManageDatabase.shared.clearDatabase(account: account, removeAccount: true)
  502. NCKeychain().clearAllKeysEndToEnd(account: account)
  503. NCKeychain().clearAllKeysPushNotification(account: account)
  504. NCKeychain().setPassword(account: account, password: nil)
  505. self.account = ""
  506. self.urlBase = ""
  507. self.user = ""
  508. self.userId = ""
  509. self.password = ""
  510. if wipe {
  511. let accounts = NCManageDatabase.shared.getAccounts()
  512. if accounts?.count ?? 0 > 0 {
  513. if let newAccount = accounts?.first {
  514. self.changeAccount(newAccount, userProfile: nil)
  515. }
  516. } else {
  517. openLogin(viewController: window?.rootViewController, selector: NCGlobal.shared.introLogin, openLoginWeb: false)
  518. }
  519. }
  520. }
  521. func deleteAllAccounts() {
  522. let accounts = NCManageDatabase.shared.getAccounts()
  523. accounts?.forEach({ account in
  524. deleteAccount(account, wipe: true)
  525. })
  526. }
  527. func updateShareAccounts() -> Error? {
  528. guard let dirGroupApps = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: NCBrandOptions.shared.capabilitiesGroupApps) else { return nil }
  529. let tableAccount = NCManageDatabase.shared.getAllAccount()
  530. var accounts = [NKShareAccounts.DataAccounts]()
  531. for account in tableAccount {
  532. let name = account.alias.isEmpty ? account.displayName : account.alias
  533. let userBaseUrl = account.user + "-" + (URL(string: account.urlBase)?.host ?? "")
  534. let avatarFileName = userBaseUrl + "-\(account.user).png"
  535. let pathAvatarFileName = NCUtilityFileSystem().directoryUserData + "/" + avatarFileName
  536. let image = UIImage(contentsOfFile: pathAvatarFileName)
  537. accounts.append(NKShareAccounts.DataAccounts(withUrl: account.urlBase, user: account.user, name: name, image: image))
  538. }
  539. return NKShareAccounts().putShareAccounts(at: dirGroupApps, app: NCGlobal.shared.appScheme, dataAccounts: accounts)
  540. }
  541. // MARK: - Account Request
  542. func accountRequestChangeAccount(account: String) {
  543. changeAccount(account, userProfile: nil)
  544. }
  545. func requestAccount() {
  546. if isPasscodePresented { return }
  547. if !NCKeychain().accountRequest { return }
  548. let accounts = NCManageDatabase.shared.getAllAccount()
  549. if accounts.count > 1 {
  550. if let vcAccountRequest = UIStoryboard(name: "NCAccountRequest", bundle: nil).instantiateInitialViewController() as? NCAccountRequest {
  551. vcAccountRequest.activeAccount = NCManageDatabase.shared.getActiveAccount()
  552. vcAccountRequest.accounts = accounts
  553. vcAccountRequest.enableTimerProgress = true
  554. vcAccountRequest.enableAddAccount = false
  555. vcAccountRequest.dismissDidEnterBackground = false
  556. vcAccountRequest.delegate = self
  557. let screenHeighMax = UIScreen.main.bounds.height - (UIScreen.main.bounds.height / 5)
  558. let numberCell = accounts.count
  559. let height = min(CGFloat(numberCell * Int(vcAccountRequest.heightCell) + 45), screenHeighMax)
  560. let popup = NCPopupViewController(contentController: vcAccountRequest, popupWidth: 300, popupHeight: height + 20)
  561. popup.backgroundAlpha = 0.8
  562. window?.rootViewController?.present(popup, animated: true)
  563. vcAccountRequest.startTimer()
  564. }
  565. }
  566. }
  567. // MARK: - Passcode
  568. var isPasscodeReset: Bool {
  569. let passcodeCounterFailReset = NCKeychain().passcodeCounterFailReset
  570. return NCKeychain().resetAppCounterFail && passcodeCounterFailReset >= NCBrandOptions.shared.resetAppPasscodeAttempts
  571. }
  572. var isPasscodeFail: Bool {
  573. let passcodeCounterFail = NCKeychain().passcodeCounterFail
  574. return passcodeCounterFail > 0 && passcodeCounterFail.isMultiple(of: 3)
  575. }
  576. var isPasscodePresented: Bool {
  577. return privacyProtectionWindow?.rootViewController?.presentedViewController is TOPasscodeViewController
  578. }
  579. func presentPasscode(completion: @escaping () -> Void) {
  580. var error: NSError?
  581. defer { self.requestAccount() }
  582. let presentedViewController = window?.rootViewController?.presentedViewController
  583. guard !account.isEmpty, NCKeychain().passcode != nil, NCKeychain().requestPasscodeAtStart, !(presentedViewController is NCLoginNavigationController) else { return }
  584. // Make sure we have a privacy window (in case it's not enabled)
  585. showPrivacyProtectionWindow()
  586. let passcodeViewController = TOPasscodeViewController(passcodeType: .sixDigits, allowCancel: false)
  587. passcodeViewController.delegate = self
  588. passcodeViewController.keypadButtonShowLettering = false
  589. if NCKeychain().touchFaceID, LAContext().canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error) {
  590. if error == nil {
  591. if LAContext().biometryType == .faceID {
  592. passcodeViewController.biometryType = .faceID
  593. } else if LAContext().biometryType == .touchID {
  594. passcodeViewController.biometryType = .touchID
  595. }
  596. passcodeViewController.allowBiometricValidation = true
  597. passcodeViewController.automaticallyPromptForBiometricValidation = false
  598. }
  599. }
  600. // show passcode on top of privacy window
  601. privacyProtectionWindow?.rootViewController?.present(passcodeViewController, animated: true, completion: {
  602. self.openAlert(passcodeViewController: passcodeViewController)
  603. completion()
  604. })
  605. }
  606. func enableTouchFaceID() {
  607. guard !account.isEmpty,
  608. NCKeychain().touchFaceID,
  609. NCKeychain().passcode != nil,
  610. NCKeychain().requestPasscodeAtStart,
  611. !isPasscodeFail,
  612. !isPasscodeReset,
  613. let passcodeViewController = privacyProtectionWindow?.rootViewController?.presentedViewController as? TOPasscodeViewController
  614. else { return }
  615. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  616. LAContext().evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: NCBrandOptions.shared.brand) { success, evaluateError in
  617. if success {
  618. DispatchQueue.main.async {
  619. passcodeViewController.dismiss(animated: true) {
  620. NCKeychain().passcodeCounterFail = 0
  621. NCKeychain().passcodeCounterFailReset = 0
  622. self.hidePrivacyProtectionWindow()
  623. self.requestAccount()
  624. }
  625. }
  626. } else {
  627. if let error = evaluateError {
  628. switch error._code {
  629. case LAError.userFallback.rawValue, LAError.authenticationFailed.rawValue:
  630. if LAContext().biometryType == .faceID {
  631. NCKeychain().passcodeCounterFail = 2
  632. NCKeychain().passcodeCounterFailReset += 2
  633. } else {
  634. NCKeychain().passcodeCounterFail = 3
  635. NCKeychain().passcodeCounterFailReset += 3
  636. }
  637. self.openAlert(passcodeViewController: passcodeViewController)
  638. case LAError.biometryLockout.rawValue:
  639. LAContext().evaluatePolicy(LAPolicy.deviceOwnerAuthentication, localizedReason: NSLocalizedString("_deviceOwnerAuthentication_", comment: ""), reply: { success, _ in
  640. if success {
  641. DispatchQueue.main.async {
  642. NCKeychain().passcodeCounterFail = 0
  643. self.enableTouchFaceID()
  644. }
  645. }
  646. })
  647. case LAError.userCancel.rawValue:
  648. NCKeychain().passcodeCounterFail += 1
  649. NCKeychain().passcodeCounterFailReset += 1
  650. default:
  651. break
  652. }
  653. }
  654. }
  655. }
  656. }
  657. }
  658. func didInputCorrectPasscode(in passcodeViewController: TOPasscodeViewController) {
  659. DispatchQueue.main.async {
  660. passcodeViewController.dismiss(animated: true) {
  661. NCKeychain().passcodeCounterFail = 0
  662. NCKeychain().passcodeCounterFailReset = 0
  663. self.hidePrivacyProtectionWindow()
  664. self.requestAccount()
  665. }
  666. }
  667. }
  668. func passcodeViewController(_ passcodeViewController: TOPasscodeViewController, isCorrectCode code: String) -> Bool {
  669. if code == NCKeychain().passcode {
  670. return true
  671. } else {
  672. NCKeychain().passcodeCounterFail += 1
  673. NCKeychain().passcodeCounterFailReset += 1
  674. openAlert(passcodeViewController: passcodeViewController)
  675. return false
  676. }
  677. }
  678. func didPerformBiometricValidationRequest(in passcodeViewController: TOPasscodeViewController) {
  679. enableTouchFaceID()
  680. }
  681. func openAlert(passcodeViewController: TOPasscodeViewController) {
  682. DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
  683. if self.isPasscodeReset {
  684. passcodeViewController.setContentHidden(true, animated: true)
  685. let alertController = UIAlertController(title: NSLocalizedString("_reset_wrong_passcode_", comment: ""), message: nil, preferredStyle: .alert)
  686. passcodeViewController.present(alertController, animated: true, completion: { })
  687. DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
  688. self.resetApplication()
  689. }
  690. } else if self.isPasscodeFail {
  691. passcodeViewController.setContentHidden(true, animated: true)
  692. let alertController = UIAlertController(title: NSLocalizedString("_passcode_counter_fail_", comment: ""), message: nil, preferredStyle: .alert)
  693. passcodeViewController.present(alertController, animated: true, completion: { })
  694. var seconds = NCBrandOptions.shared.passcodeSecondsFail
  695. _ = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { timer in
  696. alertController.message = "\(seconds) " + NSLocalizedString("_seconds_", comment: "")
  697. seconds -= 1
  698. if seconds < 0 {
  699. timer.invalidate()
  700. alertController.dismiss(animated: true)
  701. passcodeViewController.setContentHidden(false, animated: true)
  702. NCKeychain().passcodeCounterFail = 0
  703. self.enableTouchFaceID()
  704. }
  705. }
  706. }
  707. }
  708. }
  709. // MARK: - Reset Application
  710. @objc func resetApplication() {
  711. let utilityFileSystem = NCUtilityFileSystem()
  712. NCNetworking.shared.cancelDataTask()
  713. NCNetworking.shared.cancelDownloadTasks()
  714. NCNetworking.shared.cancelUploadTasks()
  715. NCNetworking.shared.cancelUploadBackgroundTask()
  716. URLCache.shared.memoryCapacity = 0
  717. URLCache.shared.diskCapacity = 0
  718. utilityFileSystem.removeGroupDirectoryProviderStorage()
  719. utilityFileSystem.removeGroupApplicationSupport()
  720. utilityFileSystem.removeDocumentsDirectory()
  721. utilityFileSystem.removeTemporaryDirectory()
  722. NCKeychain().removeAll()
  723. exit(0)
  724. }
  725. // MARK: - Privacy Protection
  726. private func showPrivacyProtectionWindow() {
  727. guard privacyProtectionWindow == nil else {
  728. privacyProtectionWindow?.isHidden = false
  729. return
  730. }
  731. privacyProtectionWindow = UIWindow(frame: UIScreen.main.bounds)
  732. let storyboard = UIStoryboard(name: "LaunchScreen", bundle: nil)
  733. let initialViewController = storyboard.instantiateInitialViewController()
  734. self.privacyProtectionWindow?.rootViewController = initialViewController
  735. privacyProtectionWindow?.windowLevel = .alert + 1
  736. privacyProtectionWindow?.makeKeyAndVisible()
  737. }
  738. func hidePrivacyProtectionWindow() {
  739. guard !(privacyProtectionWindow?.rootViewController?.presentedViewController is TOPasscodeViewController) else { return }
  740. UIWindow.animate(withDuration: 0.25) {
  741. self.privacyProtectionWindow?.alpha = 0
  742. } completion: { _ in
  743. self.privacyProtectionWindow?.isHidden = true
  744. self.privacyProtectionWindow = nil
  745. }
  746. }
  747. // MARK: - Queue
  748. @objc func cancelAllQueue() {
  749. downloadQueue.cancelAll()
  750. downloadThumbnailQueue.cancelAll()
  751. downloadThumbnailActivityQueue.cancelAll()
  752. downloadAvatarQueue.cancelAll()
  753. unifiedSearchQueue.cancelAll()
  754. saveLivePhotoQueue.cancelAll()
  755. }
  756. // MARK: - Universal Links
  757. func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
  758. let applicationHandle = NCApplicationHandle()
  759. return applicationHandle.applicationOpenUserActivity(userActivity)
  760. }
  761. // MARK: - Scheme URL
  762. func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool {
  763. let scheme = url.scheme
  764. let action = url.host
  765. var fileName: String = ""
  766. var serverUrl: String = ""
  767. /*
  768. Example: nextcloud://open-action?action=create-voice-memo&&user=marinofaggiana&url=https://cloud.nextcloud.com
  769. */
  770. if !account.isEmpty && scheme == NCGlobal.shared.appScheme && action == "open-action" {
  771. if let urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false) {
  772. let queryItems = urlComponents.queryItems
  773. guard let actionScheme = queryItems?.filter({ $0.name == "action" }).first?.value,
  774. let userScheme = queryItems?.filter({ $0.name == "user" }).first?.value,
  775. let urlScheme = queryItems?.filter({ $0.name == "url" }).first?.value,
  776. let rootViewController = window?.rootViewController else { return false }
  777. if getMatchedAccount(userId: userScheme, url: urlScheme) == nil {
  778. let message = NSLocalizedString("_the_account_", comment: "") + " " + userScheme + NSLocalizedString("_of_", comment: "") + " " + urlScheme + " " + NSLocalizedString("_does_not_exist_", comment: "")
  779. let alertController = UIAlertController(title: NSLocalizedString("_info_", comment: ""), message: message, preferredStyle: .alert)
  780. alertController.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { _ in }))
  781. window?.rootViewController?.present(alertController, animated: true, completion: { })
  782. return false
  783. }
  784. switch actionScheme {
  785. case NCGlobal.shared.actionUploadAsset:
  786. NCAskAuthorization().askAuthorizationPhotoLibrary(viewController: rootViewController) { hasPermission in
  787. if hasPermission {
  788. NCPhotosPickerViewController(viewController: rootViewController, maxSelectedAssets: 0, singleSelectedMode: false)
  789. }
  790. }
  791. case NCGlobal.shared.actionScanDocument:
  792. NCDocumentCamera.shared.openScannerDocument(viewController: rootViewController)
  793. case NCGlobal.shared.actionTextDocument:
  794. guard let navigationController = UIStoryboard(name: "NCCreateFormUploadDocuments", bundle: nil).instantiateInitialViewController(),
  795. let directEditingCreators = NCManageDatabase.shared.getDirectEditingCreators(account: account),
  796. let directEditingCreator = directEditingCreators.first(where: { $0.editor == NCGlobal.shared.editorText}),
  797. let viewController = (navigationController as? UINavigationController)?.topViewController as? NCCreateFormUploadDocuments else { return false }
  798. navigationController.modalPresentationStyle = UIModalPresentationStyle.formSheet
  799. viewController.editorId = NCGlobal.shared.editorText
  800. viewController.creatorId = directEditingCreator.identifier
  801. viewController.typeTemplate = NCGlobal.shared.templateDocument
  802. viewController.serverUrl = activeServerUrl
  803. viewController.titleForm = NSLocalizedString("_create_nextcloudtext_document_", comment: "")
  804. rootViewController.present(navigationController, animated: true, completion: nil)
  805. case NCGlobal.shared.actionVoiceMemo:
  806. NCAskAuthorization().askAuthorizationAudioRecord(viewController: rootViewController) { hasPermission in
  807. if hasPermission {
  808. let fileName = NCUtilityFileSystem().createFileNameDate(NSLocalizedString("_voice_memo_filename_", comment: ""), ext: "m4a")
  809. if let viewController = UIStoryboard(name: "NCAudioRecorderViewController", bundle: nil).instantiateInitialViewController() as? NCAudioRecorderViewController {
  810. viewController.delegate = self
  811. viewController.createRecorder(fileName: fileName)
  812. viewController.modalTransitionStyle = .crossDissolve
  813. viewController.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext
  814. rootViewController.present(viewController, animated: true, completion: nil)
  815. }
  816. }
  817. }
  818. default:
  819. print("No action")
  820. }
  821. }
  822. return true
  823. }
  824. /*
  825. Example: nextcloud://open-file?path=Talk/IMG_0000123.jpg&user=marinofaggiana&link=https://cloud.nextcloud.com/f/123
  826. */
  827. else if !account.isEmpty && scheme == NCGlobal.shared.appScheme && action == "open-file" {
  828. if let urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false) {
  829. let queryItems = urlComponents.queryItems
  830. guard let userScheme = queryItems?.filter({ $0.name == "user" }).first?.value,
  831. let pathScheme = queryItems?.filter({ $0.name == "path" }).first?.value,
  832. let linkScheme = queryItems?.filter({ $0.name == "link" }).first?.value else { return false}
  833. guard let matchedAccount = getMatchedAccount(userId: userScheme, url: linkScheme) else {
  834. guard let domain = URL(string: linkScheme)?.host else { return true }
  835. fileName = (pathScheme as NSString).lastPathComponent
  836. let message = String(format: NSLocalizedString("_account_not_available_", comment: ""), userScheme, domain, fileName)
  837. let alertController = UIAlertController(title: NSLocalizedString("_info_", comment: ""), message: message, preferredStyle: .alert)
  838. alertController.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { _ in }))
  839. window?.rootViewController?.present(alertController, animated: true, completion: { })
  840. return false
  841. }
  842. let davFiles = NextcloudKit.shared.nkCommonInstance.dav + "/files/" + self.userId
  843. if pathScheme.contains("/") {
  844. fileName = (pathScheme as NSString).lastPathComponent
  845. serverUrl = matchedAccount.urlBase + "/" + davFiles + "/" + (pathScheme as NSString).deletingLastPathComponent
  846. } else {
  847. fileName = pathScheme
  848. serverUrl = matchedAccount.urlBase + "/" + davFiles
  849. }
  850. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  851. NCActionCenter.shared.openFileViewInFolder(serverUrl: serverUrl, fileNameBlink: nil, fileNameOpen: fileName)
  852. }
  853. }
  854. return true
  855. /*
  856. Example: nextcloud://open-and-switch-account?user=marinofaggiana&url=https://cloud.nextcloud.com
  857. */
  858. } else if !account.isEmpty && scheme == NCGlobal.shared.appScheme && action == "open-and-switch-account" {
  859. guard let urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false) else { return false }
  860. let queryItems = urlComponents.queryItems
  861. guard let userScheme = queryItems?.filter({ $0.name == "user" }).first?.value,
  862. let urlScheme = queryItems?.filter({ $0.name == "url" }).first?.value else { return false}
  863. // If the account doesn't exist, return false which will open the app without switching
  864. if getMatchedAccount(userId: userScheme, url: urlScheme) == nil {
  865. return false
  866. }
  867. // Otherwise open the app and switch accounts
  868. return true
  869. } else {
  870. let applicationHandle = NCApplicationHandle()
  871. let isHandled = applicationHandle.applicationOpenURL(url)
  872. if isHandled {
  873. return true
  874. } else {
  875. app.open(url)
  876. return true
  877. }
  878. }
  879. }
  880. func getMatchedAccount(userId: String, url: String) -> tableAccount? {
  881. if let activeAccount = NCManageDatabase.shared.getActiveAccount() {
  882. let urlBase = URL(string: activeAccount.urlBase)
  883. if url.contains(urlBase?.host ?? "") && userId == activeAccount.userId {
  884. return activeAccount
  885. } else {
  886. let accounts = NCManageDatabase.shared.getAllAccount()
  887. for account in accounts {
  888. let urlBase = URL(string: account.urlBase)
  889. if url.contains(urlBase?.host ?? "") && userId == account.userId {
  890. changeAccount(account.account, userProfile: nil)
  891. return account
  892. }
  893. }
  894. }
  895. }
  896. return nil
  897. }
  898. }
  899. // MARK: - NCAudioRecorder ViewController Delegate
  900. extension AppDelegate: NCAudioRecorderViewControllerDelegate {
  901. func didFinishRecording(_ viewController: NCAudioRecorderViewController, fileName: String) {
  902. guard let navigationController = UIStoryboard(name: "NCCreateFormUploadVoiceNote", bundle: nil).instantiateInitialViewController() as? UINavigationController,
  903. let viewController = navigationController.topViewController as? NCCreateFormUploadVoiceNote else { return }
  904. navigationController.modalPresentationStyle = .formSheet
  905. viewController.setup(serverUrl: activeServerUrl, fileNamePath: NSTemporaryDirectory() + fileName, fileName: fileName)
  906. window?.rootViewController?.present(navigationController, animated: true)
  907. }
  908. func didFinishWithoutRecording(_ viewController: NCAudioRecorderViewController, fileName: String) { }
  909. }
  910. extension AppDelegate: NCCreateFormUploadConflictDelegate {
  911. func dismissCreateFormUploadConflict(metadatas: [tableMetadata]?) {
  912. guard let metadatas = metadatas, !metadatas.isEmpty else { return }
  913. NCNetworkingProcessUpload.shared.createProcessUploads(metadatas: metadatas) { _ in }
  914. }
  915. }