-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathAppScene.swift
More file actions
614 lines (540 loc) · 23.3 KB
/
AppScene.swift
File metadata and controls
614 lines (540 loc) · 23.3 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
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
import Combine
import LDKNode
import SwiftUI
import UserNotifications
struct AppScene: View {
@Environment(\.scenePhase) var scenePhase
@EnvironmentObject private var session: SessionManager
@StateObject private var app: AppViewModel
@StateObject private var navigation = NavigationViewModel()
@StateObject private var network = NetworkMonitor()
@StateObject private var sheets = SheetViewModel()
@StateObject private var wallet: WalletViewModel
@StateObject private var currency = CurrencyViewModel()
@StateObject private var blocktank = BlocktankViewModel()
@StateObject private var activity: ActivityListViewModel
@StateObject private var feeEstimatesManager: FeeEstimatesManager
@StateObject private var transfer: TransferViewModel
@StateObject private var widgets = WidgetsViewModel()
@State private var cameraManager = CameraManager.shared
@StateObject private var pushManager = PushNotificationManager.shared
@StateObject private var scannerManager = ScannerManager()
@StateObject private var settings = SettingsViewModel.shared
@StateObject private var suggestionsManager = SuggestionsManager()
@StateObject private var tagManager = TagManager()
@StateObject private var transferTracking: TransferTrackingManager
@StateObject private var channelDetails = ChannelDetailsViewModel.shared
@StateObject private var migrations = MigrationsService.shared
@StateObject private var pubkyProfile = PubkyProfileManager()
@StateObject private var contactsManager = ContactsManager()
@State private var keyboardManager = KeyboardManager()
@State private var hideSplash = false
@State private var removeSplash = false
@State private var walletIsInitializing: Bool? = nil
@State private var walletInitShouldFinish = false
@State private var isPinVerified: Bool = false
@State private var showRecoveryScreen = false
/// Check if there's a critical update available
private var hasCriticalUpdate: Bool {
AppUpdateService.shared.availableUpdate?.critical == true && !Env.isDebug
}
init() {
let sheetViewModel = SheetViewModel()
let navigationViewModel = NavigationViewModel()
let transferService = TransferService(
lightningService: LightningService.shared,
blocktankService: CoreService.shared.blocktank
)
// Run app data migrations before any feature code loads migrated state
AppDataMigrations.run()
_app = StateObject(wrappedValue: AppViewModel(sheetViewModel: sheetViewModel, navigationViewModel: navigationViewModel))
_sheets = StateObject(wrappedValue: sheetViewModel)
_navigation = StateObject(wrappedValue: navigationViewModel)
let feeEstimatesManager = FeeEstimatesManager()
let walletVm = WalletViewModel(
transferService: transferService,
sheetViewModel: sheetViewModel,
feeEstimatesManager: feeEstimatesManager
)
_wallet = StateObject(wrappedValue: walletVm)
_currency = StateObject(wrappedValue: CurrencyViewModel())
_blocktank = StateObject(wrappedValue: BlocktankViewModel())
_feeEstimatesManager = StateObject(wrappedValue: feeEstimatesManager)
_activity = StateObject(wrappedValue: ActivityListViewModel(transferService: transferService))
_transfer = StateObject(wrappedValue: TransferViewModel(
transferService: transferService,
sheetViewModel: sheetViewModel,
onBalanceRefresh: { await walletVm.updateBalanceState() }
))
_widgets = StateObject(wrappedValue: WidgetsViewModel())
_settings = StateObject(wrappedValue: SettingsViewModel.shared)
_transferTracking = StateObject(wrappedValue: TransferTrackingManager(service: transferService))
}
var body: some View {
mainContent
.sheet(
item: $sheets.forgotPinSheetItem,
onDismiss: { sheets.hideSheet() }
) {
config in ForgotPinSheet(config: config)
}
.task(priority: .userInitiated, setupTask)
.onChange(of: currency.hasStaleData) { _, newValue in handleCurrencyStaleData(newValue) }
.onChange(of: wallet.walletExists) { _, newValue in handleWalletExistsChange(newValue) }
.onChange(of: wallet.nodeLifecycleState) { _, newValue in handleNodeLifecycleChange(newValue) }
.onChange(of: scenePhase) { _, newValue in handleScenePhaseChange(newValue) }
.onChange(of: migrations.isShowingMigrationLoading) { _, isLoading in
if !isLoading {
SettingsViewModel.shared.updatePinEnabledState()
widgets.loadSavedWidgets()
suggestionsManager.reloadDismissed()
tagManager.reloadLastUsedTags()
if UserDefaults.standard.bool(forKey: "pinOnLaunch") && settings.pinEnabled {
isPinVerified = false
}
if migrations.needsPostMigrationSync {
app.toast(
type: .warning,
title: t("migration__network_required_title"),
description: t("migration__network_required_msg"),
visibilityTime: 8.0
)
}
}
}
.onChange(of: network.isConnected) { _, isConnected in
// Retry starting wallet when network comes back online
if isConnected {
handleNetworkRestored()
}
}
.environmentObject(app)
.environmentObject(navigation)
.environmentObject(network)
.environmentObject(sheets)
.environmentObject(wallet)
.environmentObject(currency)
.environmentObject(blocktank)
.environmentObject(feeEstimatesManager)
.environmentObject(activity)
.environmentObject(transfer)
.environmentObject(widgets)
.environment(cameraManager)
.environmentObject(pushManager)
.environmentObject(scannerManager)
.environmentObject(settings)
.environmentObject(suggestionsManager)
.environmentObject(tagManager)
.environmentObject(transferTracking)
.environmentObject(channelDetails)
.environmentObject(pubkyProfile)
.environmentObject(contactsManager)
.environment(keyboardManager)
.onChange(of: pubkyProfile.authState, initial: true) { _, authState in
if authState == .authenticated, let pk = pubkyProfile.publicKey {
Task { try? await contactsManager.loadContacts(for: pk) }
} else if authState == .idle {
contactsManager.reset()
}
}
.onChange(of: pubkyProfile.sessionRestorationFailed) { _, failed in
if failed {
pubkyProfile.sessionRestorationFailed = false
app.toast(type: .error, title: t("profile__session_expired_title"), description: t("profile__session_expired_description"))
}
}
.onAppear {
if !settings.pinEnabled {
isPinVerified = true
}
// Listen for quick action notifications
NotificationCenter.default.addObserver(
forName: .quickActionSelected,
object: nil,
queue: .main
) { notification in
handleQuickAction(notification)
}
}
.onReceive(BackupService.shared.backupFailurePublisher) { intervalMinutes in
handleBackupFailure(intervalMinutes: intervalMinutes)
}
}
private var mainContent: some View {
ZStack {
if migrations.isShowingMigrationLoading {
migrationLoadingContent
} else if showRecoveryScreen {
RecoveryRouter()
.accentColor(.white)
} else if hasCriticalUpdate {
AppUpdateScreen()
} else {
walletContent
}
if !removeSplash && !session.skipSplashOnce {
SplashView()
.opacity(hideSplash ? 0 : 1)
}
}
}
private var migrationLoadingContent: some View {
VStack(spacing: 0) {
NavigationBar(title: t("migration__title"), showBackButton: false, showMenuButton: false)
VStack(spacing: 0) {
VStack {
Spacer()
Image("wallet")
.resizable()
.scaledToFit()
.frame(maxWidth: .infinity)
.aspectRatio(1, contentMode: .fit)
Spacer()
}
.frame(maxWidth: .infinity)
.frame(maxHeight: .infinity)
.layoutPriority(1)
VStack(alignment: .leading, spacing: 14) {
DisplayText(t("migration__headline"))
.frame(maxWidth: .infinity, alignment: .leading)
.fixedSize(horizontal: false, vertical: true)
BodyMText(t("migration__description"))
.frame(maxWidth: .infinity, alignment: .leading)
.fixedSize(horizontal: false, vertical: true)
}
ActivityIndicator(size: 32)
.padding(.top, 32)
}
.padding(.horizontal, 16)
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.padding(.horizontal, 16)
.bottomSafeAreaPadding()
.background(Color.customBlack)
.onAppear {
UIApplication.shared.isIdleTimerDisabled = true
}
.onDisappear {
UIApplication.shared.isIdleTimerDisabled = false
}
}
@ViewBuilder
private var walletContent: some View {
if wallet.walletExists == true {
existingWalletContent
} else if wallet.walletExists == false {
onboardingContent
}
}
@ViewBuilder
private var existingWalletContent: some View {
if walletIsInitializing == true {
// New wallet is being created or restored
initializingContent
} else if wallet.isRestoringWallet {
// Wallet exists and has been restored from backup. isRestoringWallet is set to false inside below component
WalletRestoreSuccess()
} else {
if !isPinVerified && settings.pinEnabled {
AuthCheck(
onCancel: nil,
onPinVerified: {
isPinVerified = true
}
)
} else {
MainNavView()
}
}
}
@ViewBuilder
private var initializingContent: some View {
if case .errorStarting = wallet.nodeLifecycleState {
WalletRestoreError()
} else {
InitializingWalletView(shouldFinish: $walletInitShouldFinish) {
Logger.debug("Wallet finished initializing but node state is \(wallet.nodeLifecycleState)")
if wallet.nodeLifecycleState == .running {
walletIsInitializing = false
}
}
}
}
private var onboardingContent: some View {
NavigationStack {
TermsView()
}
.accentColor(.white)
.onAppear {
// Reset these values if the wallet is wiped
walletIsInitializing = nil
walletInitShouldFinish = false
}
}
// MARK: - Event Handlers
private func handleCurrencyStaleData(_: Bool) {
if currency.hasStaleData {
app.toast(type: .error, title: "Rates currently unavailable", description: "An error has occurred. Please try again later.")
}
}
private func handleWalletExistsChange(_: Bool?) {
Logger.info("Wallet exists state changed: \(wallet.walletExists?.description ?? "nil")")
if wallet.walletExists != nil {
withAnimation(.easeInOut(duration: 0.2).delay(0.2)) {
hideSplash = true
}
// Remove splash view after animation completes
DispatchQueue.main.asyncAfter(deadline: .now() + 0.4) {
removeSplash = true
}
}
guard wallet.walletExists == true else { return }
// Don't start wallet if we're in recovery mode
guard !showRecoveryScreen else { return }
wallet.addOnEvent(id: "toasts-and-sheets") { [weak app] lightningEvent in
app?.handleLdkNodeEvent(lightningEvent)
}
if wallet.isRestoringWallet {
Task {
await restoreFromMostRecentBackup()
await MainActor.run {
widgets.loadSavedWidgets()
widgets.objectWillChange.send()
}
await startWallet()
}
} else {
Task { await startWallet() }
}
}
private func startWallet() async {
// Check network before attempting to start - LDK hangs when VSS is unreachable
guard network.isConnected else {
Logger.warn("Network offline, skipping wallet start", context: "AppScene")
if MigrationsService.shared.isShowingMigrationLoading {
await MainActor.run {
MigrationsService.shared.isShowingMigrationLoading = false
SettingsViewModel.shared.updatePinEnabledState()
}
}
return
}
do {
try await wallet.start()
try await activity.syncLdkNodePayments()
// Start watching pending orders after wallet is ready
await blocktank.startWatchingPendingOrders(transferViewModel: transfer)
// Schedule full backup after wallet create/restore to prevent epoch dates in backup status
await BackupService.shared.scheduleFullBackup()
} catch {
Logger.error(error, context: "Failed to start wallet")
Haptics.notify(.error)
if MigrationsService.shared.isShowingMigrationLoading {
await MainActor.run {
MigrationsService.shared.isShowingMigrationLoading = false
SettingsViewModel.shared.updatePinEnabledState()
}
}
}
}
/// Handle orphaned keychain entries from previous app installs.
/// If the installation marker doesn't exist but keychain has data, the app was reinstalled
/// and the keychain data is orphaned (corresponding wallet data was deleted with the app).
private func handleOrphanedKeychain() {
// If marker exists, app was installed before - keychain is valid
if InstallationMarker.exists() {
Logger.debug("Installation marker exists, skipping orphaned keychain check", context: "AppScene")
return
}
// Check if native keychain has data (orphaned from previous install)
let hasNativeKeychain = (try? Keychain.exists(key: .bip39Mnemonic(index: 0))) == true
// Check if RN keychain has data without corresponding RN files (orphaned)
let hasOrphanedRNKeychain = MigrationsService.shared.hasOrphanedRNKeychain()
if hasNativeKeychain || hasOrphanedRNKeychain {
Logger.warn("Orphaned keychain detected, wiping", context: "AppScene")
try? Keychain.wipeEntireKeychain()
if hasOrphanedRNKeychain {
MigrationsService.shared.cleanupRNKeychain()
}
}
// Create marker for this installation
do {
try InstallationMarker.create()
} catch {
Logger.error("Failed to create installation marker: \(error)", context: "AppScene")
}
}
@Sendable
private func setupTask() async {
do {
// Handle orphaned keychain before anything else
handleOrphanedKeychain()
// Start Pubky/Paykit initialization after keychain cleanup so
// session restoration never races orphaned-keychain wiping.
Task { await pubkyProfile.initialize() }
await checkAndPerformRNMigration()
try wallet.setWalletExistsState()
// Setup TimedSheetManager with all timed sheets
TimedSheetManager.shared.setup(
sheetViewModel: sheets,
appViewModel: app,
settingsViewModel: settings,
walletViewModel: wallet,
currencyViewModel: currency
)
} catch {
app.toast(error)
}
}
private func checkAndPerformRNMigration() async {
let migrations = MigrationsService.shared
guard !migrations.isMigrationChecked else {
Logger.debug("RN migration already checked, skipping", context: "AppScene")
return
}
guard !migrations.hasNativeWalletData() else {
Logger.info("Native wallet data exists, skipping RN migration", context: "AppScene")
migrations.markMigrationChecked()
return
}
// Check if RN wallet data exists AND is not orphaned (has corresponding files)
guard migrations.hasRNWalletData(), !migrations.hasOrphanedRNKeychain() else {
Logger.info("No valid RN wallet data found, skipping migration", context: "AppScene")
migrations.markMigrationChecked()
return
}
await MainActor.run { migrations.isShowingMigrationLoading = true }
Logger.info("RN wallet data found, starting migration...", context: "AppScene")
do {
try await migrations.migrateFromReactNative()
} catch {
Logger.error("RN migration failed: \(error)", context: "AppScene")
migrations.markMigrationChecked()
await MainActor.run { migrations.isShowingMigrationLoading = false }
app.toast(
type: .error,
title: "Migration Failed",
description: "Please restore your wallet manually using your recovery phrase"
)
}
}
private func restoreFromMostRecentBackup() async {
BackupService.shared.setRestoring(true)
defer { BackupService.shared.setRestoring(false) }
guard let mnemonicData = try? Keychain.load(key: .bip39Mnemonic(index: 0)),
let mnemonic = String(data: mnemonicData, encoding: .utf8)
else { return }
let passphrase: String? = {
guard let data = try? Keychain.load(key: .bip39Passphrase(index: 0)) else { return nil }
return String(data: data, encoding: .utf8)
}()
// Check for RN backup and get its timestamp
let hasRNBackup = await MigrationsService.shared.hasRNRemoteBackup(mnemonic: mnemonic, passphrase: passphrase)
let rnTimestamp: UInt64? = await hasRNBackup ? (try? RNBackupClient.shared.getLatestBackupTimestamp()) : nil
// Get VSS backup timestamp
let vssTimestamp = await BackupService.shared.getLatestBackupTime()
// Determine which backup is more recent
let shouldRestoreRN: Bool = {
guard hasRNBackup else { return false }
guard let vss = vssTimestamp, vss > 0 else { return true } // No VSS, use RN
guard let rn = rnTimestamp else { return false } // No RN timestamp, use VSS
return rn >= vss // RN is same or newer
}()
if shouldRestoreRN {
do {
try await MigrationsService.shared.restoreFromRNRemoteBackup(mnemonic: mnemonic, passphrase: passphrase)
} catch {
Logger.error("RN remote backup restore failed: \(error)", context: "AppScene")
// Fall back to VSS
await BackupService.shared.performFullRestoreFromLatestBackup()
}
} else {
await BackupService.shared.performFullRestoreFromLatestBackup()
}
}
private func handleNodeLifecycleChange(_ state: NodeLifecycleState) {
if state == .initializing {
walletIsInitializing = true
} else if state == .running {
walletInitShouldFinish = true
app.markAppStatusInit()
BackupService.shared.startObservingBackups()
} else {
if case .errorStarting = state {
walletInitShouldFinish = true
}
Task {
await BackupService.shared.stopObservingBackups()
}
}
}
private func handleScenePhaseChange(_ newPhase: ScenePhase) {
Logger.debug("Scene phase changed: \(newPhase)")
if newPhase == .background {
if settings.pinEnabled {
// If PIN is enabled, lock the app when the app goes to the background
isPinVerified = false
}
if wallet.walletExists == true {
app.resetAppStatusInit()
}
}
if newPhase == .active {
if wallet.walletExists == true {
Task {
await clearDeliveredNotifications()
await LightningService.shared.reconnectPeers()
}
}
}
}
/// Removes all delivered notifications from Notification Center so the app can handle them when opened.
private func clearDeliveredNotifications() async {
let center = UNUserNotificationCenter.current()
let deliveredNotifications = await center.deliveredNotifications()
guard !deliveredNotifications.isEmpty else { return }
center.removeDeliveredNotifications(withIdentifiers: deliveredNotifications.map(\.request.identifier))
}
private func handleNetworkRestored() {
// Refresh currency rates when network is restored - critical for UI
// to display balances (MoneyText returns "0" if rates are nil)
Task {
await currency.refresh()
}
guard wallet.walletExists == true,
scenePhase == .active
else {
return
}
// If node is stopped/failed, restart it
switch wallet.nodeLifecycleState {
case .stopped, .errorStarting:
Logger.info("Network restored, retrying wallet start...", context: "AppScene")
Task {
await startWallet()
}
default:
break
}
}
private func handleQuickAction(_ notification: Notification) {
guard let userInfo = notification.userInfo,
let shortcutType = userInfo["shortcutType"] as? String
else {
return
}
switch shortcutType {
case "Recovery":
showRecoveryScreen = true
default:
break
}
}
private func handleBackupFailure(intervalMinutes: Int) {
app.toast(
type: .error,
title: t("settings__backup__failed_title"),
description: tPlural("settings__backup__failed_message", arguments: ["interval": intervalMinutes])
)
}
}