-
-
Notifications
You must be signed in to change notification settings - Fork 1k
Expand file tree
/
Copy pathAppDelegate.swift
More file actions
325 lines (259 loc) · 14.2 KB
/
Copy pathAppDelegate.swift
File metadata and controls
325 lines (259 loc) · 14.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
// SPDX-FileCopyrightText: Nextcloud GmbH
// SPDX-FileCopyrightText: 2014 Marino Faggiana [Start 04/09/14]
// SPDX-FileCopyrightText: 2021 Marino Faggiana [Swift 19/02/21]
// SPDX-License-Identifier: GPL-3.0-or-later
import UIKit
import BackgroundTasks
import NextcloudKit
import LocalAuthentication
import Firebase
import WidgetKit
import EasyTipView
import SwiftUI
import RealmSwift
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
var backgroundSessionCompletionHandler: (() -> Void)?
var isUiTestingEnabled: Bool {
return ProcessInfo.processInfo.arguments.contains("UI_TESTING")
}
var notificationSettings: UNNotificationSettings?
var loginFlowV2Token = ""
var loginFlowV2Endpoint = ""
var loginFlowV2Login = ""
let backgroundQueue = DispatchQueue(label: "com.nextcloud.bgTaskQueue")
let global = NCGlobal.shared
var bgTask: UIBackgroundTaskIdentifier = .invalid
var pushSubscriptionTask: Task<Void, Never>?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
if isUiTestingEnabled {
Task {
await NCAccount().deleteAllAccounts()
}
}
let utilityFileSystem = NCUtilityFileSystem()
let utility = NCUtility()
utilityFileSystem.createDirectoryStandard()
utilityFileSystem.emptyTemporaryDirectory()
utilityFileSystem.clearCacheDirectory("com.limit-point.LivePhoto")
let versionNextcloudiOS = String(format: NCBrandOptions.shared.textCopyrightNextcloudiOS, utility.getVersionBuild())
NCAppVersionManager.shared.checkAndUpdateInstallState()
NCSettingsBundleHelper.checkAndExecuteSettings(delay: 0)
UserDefaults.standard.register(defaults: ["UserAgent": userAgent])
if !NCPreferences().disableCrashservice, !NCBrandOptions.shared.disable_crash_service {
FirebaseApp.configure()
}
NCBrandColor.shared.createUserColors()
// Setup Networking
//
NextcloudKit.shared.setup(groupIdentifier: NCBrandOptions.shared.capabilitiesGroup,
delegate: NCNetworking.shared)
NCNetworking.shared.setupTransferDelegate()
NextcloudKit.configureLogger(logLevel: (NCBrandOptions.shared.disable_log ? .disabled : NCPreferences().log))
#if DEBUG
// For the tags look NCGlobal LOG TAG
// var black: [String] = []
// black.append("NETWORKING TASKS")
// NextcloudKit.configureLoggerBlacklist(blacklist: black)
// var white: [String] = []
// white.append("SYNC METADATA")
// NextcloudKit.configureLoggerWhitelist(whitelist: white)
#endif
nkLog(start: "Start session with level \(NCPreferences().log) " + versionNextcloudiOS)
// Push Notification & display notification
UNUserNotificationCenter.current().getNotificationSettings { settings in
self.notificationSettings = settings
}
application.registerForRemoteNotifications()
UNUserNotificationCenter.current().delegate = self
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { _, _ in }
#if !targetEnvironment(simulator)
let review = NCStoreReview()
review.incrementAppRuns()
review.showStoreReview()
#endif
BGTaskScheduler.shared.register(forTaskWithIdentifier: global.refreshTask, using: backgroundQueue) { task in
guard let appRefreshTask = task as? BGAppRefreshTask else {
task.setTaskCompleted(success: false)
return
}
self.handleAppRefresh(appRefreshTask)
}
scheduleAppRefresh()
BGTaskScheduler.shared.register(forTaskWithIdentifier: global.processingTask, using: backgroundQueue) { task in
guard let processingTask = task as? BGProcessingTask else {
task.setTaskCompleted(success: false)
return
}
self.handleProcessingTask(processingTask)
}
scheduleAppProcessing()
if NCBrandOptions.shared.enforce_passcode_lock {
NCPreferences().requestPasscodeAtStart = true
}
return true
}
func applicationWillTerminate(_ application: UIApplication) {
if self.notificationSettings?.authorizationStatus != .denied && UIApplication.shared.backgroundRefreshStatus == .available {
let content = UNMutableNotificationContent()
content.title = NCBrandOptions.shared.brand
content.body = NSLocalizedString("_keep_running_", comment: "")
let req = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: nil)
let notificationCenter = UNUserNotificationCenter.current()
notificationCenter.add(req)
}
nkLog(debug: "App is terminating")
}
// MARK: - UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
// MARK: - Background Networking Session
func application(_ application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: @escaping () -> Void) {
nkLog(debug: "Handle events For background URLSession: \(identifier)")
NCManageDatabase.shared.openRealmBackground()
backgroundSessionCompletionHandler = completionHandler
}
// MARK: - Push Notifications
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.list, .banner, .sound])
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
if let pref = UserDefaults(suiteName: NCBrandOptions.shared.capabilitiesGroup),
let data = pref.object(forKey: "NOTIFICATION_DATA") as? [String: AnyObject] {
nextcloudPushNotificationAction(data: data)
pref.set(nil, forKey: "NOTIFICATION_DATA")
}
completionHandler()
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
guard !isXcodeRunningForPreviews,
application.applicationState != .background else {
return
}
if let deviceToken = NCPushNotificationEncryption.shared().string(withDeviceToken: deviceToken) {
NCPreferences().deviceTokenPushNotification = deviceToken
pushSubscriptionTask = Task.detached {
// Wait bounded time for maintenance to be OFF
let canProceed = await NCAppStateManager.shared.waitForMaintenanceOffAsync()
guard canProceed else {
nkLog(error: "[PUSH] Skipping subscription: maintenance mode still ON after timeout")
return
}
try? await Task.sleep(for: .seconds(1))
let tblAccounts = await NCManageDatabase.shared.getAllTableAccountAsync()
for tblAccount in tblAccounts {
await NCPushNotification.shared.subscribingNextcloudServerPushNotification(account: tblAccount.account, urlBase: tblAccount.urlBase)
}
}
}
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
NCPushNotification.shared.applicationdidReceiveRemoteNotification(userInfo: userInfo) { result in
completionHandler(result)
}
}
func nextcloudPushNotificationAction(data: [String: AnyObject]) {
let account = data["account"] as? String ?? "unavailable"
let app = data["app"] as? String
func openNotification(controller: NCMainTabBarController) {
if app == NCGlobal.shared.termsOfServiceName {
Task {
await NCNetworking.shared.transferDispatcher.notifyAllDelegatesAsync { delegate in
try? await Task.sleep(for: .seconds(0.5))
delegate.transferReloadDataSource(serverUrl: nil, requestData: true, status: nil)
}
}
} else if let navigationController = UIStoryboard(name: "NCNotification", bundle: nil).instantiateInitialViewController() as? UINavigationController,
let viewController = navigationController.topViewController as? NCNotification {
viewController.modalPresentationStyle = .pageSheet
viewController.session = NCSession.shared.getSession(account: account)
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
controller.present(navigationController, animated: true, completion: nil)
}
}
}
if let controller = SceneManager.shared.getControllers().first(where: { $0.account == account }) {
openNotification(controller: controller)
} else if let tblAccount = NCManageDatabase.shared.getAllTableAccount().first(where: { $0.account == account }),
let controller = UIApplication.shared.mainAppWindow?.rootViewController as? NCMainTabBarController {
Task { @MainActor in
await NCAccount().changeAccount(tblAccount.account, userProfile: nil, controller: controller)
openNotification(controller: controller)
}
} else {
let message = String(
format: NSLocalizedString("account_does_not_exist", comment: ""),
account
)
let alertController = UIAlertController(title: NSLocalizedString("_info_", comment: ""), message: message, preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { _ in }))
UIApplication.shared.mainAppWindow?.rootViewController?.present(alertController, animated: true, completion: { })
}
}
// MARK: -
func trustCertificateError(host: String) {
guard let activeTblAccount = NCManageDatabase.shared.getActiveTableAccount(),
let currentHost = URL(string: activeTblAccount.urlBase)?.host,
let pushNotificationServerProxyHost = URL(string: NCBrandOptions.shared.pushNotificationServerProxy)?.host,
host != pushNotificationServerProxyHost,
host == currentHost
else { return }
let certificateHostSavedPath = NCUtilityFileSystem().directoryCertificates + "/" + host + ".der"
var title = NSLocalizedString("_ssl_certificate_changed_", comment: "")
if !FileManager.default.fileExists(atPath: certificateHostSavedPath) {
title = NSLocalizedString("_connect_server_anyway_", comment: "")
}
let alertController = UIAlertController(title: title, message: NSLocalizedString("_server_is_trusted_", comment: ""), preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: NSLocalizedString("_yes_", comment: ""), style: .default, handler: { _ in
NCNetworking.shared.writeCertificate(host: host)
}))
alertController.addAction(UIAlertAction(title: NSLocalizedString("_no_", comment: ""), style: .default, handler: { _ in }))
alertController.addAction(UIAlertAction(title: NSLocalizedString("_certificate_details_", comment: ""), style: .default, handler: { _ in
if let navigationController = UIStoryboard(name: "NCViewCertificateDetails", bundle: nil).instantiateInitialViewController() as? UINavigationController,
let viewController = navigationController.topViewController as? NCViewCertificateDetails {
viewController.delegate = self
viewController.host = host
UIApplication.shared.mainAppWindow?.rootViewController?.present(navigationController, animated: true)
}
}))
UIApplication.shared.mainAppWindow?.rootViewController?.present(alertController, animated: true)
}
// MARK: - Reset Application
func resetApplication() {
let utilityFileSystem = NCUtilityFileSystem()
NCNetworking.shared.cancelAllTask()
URLCache.shared.removeAllCachedResponses()
utilityFileSystem.removeGroupDirectoryProviderStorage()
utilityFileSystem.removeGroupApplicationSupport()
utilityFileSystem.removeDocumentsDirectory()
utilityFileSystem.removeTemporaryDirectory()
NCPreferences().removeAll()
exit(0)
}
// MARK: - Universal Links
func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
return false
}
}
// MARK: - Extension
extension AppDelegate: NCViewCertificateDetailsDelegate {
func viewCertificateDetailsDismiss(host: String) {
trustCertificateError(host: host)
}
}
extension AppDelegate: NCCreateFormUploadConflictDelegate {
func dismissCreateFormUploadConflict(metadatas: [tableMetadata]?) {
if let metadatas {
Task {
await NCManageDatabase.shared.addMetadatasAsync(metadatas)
}
}
}
}