AppDelegate.swift 45 KB

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