AppDelegate.swift 47 KB

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