AppDelegate.swift 47 KB

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