AppDelegate.swift 45 KB

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