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
|
import Foundation
#if canImport(WidgetKit)
import WidgetKit
#endif
enum SystemStatusWidgetConfiguration {
static let kind = "SystemStatusWidget"
}
struct SystemStatusWidgetSnapshot: Codable, Sendable {
let services: [ServiceEntry]
let hasDisruption: Bool
let overallStatusText: String
let bannerSummary: String
let updatedAt: Date
struct ServiceEntry: Codable, Sendable, Identifiable {
let id: String
let name: String
let status: String
let requiresAttention: Bool
}
static let unavailable = SystemStatusWidgetSnapshot(
services: [],
hasDisruption: false,
overallStatusText: "Unavailable",
bannerSummary: "",
updatedAt: .now
)
}
enum SystemStatusWidgetSnapshotStore {
private static let snapshotKey = "systemStatus.widgetSnapshot"
static func load(
accountID: String? = ActiveAccountContextStore.load(),
defaults: UserDefaults? = sharedDefaults()
) -> SystemStatusWidgetSnapshot? {
guard let defaults,
let data = defaults.data(forKey: scopedKey(for: accountID)) else {
return nil
}
return try? JSONDecoder().decode(SystemStatusWidgetSnapshot.self, from: data)
}
static func save(
_ snapshot: SystemStatusWidgetSnapshot,
accountID: String? = ActiveAccountContextStore.load(),
defaults: UserDefaults? = sharedDefaults()
) {
guard let defaults,
let data = try? JSONEncoder().encode(snapshot) else {
return
}
defaults.set(data, forKey: scopedKey(for: accountID))
reloadWidgetTimelines()
}
static func clear(
accountID: String? = ActiveAccountContextStore.load(),
defaults: UserDefaults? = sharedDefaults()
) {
defaults?.removeObject(forKey: scopedKey(for: accountID))
reloadWidgetTimelines()
}
private static func sharedDefaults() -> UserDefaults? {
UserDefaults(suiteName: HutchAppGroup.identifier)
}
private static func scopedKey(for accountID: String?) -> String {
guard let accountID, !accountID.isEmpty else { return snapshotKey }
return "\(snapshotKey).\(accountID)"
}
private static func reloadWidgetTimelines() {
#if canImport(WidgetKit)
WidgetCenter.shared.reloadTimelines(ofKind: SystemStatusWidgetConfiguration.kind)
#endif
}
}
|