AppDelegate.swift 43 KB

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