AppDelegate.swift 44 KB

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