AppDelegate.swift 45 KB

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