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 4f9a36c696

4f9a36c696b07a20ce9ee202e9ab07d22af90148

parent: 81afc1b9eb

Unsigned

cmc <hello@cleberg.net> · 2026-10-21 17:56 UTC

Sun tab: skip black and partly covered SDO frames (!86)

SDO's `latest_1024_<channel>.jpg` for 171, 193 and 304 Å is often black apart from the label line, or has part of the disk cut off (curved dark edge, or a straight vertical cut as on 171 Å at 17:35 UT today). The Sun tab showed those frames.

## Frame check (`SolarImage.isUsable`, Feeds)

ImageIO decodes a 64 px thumbnail; the check counts pixels brighter than 16/255 inside the disk circle above the bottom 5% (label strip). Disk radius as a fraction of width: 0.39 AIA, 0.45 HMI, from radial profiles of the fixtures. Usable if at least 95% of the disk is lit.

Lit fraction on 47 frames from today's archive plus the six fixtures:

| Frames | Lit fraction |
|---|---|
| 171, 304, HMIIC whole frames | 1.000 |
| 193 Å whole frames (coronal holes) | 0.991–0.994 |
| Partly covered 171 / 193 / 304 | 0.25–0.59 |
| Current latest 171 Å (vertical cut) | 0.82 |
| Black frames | 0.000 |

Six fixtures (two good, two black, two partly covered 193 Å), downscaled to 256 px, 51 KB total.

## Archive fallback

`archiveURL(day:)` lists `browse/YYYY/MM/DD/?P=*_1024_<channel>.jpg`. Apache's `P=` filter cuts the listing from 1.1 MB to about 15 KB. `frames(inListing:at:)` matches `YYYYMMDD_HHMMSS_1024_<channel>.jpg` anywhere in the HTML and sorts newest first. `lastUsableFrame()` reads today's UTC listing, and yesterday's when today lists fewer than 6 frames, then downloads at most 6 frames, newest first, until one is usable.

## Sun tab

- Latest usable: shown, and saved with its `Last-Modified` as the file date.
- Latest unusable: shows the saved image if it passes the check, otherwise searches the archive and saves the frame it finds there, dated with the frame time. Shows the caption "Latest complete frame from 17:26 UT", with the day added when it is not today in UT. If neither source has a usable frame, the latest is shown as before.
- Offline: the saved image is shown only if it passes the check, because files saved before this change may be black. The caption now reads "This one is from …" because the file date is now the frame time, not the save time.
- HMIIC: same path. Every current HMIIC frame passes.

## Tests

- `swift test` (Packages/MoonriseKit): all pass. New: `solarFrameUsable` (6 fixtures), `solarFrameUsableRejectsNonImages`, `solarArchiveListing`.
- `npm test` (server): 58/58 pass.
- `xcodegen generate` + `xcodebuild test -scheme Moonrise` (iPhone 18 Pro, iOS 27.0): pass.

Audit (`AccessibilityAuditTests`). SDO's latest 171 Å was cut during both runs, so the new caption was on screen on Sun:

| Screen | main's Sun sources | this MR |
|---|---|---|
| Sky | 4 | 4 |
| Settings | 2 | 2 |
| System | 7 | 7 |
| Sun | 3 | 3 |
| News & launches | 21 | 20 |
| Library | 14 | 14 |
| Library page: Saturn | 13 | 13 |
| Total | 64 | 63 |

News & launches changes with the live feed. With `.caption2` the new caption was flagged as "Dynamic Type font sizes are partially unsupported" (as in !64), so it uses `.caption`.

Checked in the simulator: 171 Å fell back to the saved frame. With the 193 Å URL temporarily pointed at a black archive frame and nothing saved, the tab found the 17:26:54 archive frame, showed "Latest complete frame from 17:26 UT", and saved it dated 17:26:54.

Not covered: the caption for a frame saved from `latest` uses `Last-Modified`, which runs about 7 min after the frame time for AIA and about 80 min after for HMIIC. Blurred or streaked frames with a lit disk pass the check.

Layout: unified · split

