AppDelegate.swift 47 KB

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