AppDelegate.swift 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  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. // Background task: register
  161. if #available(iOS 13.0, *) {
  162. } else {
  163. application.setMinimumBackgroundFetchInterval(UIApplication.backgroundFetchIntervalMinimum)
  164. }
  165. /*
  166. if (@available(iOS 13.0, *)) {
  167. [[BGTaskScheduler sharedScheduler] registerForTaskWithIdentifier:NCBrandGlobal.shared.refreshTask usingQueue:nil launchHandler:^(BGTask *task) {
  168. [self handleRefreshTask:task];
  169. }];
  170. [[BGTaskScheduler sharedScheduler] registerForTaskWithIdentifier:NCBrandGlobal.shared.processingTask usingQueue:nil launchHandler:^(BGTask *task) {
  171. [self handleProcessingTask:task];
  172. }];
  173. }
  174. */
  175. return true
  176. }
  177. // L' applicazione entrerà in primo piano (attivo sempre)
  178. func applicationDidBecomeActive(_ application: UIApplication) {
  179. NCSettingsBundleHelper.setVersionAndBuildNumber()
  180. if account == "" { return}
  181. NCNetworking.shared.verifyUploadZombie()
  182. }
  183. // L' applicazione entrerà in primo piano (attivo solo dopo il background)
  184. func applicationWillEnterForeground(_ application: UIApplication) {
  185. if account == "" { return}
  186. NCCommunicationCommon.shared.writeLog("Application will enter in foreground")
  187. // Request Passcode
  188. passcodeWithAutomaticallyPromptForBiometricValidation(true)
  189. // Initialize Auto upload
  190. NCAutoUpload.shared.initAutoUpload(viewController: nil) { (_) in }
  191. // Required unsubscribing / subscribing
  192. NCPushNotification.shared().pushNotification()
  193. // Request Service Server Nextcloud
  194. NCService.shared.startRequestServicesServer()
  195. NotificationCenter.default.postOnMainThread(name: NCBrandGlobal.shared.notificationCenterApplicationWillEnterForeground)
  196. NotificationCenter.default.postOnMainThread(name: NCBrandGlobal.shared.notificationCenterRichdocumentGrabFocus)
  197. NotificationCenter.default.postOnMainThread(name: NCBrandGlobal.shared.notificationCenterReloadDataSourceNetworkForced)
  198. }
  199. func applicationWillResignActive(_ application: UIApplication) {
  200. if account == "" { return}
  201. if activeFileViewInFolder != nil {
  202. activeFileViewInFolder?.dismiss(animated: false, completion: {
  203. self.activeFileViewInFolder = nil
  204. })
  205. }
  206. }
  207. func applicationDidEnterBackground(_ application: UIApplication) {
  208. if account == "" { return}
  209. NCCommunicationCommon.shared.writeLog("Application did enter in background")
  210. NotificationCenter.default.postOnMainThread(name: NCBrandGlobal.shared.notificationCenterApplicationDidEnterBackground)
  211. passcodeWithAutomaticallyPromptForBiometricValidation(false)
  212. if #available(iOS 13.0, *) {
  213. }
  214. }
  215. func applicationWillTerminate(_ application: UIApplication) {
  216. NCCommunicationCommon.shared.writeLog("bye bye")
  217. }
  218. // MARK: -
  219. @objc func initializeMain(notification: NSNotification) {
  220. if account == "" { return}
  221. NCCommunicationCommon.shared.writeLog("initialize Main")
  222. // Clear error certificate
  223. CCUtility.setCertificateError(account, error: false)
  224. // Registeration push notification
  225. NCPushNotification.shared().pushNotification()
  226. // Setting Theming
  227. NCBrandColor.shared.settingThemingColor(account: account)
  228. // Start Auto Upload
  229. NCAutoUpload.shared.initAutoUpload(viewController: nil) { (_) in }
  230. // Start services
  231. NCService.shared.startRequestServicesServer()
  232. // close detail
  233. NotificationCenter.default.postOnMainThread(name: NCBrandGlobal.shared.notificationCenterMenuDetailClose)
  234. // Registeration domain File Provider
  235. //FileProviderDomain *fileProviderDomain = [FileProviderDomain new];
  236. //[fileProviderDomain removeAllDomains];
  237. //[fileProviderDomain registerDomains];
  238. }
  239. // MARK: - Background Task
  240. // MARK: - Push Notifications
  241. // MARK: - Login & checkErrorNetworking
  242. @objc func openLogin(viewController: UIViewController?, selector: Int, openLoginWeb: Bool) {
  243. }
  244. @objc func startTimerErrorNetworking() {
  245. timerErrorNetworking = Timer.scheduledTimer(timeInterval: 3, target: self, selector: #selector(checkErrorNetworking), userInfo: nil, repeats: true)
  246. }
  247. @objc func checkErrorNetworking() {
  248. if account == "" { return }
  249. // check unauthorized server (401)
  250. if CCUtility.getPasscode()?.count == 0 {
  251. openLogin(viewController: window?.rootViewController, selector: NCBrandGlobal.shared.introLogin, openLoginWeb: true)
  252. }
  253. // check certificate untrusted (-1202)
  254. if CCUtility.getCertificateError(account) {
  255. let alertController = UIAlertController(title: NSLocalizedString("_ssl_certificate_untrusted_", comment: ""), message: NSLocalizedString("_connect_server_anyway_", comment: ""), preferredStyle: .alert)
  256. alertController.addAction(UIAlertAction(title: NSLocalizedString("_yes_", comment: ""), style: .default, handler: { action in
  257. NCNetworking.shared.writeCertificate(directoryCertificate: CCUtility.getDirectoryCerificates())
  258. self.startTimerErrorNetworking()
  259. }))
  260. alertController.addAction(UIAlertAction(title: NSLocalizedString("_no_", comment: ""), style: .default, handler: { action in
  261. self.startTimerErrorNetworking()
  262. }))
  263. window?.rootViewController?.present(alertController, animated: true, completion: {
  264. self.timerErrorNetworking?.invalidate()
  265. })
  266. }
  267. }
  268. // MARK: - Account & Communication
  269. @objc func settingAccount(_ account: String, urlBase: String, user: String, userID: String, password: String) {
  270. self.account = account
  271. self.urlBase = urlBase
  272. self.user = user
  273. self.userID = userID
  274. self.password = password
  275. _ = NCNetworkingNotificationCenter.shared
  276. NCCommunicationCommon.shared.setup(account: account, user: user, userId: userID, password: password, urlBase: urlBase)
  277. NCCommunicationCommon.shared.setup(webDav: NCUtilityFileSystem.shared.getWebDAV(account: account))
  278. NCCommunicationCommon.shared.setup(dav: NCUtilityFileSystem.shared.getDAV())
  279. let serverVersionMajor = NCManageDatabase.shared.getCapabilitiesServerInt(account: account, elements: NCElementsJSON.shared.capabilitiesVersionMajor)
  280. if serverVersionMajor > 0 {
  281. NCCommunicationCommon.shared.setup(nextcloudVersion: serverVersionMajor)
  282. }
  283. }
  284. @objc func deleteAccount(_ account: String, wipe: Bool) {
  285. }
  286. // MARK: - Passcode & Delegate
  287. func passcodeWithAutomaticallyPromptForBiometricValidation(_ automaticallyPromptForBiometricValidation: Bool) {
  288. }
  289. }