krz/moonrise

Night-sky companion for iPhone, Apple Watch and Vision Pro: what's up tonight, the Moon, planets, launches and missions, and a Library of the solar system. SwiftUI app with a Cloudflare Workers backend. astronomy cloudflare-workers ios night-sky space swiftui visionos watchos

Commit 4d8a6103ce

4d8a6103cee085e912f140f34b4f6adc837250fd

parent: 40f42df124

Unsigned

cmc <hello@cleberg.net> · 2026-10-22 00:18 UTC

App: provider usage terms (!103)

- Kp (`SpaceWeather.fetch(base:)`): from the Worker's `/v1/today`; SWPC directly only if the backend is unset or fails. Sky, System 3D and Siri answers. The Sun tab's charts and OVATION still come from SWPC.
- News (`NewsArticle.latest(base:)`): from `/v1/news`; SNAPI directly only without a backend. The Space Devs ask clients not to call their APIs directly.
- DSN Now: `reloadIgnoringLocalCacheData`. `dsn.xml` is served with `max-age=3600` and changes every few seconds, so the panel could show data up to an hour old.
- Perseverance raw images: 25 per request (all 25 are usable full frames). Curiosity stays at 100: only 6 of 25 and 8 of 100 are full frames.
- `ImageLoader`: `.returnCacheDataElseLoad`, so NASA's `max-age=300` images are not revalidated on every view.
- Library thumbnails with a CC licence show the credit (two lines; the page shows it in full).
- Tests for `/v1/today` and `/v1/news` decoding. MoonriseKit tests pass; iOS and watchOS build.

Layout: unified · split

