AppDelegate.swift 47 KB

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