AppDelegate.swift 45 KB

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