DomainDig/DomainDigApp.swift

90 lines · 4080 bytes

 1//
 2//  DomainDigApp.swift
 3//  DomainDig
 4//
 5//  Created by cmc on 2026-03-10.
 6//
 7
 8import SwiftUI
 9
10@main
11struct DomainDigApp: App {
12    @UIApplicationDelegateAdaptor(DomainDigAppDelegate.self) private var appDelegate
13    @Environment(\.scenePhase) private var scenePhase
14    @AppStorage(AppDensity.userDefaultsKey) private var density = AppDensity.compact.rawValue
15    @AppStorage(AppAppearance.userDefaultsKey) private var appearance = AppAppearance.system.rawValue
16    @AppStorage(AccentTheme.userDefaultsKey) private var accent = AccentTheme.default.rawValue
17    @State private var viewModel = DomainViewModel()
18    @State private var purchaseService = PurchaseService.shared
19    @State private var cloudSyncService = CloudSyncService.shared
20    @State private var localAPIService = LocalAPIService.shared
21
22    /// Falls back to the default when the tier does not include themes, so a
23    /// lapsed subscriber sees the stock palette rather than a theme they can no
24    /// longer change.
25    private var selectedAccent: AccentTheme {
26        guard FeatureAccessService.hasAccess(to: .accentTheme) else { return .default }
27        return AccentTheme(rawValue: accent) ?? .default
28    }
29
30    init() {
31        LocalNotificationService.shared.configureForegroundPresentation()
32        DomainMonitoringScheduler.shared.registerBackgroundTask()
33        ScheduledReportScheduler.shared.registerBackgroundTask()
34    }
35
36    var body: some Scene {
37        WindowGroup {
38            RootTabView(viewModel: viewModel)
39                .environment(\.appDensity, AppDensity(rawValue: density) ?? .compact)
40                .environment(\.theme, selectedAccent.theme)
41                // So standard controls pick the accent up too, not only the
42                // views that name a token.
43                .tint(selectedAccent == .default ? nil : selectedAccent.theme.accentFill)
44                // The single place appearance is applied. Keep it that way.
45                .preferredColorScheme((AppAppearance(rawValue: appearance) ?? .system).colorScheme)
46                .task {
47                    #if DEBUG
48                    viewModel.seedAuditFixturesIfRequested()
49                    #endif
50                    await refreshAfterBecomingActive()
51                }
52                .onReceive(NotificationCenter.default.publisher(for: .cloudSyncDidApplyChanges)) { _ in
53                    viewModel.refreshPersistedData()
54                    viewModel.monitoringStatusMessage = DomainMonitoringScheduler.shared.syncSchedule()
55                    IntegrationService.shared.refresh()
56                }
57        }
58        .onChange(of: scenePhase) { _, newValue in
59            guard newValue == .active else { return }
60            Task { await refreshAfterBecomingActive() }
61        }
62    }
63
64    /// Everything that must re-run whenever the app becomes active.
65    ///
66    /// Launch and foreground carried near-duplicates of this, and the
67    /// foreground copy left out `refreshEntitlements()` — so a purchase or
68    /// cancellation made outside the app was not picked up until the next cold
69    /// launch.
70    private func refreshAfterBecomingActive() async {
71        await purchaseService.refreshEntitlements()
72        viewModel.refreshMonitoringState()
73        await viewModel.refreshMonitoringAuthorizationStatus()
74        await cloudSyncService.refreshAvailability()
75        localAPIService.refresh()
76        cloudSyncService.scheduleSyncIfNeeded(trigger: .launch)
77        viewModel.monitoringStatusMessage = DomainMonitoringScheduler.shared.syncSchedule()
78        ScheduledReportScheduler.shared.syncSchedule()
79        IntegrationService.shared.processQueueNow()
80        viewModel.refreshWidgetData()
81        consumeShareInbox()
82    }
83
84    /// Picks up a domain shared via the share extension and routes it into an
85    /// inspection through the intent router (consumed by `RootTabView`).
86    private func consumeShareInbox() {
87        guard let domain = DomainDigShareInbox.consume() else { return }
88        DomainDigIntentRouter.shared.pendingAction = .inspect(domain)
89    }
90}