AppDelegate.swift 47 KB

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