AppDelegate.swift 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  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 NCCommunication
  25. import TOPasscodeViewController
  26. import LocalAuthentication
  27. import Firebase
  28. @UIApplicationMain
  29. class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, TOPasscodeViewControllerDelegate {
  30. var backgroundSessionCompletionHandler: (() -> Void)?
  31. var window: UIWindow?
  32. @objc var account: String = ""
  33. @objc var urlBase: String = ""
  34. @objc var user: String = ""
  35. @objc var userID: String = ""
  36. @objc var password: String = ""
  37. var activeFavorite: NCFavorite?
  38. var activeFiles: NCFiles?
  39. var activeFileViewInFolder: NCFileViewInFolder?
  40. var activeLogin: CCLogin?
  41. var activeLoginWeb: NCLoginWeb?
  42. @objc var activeMedia: NCMedia?
  43. var activeMore: NCMore?
  44. var activeOffline: NCOffline?
  45. var activeRecent: NCRecent?
  46. var activeServerUrl: String = ""
  47. var activeShares: NCShares?
  48. var activeTransfers: NCTransfers?
  49. var activeTrash: NCTrash?
  50. var activeViewController: UIViewController?
  51. var activeViewerVideo: NCViewerVideo?
  52. struct progressType {
  53. var progress: Float
  54. var totalBytes: Int64
  55. var totalBytesExpected: Int64
  56. }
  57. var listFilesVC: [String:NCFiles] = [:]
  58. var listFavoriteVC: [String:NCFavorite] = [:]
  59. var listOfflineVC: [String:NCOffline] = [:]
  60. var listProgress: [String:progressType] = [:]
  61. var disableSharesView: Bool = false
  62. var documentPickerViewController: NCDocumentPickerViewController?
  63. var networkingAutoUpload: NCNetworkingAutoUpload?
  64. var passcodeViewController: TOPasscodeViewController?
  65. var pasteboardOcIds: [String] = []
  66. var shares: [tableShare] = []
  67. var ncUserDefaults: UserDefaults?
  68. @objc var timerErrorNetworking: Timer?
  69. func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
  70. let userAgent = CCUtility.getUserAgent() as String
  71. let isSimulatorOrTestFlight = NCUtility.shared.isSimulatorOrTestFlight()
  72. let versionNextcloudiOS = String(format: NCBrandOptions.shared.textCopyrightNextcloudiOS, NCUtility.shared.getVersionApp())
  73. UserDefaults.standard.register(defaults: ["UserAgent" : userAgent])
  74. if !CCUtility.getDisableCrashservice() && !NCBrandOptions.shared.disable_crash_service == false {
  75. FirebaseApp.configure()
  76. }
  77. CCUtility.createDirectoryStandard()
  78. CCUtility.emptyTemporaryDirectory()
  79. NCCommunicationCommon.shared.setup(delegate: NCNetworking.shared)
  80. NCCommunicationCommon.shared.setup(userAgent: userAgent)
  81. startTimerErrorNetworking()
  82. // LOG
  83. let levelLog = CCUtility.getLogLevel()
  84. NCCommunicationCommon.shared.levelLog = levelLog
  85. if let pathDirectoryGroup = CCUtility.getDirectoryGroup()?.path {
  86. NCCommunicationCommon.shared.pathLog = pathDirectoryGroup
  87. }
  88. NCCommunicationCommon.shared.copyLogToDocumentDirectory = true
  89. if isSimulatorOrTestFlight {
  90. NCCommunicationCommon.shared.writeLog("Start session with level \(levelLog) " + versionNextcloudiOS + " (Simulator / TestFlight)")
  91. } else {
  92. NCCommunicationCommon.shared.writeLog("Start session with level \(levelLog) " + versionNextcloudiOS)
  93. }
  94. NotificationCenter.default.addObserver(self, selector: #selector(initializeMain(notification:)), name: NSNotification.Name(rawValue: NCBrandGlobal.shared.notificationCenterInitializeMain), object: nil)
  95. if let tableAccount = NCManageDatabase.shared.getAccountActive() {
  96. // FIX 3.0.5 lost urlbase
  97. if tableAccount.urlBase.count == 0 {
  98. let user = tableAccount.user + " "
  99. let urlBase = tableAccount.account.replacingOccurrences(of: user, with: "")
  100. tableAccount.urlBase = urlBase
  101. NCManageDatabase.shared.updateAccount(tableAccount)
  102. }
  103. settingAccount(tableAccount.account, urlBase: tableAccount.urlBase, user: tableAccount.user, userID: tableAccount.userID, password: CCUtility.getPassword(tableAccount.account))
  104. } else {
  105. CCUtility.deleteAllChainStore()
  106. if let bundleID = Bundle.main.bundleIdentifier {
  107. UserDefaults.standard.removePersistentDomain(forName: bundleID)
  108. }
  109. }
  110. ncUserDefaults = UserDefaults(suiteName: NCBrandOptions.shared.capabilitiesGroups)
  111. // Push Notification
  112. application.registerForRemoteNotifications()
  113. UNUserNotificationCenter.current().delegate = self
  114. UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { (_, _) in }
  115. // AV
  116. do {
  117. try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default)
  118. try AVAudioSession.sharedInstance().setActive(true)
  119. } catch {
  120. print(error)
  121. }
  122. application.beginReceivingRemoteControlEvents()
  123. // Store review
  124. if !NCUtility.shared.isSimulatorOrTestFlight() {
  125. let review = NCStoreReview()
  126. review.incrementAppRuns()
  127. review.showStoreReview()
  128. }
  129. // Detect Dark mode
  130. if #available(iOS 13.0, *) {
  131. if CCUtility.getDarkModeDetect() {
  132. if UITraitCollection.current.userInterfaceStyle == .dark {
  133. CCUtility.setDarkMode(true)
  134. } else {
  135. CCUtility.setDarkMode(false)
  136. }
  137. }
  138. }
  139. if NCBrandOptions.shared.disable_intro {
  140. CCUtility.setIntro(true)
  141. if account == "" {
  142. openLogin(viewController: nil, selector: NCBrandGlobal.shared.introLogin, openLoginWeb: false)
  143. }
  144. } else {
  145. if !CCUtility.getIntro() {
  146. if let introViewController = UIStoryboard(name: "NCIntro", bundle: nil).instantiateInitialViewController() {
  147. let navController = UINavigationController(rootViewController: introViewController)
  148. window?.rootViewController = navController
  149. window?.makeKeyAndVisible()
  150. }
  151. }
  152. }
  153. // init home
  154. NotificationCenter.default.postOnMainThread(name: NCBrandGlobal.shared.notificationCenterInitializeMain)
  155. // Passcode
  156. // dispatch_async(dispatch_get_main_queue(), ^{
  157. // [self passcodeWithAutomaticallyPromptForBiometricValidation:true];
  158. // });
  159. // Auto upload
  160. networkingAutoUpload = NCNetworkingAutoUpload.init()
  161. // Background task: register
  162. if #available(iOS 13.0, *) {
  163. } else {
  164. application.setMinimumBackgroundFetchInterval(UIApplication.backgroundFetchIntervalMinimum)
  165. }
  166. /*
  167. if (@available(iOS 13.0, *)) {
  168. [[BGTaskScheduler sharedScheduler] registerForTaskWithIdentifier:NCBrandGlobal.shared.refreshTask usingQueue:nil launchHandler:^(BGTask *task) {
  169. [self handleRefreshTask:task];
  170. }];
  171. [[BGTaskScheduler sharedScheduler] registerForTaskWithIdentifier:NCBrandGlobal.shared.processingTask usingQueue:nil launchHandler:^(BGTask *task) {
  172. [self handleProcessingTask:task];
  173. }];
  174. }
  175. */
  176. return true
  177. }
  178. // L' applicazione entrerà in primo piano (attivo sempre)
  179. func applicationDidBecomeActive(_ application: UIApplication) {
  180. NCSettingsBundleHelper.setVersionAndBuildNumber()
  181. if account == "" { return}
  182. NCNetworking.shared.verifyUploadZombie()
  183. }
  184. // L' applicazione entrerà in primo piano (attivo solo dopo il background)
  185. func applicationWillEnterForeground(_ application: UIApplication) {
  186. if account == "" { return}
  187. NCCommunicationCommon.shared.writeLog("Application will enter in foreground")
  188. // Request Passcode
  189. passcodeWithAutomaticallyPromptForBiometricValidation(true)
  190. // Initialize Auto upload
  191. NCAutoUpload.shared.initAutoUpload(viewController: nil) { (_) in }
  192. // Required unsubscribing / subscribing
  193. NCPushNotification.shared().pushNotification()
  194. // Request Service Server Nextcloud
  195. NCService.shared.startRequestServicesServer()
  196. NotificationCenter.default.postOnMainThread(name: NCBrandGlobal.shared.notificationCenterApplicationWillEnterForeground)
  197. NotificationCenter.default.postOnMainThread(name: NCBrandGlobal.shared.notificationCenterRichdocumentGrabFocus)
  198. NotificationCenter.default.postOnMainThread(name: NCBrandGlobal.shared.notificationCenterReloadDataSourceNetworkForced)
  199. }
  200. func applicationWillResignActive(_ application: UIApplication) {
  201. if account == "" { return}
  202. if activeFileViewInFolder != nil {
  203. activeFileViewInFolder?.dismiss(animated: false, completion: {
  204. self.activeFileViewInFolder = nil
  205. })
  206. }
  207. }
  208. func applicationDidEnterBackground(_ application: UIApplication) {
  209. if account == "" { return}
  210. NCCommunicationCommon.shared.writeLog("Application did enter in background")
  211. NotificationCenter.default.postOnMainThread(name: NCBrandGlobal.shared.notificationCenterApplicationDidEnterBackground)
  212. passcodeWithAutomaticallyPromptForBiometricValidation(false)
  213. if #available(iOS 13.0, *) {
  214. }
  215. }
  216. func applicationWillTerminate(_ application: UIApplication) {
  217. NCCommunicationCommon.shared.writeLog("bye bye")
  218. }
  219. // MARK: -
  220. @objc func initializeMain(notification: NSNotification) {
  221. if account == "" { return}
  222. NCCommunicationCommon.shared.writeLog("initialize Main")
  223. // Clear error certificate
  224. CCUtility.setCertificateError(account, error: false)
  225. // Registeration push notification
  226. NCPushNotification.shared().pushNotification()
  227. // Setting Theming
  228. NCBrandColor.shared.settingThemingColor(account: account)
  229. // Start Auto Upload
  230. NCAutoUpload.shared.initAutoUpload(viewController: nil) { (_) in }
  231. // Start services
  232. NCService.shared.startRequestServicesServer()
  233. // close detail
  234. NotificationCenter.default.postOnMainThread(name: NCBrandGlobal.shared.notificationCenterMenuDetailClose)
  235. // Registeration domain File Provider
  236. //FileProviderDomain *fileProviderDomain = [FileProviderDomain new];
  237. //[fileProviderDomain removeAllDomains];
  238. //[fileProviderDomain registerDomains];
  239. }
  240. // MARK: - Background Task
  241. // MARK: - Push Notifications
  242. // MARK: - Login & checkErrorNetworking
  243. @objc func openLogin(viewController: UIViewController?, selector: Int, openLoginWeb: Bool) {
  244. }
  245. @objc func startTimerErrorNetworking() {
  246. timerErrorNetworking = Timer.scheduledTimer(timeInterval: 3, target: self, selector: #selector(checkErrorNetworking), userInfo: nil, repeats: true)
  247. }
  248. @objc func checkErrorNetworking() {
  249. if account == "" { return }
  250. // check unauthorized server (401)
  251. if CCUtility.getPasscode()?.count == 0 {
  252. openLogin(viewController: window?.rootViewController, selector: NCBrandGlobal.shared.introLogin, openLoginWeb: true)
  253. }
  254. // check certificate untrusted (-1202)
  255. if CCUtility.getCertificateError(account) {
  256. let alertController = UIAlertController(title: NSLocalizedString("_ssl_certificate_untrusted_", comment: ""), message: NSLocalizedString("_connect_server_anyway_", comment: ""), preferredStyle: .alert)
  257. alertController.addAction(UIAlertAction(title: NSLocalizedString("_yes_", comment: ""), style: .default, handler: { action in
  258. NCNetworking.shared.writeCertificate(directoryCertificate: CCUtility.getDirectoryCerificates())
  259. self.startTimerErrorNetworking()
  260. }))
  261. alertController.addAction(UIAlertAction(title: NSLocalizedString("_no_", comment: ""), style: .default, handler: { action in
  262. self.startTimerErrorNetworking()
  263. }))
  264. window?.rootViewController?.present(alertController, animated: true, completion: {
  265. self.timerErrorNetworking?.invalidate()
  266. })
  267. }
  268. }
  269. // MARK: - Account & Communication
  270. @objc func settingAccount(_ account: String, urlBase: String, user: String, userID: String, password: String) {
  271. self.account = account
  272. self.urlBase = urlBase
  273. self.user = user
  274. self.userID = userID
  275. self.password = password
  276. _ = NCNetworkingNotificationCenter.shared
  277. NCCommunicationCommon.shared.setup(account: account, user: user, userId: userID, password: password, urlBase: urlBase)
  278. NCCommunicationCommon.shared.setup(webDav: NCUtilityFileSystem.shared.getWebDAV(account: account))
  279. NCCommunicationCommon.shared.setup(dav: NCUtilityFileSystem.shared.getDAV())
  280. let serverVersionMajor = NCManageDatabase.shared.getCapabilitiesServerInt(account: account, elements: NCElementsJSON.shared.capabilitiesVersionMajor)
  281. if serverVersionMajor > 0 {
  282. NCCommunicationCommon.shared.setup(nextcloudVersion: serverVersionMajor)
  283. }
  284. }
  285. @objc func deleteAccount(_ account: String, wipe: Bool) {
  286. }
  287. // MARK: - TOPasscodeViewController
  288. func passcodeWithAutomaticallyPromptForBiometricValidation(_ automaticallyPromptForBiometricValidation: Bool) {
  289. let laContext = LAContext()
  290. var error: NSError?
  291. if CCUtility.getPasscode()?.count == 0 || account == "" || CCUtility.getNotPasscodeAtStart() { return }
  292. if passcodeViewController == nil {
  293. passcodeViewController = TOPasscodeViewController.init(style: .translucentLight, passcodeType: .sixDigits)
  294. if #available(iOS 13.0, *) {
  295. if UITraitCollection.current.userInterfaceStyle == .dark {
  296. passcodeViewController?.style = .translucentDark
  297. }
  298. }
  299. passcodeViewController?.delegate = self
  300. passcodeViewController?.keypadButtonShowLettering = false
  301. if CCUtility.getEnableTouchFaceID() && laContext.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error) {
  302. if error == nil {
  303. if laContext.biometryType == .faceID {
  304. passcodeViewController?.biometryType = .faceID
  305. passcodeViewController?.allowBiometricValidation = true
  306. } else if laContext.biometryType == .touchID {
  307. passcodeViewController?.biometryType = .touchID
  308. passcodeViewController?.allowBiometricValidation = true
  309. }
  310. }
  311. }
  312. if let passcodeViewController = self.passcodeViewController {
  313. window?.rootViewController?.present(passcodeViewController, animated: true, completion: {
  314. self.enableTouchFaceID(automaticallyPromptForBiometricValidation)
  315. })
  316. }
  317. } else {
  318. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  319. self.enableTouchFaceID(automaticallyPromptForBiometricValidation)
  320. }
  321. }
  322. }
  323. func didInputCorrectPasscode(in passcodeViewController: TOPasscodeViewController) {
  324. passcodeViewController.dismiss(animated: true) {
  325. self.passcodeViewController = nil
  326. }
  327. }
  328. func passcodeViewController(_ passcodeViewController: TOPasscodeViewController, isCorrectCode code: String) -> Bool {
  329. return code == CCUtility.getPasscode()
  330. }
  331. func didPerformBiometricValidationRequest(in passcodeViewController: TOPasscodeViewController) {
  332. LAContext().evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: NCBrandOptions.shared.brand) { (success, error) in
  333. if success {
  334. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  335. passcodeViewController.dismiss(animated: true) {
  336. self.passcodeViewController = nil
  337. }
  338. }
  339. }
  340. }
  341. }
  342. func enableTouchFaceID(_ automaticallyPromptForBiometricValidation: Bool) {
  343. if CCUtility.getEnableTouchFaceID() && automaticallyPromptForBiometricValidation && passcodeViewController?.view.window != nil {
  344. LAContext().evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: NCBrandOptions.shared.brand) { (success, error) in
  345. if success {
  346. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  347. self.passcodeViewController?.dismiss(animated: true) {
  348. self.passcodeViewController = nil
  349. }
  350. }
  351. }
  352. }
  353. }
  354. }
  355. }