App/Sources/Intents/AnswerIntents.swift +1 −1
@@ -113,7 +113,7 @@ struct SpaceWeatherIntent: AppIntent {
113 static let supportedModes: IntentModes = .background 113 static let supportedModes: IntentModes = .background
114 114
115 func perform() async throws -> some IntentResult & ProvidesDialog & ShowsSnippetView { 115 func perform() async throws -> some IntentResult & ProvidesDialog & ShowsSnippetView {
116 guard let weather = try? await SpaceWeather.fetch() else { throw AnswerError.offline } 116 guard let weather = try? await SpaceWeather.fetch(base: apiBase) else { throw AnswerError.offline }
117 let place = Place.current 117 let place = Place.current
118 let a = AuroraAnswer(weather: weather, place: place) 118 let a = AuroraAnswer(weather: weather, place: place)
119 return .result(dialog: dialog(a.spoken), view: AnswerSnippet(heading: "Space weather · \(place.label)", rows: a.rows, footnote: a.footnote)) 119 return .result(dialog: dialog(a.spoken), view: AnswerSnippet(heading: "Space weather · \(place.label)", rows: a.rows, footnote: a.footnote))
App/Sources/LibraryScreen.swift +9
@@ -289,6 +289,15 @@ struct PageThumb: View {
289 // Library of Congress scans carry a frame and colour bars; crop to the plate. 289 // Library of Congress scans carry a frame and colour bars; crop to the plate.
290 RemoteImage(url: image.url, points: large ? 640 : 260) { fallback } 290 RemoteImage(url: image.url, points: large ? 640 : 260) { fallback }
291 .scaleEffect(image.url.host() == "tile.loc.gov" ? 1.45 : 1) 291 .scaleEffect(image.url.host() == "tile.loc.gov" ? 1.45 : 1)
292 // CC BY providers (ESA, ESO, NOIRLab) ask that the credit stay with the image. Long credits are
293 // cut here; the page the thumbnail opens shows them in full with the licence.
294 if image.licence.hasPrefix("CC") {
295 Text(image.credit)
296 .font(.system(size: large ? 10 : 8)).lineLimit(2)
297 .foregroundStyle(.white.opacity(0.85)).shadow(color: .black, radius: 2)
298 .padding(4)
299 .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .bottomLeading)
300 }
292 } else { 301 } else {
293 fallback 302 fallback
294 } 303 }
App/Sources/NewsList.swift +1 −1
@@ -33,7 +33,7 @@ struct NewsList: View {
33 func load(force: Bool) async { 33 func load(force: Bool) async {
34 if !force, let cached: [NewsArticle] = FeedMemo.get("news", maxAge: 600) { articles = cached; return } 34 if !force, let cached: [NewsArticle] = FeedMemo.get("news", maxAge: 600) { articles = cached; return }
35 do { 35 do {
36 articles = try await NewsArticle.latest() 36 articles = try await NewsArticle.latest(base: apiBase)
37 if let articles { FeedMemo.set("news", articles) } 37 if let articles { FeedMemo.set("news", articles) }
38 failed = false 38 failed = false
39 } catch { 39 } catch {
App/Sources/RemoteImage.swift +2 −1
@@ -32,7 +32,8 @@ enum ImageLoader {
32 if let hit = cached(url, maxPixels: maxPixels) { return hit } 32 if let hit = cached(url, maxPixels: maxPixels) { return hit }
33 let data: Data 33 let data: Data
34 do { 34 do {
35 data = try await URLSession.shared.data(for: URLRequest(url: url), delegate: CancelLargeBody(limit: largeBody)).0 35 // Image URLs are never reused for new content, so a cached copy is used without asking the host again.
36 data = try await URLSession.shared.data(for: URLRequest(url: url, cachePolicy: .returnCacheDataElseLoad), delegate: CancelLargeBody(limit: largeBody)).0
36 } catch let error as URLError where error.code == .cancelled && !Task.isCancelled { 37 } catch let error as URLError where error.code == .cancelled && !Task.isCancelled {
37 // A data task holds the whole body in memory, twice while it finishes. Download to a file instead 38 // A data task holds the whole body in memory, twice while it finishes. Download to a file instead
38 // and map it, so ImageIO reads it from disk. 39 // and map it, so ImageIO reads it from disk.
App/Sources/SkyModel.swift +2 −2
@@ -174,11 +174,11 @@ final class SkyModel: NSObject, CLLocationManagerDelegate {
174 passesComputed = (.now, observer, elementsFetched) 174 passesComputed = (.now, observer, elementsFetched)
175 } 175 }
176 176
177 /// SWPC asks for no more than once a minute; this checks every 10. 177 /// The backend polls SWPC every 5 minutes; this checks every 10.
178 func refreshSpaceWeather() async { 178 func refreshSpaceWeather() async {
179 if let weatherFetched, Date.now.timeIntervalSince(weatherFetched) < 600 { return } 179 if let weatherFetched, Date.now.timeIntervalSince(weatherFetched) < 600 { return }
180 do { 180 do {
181 spaceWeather = try await SpaceWeather.fetch() 181 spaceWeather = try await SpaceWeather.fetch(base: apiBase)
182 weatherFetched = .now 182 weatherFetched = .now
183 } catch { 183 } catch {
184 log.error("Space weather failed: \(error.localizedDescription, privacy: .public)") 184 log.error("Space weather failed: \(error.localizedDescription, privacy: .public)")
App/Sources/SolarSystem3D.swift +1 −1
@@ -946,7 +946,7 @@ struct SolarSystem3DView: View {
946 946
947 private func loadWeather() async { 947 private func loadWeather() async {
948 while !Task.isCancelled { 948 while !Task.isCancelled {
949 async let kp = try? SpaceWeather.fetch() 949 async let kp = try? SpaceWeather.fetch(base: apiBase)
950 async let sun = SunFeeds.load(force: false) 950 async let sun = SunFeeds.load(force: false)
951 let (k, s) = await (kp, sun) 951 let (k, s) = await (kp, sun)
952 var w = SolarWeather(kp: k?.kpNow) 952 var w = SolarWeather(kp: k?.kpNow)
Packages/MoonriseKit/Sources/Feeds/DSN.swift +2 −1
@@ -29,8 +29,9 @@ public struct DSNStatus: Sendable {
29 29
30 public static let url = URL(string: "https://eyes.nasa.gov/dsn/data/dsn.xml")! 30 public static let url = URL(string: "https://eyes.nasa.gov/dsn/data/dsn.xml")!
31 31
32 /// The file changes every few seconds but is served with max-age=3600, so the local cache is skipped.
32 public static func fetch(session: URLSession = .shared) async throws -> DSNStatus { 33 public static func fetch(session: URLSession = .shared) async throws -> DSNStatus {
33 try decode(await session.data(from: url).0) 34 try decode(await session.data(for: URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData)).0)
34 } 35 }
35 36
36 public static func decode(_ data: Data) throws -> DSNStatus { 37 public static func decode(_ data: Data) throws -> DSNStatus {
Packages/MoonriseKit/Sources/Feeds/MarsImages.swift +1 −1
@@ -11,7 +11,7 @@ public struct MarsImage: Sendable, Identifiable, Hashable {
11 public var image: URL 11 public var image: URL
12 public var credit: String 12 public var credit: String
13 13
14 public static let perseveranceURL = URL(string: "https://mars.nasa.gov/rss/api/?feed=raw_images&category=mars2020&feedtype=json&num=100&page=0&order=sol+desc")! 14 public static let perseveranceURL = URL(string: "https://mars.nasa.gov/rss/api/?feed=raw_images&category=mars2020&feedtype=json&num=25&page=0&order=sol+desc")!
15 public static let curiosityURL = URL(string: "https://mars.nasa.gov/api/v1/raw_image_items/?order=sol%20desc,date_taken%20desc&per_page=100&page=0&condition_1=msl:mission")! 15 public static let curiosityURL = URL(string: "https://mars.nasa.gov/api/v1/raw_image_items/?order=sol%20desc,date_taken%20desc&per_page=100&page=0&condition_1=msl:mission")!
16 16
17 /// Newest full frames from both rovers, `limit` per rover. A rover whose feed fails is left out. 17 /// Newest full frames from both rovers, `limit` per rover. A rover whose feed fails is left out.
Packages/MoonriseKit/Sources/Feeds/News.swift +5 −3
@@ -1,6 +1,7 @@
1import Foundation 1import Foundation
2 2
3/// Space news from the Spaceflight News API (The Space Devs): headline, summary and a link to the article. 3/// Space news from the Spaceflight News API (The Space Devs), through the backend's /v1/news, which The Space Devs
4/// prefer to clients calling them directly: headline, summary and a link to the article.
4public struct NewsArticle: Sendable, Identifiable, Hashable, Decodable { 5public struct NewsArticle: Sendable, Identifiable, Hashable, Decodable {
5 public var id: Int 6 public var id: Int
6 public var title: String 7 public var title: String
@@ -12,8 +13,9 @@ public struct NewsArticle: Sendable, Identifiable, Hashable, Decodable {
12 13
13 public static let url = URL(string: "https://api.spaceflightnewsapi.net/v4/articles/?limit=40")! 14 public static let url = URL(string: "https://api.spaceflightnewsapi.net/v4/articles/?limit=40")!
14 15
15 public static func latest(session: URLSession = .shared) async throws -> [NewsArticle] { 16 /// Straight from the Spaceflight News API only when no backend is configured.
16 try decode(await session.data(from: url).0) 17 public static func latest(base: URL?, session: URLSession = .shared) async throws -> [NewsArticle] {
18 try decode(await session.data(from: base?.appending(path: "v1/news") ?? url).0)
17 } 19 }
18 20
19 /// Decodes a page, leaving out Astronomy Picture of the Day posts, whose summaries are page navigation. 21 /// Decodes a page, leaving out Astronomy Picture of the Day posts, whose summaries are page navigation.
Packages/MoonriseKit/Sources/Feeds/SpaceWeather.swift +17 −1
@@ -42,12 +42,28 @@ public struct SpaceWeather: Sendable, Equatable {
42 return SpaceWeather(kpNow: last.estimated_kp, observedAt: observedAt, kpNext24h: next) 42 return SpaceWeather(kpNow: last.estimated_kp, observedAt: observedAt, kpNext24h: next)
43 } 43 }
44 44
45 public static func fetch(session: URLSession = .shared, at date: Date = .now) async throws -> SpaceWeather { 45 /// From the backend's /v1/today, which polls SWPC for every install; straight from SWPC if the backend
46 /// is unset or fails.
47 public static func fetch(base: URL?, session: URLSession = .shared, at date: Date = .now) async throws -> SpaceWeather {
48 if let base, let w = try? decodeToday(await session.data(from: base.appending(path: "v1/today")).0) { return w }
46 async let now = session.data(from: nowURL).0 49 async let now = session.data(from: nowURL).0
47 async let forecast = session.data(from: forecastURL).0 50 async let forecast = session.data(from: forecastURL).0
48 return try decode(now: await now, forecast: await forecast, at: date) 51 return try decode(now: await now, forecast: await forecast, at: date)
49 } 52 }
50 53
54 /// The `spaceWeather` object of the backend's GET /v1/today.
55 static func decodeToday(_ data: Data) throws -> SpaceWeather {
56 struct Today: Decodable {
57 struct Weather: Decodable { var kpNow: Double; var observedAt: String; var kpNext24h: Double? }
58 var spaceWeather: Weather
59 }
60 let w = try JSONDecoder().decode(Today.self, from: data).spaceWeather
61 guard let observedAt = try? Date(w.observedAt, strategy: Date.ISO8601FormatStyle(includingFractionalSeconds: true)) else {
62 throw DecodingError.dataCorrupted(.init(codingPath: [], debugDescription: "bad observedAt"))
63 }
64 return SpaceWeather(kpNow: w.kpNow, observedAt: observedAt, kpNext24h: w.kpNext24h)
65 }
66
51 /// NOAA G-scale for a Kp value: G1 at Kp 5 through G5 at Kp 9. 67 /// NOAA G-scale for a Kp value: G1 at Kp 5 through G5 at Kp 9.
52 public static func gScale(_ kp: Double) -> Int? { 68 public static func gScale(_ kp: Double) -> Int? {
53 kp >= 5 ? min(Int(kp.rounded(.down)) - 4, 5) : nil 69 kp >= 5 ? min(Int(kp.rounded(.down)) - 4, 5) : nil
Packages/MoonriseKit/Tests/FeedsTests/NewsTests.swift +8
@@ -14,3 +14,11 @@ import Testing
14 #expect(articles[0].published == Date(timeIntervalSince1970: 1_792_341_122)) 14 #expect(articles[0].published == Date(timeIntervalSince1970: 1_792_341_122))
15 #expect(!articles[0].summary.hasSuffix(" ")) 15 #expect(!articles[0].summary.hasSuffix(" "))
16} 16}
17
18@Test func decodesBackendNews() throws {
19 let data = Data(#"{"fetchedAt":"2026-10-22T00:10:00.000Z","results":[{"id":7,"title":"t","summary":" s ","url":"https://example.com/a","image_url":null,"news_site":"ESA","published_at":"2026-10-20T13:00:00Z"}]}"#.utf8)
20 let a = try NewsArticle.decode(data)
21 #expect(a.map(\.id) == [7])
22 #expect(a.first?.summary == "s")
23 #expect(a.first?.image == nil)
24}
Packages/MoonriseKit/Tests/FeedsTests/SpaceWeatherTests.swift +6
@@ -28,3 +28,9 @@ let forecast = Data("""
28 #expect(SpaceWeather.gScale(5.33) == 1) 28 #expect(SpaceWeather.gScale(5.33) == 1)
29 #expect(SpaceWeather.gScale(9) == 5) 29 #expect(SpaceWeather.gScale(9) == 5)
30} 30}
31
32@Test func decodesBackendToday() throws {
33 let data = Data(#"{"spaceWeather":{"kpNow":2.33,"observedAt":"2026-10-22T00:05:00.000Z","kpNext24h":4.67,"fetchedAt":"2026-10-22T00:10:12.964Z"}}"#.utf8)
34 let w = try SpaceWeather.decodeToday(data)
35 #expect(w == SpaceWeather(kpNow: 2.33, observedAt: try Date("2026-10-22T00:05:00Z", strategy: .iso8601), kpNext24h: 4.67))
36}