App/Sources/SunScreen.swift +53 −11
@@ -85,16 +85,19 @@ struct SunScreen: View {
85 summary = await SunFeeds.summary(snapshot) 85 summary = await SunFeeds.summary(snapshot)
86 } 86 }
87 87
88 /// An SDO image, with the time it was saved when it comes from the cache. 88 /// An SDO image, with the frame's time when it comes from the cache because nothing loaded (`saved`) or because
89 /// SDO's latest frame was not usable (`frame`).
89 private struct Picture { 90 private struct Picture {
90 var wavelength: SolarImage 91 var wavelength: SolarImage
91 var image: UIImage 92 var image: UIImage
92 var loaded: Date 93 var loaded: Date
93 var saved: Date? 94 var saved: Date?
95 var frame: Date?
94 } 96 }
95 97
96 /// SDO sends no-store, so the last image of each wavelength is saved to Caches for use offline. 98 /// SDO sends no-store, so the last usable image of each wavelength is saved to Caches for use offline, dated with
97 /// A fresh image of the same wavelength under 5 minutes old is kept. 99 /// the frame's time. When the latest frame is black or partly covered, the saved one or one from SDO's archive is
100 /// shown instead. A fresh image of the same wavelength under 5 minutes old is kept.
98 private func loadImage() async { 101 private func loadImage() async {
99 let w = wavelength 102 let w = wavelength
100 if let p = picture, p.wavelength == w, p.saved == nil, p.loaded > imageID, Date.now.timeIntervalSince(p.loaded) < 300 { return } 103 if let p = picture, p.wavelength == w, p.saved == nil, p.loaded > imageID, Date.now.timeIntervalSince(p.loaded) < 300 { return }
@@ -102,21 +105,58 @@ struct SunScreen: View {
102 picture = nil 105 picture = nil
103 imageFailed = false 106 imageFailed = false
104 if let (data, response) = try? await URLSession.shared.data(from: w.url(size: 1024)), 107 if let (data, response) = try? await URLSession.shared.data(from: w.url(size: 1024)),
105 (response as? HTTPURLResponse)?.statusCode == 200, let image = UIImage(data: data) { 108 let http = response as? HTTPURLResponse, http.statusCode == 200, let image = UIImage(data: data) {
106 picture = Picture(wavelength: w, image: image, loaded: .now) 109 if w.isUsable(data) {
107 try? FileManager.default.createDirectory(at: file.deletingLastPathComponent(), withIntermediateDirectories: true) 110 picture = Picture(wavelength: w, image: image, loaded: .now)
108 try? data.write(to: file, options: .atomic) 111 let modified = http.value(forHTTPHeaderField: "Last-Modified").flatMap { try? Date($0, strategy: .http) }
112 save(data, time: modified ?? .now, to: file)
113 return
114 }
115 var frame = savedFrame(file, w)
116 if frame == nil, let found = await w.lastUsableFrame() {
117 frame = found
118 save(found.data, time: found.time, to: file)
119 }
120 guard !Task.isCancelled else { return }
121 if let frame, let saved = UIImage(data: frame.data) {
122 picture = Picture(wavelength: w, image: saved, loaded: .now, frame: frame.time)
123 } else {
124 picture = Picture(wavelength: w, image: image, loaded: .now)
125 }
109 return 126 return
110 } 127 }
111 guard !Task.isCancelled else { return } 128 guard !Task.isCancelled else { return }
112 if let image = UIImage(contentsOfFile: file.path(percentEncoded: false)) { 129 if let frame = savedFrame(file, w), let image = UIImage(data: frame.data) {
113 let saved = (try? file.resourceValues(forKeys: [.contentModificationDateKey]))?.contentModificationDate 130 picture = Picture(wavelength: w, image: image, loaded: .now, saved: frame.time)
114 picture = Picture(wavelength: w, image: image, loaded: .now, saved: saved ?? .distantPast)
115 } else { 131 } else {
116 imageFailed = true 132 imageFailed = true
117 } 133 }
118 } 134 }
119 135
136 /// The saved image and its frame time, if it is usable: images saved before the check may be black.
137 private func savedFrame(_ file: URL, _ w: SolarImage) -> (data: Data, time: Date)? {
138 guard let data = try? Data(contentsOf: file), w.isUsable(data) else { return nil }
139 let time = (try? file.resourceValues(forKeys: [.contentModificationDateKey]))?.contentModificationDate
140 return (data, time ?? .distantPast)
141 }
142
143 private func save(_ data: Data, time: Date, to file: URL) {
144 try? FileManager.default.createDirectory(at: file.deletingLastPathComponent(), withIntermediateDirectories: true)
145 try? data.write(to: file, options: .atomic)
146 try? FileManager.default.setAttributes([.modificationDate: time], ofItemAtPath: file.path(percentEncoded: false))
147 }
148
149 /// "16:26 UT", with the day when it is not today in UT.
150 private func universalTime(_ date: Date) -> String {
151 let utc = TimeZone(identifier: "UTC")!
152 var calendar = Calendar(identifier: .gregorian)
153 calendar.timeZone = utc
154 let format: Date.FormatString = calendar.isDate(date, inSameDayAs: .now)
155 ? "\(hour: .twoDigits(clock: .twentyFourHour, hourCycle: .zeroBased)):\(minute: .twoDigits)"
156 : "\(day: .defaultDigits) \(month: .abbreviated) \(hour: .twoDigits(clock: .twentyFourHour, hourCycle: .zeroBased)):\(minute: .twoDigits)"
157 return date.formatted(Date.VerbatimFormatStyle(format: format, locale: .current, timeZone: utc, calendar: calendar)) + " UT"
158 }
159
120 private var image: some View { 160 private var image: some View {
121 VStack(alignment: .leading, spacing: 4) { 161 VStack(alignment: .leading, spacing: 4) {
122 Group { 162 Group {
@@ -131,8 +171,10 @@ struct SunScreen: View {
131 .aspectRatio(1, contentMode: .fit) 171 .aspectRatio(1, contentMode: .fit)
132 .accessibilityLabel("The Sun at \(wavelength.name)") 172 .accessibilityLabel("The Sun at \(wavelength.name)")
133 if let saved = picture?.saved { 173 if let saved = picture?.saved {
134 Text("Couldn't load a new image. This one was saved \(saved.formatted(.relative(presentation: .named))).") 174 Text("Couldn't load a new image. This one is from \(saved.formatted(.relative(presentation: .named))).")
135 .font(.caption2).foregroundStyle(accent) 175 .font(.caption2).foregroundStyle(accent)
176 } else if let frame = picture?.frame {
177 Text("Latest complete frame from \(universalTime(frame))").font(.caption).dimmed(0.6)
136 } 178 }
137 } 179 }
138 } 180 }
Packages/MoonriseKit/Sources/Feeds/Sun.swift +75
@@ -1,4 +1,6 @@
1import CoreGraphics
1import Foundation 2import Foundation
3import ImageIO
2 4
3/// Latest full-disk images from NASA's Solar Dynamics Observatory. 5/// Latest full-disk images from NASA's Solar Dynamics Observatory.
4/// Credit: "Courtesy of NASA/SDO and the AIA, EVE, and HMI science teams." 6/// Credit: "Courtesy of NASA/SDO and the AIA, EVE, and HMI science teams."
@@ -34,6 +36,79 @@ public enum SolarImage: String, CaseIterable, Sendable, Identifiable {
34 } 36 }
35 37
36 public static let credit = "Courtesy of NASA/SDO and the AIA, EVE, and HMI science teams." 38 public static let credit = "Courtesy of NASA/SDO and the AIA, EVE, and HMI science teams."
39
40 /// Disk radius as a fraction of the frame's width.
41 var diskRadius: Double { self == .visible ? 0.45 : 0.39 }
42
43 /// Whether a frame shows the whole disk. SDO publishes AIA frames that are black apart from the label along the
44 /// bottom, and some with part of the disk behind a curved dark edge. On a 64 px thumbnail, the share of the disk
45 /// (above the label) brighter than 16/255: whole frames measure 0.99 or more, 193 Å with its coronal holes being the
46 /// lowest, and covered ones 0.6 or less, so 0.95 is the cut.
47 public func isUsable(_ data: Data) -> Bool {
48 let n = 64
49 guard let source = CGImageSourceCreateWithData(data as CFData, nil),
50 let image = CGImageSourceCreateThumbnailAtIndex(source, 0, [kCGImageSourceCreateThumbnailFromImageAlways: true, kCGImageSourceThumbnailMaxPixelSize: n] as CFDictionary),
51 let context = CGContext(data: nil, width: n, height: n, bitsPerComponent: 8, bytesPerRow: n, space: CGColorSpaceCreateDeviceGray(), bitmapInfo: CGImageAlphaInfo.none.rawValue)
52 else { return false }
53 context.draw(image, in: CGRect(x: 0, y: 0, width: n, height: n))
54 guard let pixels = context.data?.assumingMemoryBound(to: UInt8.self) else { return false }
55 let r = diskRadius * Double(n), c = Double(n) / 2
56 var disk = 0, lit = 0
57 for y in 0..<n * 95 / 100 {
58 for x in 0..<n {
59 let dx = Double(x) + 0.5 - c, dy = Double(y) + 0.5 - c
60 guard dx * dx + dy * dy <= r * r else { continue }
61 disk += 1
62 if pixels[y * n + x] > 16 { lit += 1 }
63 }
64 }
65 return Double(lit) >= 0.95 * Double(disk)
66 }
67
68 /// SDO's dated archive for the UTC day of `day`, listing only this channel's frames at `size`.
69 public func archiveURL(day: Date, size: Int = 1024) -> URL {
70 var calendar = Calendar(identifier: .gregorian)
71 calendar.timeZone = TimeZone(identifier: "UTC")!
72 let d = calendar.dateComponents([.year, .month, .day], from: day)
73 let path = String(format: "%04d/%02d/%02d", d.year!, d.month!, d.day!)
74 return URL(string: "https://sdo.gsfc.nasa.gov/assets/img/browse/\(path)/?P=*_\(size)_\(rawValue).jpg")!
75 }
76
77 /// This channel's frames named in an archive listing, as `YYYYMMDD_HHMMSS_<size>_<channel>.jpg`, newest first.
78 public func frames(inListing html: String, at listing: URL, size: Int = 1024) -> [SolarFrame] {
79 let style = Date.ISO8601FormatStyle(dateSeparator: .omitted, timeSeparator: .omitted)
80 var frames: [String: SolarFrame] = [:]
81 for m in html.matches(of: /(\d{8})_(\d{6})_(\d+)_(\w+)\.jpg/) where m.3 == "\(size)" && m.4 == rawValue {
82 guard let time = try? Date("\(m.1)T\(m.2)Z", strategy: style),
83 let url = URL(string: String(m.0), relativeTo: listing)?.absoluteURL else { continue }
84 frames[String(m.0)] = SolarFrame(url: url, time: time)
85 }
86 return frames.values.sorted { $0.time > $1.time }
87 }
88
89 /// The newest usable 1024 px frame in the archive for the UTC day of `date`, and the day before when that day
90 /// lists fewer than `tries` frames. Downloads at most `tries` frames.
91 public func lastUsableFrame(at date: Date = .now, tries: Int = 6, session: URLSession = .shared) async -> (data: Data, time: Date)? {
92 var frames: [SolarFrame] = []
93 for day in [date, date.addingTimeInterval(-86_400)] where frames.count < tries {
94 let listing = archiveURL(day: day)
95 guard let (html, _) = try? await session.data(from: listing) else { continue }
96 frames += self.frames(inListing: String(decoding: html, as: UTF8.self), at: listing)
97 }
98 for frame in frames.prefix(tries) {
99 if let (data, response) = try? await session.data(from: frame.url),
100 (response as? HTTPURLResponse)?.statusCode == 200, isUsable(data) {
101 return (data, frame.time)
102 }
103 }
104 return nil
105 }
106}
107
108/// A frame in SDO's dated archive.
109public struct SolarFrame: Sendable, Equatable {
110 public var url: URL
111 public var time: Date
37} 112}
38 113
39/// Three-hour planetary Kp, observed and predicted (SWPC 3-day forecast product). 114/// Three-hour planetary Kp, observed and predicted (SWPC 3-day forecast product).
Packages/MoonriseKit/Tests/FeedsTests/Fixtures/sdo-0171.jpg added

Binary file not shown.

Packages/MoonriseKit/Tests/FeedsTests/Fixtures/sdo-0193-black.jpg added

Binary file not shown.

Packages/MoonriseKit/Tests/FeedsTests/Fixtures/sdo-0193-covered-151634.jpg added

Binary file not shown.

Packages/MoonriseKit/Tests/FeedsTests/Fixtures/sdo-0193-covered-163614.jpg added

Binary file not shown.

Packages/MoonriseKit/Tests/FeedsTests/Fixtures/sdo-0304-black.jpg added

Binary file not shown.

Packages/MoonriseKit/Tests/FeedsTests/Fixtures/sdo-HMIIC.jpg added

Binary file not shown.

Packages/MoonriseKit/Tests/FeedsTests/SunTests.swift +41
@@ -47,6 +47,47 @@ import Testing
47 #expect(SolarImage.corona.url().absoluteString == "https://sdo.gsfc.nasa.gov/assets/img/latest/latest_1024_0171.jpg") 47 #expect(SolarImage.corona.url().absoluteString == "https://sdo.gsfc.nasa.gov/assets/img/latest/latest_1024_0171.jpg")
48} 48}
49 49
50/// SDO frames from 2026-10-21, downscaled to 256 px.
51@Test(arguments: [
52 ("sdo-0171", SolarImage.corona, true),
53 ("sdo-HMIIC", .visible, true),
54 ("sdo-0193-black", .hotCorona, false),
55 ("sdo-0304-black", .chromosphere, false),
56 ("sdo-0193-covered-151634", .hotCorona, false),
57 ("sdo-0193-covered-163614", .hotCorona, false),
58])
59func solarFrameUsable(name: String, image: SolarImage, usable: Bool) throws {
60 let url = try #require(Bundle.module.url(forResource: "Fixtures/\(name)", withExtension: "jpg"))
61 #expect(image.isUsable(try Data(contentsOf: url)) == usable)
62}
63
64@Test func solarFrameUsableRejectsNonImages() {
65 #expect(!SolarImage.corona.isUsable(Data("<html></html>".utf8)))
66}
67
68@Test func solarArchiveListing() throws {
69 let day = try Date("2026-10-21T17:00:00Z", strategy: .iso8601)
70 let listing = SolarImage.hotCorona.archiveURL(day: day)
71 #expect(listing.absoluteString == "https://sdo.gsfc.nasa.gov/assets/img/browse/2026/10/21/?P=*_1024_0193.jpg")
72 // Lines from the listing on 2026-10-21.
73 let html = """
74 <img src="/icons/back.gif" alt="[PARENTDIR]"> <a href="/assets/img/browse/2026/10/">Parent Directory</a> -
75 <img src="/icons/image2.gif" alt="[IMG]"> <a href="20261021_000653_1024_0193.jpg">20261021_000653_1024_0193.jpg</a> 2026-10-20 19:13 138K
76 <img src="/icons/image2.gif" alt="[IMG]"> <a href="20261021_000653_512_0193.jpg">20261021_000653_512_0193.jpg</a> 2026-10-20 19:13 45K
77 <img src="/icons/image2.gif" alt="[IMG]"> <a href="20261021_000658_1024_0171.jpg">20261021_000658_1024_0171.jpg</a> 2026-10-20 19:12 182K
78 <img src="/icons/image2.gif" alt="[IMG]"> <a href="20261021_162634_1024_0193.jpg">20261021_162634_1024_0193.jpg</a> 2026-10-21 11:33 90K
79 <img src="/icons/image2.gif" alt="[IMG]"> <a href="20261021_172654_1024_0193.jpg">20261021_172654_1024_0193.jpg</a> 2026-10-21 12:33 134K
80 """
81 let frames = SolarImage.hotCorona.frames(inListing: html, at: listing)
82 #expect(frames.map(\.url.absoluteString) == [
83 "https://sdo.gsfc.nasa.gov/assets/img/browse/2026/10/21/20261021_172654_1024_0193.jpg",
84 "https://sdo.gsfc.nasa.gov/assets/img/browse/2026/10/21/20261021_162634_1024_0193.jpg",
85 "https://sdo.gsfc.nasa.gov/assets/img/browse/2026/10/21/20261021_000653_1024_0193.jpg",
86 ])
87 #expect(frames[1].time == (try Date("2026-10-21T16:26:34Z", strategy: .iso8601)))
88 #expect(SolarImage.hotCorona.frames(inListing: "<html>Not Found</html>", at: listing).isEmpty)
89}
90
50@Test func ovationKeepsNonZeroCells() throws { 91@Test func ovationKeepsNonZeroCells() throws {
51 // Shape from ovation_aurora_latest.json on 2026-10-17. 92 // Shape from ovation_aurora_latest.json on 2026-10-17.
52 let data = Data(""" 93 let data = Data("""