AppDelegate.swift 45 KB

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