Branchwell

Glimmer / app · glimmertoday.ai / native / Glimmer / EditorialLibrary.swift

Raw 8.0 KB on 373be588c5c7abca97cdec6f7aa4be565975b988
1import Foundation
2import Observation
3
4/// One public document provides the coaching library and the media index.
5struct EditorialEdition: Decodable {
6 let schemaVersion: Int
7 let content: Catalog
8 let gallery: GalleryCatalog
9
10 func validate(against bundled: Catalog, bundledGallery: GalleryCatalog) throws {
11 let lessons = content.lessons
12 let originalLessons = bundled.lessons
13 let lessonIDs = lessons.map(\.id)
14 let stableLessons = zip(originalLessons, lessons).allSatisfy { original, replacement in
15 original.id == replacement.id
16 && original.pages.map(\.kind) == replacement.pages.map(\.kind)
17 && zip(original.pages, replacement.pages).allSatisfy { $0.options?.count == $1.options?.count }
18 }
19 let validOnboarding = bundled.onboarding.count == content.onboarding.count
20 && zip(bundled.onboarding, content.onboarding).allSatisfy { original, replacement in
21 original.kind == replacement.kind && original.key == replacement.key
22 && original.mode == replacement.mode
23 && original.options?.map(\.id) == replacement.options?.map(\.id)
24 }
25 guard schemaVersion == 1, lessons.count >= originalLessons.count, stableLessons,
26 lessons.map(\.number) == Array(1...lessons.count),
27 Set(lessonIDs).count == lessons.count,
28 lessons.allSatisfy({ !$0.title.isEmpty && !$0.pages.isEmpty }),
29 validOnboarding,
30 Set(bundled.startingPractices.keys).isSubset(of: Set(content.startingPractices.keys)),
31 preserves(bundled.challenges.map(\.id), in: content.challenges.map(\.id)),
32 preserves(bundled.habits.map(\.id), in: content.habits.map(\.id)),
33 content.energy.map(\.id) == bundled.energy.map(\.id),
34 preserves(bundled.practiceTopics.map(\.id), in: content.practiceTopics.map(\.id)),
35 preserves(bundled.practiceTopics.flatMap { $0.exercises.map(\.id) },
36 in: content.practiceTopics.flatMap { $0.exercises.map(\.id) }),
37 preserves(bundled.cleaning.rooms.map(\.id), in: content.cleaning.rooms.map(\.id)),
38 preserves(bundled.cleaning.speed.map(\.id), in: content.cleaning.speed.map(\.id)),
39 content.cleaning.daily.id == bundled.cleaning.daily.id,
40 validSeasonal(against: bundled),
41 validQuotes(against: bundled) else {
42 throw CocoaError(.fileReadCorruptFile)
43 }
44 try gallery.validate(bundledIDs: Set(bundledGallery.plates.map(\.id)))
45 }
46
47 private func validQuotes(against bundled: Catalog) -> Bool {
48 guard let quotes = content.quotes else { return true }
49 let original = bundled.quotes ?? []
50 let ids = quotes.map(\.id)
51 return Array(ids.prefix(original.count)) == original.map(\.id)
52 && Set(ids).count == ids.count
53 && quotes.allSatisfy {
54 !$0.id.isEmpty && !$0.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
55 && !$0.author.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
56 }
57 }
58
59 private func validSeasonal(against bundled: Catalog) -> Bool {
60 guard let editions = content.seasonal else { return true }
61 let original = bundled.seasonal ?? []
62 guard preserves(original.map(\.id), in: editions.map(\.id)) else { return false }
63 let maintenance = Set((content.cleaning.maintenance ?? bundled.cleaning.maintenance ?? []).map(\.id))
64 return editions.allSatisfy { edition in
65 let baseline = original.first { $0.id == edition.id }
66 return PracticeDate.parse("2000-" + edition.start) != nil
67 && PracticeDate.parse("2000-" + edition.end) != nil
68 && (baseline == nil || baseline?.start == edition.start)
69 && preserves(baseline?.tips.map(\.id) ?? [], in: edition.tips.map(\.id))
70 && preserves(baseline?.checklists.map(\.id) ?? [], in: edition.checklists.map(\.id))
71 && (edition.resources ?? []).allSatisfy { $0.url.scheme == "https" && $0.url.host != nil }
72 && Set(edition.maintenance).isSubset(of: maintenance)
73 && edition.checklists.allSatisfy { list in
74 let originalItems = baseline?.checklists.first { $0.id == list.id }?.items ?? []
75 return !list.items.isEmpty && preserves(originalItems.map(\.id), in: list.items.map(\.id))
76 }
77 }
78 }
79
80 private func preserves(_ old: [String], in new: [String]) -> Bool {
81 let ids = Set(new)
82 return new.count == ids.count && Set(old).isSubset(of: ids)
83 }
84}
85
86@MainActor @Observable
87final class EditorialLibrary {
88 static let endpoint = URL(string: "https://media.protomota.com/glimmer/content/library-v1.json")!
89 nonisolated static let defaultDirectory = URL.applicationSupportDirectory.appending(path: "GlimmerMedia")
90 static let maxBytes = 2 * 1024 * 1024
91 static let refreshInterval: TimeInterval = 15 * 60
92
93 private struct Snapshot: Codable {
94 let bytes: Data
95 let etag: String?
96 }
97
98 private(set) var edition: EditorialEdition?
99 @ObservationIgnored private var snapshot: Snapshot?
100 @ObservationIgnored private var lastAttempt: Date?
101 @ObservationIgnored private var refreshing = false
102 @ObservationIgnored private let file: URL
103 @ObservationIgnored private let bundled: Catalog
104 @ObservationIgnored private let bundledGallery: GalleryCatalog
105
106 init(bundled: Catalog, bundledGallery: GalleryCatalog = .bundled, directory: URL = defaultDirectory) {
107 self.bundled = bundled
108 self.bundledGallery = bundledGallery
109 file = directory.appending(path: "editorial-v1.json")
110 if let size = try? file.resourceValues(forKeys: [.fileSizeKey]).fileSize,
111 size < 3 * Self.maxBytes,
112 let bytes = try? Data(contentsOf: file),
113 let saved = try? JSONDecoder().decode(Snapshot.self, from: bytes),
114 let accepted = try? decode(saved.bytes) {
115 snapshot = saved
116 edition = accepted
117 }
118 }
119
120 func refreshIfNeeded(now: Date = .now,
121 fetch: (URLRequest, Int) async throws -> (Data, HTTPURLResponse) = GalleryHTTP.fetch) async {
122 guard !refreshing, now.timeIntervalSince(lastAttempt ?? .distantPast) >= Self.refreshInterval else { return }
123 refreshing = true
124 lastAttempt = now
125 defer { refreshing = false }
126
127 var request = URLRequest(url: Self.endpoint, cachePolicy: .reloadIgnoringLocalCacheData)
128 request.setValue("application/json", forHTTPHeaderField: "Accept")
129 request.setValue(snapshot?.etag, forHTTPHeaderField: "If-None-Match")
130 do {
131 let (bytes, response) = try await fetch(request, Self.maxBytes)
132 try Task.checkCancellation()
133 guard response.url == Self.endpoint, response.statusCode == 200,
134 response.mimeType == "application/json" else { return }
135 let accepted = try decode(bytes)
136 let next = Snapshot(bytes: bytes, etag: response.value(forHTTPHeaderField: "ETag"))
137 try FileManager.default.createDirectory(at: file.deletingLastPathComponent(), withIntermediateDirectories: true)
138 try JSONEncoder().encode(next).write(to: file, options: .atomic)
139 snapshot = next
140 edition = accepted
141 } catch {
142 // No partially downloaded or rejected edition replaces the last valid edition.
143 if Task.isCancelled { lastAttempt = nil }
144 }
145 }
146
147 private func decode(_ bytes: Data) throws -> EditorialEdition {
148 guard bytes.count <= Self.maxBytes else { throw URLError(.dataLengthExceedsMaximum) }
149 let edition = try JSONDecoder().decode(EditorialEdition.self, from: bytes)
150 try edition.validate(against: bundled, bundledGallery: bundledGallery)
151 if let current = self.edition {
152 try edition.validate(against: current.content, bundledGallery: bundledGallery)
153 }
154 return edition
155 }
156}