krz/domain-dig

an ios app for DNS & SSL analysis

clone: git clone https://gitbay.org/krz/domain-dig.git

v5.0.2: DomainDig/DomainViewModel+Widget.swift · raw

 1import Foundation
 2import WidgetKit
 3
 4extension DomainViewModel {
 5    /// Publishes the current portfolio state to the App Group container so the
 6    /// widget can render it, then asks WidgetKit to refresh its timelines.
 7    func refreshWidgetData() {
 8        #if DEBUG
 9        // Fixture sessions must not write fixture domains into the shared
10        // widget store  it is an App Group file that outlives the launch.
11        if auditFixturesActive { return }
12        #endif
13        let data = portfolioDashboardData
14        let snapshot = data.snapshot
15
16        let ordered = data.domainStates.sorted { lhs, rhs in
17            if lhs.trackedDomain.isPinned != rhs.trackedDomain.isPinned {
18                return lhs.trackedDomain.isPinned
19            }
20            return lhs.health.widgetSeverityRank > rhs.health.widgetSeverityRank
21        }
22
23        let domains = ordered.prefix(6).map { state in
24            DomainDigWidgetDomain(
25                domain: state.trackedDomain.domain,
26                isPinned: state.trackedDomain.isPinned,
27                status: state.health.widgetStatus,
28                certDaysRemaining: state.certificateDaysRemaining,
29                lastChange: state.lastChangeDate
30            )
31        }
32
33        DomainDigWidgetStore.write(
34            DomainDigWidgetData(
35                generatedAt: Date(),
36                totalDomains: snapshot.totalDomains,
37                healthyCount: snapshot.healthyCount,
38                warningCount: snapshot.warningCount,
39                criticalCount: snapshot.criticalCount,
40                expiringSoonCount: snapshot.expiringSoonCount,
41                unreachableCount: snapshot.unreachableCount,
42                domains: Array(domains)
43            )
44        )
45        WidgetCenter.shared.reloadAllTimelines()
46    }
47}
48
49private extension DomainHealth {
50    var widgetStatus: DomainDigWidgetStatus {
51        switch self {
52        case .healthy: return .healthy
53        case .warning: return .warning
54        case .critical: return .critical
55        }
56    }
57
58    var widgetSeverityRank: Int {
59        switch self {
60        case .healthy: return 0
61        case .warning: return 1
62        case .critical: return 2
63        }
64    }
65}