AppDelegate.swift 47 KB

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