forked from home-assistant/iOS
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAppDelegate.swift
More file actions
484 lines (414 loc) · 16.9 KB
/
AppDelegate.swift
File metadata and controls
484 lines (414 loc) · 16.9 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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
import Alamofire
import CallbackURLKit
import Communicator
import FirebaseCore
import FirebaseMessaging
import Intents
import KeychainAccess
import MBProgressHUD
import ObjectMapper
import PromiseKit
import RealmSwift
import SafariServices
import Shared
import UIKit
import WidgetKit
import XCGLogger
let keychain = AppConstants.Keychain
let prefs = UserDefaults(suiteName: AppConstants.AppGroupID)!
private extension UIApplication {
var typedDelegate: AppDelegate {
// swiftlint:disable:next force_cast
delegate as! AppDelegate
}
}
extension AppEnvironment {
var sceneManager: SceneManager {
UIApplication.shared.typedDelegate.sceneManager
}
var notificationManager: NotificationManager {
UIApplication.shared.typedDelegate.notificationManager
}
}
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
let sceneManager = SceneManager()
private let lifecycleManager = LifecycleManager()
let notificationManager = NotificationManager()
private var zoneManager: ZoneManager?
private var titleSubscription: MenuManagerTitleSubscription? {
didSet {
if oldValue != titleSubscription {
oldValue?.cancel()
}
}
}
private var shouldRefreshTitleSubscription = false
private var watchCommunicatorService: WatchCommunicatorService?
func application(
_ application: UIApplication,
willFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil
) -> Bool {
MaterialDesignIcons.register()
guard !Current.isRunningTests else {
return true
}
setDefaults()
// swiftlint:disable prohibit_environment_assignment
Current.backgroundTask = ApplicationBackgroundTaskRunner()
// Initialize UIApplication wrapper for shared framework
Current.application = {
UIApplication.shared
}
Current.isBackgroundRequestsImmediate = { [lifecycleManager] in
if Current.isCatalyst {
return false
} else {
return lifecycleManager.isActive
}
}
#if targetEnvironment(simulator)
Current.tags = SimulatorTagManager()
#else
Current.tags = iOSTagManager()
#endif
// swiftlint:enable prohibit_environment_assignment
notificationManager.setupNotifications()
setupLiveActivityReattachment()
setupFirebase()
setupModels()
setupLocalization()
setupMenus()
let launchingForLocation = launchOptions?[.location] != nil
let event = ClientEvent(
text: "Application Starting" + (launchingForLocation ? " due to location change" : ""),
type: .unknown
)
Current.clientEventStore.addEvent(event)
zoneManager = ZoneManager()
UIApplication.shared.setMinimumBackgroundFetchInterval(UIApplication.backgroundFetchIntervalMinimum)
setupWatchCommunicator()
setupUIApplicationShortcutItems()
migrateIfNeeded()
return true
}
func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
if NSClassFromString("XCTest") != nil {
return true
}
lifecycleManager.didFinishLaunching()
checkForUpdate()
checkForAlerts()
return true
}
override func buildMenu(with builder: UIMenuBuilder) {
if builder.system == .main {
let manager = MenuManager(builder: builder)
manager.update()
#if targetEnvironment(macCatalyst)
titleSubscription = manager.subscribeStatusItemTitle(
existing: shouldRefreshTitleSubscription ? nil : titleSubscription,
update: Current.macBridge.configureStatusItem(title:)
)
shouldRefreshTitleSubscription = false
#endif
}
}
@objc func openAbout() {
precondition(Current.sceneManager.supportsMultipleScenes)
sceneManager.activateAnyScene(for: .about)
}
@objc func openMenuUrl(_ command: AnyObject) {
guard let command = command as? UICommand, let url = MenuManager.url(from: command) else {
return
}
let delegate: Guarantee<WebViewSceneDelegate> = sceneManager.scene(for: .init(activity: .webView))
delegate.done {
$0.urlHandler?.handle(url: url)
}
}
@objc func openPreferences() {
precondition(Current.sceneManager.supportsMultipleScenes)
sceneManager.activateAnyScene(for: .settings)
}
@objc func openActionsPreferences() {
precondition(Current.sceneManager.supportsMultipleScenes)
let delegate: Guarantee<SettingsSceneDelegate> = sceneManager.scene(for: .init(activity: .settings))
delegate.done { $0.pushActions(animated: true) }
}
@objc func openHelp() {
openURLInBrowser(
URL(string: "https://companion.home-assistant.io")!,
nil
)
}
func application(
_ application: UIApplication,
configurationForConnecting connectingSceneSession: UISceneSession,
options: UIScene.ConnectionOptions
) -> UISceneConfiguration {
if #available(iOS 16.0, *), connectingSceneSession.role == UISceneSession.Role.carTemplateApplication {
return SceneActivity.carPlay.configuration
} else {
let activity = options.userActivities
.compactMap { SceneActivity(activityIdentifier: $0.activityType) }
.first ?? .webView
return activity.configuration
}
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
notificationManager.didFailToRegisterForRemoteNotifications(error: error)
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
notificationManager.didRegisterForRemoteNotifications(deviceToken: deviceToken)
}
func application(
_ application: UIApplication,
didReceiveRemoteNotification userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void
) {
notificationManager.didReceiveRemoteNotification(userInfo: userInfo, fetchCompletionHandler: completionHandler)
}
func application(
_ application: UIApplication,
performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void
) {
Current.clientEventStore.addEvent(ClientEvent(text: "Background fetch activated", type: .backgroundOperation))
Current.backgroundTask(withName: BackgroundTask.backgroundFetch.rawValue) { remaining in
let updatePromise: Promise<Void>
if Current.settingsStore.isLocationEnabled(for: UIApplication.shared.applicationState),
Current.settingsStore.locationSources.backgroundFetch {
updatePromise = firstly {
Current.location.oneShotLocation(.BackgroundFetch, remaining)
}.then { location in
when(fulfilled: Current.apis.map {
$0.SubmitLocation(updateType: .BackgroundFetch, location: location, zone: nil)
})
}.asVoid()
} else {
updatePromise = when(fulfilled: Current.apis.map {
$0.UpdateSensors(trigger: .BackgroundFetch, location: nil)
})
}
return updatePromise
}.done {
completionHandler(.newData)
}.catch { error in
Current.Log.error("Error when attempting to update data during background fetch: \(error)")
completionHandler(.failed)
}
}
func application(
_ application: UIApplication,
handleEventsForBackgroundURLSession identifier: String,
completionHandler: @escaping () -> Void
) {
if WebhookManager.isManager(forSessionIdentifier: identifier) {
Current.Log.info("starting webhook handler for \(identifier)")
Current.webhooks.handleBackground(for: identifier, completionHandler: completionHandler)
} else {
Current.Log.error("couldn't find appropriate session for for \(identifier)")
completionHandler()
}
}
func application(_ application: UIApplication, handlerFor intent: INIntent) -> Any? {
IntentHandlerFactory.handler(for: intent)
}
// MARK: - Private helpers
@objc func checkForUpdate(_ sender: AnyObject? = nil) {
guard Current.updater.isSupported else { return }
let dueToUserInteraction = sender != nil
Current.updater.check(dueToUserInteraction: dueToUserInteraction).done { [sceneManager] update in
let alert = UIAlertController(
title: L10n.Updater.UpdateAvailable.title,
message: update.body,
preferredStyle: .alert
)
alert.addAction(UIAlertAction(
title: L10n.Updater.UpdateAvailable.open(update.name),
style: .default,
handler: { _ in
URLOpener.shared.open(update.htmlUrl, options: [:], completionHandler: nil)
}
))
alert.addAction(UIAlertAction(title: L10n.okLabel, style: .cancel, handler: nil))
sceneManager.webViewWindowControllerPromise.done {
$0.present(alert, animated: true, completion: nil)
}
}.catch { [sceneManager] error in
Current.Log.error("check error: \(error)")
if dueToUserInteraction {
let alert = UIAlertController(
title: L10n.Updater.NoUpdatesAvailable.title,
message: error.localizedDescription,
preferredStyle: .alert
)
alert.addAction(UIAlertAction(title: L10n.okLabel, style: .cancel, handler: nil))
sceneManager.webViewWindowControllerPromise.done {
$0.present(alert, animated: true, completion: nil)
}
}
}
}
private func checkForAlerts() {
firstly {
Current.serverAlerter.check(dueToUserInteraction: false)
}.done { [sceneManager] alert in
sceneManager.webViewWindowControllerPromise.done { controller in
controller.show(alert: alert)
}
}.catch { error in
Current.Log.error("check error: \(error)")
}
showNotificationCategoryAlertIfNeeded()
}
private func showNotificationCategoryAlertIfNeeded() {
guard Current.realm().objects(NotificationCategory.self).isEmpty == false else {
return
}
let userDefaults = UserDefaults.standard
let seenKey = "category-deprecation-3-" + Current.clientVersion().description
guard !userDefaults.bool(forKey: seenKey) else {
return
}
when(fulfilled: Current.apis.compactMap { $0.connection.caches.user.once().promise })
.done { [sceneManager] users in
guard users.contains(where: \.isAdmin) else {
Current.Log.info("not showing because not an admin anywhere")
return
}
let alert = UIAlertController(
title: L10n.Alerts.Deprecations.NotificationCategory.title,
message: L10n.Alerts.Deprecations.NotificationCategory.message("iOS-2022.4"),
preferredStyle: .alert
)
alert.addAction(UIAlertAction(title: L10n.Nfc.List.learnMore, style: .default, handler: { _ in
userDefaults.set(true, forKey: seenKey)
openURLInBrowser(
URL(string: "https://companion.home-assistant.io/app/ios/actionable-notifications")!,
nil
)
}))
alert.addAction(UIAlertAction(title: L10n.okLabel, style: .cancel, handler: { _ in
userDefaults.set(true, forKey: seenKey)
}))
sceneManager.webViewWindowControllerPromise.done {
$0.present(alert)
}
}.catch { error in
Current.Log.error("couldn't check for if user: \(error)")
}
}
private func setupWatchCommunicator() {
watchCommunicatorService = WatchCommunicatorService()
watchCommunicatorService?.setup()
}
func setupLocalization() {
Current.localized.add(stringProvider: { request in
if prefs.bool(forKey: "showTranslationKeys") {
return request.key
} else {
return nil
}
})
}
private func setupLiveActivityReattachment() {
#if os(iOS) && !targetEnvironment(macCatalyst)
if #available(iOS 17.2, *) {
// Pre-warm the registry on the main thread before spawning background Tasks.
// This avoids a lazy-init race if a push notification handler accesses it
// concurrently from a background thread.
guard let registry = Current.liveActivityRegistry else { return }
Task {
// Re-attach observation tasks (push token + lifecycle) to any Live Activities
// that survived the previous process termination. Must run before the first
// notification handler fires so no push token updates are missed.
await registry.reattach()
}
// Begin observing the push-to-start token stream on a separate Task.
// The stream is infinite; this Task is kept alive for the app's lifetime.
Task {
await registry.startObservingPushToStartToken()
}
}
#endif
}
private func setupFirebase() {
let optionsFile: String = {
switch Current.appConfiguration {
case .beta: return "GoogleService-Info-Beta"
case .debug, .fastlaneSnapshot: return "GoogleService-Info-Debug"
case .release: return "GoogleService-Info-Release"
}
}()
if let optionsPath = Bundle.main.path(forResource: optionsFile, ofType: "plist"),
let options = FirebaseOptions(contentsOfFile: optionsPath) {
FirebaseApp.configure(options: options)
} else {
fatalError("no firebase config found")
}
notificationManager.setupFirebase()
}
private func setupModels() {
// Force Realm migration to happen now
_ = Realm.live()
Action.setupObserver()
NotificationCategory.setupObserver()
}
private func setupMenus() {
NotificationCenter.default.addObserver(
self,
selector: #selector(menuRelatedSettingDidChange(_:)),
name: SettingsStore.menuRelatedSettingDidChange,
object: nil
)
NotificationCenter.default.addObserver(
self,
selector: #selector(apiDidConnect(_:)),
name: HomeAssistantAPI.didConnectNotification,
object: nil
)
}
@objc private func menuRelatedSettingDidChange(_ note: Notification) {
UIMenuSystem.main.setNeedsRebuild()
}
@objc private func apiDidConnect(_ note: Notification) {
// When API reconnects, rebuild the menu to refresh the status item title subscription
// Force refresh by setting the flag that will cause the subscription to be recreated
#if targetEnvironment(macCatalyst)
shouldRefreshTitleSubscription = true
#endif
UIMenuSystem.main.setNeedsRebuild()
}
private func setupUIApplicationShortcutItems() {
if Current.isCatalyst {
UIApplication.shared.shortcutItems = [.init(
type: HAApplicationShortcutItem.openSettings.rawValue,
localizedTitle: L10n.ShortcutItem.OpenSettings.title,
localizedSubtitle: nil,
icon: .init(systemSymbol: .gear)
)]
}
}
private func migrateIfNeeded() {
resetLocalPush()
}
/// Local push becomes opt-in on 2025.6, users will have local push reset and need to re-enable it
private func resetLocalPush() {
if !Current.settingsStore.migratedOptInLocalPush {
for server in Current.servers.all {
server.update { info in
info.connection.isLocalPushEnabled = false
}
}
Current.settingsStore.migratedOptInLocalPush = true
Current.Log.info("Reset local push for all servers due to migration")
} else {
Current.Log.info("No need to reset local push, migration already done")
}
}
// swiftlint:disable:next file_length
}