AppDelegate.swift 15 KB

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