AppDelegate.swift 45 KB

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