AppDelegate.swift 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  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 LocalAuthentication
  27. import Firebase
  28. import WidgetKit
  29. import Queuer
  30. import EasyTipView
  31. import SwiftUI
  32. @UIApplicationMain
  33. class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
  34. var tipView: EasyTipView?
  35. var backgroundSessionCompletionHandler: (() -> Void)?
  36. var activeLogin: NCLogin?
  37. var activeLoginWeb: NCLoginProvider?
  38. var taskAutoUploadDate: Date = Date()
  39. var isUiTestingEnabled: Bool {
  40. return ProcessInfo.processInfo.arguments.contains("UI_TESTING")
  41. }
  42. var notificationSettings: UNNotificationSettings?
  43. var loginFlowV2Token = ""
  44. var loginFlowV2Endpoint = ""
  45. var loginFlowV2Login = ""
  46. func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
  47. if isUiTestingEnabled {
  48. NCAccount().deleteAllAccounts()
  49. }
  50. let utilityFileSystem = NCUtilityFileSystem()
  51. let utility = NCUtility()
  52. var levelLog = 0
  53. let versionNextcloudiOS = String(format: NCBrandOptions.shared.textCopyrightNextcloudiOS, utility.getVersionApp())
  54. NCSettingsBundleHelper.checkAndExecuteSettings(delay: 0)
  55. UserDefaults.standard.register(defaults: ["UserAgent": userAgent])
  56. if !NCKeychain().disableCrashservice, !NCBrandOptions.shared.disable_crash_service {
  57. FirebaseApp.configure()
  58. }
  59. utilityFileSystem.createDirectoryStandard()
  60. utilityFileSystem.emptyTemporaryDirectory()
  61. utilityFileSystem.clearCacheDirectory("com.limit-point.LivePhoto")
  62. // Create users colors
  63. NCBrandColor.shared.createUserColors()
  64. NextcloudKit.shared.setup(delegate: NCNetworking.shared)
  65. NextcloudKit.shared.nkCommonInstance.pathLog = utilityFileSystem.directoryGroup
  66. if NCBrandOptions.shared.disable_log {
  67. utilityFileSystem.removeFile(atPath: NextcloudKit.shared.nkCommonInstance.filenamePathLog)
  68. utilityFileSystem.removeFile(atPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! + "/" + NextcloudKit.shared.nkCommonInstance.filenameLog)
  69. } else {
  70. levelLog = NCKeychain().logLevel
  71. NextcloudKit.shared.nkCommonInstance.levelLog = levelLog
  72. NextcloudKit.shared.nkCommonInstance.copyLogToDocumentDirectory = true
  73. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Start session with level \(levelLog) " + versionNextcloudiOS)
  74. }
  75. /// Push Notification & display notification
  76. UNUserNotificationCenter.current().getNotificationSettings { settings in
  77. self.notificationSettings = settings
  78. }
  79. application.registerForRemoteNotifications()
  80. UNUserNotificationCenter.current().delegate = self
  81. UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { _, _ in }
  82. if !utility.isSimulatorOrTestFlight() {
  83. let review = NCStoreReview()
  84. review.incrementAppRuns()
  85. review.showStoreReview()
  86. }
  87. /// Background task register
  88. BGTaskScheduler.shared.register(forTaskWithIdentifier: NCGlobal.shared.refreshTask, using: nil) { task in
  89. self.handleAppRefresh(task)
  90. }
  91. BGTaskScheduler.shared.register(forTaskWithIdentifier: NCGlobal.shared.processingTask, using: nil) { task in
  92. self.handleProcessingTask(task)
  93. }
  94. /// Activation singleton
  95. _ = NCActionCenter.shared
  96. _ = NCNetworkingProcess.shared
  97. return true
  98. }
  99. func applicationWillTerminate(_ application: UIApplication) {
  100. if self.notificationSettings?.authorizationStatus != .denied && UIApplication.shared.backgroundRefreshStatus == .available {
  101. let content = UNMutableNotificationContent()
  102. content.title = NCBrandOptions.shared.brand
  103. content.body = NSLocalizedString("_keep_running_", comment: "")
  104. let req = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: nil)
  105. let notificationCenter = UNUserNotificationCenter.current()
  106. notificationCenter.add(req)
  107. }
  108. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] bye bye")
  109. }
  110. // MARK: - UISceneSession Lifecycle
  111. func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
  112. // Called when a new scene session is being created.
  113. // Use this method to select a configuration to create the new scene with.
  114. return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
  115. }
  116. func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
  117. // Called when the user discards a scene session.
  118. // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
  119. // Use this method to release any resources that were specific to the discarded scenes, as they will not return.
  120. }
  121. // MARK: - Background Task
  122. /*
  123. @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.
  124. */
  125. func scheduleAppRefresh() {
  126. let request = BGAppRefreshTaskRequest(identifier: NCGlobal.shared.refreshTask)
  127. request.earliestBeginDate = Date(timeIntervalSinceNow: 60) // Refresh after 60 seconds.
  128. do {
  129. try BGTaskScheduler.shared.submit(request)
  130. } catch {
  131. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] Refresh task failed to submit request: \(error)")
  132. }
  133. }
  134. /*
  135. @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.
  136. */
  137. func scheduleAppProcessing() {
  138. let request = BGProcessingTaskRequest(identifier: NCGlobal.shared.processingTask)
  139. request.earliestBeginDate = Date(timeIntervalSinceNow: 5 * 60) // Refresh after 5 minutes.
  140. request.requiresNetworkConnectivity = false
  141. request.requiresExternalPower = false
  142. do {
  143. try BGTaskScheduler.shared.submit(request)
  144. } catch {
  145. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] Background Processing task failed to submit request: \(error)")
  146. }
  147. }
  148. func handleAppRefresh(_ task: BGTask) {
  149. scheduleAppRefresh()
  150. handleAppRefreshProcessingTask(taskText: "AppRefresh") {
  151. task.setTaskCompleted(success: true)
  152. }
  153. }
  154. func handleProcessingTask(_ task: BGTask) {
  155. scheduleAppProcessing()
  156. handleAppRefreshProcessingTask(taskText: "ProcessingTask") {
  157. task.setTaskCompleted(success: true)
  158. }
  159. }
  160. func handleAppRefreshProcessingTask(taskText: String, completion: @escaping () -> Void = {}) {
  161. Task {
  162. var numAutoUpload = 0
  163. guard let account = NCManageDatabase.shared.getActiveTableAccount()?.account else {
  164. return
  165. }
  166. NextcloudKit.shared.nkCommonInstance.writeLog("[DEBUG] \(taskText) start handle")
  167. // Test every > 1 min
  168. if Date() > self.taskAutoUploadDate.addingTimeInterval(60) {
  169. self.taskAutoUploadDate = Date()
  170. numAutoUpload = await NCAutoUpload.shared.initAutoUpload(account: account)
  171. NextcloudKit.shared.nkCommonInstance.writeLog("[DEBUG] \(taskText) auto upload with \(numAutoUpload) uploads")
  172. } else {
  173. NextcloudKit.shared.nkCommonInstance.writeLog("[DEBUG] \(taskText) disabled auto upload")
  174. }
  175. let results = await NCNetworkingProcess.shared.refreshProcessingTask()
  176. NextcloudKit.shared.nkCommonInstance.writeLog("[DEBUG] \(taskText) networking process with download: \(results.counterDownloading) upload: \(results.counterUploading)")
  177. if taskText == "ProcessingTask",
  178. numAutoUpload == 0,
  179. results.counterDownloading == 0,
  180. results.counterUploading == 0,
  181. let directories = NCManageDatabase.shared.getTablesDirectory(predicate: NSPredicate(format: "account == %@ AND offline == true", account), sorted: "offlineDate", ascending: true) {
  182. for directory: tableDirectory in directories {
  183. // test only 3 time for day (every 8 h.)
  184. if let offlineDate = directory.offlineDate, offlineDate.addingTimeInterval(28800) > Date() {
  185. NextcloudKit.shared.nkCommonInstance.writeLog("[DEBUG] \(taskText) skip synchronization for \(directory.serverUrl) in date \(offlineDate)")
  186. continue
  187. }
  188. let results = await NCNetworking.shared.synchronization(account: account, serverUrl: directory.serverUrl, add: false)
  189. NextcloudKit.shared.nkCommonInstance.writeLog("[DEBUG] \(taskText) end synchronization for \(directory.serverUrl), errorCode: \(results.errorCode), item: \(results.num)")
  190. }
  191. }
  192. let counter = NCManageDatabase.shared.getResultsMetadatas(predicate: NSPredicate(format: "account == %@ AND (session == %@ || session == %@) AND status != %d",
  193. account,
  194. NCNetworking.shared.sessionDownloadBackground,
  195. NCNetworking.shared.sessionUploadBackground,
  196. NCGlobal.shared.metadataStatusNormal))?.count ?? 0
  197. UIApplication.shared.applicationIconBadgeNumber = counter
  198. NextcloudKit.shared.nkCommonInstance.writeLog("[DEBUG] \(taskText) completion handle")
  199. completion()
  200. }
  201. }
  202. // MARK: - Background Networking Session
  203. func application(_ application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: @escaping () -> Void) {
  204. NextcloudKit.shared.nkCommonInstance.writeLog("[DEBUG] Start handle Events For Background URLSession: \(identifier)")
  205. WidgetCenter.shared.reloadAllTimelines()
  206. backgroundSessionCompletionHandler = completionHandler
  207. }
  208. // MARK: - Push Notifications
  209. func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
  210. completionHandler([.list, .banner, .sound])
  211. }
  212. func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
  213. if let pref = UserDefaults(suiteName: NCBrandOptions.shared.capabilitiesGroup),
  214. let data = pref.object(forKey: "NOTIFICATION_DATA") as? [String: AnyObject] {
  215. nextcloudPushNotificationAction(data: data)
  216. pref.set(nil, forKey: "NOTIFICATION_DATA")
  217. }
  218. completionHandler()
  219. }
  220. func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
  221. NCNetworking.shared.checkPushNotificationServerProxyCertificateUntrusted(viewController: UIApplication.shared.firstWindow?.rootViewController) { error in
  222. if error == .success {
  223. NCPushNotification.shared.registerForRemoteNotificationsWithDeviceToken(deviceToken)
  224. }
  225. }
  226. }
  227. func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
  228. NCPushNotification.shared.applicationdidReceiveRemoteNotification(userInfo: userInfo) { result in
  229. completionHandler(result)
  230. }
  231. }
  232. func nextcloudPushNotificationAction(data: [String: AnyObject]) {
  233. guard let data = NCApplicationHandle().nextcloudPushNotificationAction(data: data) else { return }
  234. var findAccount: String?
  235. if let accountPush = data["account"] as? String {
  236. for tableAccount in NCManageDatabase.shared.getAllTableAccount() {
  237. if tableAccount.account == accountPush {
  238. for controller in SceneManager.shared.getControllers() {
  239. if controller.account == accountPush {
  240. NCAccount().changeAccount(tableAccount.account, userProfile: nil, controller: controller) {
  241. findAccount = tableAccount.account
  242. }
  243. }
  244. }
  245. }
  246. }
  247. if let account = findAccount, let viewController = UIStoryboard(name: "NCNotification", bundle: nil).instantiateInitialViewController() as? NCNotification {
  248. viewController.session = NCSession.shared.getSession(account: account)
  249. DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
  250. let navigationController = UINavigationController(rootViewController: viewController)
  251. navigationController.modalPresentationStyle = .fullScreen
  252. UIApplication.shared.firstWindow?.rootViewController?.present(navigationController, animated: true)
  253. }
  254. } else {
  255. let message = NSLocalizedString("_the_account_", comment: "") + " " + accountPush + " " + NSLocalizedString("_does_not_exist_", comment: "")
  256. let alertController = UIAlertController(title: NSLocalizedString("_info_", comment: ""), message: message, preferredStyle: .alert)
  257. alertController.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { _ in }))
  258. UIApplication.shared.firstWindow?.rootViewController?.present(alertController, animated: true, completion: { })
  259. }
  260. }
  261. }
  262. // MARK: - Login
  263. func openLogin(selector: Int, window: UIWindow? = nil) {
  264. UIApplication.shared.allSceneSessionDestructionExceptFirst()
  265. func showLoginViewController(_ viewController: UIViewController?) {
  266. guard let viewController else { return }
  267. let navigationController = NCLoginNavigationController(rootViewController: viewController)
  268. navigationController.modalPresentationStyle = .fullScreen
  269. navigationController.navigationBar.barStyle = .black
  270. navigationController.navigationBar.tintColor = NCBrandColor.shared.customerText
  271. navigationController.navigationBar.barTintColor = NCBrandColor.shared.customer
  272. navigationController.navigationBar.isTranslucent = false
  273. if let controller = UIApplication.shared.firstWindow?.rootViewController {
  274. if let presentedVC = controller.presentedViewController, !(presentedVC is NCLoginNavigationController) {
  275. presentedVC.dismiss(animated: false) {
  276. controller.present(navigationController, animated: true)
  277. }
  278. } else {
  279. controller.present(navigationController, animated: true)
  280. }
  281. } else {
  282. window?.rootViewController = navigationController
  283. window?.makeKeyAndVisible()
  284. }
  285. }
  286. // Nextcloud standard login
  287. if selector == NCGlobal.shared.introSignup {
  288. if activeLogin?.view.window == nil {
  289. if selector == NCGlobal.shared.introSignup {
  290. let web = UIStoryboard(name: "NCLogin", bundle: nil).instantiateViewController(withIdentifier: "NCLoginProvider") as? NCLoginProvider
  291. web?.urlBase = NCBrandOptions.shared.linkloginPreferredProviders
  292. showLoginViewController(web)
  293. } else {
  294. activeLogin = UIStoryboard(name: "NCLogin", bundle: nil).instantiateViewController(withIdentifier: "NCLogin") as? NCLogin
  295. if let controller = UIApplication.shared.firstWindow?.rootViewController as? NCMainTabBarController, !controller.account.isEmpty {
  296. let session = NCSession.shared.getSession(account: controller.account)
  297. activeLogin?.urlBase = session.urlBase
  298. }
  299. showLoginViewController(activeLogin)
  300. }
  301. }
  302. } else {
  303. if activeLogin?.view.window == nil {
  304. activeLogin = UIStoryboard(name: "NCLogin", bundle: nil).instantiateViewController(withIdentifier: "NCLogin") as? NCLogin
  305. activeLogin?.urlBase = NCBrandOptions.shared.disable_request_login_url ? NCBrandOptions.shared.loginBaseUrl : ""
  306. showLoginViewController(activeLogin)
  307. }
  308. }
  309. }
  310. // MARK: -
  311. func trustCertificateError(host: String) {
  312. guard let activeTableAccount = NCManageDatabase.shared.getActiveTableAccount(),
  313. let currentHost = URL(string: activeTableAccount.urlBase)?.host,
  314. let pushNotificationServerProxyHost = URL(string: NCBrandOptions.shared.pushNotificationServerProxy)?.host,
  315. host != pushNotificationServerProxyHost,
  316. host == currentHost
  317. else { return }
  318. let certificateHostSavedPath = NCUtilityFileSystem().directoryCertificates + "/" + host + ".der"
  319. var title = NSLocalizedString("_ssl_certificate_changed_", comment: "")
  320. if !FileManager.default.fileExists(atPath: certificateHostSavedPath) {
  321. title = NSLocalizedString("_connect_server_anyway_", comment: "")
  322. }
  323. let alertController = UIAlertController(title: title, message: NSLocalizedString("_server_is_trusted_", comment: ""), preferredStyle: .alert)
  324. alertController.addAction(UIAlertAction(title: NSLocalizedString("_yes_", comment: ""), style: .default, handler: { _ in
  325. NCNetworking.shared.writeCertificate(host: host)
  326. }))
  327. alertController.addAction(UIAlertAction(title: NSLocalizedString("_no_", comment: ""), style: .default, handler: { _ in }))
  328. alertController.addAction(UIAlertAction(title: NSLocalizedString("_certificate_details_", comment: ""), style: .default, handler: { _ in
  329. if let navigationController = UIStoryboard(name: "NCViewCertificateDetails", bundle: nil).instantiateInitialViewController() as? UINavigationController,
  330. let viewController = navigationController.topViewController as? NCViewCertificateDetails {
  331. viewController.delegate = self
  332. viewController.host = host
  333. UIApplication.shared.firstWindow?.rootViewController?.present(navigationController, animated: true)
  334. }
  335. }))
  336. UIApplication.shared.firstWindow?.rootViewController?.present(alertController, animated: true)
  337. }
  338. // MARK: - Reset Application
  339. func resetApplication() {
  340. let utilityFileSystem = NCUtilityFileSystem()
  341. NCNetworking.shared.cancelAllTask()
  342. URLCache.shared.removeAllCachedResponses()
  343. utilityFileSystem.removeGroupDirectoryProviderStorage()
  344. utilityFileSystem.removeGroupApplicationSupport()
  345. utilityFileSystem.removeDocumentsDirectory()
  346. utilityFileSystem.removeTemporaryDirectory()
  347. NCKeychain().removeAll()
  348. NCNetworking.shared.removeAllKeyUserDefaultsData(account: nil)
  349. exit(0)
  350. }
  351. // MARK: - Universal Links
  352. func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
  353. let applicationHandle = NCApplicationHandle()
  354. return applicationHandle.applicationOpenUserActivity(userActivity)
  355. }
  356. }
  357. // MARK: - Extension
  358. extension AppDelegate: NCViewCertificateDetailsDelegate {
  359. func viewCertificateDetailsDismiss(host: String) {
  360. trustCertificateError(host: host)
  361. }
  362. }
  363. extension AppDelegate: NCCreateFormUploadConflictDelegate {
  364. func dismissCreateFormUploadConflict(metadatas: [tableMetadata]?) {
  365. guard let metadatas = metadatas, !metadatas.isEmpty else { return }
  366. NCNetworkingProcess.shared.createProcessUploads(metadatas: metadatas)
  367. }
  368. }