Commit 4f9a36c696
Unsigned
Layout: unified · split
App/Sources/SunScreen.swift +53 −11
| @@ -85,16 +85,19 @@ struct SunScreen: View { | ||
| 85 | 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 | 90 | private struct Picture { |
| 90 | 91 | var wavelength: SolarImage |
| 91 | 92 | var image: UIImage |
| 92 | 93 | var loaded: Date |
| 93 | 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. | |
| 97 | /// A fresh image of the same wavelength under 5 minutes old is kept. | |
| 98 | /// SDO sends no-store, so the last usable image of each wavelength is saved to Caches for use offline, dated with | |
| 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 | 101 | private func loadImage() async { |
| 99 | 102 | let w = wavelength |
| 100 | 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 | 105 | picture = nil |
| 103 | 106 | imageFailed = false |
| 104 | 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) { | |
| 106 | picture = Picture(wavelength: w, image: image, loaded: .now) | |
| 107 | try? FileManager.default.createDirectory(at: file.deletingLastPathComponent(), withIntermediateDirectories: true) | |
| 108 | try? data.write(to: file, options: .atomic) | |
| 108 | let http = response as? HTTPURLResponse, http.statusCode == 200, let image = UIImage(data: data) { | |
| 109 | if w.isUsable(data) { | |
| 110 | picture = Picture(wavelength: w, image: image, loaded: .now) | |
| 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 | 126 | return |
| 110 | 127 | } |
| 111 | 128 | guard !Task.isCancelled else { return } |
| 112 | if let image = UIImage(contentsOfFile: file.path(percentEncoded: false)) { | |
| 113 | let saved = (try? file.resourceValues(forKeys: [.contentModificationDateKey]))?.contentModificationDate | |
| 114 | picture = Picture(wavelength: w, image: image, loaded: .now, saved: saved ?? .distantPast) | |
| 129 | if let frame = savedFrame(file, w), let image = UIImage(data: frame.data) { | |
| 130 | picture = Picture(wavelength: w, image: image, loaded: .now, saved: frame.time) | |
| 115 | 131 | } else { |
| 116 | 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 | 160 | private var image: some View { |
| 121 | 161 | VStack(alignment: .leading, spacing: 4) { |
| 122 | 162 | Group { |
| @@ -131,8 +171,10 @@ struct SunScreen: View { | ||
| 131 | 171 | .aspectRatio(1, contentMode: .fit) |
| 132 | 172 | .accessibilityLabel("The Sun at \(wavelength.name)") |
| 133 | 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 | 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 @@ | ||
| 1 | import CoreGraphics | |
| 1 | 2 | import Foundation |
| 3 | import ImageIO | |
| 2 | 4 | |
| 3 | 5 | /// Latest full-disk images from NASA's Solar Dynamics Observatory. |
| 4 | 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 | 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. | |
| 109 | public struct SolarFrame: Sendable, Equatable { | |
| 110 | public var url: URL | |
| 111 | public var time: Date | |
| 37 | 112 | } |
| 38 | 113 | |
| 39 | 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 | 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 | ]) | |
| 59 | func 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 | 91 | @Test func ovationKeepsNonZeroCells() throws { |
| 51 | 92 | // Shape from ovation_aurora_latest.json on 2026-10-17. |
| 52 | 93 | let data = Data(""" |