AppDelegate.swift 52 KB

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