AppDelegate.swift 46 KB

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