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 e601dfc47e

e601dfc47ea28cbe9528d714cf7d5ac41c01a9e1

parent: c75305d4c5

Unsigned

cmc <hello@cleberg.net> · 2026-10-20 23:52 UTC

Observing conditions, phase 2: opt-in WeatherKit cloud forecasts (!69)

Cloud forecasts from WeatherKit, fetched on the device, off by default.

Settings
- "Cloud forecasts" toggle (off by default). The footer says a location rounded to about 10 km goes to Apple's weather service and links to the privacy policy (`#cloud-forecasts`). Turning it off deletes the cached forecast.
- While it is off nothing is requested and every screen shows what it shows on main.

Fetching (`Feeds/CloudForecast.swift`, `SkyModel.refreshForecast`)
- One `WeatherService.weather(for:including: .hourly(start, start + 240 h))` call at the location rounded to 0.1°, plus `WeatherService.attribution`. Stored as `SavedForecast` (cell, `CloudForecast`, mark and legal URLs) in `Caches/cloud-forecast.json`.
- At most once per cell per 3 h, from the Today bar's 10-minute loop and when the Today sheet opens. Nothing before a location fix or a chosen city. A forecast for another cell is not shown.

Rating (`SkyEngine/Conditions.swift`, unit-tested)
- Bright targets (passes, eclipses) use max(low, mid) cover, faint targets (tonight, meteor showers) total cover. Clear <= 30%, cloudy > 70%, or precipitation chance >= 50% or visibility < 2 km.
- Moments (pass peak, eclipse maximum): clear = go, partial = marginal, cloudy or wet = no.
- Windows: a good hour is clear and, for faint targets, has the Moon down or < 25% lit (any Moon-up time in the hour counts). Go: >= 2 h good, or >= half of a window under 2 h. Marginal: >= 1 h good, or >= 2 h clear but moonlit. Otherwise no. Moon data alone never gives go.
- No rating when the forecast is over 24 h old or the time is more than 72 h after it was issued; the cloud figure is still shown. No outlook at all unless the forecast covers the whole window.

Display
- Today sheet, Tonight: rating line ("GO  Clear 3:00–5:36"), the phase 1 Moon and darkness line, an hourly high/mid/low strip over the dark window with a Moon-up line, then the Apple Weather mark, "Other data sources" legal link and "Cloud forecast from 18:32". Rating and strip dim after 6 h.
- Visible satellite passes: " · 5% low and mid cloud" at peak; row dimmed when rated no.
- Events: rating line under meteor shower peaks (dark window of the peak night) and eclipses seen from here, within the forecast; mark and legal link under the filter when any are shown. `SkyEvent.window` added.

Attribution
- developer.apple.com/weatherkit/get-started: the Apple Weather mark and the legal link to other data sources wherever Apple weather data is shown. The mark is `combinedMarkDarkURL` (the white variant; all these screens are dark), loaded with `AsyncImage`, with "\u{F8FF}Weather" text as the placeholder. In night mode the mark stays white.

Other
- `com.apple.developer.weatherkit` on the Moonrise target only.
- `server/src/privacy.ts`: location is never sent to our server; new "Cloud forecasts" section. Needs a Worker deploy to go live.

Not covered: TodayBar summary line, eclipse screen line, daily summary, widgets, Watch, background refresh.

Layout: unified · split

App/Sources/CloudViews.swift added +100
@@ -0,0 +1,100 @@
1import Feeds
2import SkyEngine
3import SwiftUI
4
5/// The rating word, set like a section label, then its reason: "GO Clear 22:00–4:00".
6struct OutlookLine: View {
7 var outlook: Outlook
8
9 var body: some View {
10 HStack(alignment: .firstTextBaseline, spacing: 8) {
11 if let r = outlook.rating {
12 Text(r.rawValue).font(.caption.weight(.semibold)).textCase(.uppercase).tracking(0.8)
13 }
14 Text(outlook.reason)
15 }
16 .accessibilityElement(children: .combine)
17 }
18}
19
20/// Hourly high, mid and low cloud across `window`, darker for more cover, with the Moon's time up drawn beneath.
21struct CloudStrip: View {
22 var forecast: CloudForecast
23 var window: DateInterval
24 var moonUp: [DateInterval]
25 var ink: Color
26 private let row: CGFloat = 12
27
28 private var parts: [(hour: HourSample, span: DateInterval)] {
29 forecast.hours.compactMap { h in
30 guard let span = DateInterval(start: h.date, duration: 3600).intersection(with: window), span.duration > 0 else { return nil }
31 return (h, span)
32 }
33 }
34
35 var body: some View {
36 HStack(alignment: .top, spacing: 8) {
37 VStack(alignment: .trailing, spacing: 0) {
38 ForEach(["High", "Mid", "Low", "Moon"], id: \.self) { Text($0).frame(height: row) }
39 }
40 .font(.caption2).dimmed(0.6)
41 VStack(spacing: 2) {
42 Canvas { context, size in
43 let x = { (d: Date) in CGFloat(d.timeIntervalSince(window.start) / window.duration) * size.width }
44 for (i, cover) in [\HourSample.cloudHigh, \.cloudMid, \.cloudLow].enumerated() {
45 let y = CGFloat(i) * row + 2
46 context.fill(Path(CGRect(x: 0, y: y, width: size.width, height: row - 4)), with: .color(ink.opacity(0.1)))
47 for p in parts {
48 let r = CGRect(x: x(p.span.start), y: y, width: x(p.span.end) - x(p.span.start), height: row - 4)
49 context.fill(Path(r), with: .color(ink.opacity(p.hour[keyPath: cover])))
50 }
51 }
52 for p in parts where p.hour.date > window.start {
53 context.fill(Path(CGRect(x: x(p.hour.date), y: 0, width: 0.5, height: 3 * row)), with: .color(ink.opacity(0.4)))
54 }
55 for m in moonUp {
56 guard let up = m.intersection(with: window), up.duration > 0 else { continue }
57 context.fill(Path(CGRect(x: x(up.start), y: 3.5 * row - 0.5, width: x(up.end) - x(up.start), height: 1)), with: .color(ink))
58 }
59 }
60 .frame(height: 4 * row)
61 HStack {
62 Text(time(window.start))
63 Spacer()
64 Text(time(window.end))
65 }
66 .font(.caption2.monospacedDigit()).dimmed(0.6)
67 }
68 }
69 .accessibilityElement(children: .ignore)
70 .accessibilityLabel("Cloud by hour")
71 .accessibilityValue(parts.map { p in
72 "\(time(p.span.start)): low \(percent(p.hour.cloudLow)), mid \(percent(p.hour.cloudMid)), high \(percent(p.hour.cloudHigh))"
73 }.joined(separator: "; "))
74 }
75
76 private func time(_ d: Date) -> String { d.formatted(date: .omitted, time: .shortened) }
77 private func percent(_ x: Double) -> String { "\(Int((x * 100).rounded()))%" }
78}
79
80/// The Apple Weather mark and legal link that must accompany forecast data, with the time of the forecast.
81struct WeatherCreditLine: View {
82 var saved: SavedForecast
83
84 var body: some View {
85 VStack(alignment: .leading, spacing: 4) {
86 HStack(spacing: 10) {
87 AsyncImage(url: saved.credit.markURL) { image in
88 image.resizable().scaledToFit()
89 } placeholder: {
90 Text("\u{F8FF}Weather").font(.caption2)
91 }
92 .frame(height: 12)
93 .accessibilityLabel("Apple Weather")
94 Link("Other data sources", destination: saved.credit.legalURL).font(.caption2).underline()
95 }
96 Text("Cloud forecast from \(saved.forecast.fetched.formatted(Calendar.current.isDateInToday(saved.forecast.fetched) ? .dateTime.hour().minute() : .dateTime.weekday(.abbreviated).hour().minute())).")
97 .font(.caption2).dimmed(0.6)
98 }
99 }
100}
App/Sources/EventsScreen.swift +16 −2
@@ -1,3 +1,4 @@
1import Feeds
12import SkyEngine
23import SwiftUI
34
@@ -5,7 +6,11 @@ import SwiftUI
56struct EventsScreen: View {
67 var observer: Observer
78 var placeName: String
9 /// Cloud forecast, when cloud forecasts are on.
10 var forecast: SavedForecast?
811 @State private var events: [SkyEvent] = []
12 /// Cloud and rating for meteor shower peaks and eclipses within the forecast, by event id.
13 @State private var outlooks: [String: Outlook] = [:]
914 @State private var filter = "notable"
1015 @State private var eclipse: SkyEvent?
1116 @Environment(\.dismiss) private var dismiss
@@ -36,6 +41,7 @@ struct EventsScreen: View {
3641 }
3742 .pickerStyle(.segmented)
3843 .padding(.vertical, 16)
44 if let forecast, !outlooks.isEmpty { WeatherCreditLine(saved: forecast).padding(.bottom, 4) }
3945
4046 if events.isEmpty {
4147 ProgressView().tint(ink).frame(maxWidth: .infinity).padding(.top, 40)
@@ -72,8 +78,15 @@ struct EventsScreen: View {
7278 .foregroundStyle(ink)
7379 .tint(accent)
7480 .task {
75 let observer = observer
76 events = await Task.detached { SkyEngine.events(from: .now, observer: observer) }.value
81 let observer = observer, forecast = forecast?.forecast
82 (events, outlooks) = await Task.detached {
83 let events = SkyEngine.events(from: .now, observer: observer)
84 var outlooks: [String: Outlook] = [:]
85 if let forecast {
86 for e in events { outlooks[e.id] = try? SkyEngine.outlook(for: e, forecast: forecast, observer: observer, now: .now) }
87 }
88 return (events, outlooks)
89 }.value
7790 }
7891 }
7992
@@ -92,6 +105,7 @@ struct EventsScreen: View {
92105 }
93106 Text(e.date.formatted(date: .omitted, time: .shortened)).font(.footnote.monospacedDigit()).foregroundStyle(ink.opacity(0.6))
94107 if !e.detail.isEmpty { Text(e.detail).font(.footnote).foregroundStyle(ink.opacity(0.8)) }
108 if let o = outlooks[e.id] { OutlookLine(outlook: o).font(.footnote.monospacedDigit()) }
95109 if let v = e.visibleHere {
96110 HStack(spacing: 5) {
97111 Circle().fill(v ? accent : ink.opacity(0.35)).frame(width: 6, height: 6)
App/Sources/Moonrise.entitlements +2
@@ -4,5 +4,7 @@
44<dict>
55 <key>aps-environment</key>
66 <string>development</string>
7 <key>com.apple.developer.weatherkit</key>
8 <true/>
79</dict>
810</plist>
App/Sources/SettingsScreen.swift +10
@@ -1,3 +1,4 @@
1import Feeds
12import Library
23import SkyRenderer
34import SwiftUI
@@ -20,6 +21,8 @@ enum SettingsKey {
2021 static let dailySummaryMinutes = "dailySummaryMinutes"
2122 /// Messier objects on the sky chart.
2223 static let showDeepSky = "showDeepSky"
24 /// Cloud forecasts from Apple Weather; off unless turned on.
25 static let cloudForecast = "cloudForecast"
2326}
2427
2528struct City: Hashable, Identifiable {
@@ -74,6 +77,7 @@ struct SettingsScreen: View {
7477 @AppStorage(SettingsKey.dailySummary) private var dailySummary = false
7578 @AppStorage(SettingsKey.dailySummaryMinutes) private var dailySummaryMinutes = DailySummaryNotifications.defaultMinutes
7679 @State private var summaryStatus: String?
80 @AppStorage(SettingsKey.cloudForecast) private var cloudForecast = false
7781 var onChange: () -> Void
7882
7983 var body: some View {
@@ -124,6 +128,11 @@ struct SettingsScreen: View {
124128 } footer: {
125129 Text("A note each day with the Moon, the planets up that night, the best satellite pass and any events. It is worked out on this device; nothing is sent to our server.")
126130 }
131 Section {
132 Toggle("Cloud forecasts", isOn: $cloudForecast)
133 } footer: {
134 Text(LocalizedStringKey("Shows cloud for tonight, satellite passes and events. To get the forecast, Moonrise sends Apple's weather service your location rounded to about 10 km. [Privacy policy](\(privacyPolicyURL.absoluteString)#cloud-forecasts)"))
135 }
127136 Section {
128137 Picker("Constellations", selection: $skyCulture) {
129138 Text("Western (IAU)").tag("western")
@@ -167,6 +176,7 @@ struct SettingsScreen: View {
167176 onChange()
168177 }
169178 .onChange(of: locationMode) { onChange() }
179 .onChange(of: cloudForecast) { if !cloudForecast { SavedForecast.delete() } }
170180 }
171181 }
172182
App/Sources/SkyModel.swift +25
@@ -58,6 +58,8 @@ final class SkyModel: NSObject, CLLocationManagerDelegate {
5858 private var elementsFetched: Date?
5959 private var passesComputed: (at: Date, observer: Observer, elementsFetched: Date?)?
6060 private var weatherFetched: Date?
61 private var savedForecast: SavedForecast?
62 private var fetchingForecast = false
6163 /// Hours from now shown by the time scrubber.
6264 var offsetHours = 0.0 { didSet { refresh() } }
6365 /// Year shown instead of this one (astronomical numbering: 0 is 1 BCE), or nil for now.
@@ -181,6 +183,29 @@ final class SkyModel: NSObject, CLLocationManagerDelegate {
181183 }
182184 }
183185
186 /// The cloud forecast for the current place, while cloud forecasts are turned on.
187 var forecast: SavedForecast? {
188 guard UserDefaults.standard.bool(forKey: SettingsKey.cloudForecast), let f = savedForecast, f.isFor(observer) else { return nil }
189 return f
190 }
191
192 /// Apple Weather for the rounded place, at most once every three hours, and only while cloud forecasts are on.
193 func refreshForecast() async {
194 guard UserDefaults.standard.bool(forKey: SettingsKey.cloudForecast) else { savedForecast = nil; return }
195 if savedForecast == nil { savedForecast = SavedForecast.load() }
196 if let f = savedForecast, f.isFor(observer), Date.now.timeIntervalSince(f.forecast.fetched) < 3 * 3600 { return }
197 guard hasLocation, !fetchingForecast else { return }
198 fetchingForecast = true
199 defer { fetchingForecast = false }
200 do {
201 let f = try await SavedForecast.fetch(for: observer)
202 savedForecast = f
203 try f.save()
204 } catch {
205 log.error("Cloud forecast failed: \(error.localizedDescription, privacy: .public)")
206 }
207 }
208
184209 func details(of body: Body) async -> BodyDetails? {
185210 try? await astronomer.details(of: body, at: displayedDate, from: observer)
186211 }
App/Sources/SkyScreen.swift +1 −1
@@ -94,7 +94,7 @@ struct SkyScreen: View {
9494 ObservationEditor(observation: o) {}.preferredColorScheme(.dark).tint(.blue)
9595 }
9696 .sheet(isPresented: $showEvents) {
97 EventsScreen(observer: model.observer, placeName: model.placeName)
97 EventsScreen(observer: model.observer, placeName: model.placeName, forecast: model.forecast)
9898 .preferredColorScheme(.dark)
9999 }
100100 .sheet(isPresented: $showTours) {
App/Sources/TodaySheet.swift +35 −4
@@ -12,7 +12,7 @@ struct TodaySheet: View {
1212 ScrollView {
1313 VStack(alignment: .leading, spacing: 0) {
1414 if let t = model.tonight {
15 section("Tonight") { Text(t.moonAndDarkness()).font(.subheadline.monospacedDigit()) }
15 section("Tonight") { tonight(t) }
1616 section("Moon") { moon(t) }
1717 section("Planets tonight") { planets(t) }
1818 section("Sun") { sun(t) }
@@ -28,6 +28,7 @@ struct TodaySheet: View {
2828 .foregroundStyle(ink)
2929 .presentationBackground(background)
3030 .task { await model.refreshPasses() }
31 .task { await model.refreshForecast() }
3132 }
3233
3334 private func section(_ title: String, @ViewBuilder content: () -> some View) -> some View {
@@ -40,6 +41,31 @@ struct TodaySheet: View {
4041 .overlay(alignment: .top) { Rectangle().fill(ink.opacity(0.25)).frame(height: 0.5) }
4142 }
4243
44 /// The rating and cloud strip, when cloud forecasts are on, around the Moon and darkness line.
45 private func tonight(_ t: Tonight) -> some View {
46 let night = t.dark ?? DateInterval(start: t.start, end: t.end)
47 let saved = model.forecast
48 let stale = saved?.forecast.isStale(now: .now) ?? false
49 return VStack(alignment: .leading, spacing: 8) {
50 if let saved, let o = saved.forecast.outlook(over: night, target: .faint, moonUp: t.moonUp, moonIllumination: t.moonIllumination, now: .now) {
51 OutlookLine(outlook: o).font(.subheadline.monospacedDigit()).dimmed(stale ? 0.6 : 1)
52 }
53 Text(t.moonAndDarkness()).font(.subheadline.monospacedDigit())
54 if let saved {
55 if saved.forecast.hour(at: night.start) != nil {
56 CloudStrip(forecast: saved.forecast, window: night, moonUp: t.moonUp, ink: ink).dimmed(stale ? 0.6 : 1)
57 }
58 WeatherCreditLine(saved: saved)
59 }
60 }
61 }
62
63 /// "20% low and mid cloud" at a visible pass's peak; nil without a forecast, or before the Tonight section and its credit show.
64 private func cloudAtPeak(_ p: SatellitePass) -> Outlook? {
65 guard p.visible, model.tonight != nil else { return nil }
66 return model.forecast?.forecast.outlook(at: p.peak, target: .bright, now: .now)
67 }
68
4369 private func moon(_ t: Tonight) -> some View {
4470 let quarter = switch t.nextQuarter.quarter {
4571 case .new: "New moon"
@@ -88,6 +114,7 @@ struct TodaySheet: View {
88114 } else {
89115 VStack(alignment: .leading, spacing: 10) {
90116 ForEach(Array(shown)) { p in
117 let cloud = cloudAtPeak(p)
91118 VStack(alignment: .leading, spacing: 2) {
92119 HStack {
93120 Text(p.displayName).font(.subheadline.weight(.medium))
@@ -97,9 +124,10 @@ struct TodaySheet: View {
97124 }
98125 }
99126 Text(p.rise.formatted(.dateTime.weekday(.abbreviated).hour().minute()) + String(format: " · rises %@, highest %.0f°, sets %@", compass(p.riseAzimuth), p.maxAltitude, compass(p.setAzimuth))
100 + (p.moonNote(from: model.observer).map { " · \($0)" } ?? ""))
127 + (p.moonNote(from: model.observer).map { " · \($0)" } ?? "") + (cloud.map { " · \($0.reason)" } ?? ""))
101128 .font(.footnote.monospacedDigit()).dimmed(0.8)
102129 }
130 .dimmed(cloud?.rating == .no ? 0.5 : 1)
103131 .accessibilityElement(children: .combine)
104132 .frame(maxWidth: .infinity, alignment: .leading)
105133 .padding(.trailing, 44)
@@ -109,8 +137,10 @@ struct TodaySheet: View {
109137 if !others.isEmpty {
110138 Text("Also visible tonight").font(.caption2.weight(.medium)).textCase(.uppercase).tracking(0.8).dimmed(0.6).padding(.top, 6)
111139 ForEach(others) { p in
112 Text("\(p.displayName) · \(p.rise.formatted(date: .omitted, time: .shortened)), highest \(Int(p.maxAltitude.rounded()))°" + (p.moonNote(from: model.observer).map { " · \($0)" } ?? ""))
113 .font(.footnote.monospacedDigit()).dimmed(0.8)
140 let cloud = cloudAtPeak(p)
141 Text("\(p.displayName) · \(p.rise.formatted(date: .omitted, time: .shortened)), highest \(Int(p.maxAltitude.rounded()))°" + (p.moonNote(from: model.observer).map { " · \($0)" } ?? "")
142 + (cloud.map { " · \($0.reason)" } ?? ""))
143 .font(.footnote.monospacedDigit()).dimmed(cloud?.rating == .no ? 0.4 : 0.8)
114144 }
115145 }
116146 Text("Visible means sunlit while your sky is dark. Orbits: CelesTrak.").font(.caption2).dimmed(0.6)
@@ -188,6 +218,7 @@ struct TodayBar: View {
188218 .task {
189219 while !Task.isCancelled {
190220 await model.refreshSpaceWeather()
221 await model.refreshForecast()
191222 try? await Task.sleep(for: .seconds(600))
192223 }
193224 }
App/project.yml +1
@@ -38,6 +38,7 @@ targets:
3838 path: Sources/Moonrise.entitlements
3939 properties:
4040 aps-environment: development
41 com.apple.developer.weatherkit: true
4142 info:
4243 path: Sources/Info.plist
4344 properties:
Packages/MoonriseKit/Sources/Feeds/CloudForecast.swift added +59
@@ -0,0 +1,59 @@
1import CoreLocation
2import Foundation
3import SkyEngine
4import WeatherKit
5
6/// The Apple Weather mark and legal page, which WeatherKit's terms require wherever its data is shown.
7public struct WeatherCredit: Sendable, Codable, Equatable {
8 /// The combined mark in its dark variant, a white mark for dark backgrounds.
9 public var markURL: URL
10 public var legalURL: URL
11}
12
13/// A cloud forecast from Apple Weather for one rounded place, as kept on disk.
14public struct SavedForecast: Sendable, Codable, Equatable {
15 public var latitude: Double
16 public var longitude: Double
17 public var forecast: CloudForecast
18 public var credit: WeatherCredit
19
20 /// The location sent to Apple: rounded to 0.1°, about 11 km north–south.
21 public static func cell(_ observer: Observer) -> (latitude: Double, longitude: Double) {
22 ((observer.latitude * 10).rounded() / 10, (observer.longitude * 10).rounded() / 10)
23 }
24
25 public func isFor(_ observer: Observer) -> Bool {
26 let c = Self.cell(observer)
27 return c.latitude == latitude && c.longitude == longitude
28 }
29
30 public static let file = URL.cachesDirectory.appending(path: "cloud-forecast.json")
31
32 public static func load(from url: URL = file) -> SavedForecast? {
33 (try? Data(contentsOf: url)).flatMap { try? JSONDecoder().decode(SavedForecast.self, from: $0) }
34 }
35
36 public func save(to url: URL = file) throws {
37 try JSONEncoder().encode(self).write(to: url, options: .atomic)
38 }
39
40 public static func delete(at url: URL = file) {
41 try? FileManager.default.removeItem(at: url)
42 }
43
44 /// Ten days of hourly cloud for the observer's rounded location. One WeatherKit call, plus the attribution.
45 public static func fetch(for observer: Observer, now: Date = .now) async throws -> SavedForecast {
46 let c = cell(observer)
47 let start = Calendar(identifier: .gregorian).dateInterval(of: .hour, for: now)?.start ?? now
48 let service = WeatherService.shared
49 let hourly = try await service.weather(for: CLLocation(latitude: c.latitude, longitude: c.longitude),
50 including: .hourly(startDate: start, endDate: start.addingTimeInterval(240 * 3600)))
51 let attribution = try await service.attribution
52 let hours = hourly.forecast.map { h in
53 HourSample(date: h.date, cloudLow: h.cloudCoverByAltitude.low, cloudMid: h.cloudCoverByAltitude.medium, cloudHigh: h.cloudCoverByAltitude.high,
54 cloudTotal: h.cloudCover, precipitationChance: h.precipitationChance, visibility: h.visibility.converted(to: .meters).value)
55 }
56 return SavedForecast(latitude: c.latitude, longitude: c.longitude, forecast: CloudForecast(fetched: now, hours: hours),
57 credit: WeatherCredit(markURL: attribution.combinedMarkDarkURL, legalURL: attribution.legalPageURL))
58 }
59}
Packages/MoonriseKit/Sources/SkyEngine/Conditions.swift added +158
@@ -0,0 +1,158 @@
1import Foundation
2
3/// One hour of a weather forecast, from `date` to an hour later. Cover and chance run from 0 to 1.
4public struct HourSample: Sendable, Codable, Equatable {
5 public var date: Date
6 public var cloudLow: Double
7 public var cloudMid: Double
8 public var cloudHigh: Double
9 public var cloudTotal: Double
10 public var precipitationChance: Double
11 /// Metres.
12 public var visibility: Double
13
14 public init(date: Date, cloudLow: Double, cloudMid: Double, cloudHigh: Double, cloudTotal: Double, precipitationChance: Double, visibility: Double) {
15 self.date = date
16 self.cloudLow = cloudLow
17 self.cloudMid = cloudMid
18 self.cloudHigh = cloudHigh
19 self.cloudTotal = cloudTotal
20 self.precipitationChance = precipitationChance
21 self.visibility = visibility
22 }
23
24 /// Bright targets show through thin high cloud, so only low and mid cloud count for them.
25 public func cover(for target: SkyTarget) -> Double {
26 target == .bright ? max(cloudLow, cloudMid) : cloudTotal
27 }
28
29 var wet: Bool { precipitationChance >= CloudForecast.wetChance || visibility < CloudForecast.fogVisibility }
30
31 func clear(for target: SkyTarget) -> Bool { !wet && cover(for: target) <= CloudForecast.clearCover }
32 func cloudy(for target: SkyTarget) -> Bool { wet || cover(for: target) > CloudForecast.cloudyCover }
33}
34
35/// Satellites, planets, the Moon and eclipses are bright; meteors and deep-sky objects are faint and need a dark, clear sky.
36public enum SkyTarget: Sendable {
37 case bright, faint
38}
39
40public enum Rating: String, Sendable {
41 case go, marginal, no
42}
43
44/// What the forecast says about a time or window: a rating where the forecast is good enough for one, and the reason.
45public struct Outlook: Sendable, Equatable {
46 public var rating: Rating?
47 /// "Clear 22:00–04:00", "90% cloud", "Rain or fog likely".
48 public var reason: String
49}
50
51/// Hourly cloud for one place, as fetched at `fetched`.
52public struct CloudForecast: Sendable, Codable, Equatable {
53 public var fetched: Date
54 public var hours: [HourSample]
55
56 public init(fetched: Date, hours: [HourSample]) {
57 self.fetched = fetched
58 self.hours = hours
59 }
60
61 /// Hour states, at roughly the 2- and 6-okta marks.
62 static let clearCover = 0.3
63 static let cloudyCover = 0.7
64 static let wetChance = 0.5
65 static let fogVisibility = 2000.0
66 /// Ratings only for times this close to the forecast's issue, and from a forecast no older than `maxAge`.
67 static let maxLead: TimeInterval = 72 * 3600
68 static let maxAge: TimeInterval = 24 * 3600
69 /// Older than this, forecast figures are shown dimmed with the time they are from.
70 public static let staleAge: TimeInterval = 6 * 3600
71
72 public func isStale(now: Date) -> Bool { now.timeIntervalSince(fetched) > Self.staleAge }
73
74 public func hour(at date: Date) -> HourSample? {
75 hours.first { $0.date <= date && date < $0.date.addingTimeInterval(3600) }
76 }
77
78 private func ratable(until end: Date, now: Date) -> Bool {
79 now.timeIntervalSince(fetched) <= Self.maxAge && end.timeIntervalSince(fetched) <= Self.maxLead
80 }
81
82 /// Cloud at a moment, such as a satellite pass or an eclipse's maximum; nil outside the forecast.
83 public func outlook(at date: Date, target: SkyTarget, now: Date) -> Outlook? {
84 guard let h = hour(at: date) else { return nil }
85 let figure = "\(percent(h.cover(for: target)))% \(target == .bright ? "low and mid cloud" : "cloud")"
86 guard ratable(until: date, now: now) else { return Outlook(rating: nil, reason: figure) }
87 if h.wet { return Outlook(rating: .no, reason: "Rain or fog likely") }
88 return Outlook(rating: h.clear(for: target) ? .go : h.cloudy(for: target) ? .no : .marginal, reason: figure)
89 }
90
91 /// Cloud and moonlight through a window such as the dark part of a night; nil unless the forecast covers all of it.
92 /// A good hour is clear and, for faint targets, has the Moon down or under `SkyEngine.moonlightLimit` lit.
93 /// Go takes two good hours, or half of a window shorter than two; marginal takes one good hour or two clear, moonlit ones.
94 public func outlook(over window: DateInterval, target: SkyTarget, moonUp: [DateInterval], moonIllumination: Double, now: Date,
95 time: Date.FormatStyle = .init(date: .omitted, time: .shortened)) -> Outlook? {
96 let parts = hours.compactMap { h -> (hour: HourSample, span: DateInterval)? in
97 guard let span = DateInterval(start: h.date, duration: 3600).intersection(with: window), span.duration > 0 else { return nil }
98 return (h, span)
99 }
100 guard !parts.isEmpty, parts.reduce(0, { $0 + $1.span.duration }) >= window.duration - 60 else { return nil }
101
102 let covers = parts.map { percent($0.hour.cover(for: target)) }
103 let lo = covers.min()!, hi = covers.max()!
104 let figure = lo == hi ? "\(lo)% cloud" : "\(lo)–\(hi)% cloud"
105 guard ratable(until: window.end, now: now) else { return Outlook(rating: nil, reason: figure) }
106
107 let moonlight = target == .faint && moonIllumination >= SkyEngine.moonlightLimit
108 func moonlit(_ span: DateInterval) -> Bool { moonlight && moonUp.contains { ($0.intersection(with: span)?.duration ?? 0) > 0 } }
109 let good = parts.filter { $0.hour.clear(for: target) && !moonlit($0.span) }.map(\.span)
110 let goodTime = good.reduce(0) { $0 + $1.duration }
111 let litTime = parts.filter { $0.hour.clear(for: target) && moonlit($0.span) }.reduce(0) { $0 + $1.span.duration }
112 let wetTime = parts.filter { $0.hour.wet }.reduce(0) { $0 + $1.span.duration }
113 let cloudTime = window.duration - goodTime - litTime - wetTime
114
115 // The longest run of good hours.
116 var runs: [DateInterval] = []
117 for g in good {
118 if let last = runs.last, last.end == g.start { runs[runs.count - 1] = DateInterval(start: last.start, end: g.end) } else { runs.append(g) }
119 }
120 let run = runs.max { $0.duration < $1.duration }
121 let clearText = run.map { $0 == window ? "Clear throughout" : "Clear \($0.start.formatted(time))–\($0.end.formatted(time))" }
122
123 // What spoiled the rest of the window.
124 let otherwise = [(cloudTime, "cloudy"), (litTime, "moonlit"), (wetTime, "rain or fog")].max { $0.0 < $1.0 }!
125 if goodTime >= 2 * 3600 || (window.duration < 2 * 3600 && goodTime >= window.duration / 2) {
126 return Outlook(rating: .go, reason: clearText!)
127 }
128 if goodTime >= 3600 {
129 return Outlook(rating: .marginal, reason: "\(clearText!), \(otherwise.1) otherwise")
130 }
131 if litTime >= 2 * 3600 {
132 return Outlook(rating: .marginal, reason: "Clear but moonlit")
133 }
134 if otherwise.0 == wetTime { return Outlook(rating: .no, reason: "Rain or fog likely") }
135 if otherwise.0 == litTime { return Outlook(rating: .no, reason: "Too little clear, dark sky") }
136 return Outlook(rating: .no, reason: figure)
137 }
138
139 private func percent(_ x: Double) -> Int { Int((x * 100).rounded()) }
140}
141
142extension SkyEngine {
143 /// The forecast for a meteor shower's peak night or an eclipse seen from here; nil for other events or outside the forecast.
144 public static func outlook(for event: SkyEvent, forecast: CloudForecast, observer: Observer, now: Date) throws -> Outlook? {
145 guard let w = event.window else { return nil }
146 switch event.kind {
147 case .meteorShower:
148 guard forecast.hour(at: w.start) != nil, forecast.hour(at: w.end.addingTimeInterval(-1)) != nil else { return nil }
149 let moon = try moonUp(from: w.start, to: w.end, observer: observer)
150 let lit = try illumination(.moon, at: w.start + w.duration / 2).phaseFraction
151 return forecast.outlook(over: w, target: .faint, moonUp: moon, moonIllumination: lit, now: now)
152 case .lunarEclipse, .solarEclipse:
153 return forecast.outlook(at: w.start, target: .bright, now: now)
154 default:
155 return nil
156 }
157 }
158}
Packages/MoonriseKit/Sources/SkyEngine/Events.swift +11 −4
@@ -12,6 +12,9 @@ public struct SkyEvent: Sendable, Identifiable, Equatable {
1212 public var detail: String
1313 /// Whether it can be seen from the observer's location; nil when that does not apply.
1414 public var visibleHere: Bool?
15 /// When to look, for a forecast: the dark part of a meteor shower's peak night (the whole night where it never gets
16 /// fully dark), or greatest eclipse here as a zero-length interval. Nil for other events and eclipses not seen here.
17 public var window: DateInterval?
1518 public var id: String { "\(kind.rawValue)-\(title)-\(Int(date.timeIntervalSince1970))" }
1619}
1720
@@ -75,7 +78,8 @@ extension SkyEngine {
7578 let alt = Astronomy_Horizon(&peak, observer.astro, moon.ra, moon.dec, REFRACTION_NORMAL).altitude
7679 let minutes = lunar.sd_total > 0 ? lunar.sd_total * 2 : lunar.sd_partial * 2
7780 let length = minutes > 0 ? String(format: " %@ phase lasts %.0f minutes.", lunar.sd_total > 0 ? "Total" : "Partial", minutes) : ""
78 out.append(SkyEvent(kind: .lunarEclipse, date: date(lunar.peak), title: "\(eclipseKind(lunar.kind)) lunar eclipse", detail: (alt > 0 ? "The Moon is up here at mid-eclipse." : "The Moon is below the horizon here at mid-eclipse.") + length, visibleHere: alt > 0))
81 out.append(SkyEvent(kind: .lunarEclipse, date: date(lunar.peak), title: "\(eclipseKind(lunar.kind)) lunar eclipse", detail: (alt > 0 ? "The Moon is up here at mid-eclipse." : "The Moon is below the horizon here at mid-eclipse.") + length, visibleHere: alt > 0,
82 window: alt > 0 ? DateInterval(start: date(lunar.peak), duration: 0) : nil))
7983 lunar = Astronomy_NextLunarEclipse(lunar.peak)
8084 }
8185
@@ -92,8 +96,10 @@ extension SkyEngine {
9296 let here = local.first { abs($0.key.timeIntervalSince(peakDate)) < 6 * 3600 }?.value
9397 var detail: String
9498 var visible = false
99 var window: DateInterval?
95100 if let here, here.peak.altitude > 0 {
96101 visible = true
102 window = DateInterval(start: date(here.peak.time), duration: 0)
97103 detail = String(format: "From here: %@, %.0f%% of the Sun covered at %@.", eclipseKind(here.kind).lowercased(), here.obscuration * 100, date(here.peak.time).formatted(date: .omitted, time: .shortened))
98104 } else {
99105 detail = "Not visible from here."
@@ -101,7 +107,7 @@ extension SkyEngine {
101107 if solar.kind == ECLIPSE_TOTAL || solar.kind == ECLIPSE_ANNULAR {
102108 detail += String(format: " Greatest eclipse at %.1f°%@, %.1f°%@.", abs(solar.latitude), solar.latitude >= 0 ? "N" : "S", abs(solar.longitude), solar.longitude >= 0 ? "E" : "W")
103109 }
104 out.append(SkyEvent(kind: .solarEclipse, date: peakDate, title: "\(eclipseKind(solar.kind)) solar eclipse", detail: detail, visibleHere: visible))
110 out.append(SkyEvent(kind: .solarEclipse, date: peakDate, title: "\(eclipseKind(solar.kind)) solar eclipse", detail: detail, visibleHere: visible, window: window))
105111 solar = Astronomy_NextGlobalSolarEclipse(solar.peak)
106112 }
107113
@@ -148,9 +154,10 @@ extension SkyEngine {
148154 let noon = midnight.addingTimeInterval(-12 * 3600)
149155 let sunset = riseSet(.sun, after: noon, from: observer).set ?? noon
150156 let night = DateInterval(start: sunset, end: riseSet(.sun, after: sunset, from: observer).rise ?? sunset.addingTimeInterval(12 * 3600))
151 let moon = moonAndDarkness(night: night, dark: try? darkness(from: night.start, to: night.end, observer: observer),
157 let dark = try? darkness(from: night.start, to: night.end, observer: observer)
158 let moon = moonAndDarkness(night: night, dark: dark,
152159 moonUp: (try? moonUp(from: night.start, to: night.end, observer: observer)) ?? [], moonIllumination: lit)
153 out.append(SkyEvent(kind: .meteorShower, date: d, title: "\(m.name) peak", detail: "Up to about \(m.zhr) meteors an hour under dark skies. \(moon)", visibleHere: nil))
160 out.append(SkyEvent(kind: .meteorShower, date: d, title: "\(m.name) peak", detail: "Up to about \(m.zhr) meteors an hour under dark skies. \(moon)", visibleHere: nil, window: dark ?? night))
154161 }
155162 }
156163
Packages/MoonriseKit/Tests/FeedsTests/CloudForecastTests.swift added +25
@@ -0,0 +1,25 @@
1import Foundation
2import SkyEngine
3import Testing
4@testable import Feeds
5
6@Test func locationIsRoundedToATenthOfADegree() {
7 let c = SavedForecast.cell(Observer(latitude: 41.8781, longitude: -87.6298))
8 #expect(c.latitude == 41.9)
9 #expect(c.longitude == -87.6)
10}
11
12@Test func savedForecastRoundTripsAndMatchesItsCell() throws {
13 let hour = HourSample(date: Date(timeIntervalSince1970: 1_792_202_400), cloudLow: 0.1, cloudMid: 0.2, cloudHigh: 0.6, cloudTotal: 0.7,
14 precipitationChance: 0.05, visibility: 24_000)
15 let saved = SavedForecast(latitude: 41.9, longitude: -87.6, forecast: CloudForecast(fetched: hour.date, hours: [hour]),
16 credit: WeatherCredit(markURL: URL(string: "https://example.com/mark.png")!, legalURL: URL(string: "https://example.com/legal")!))
17 let url = URL.temporaryDirectory.appending(path: "cloud-forecast-\(UUID()).json")
18 defer { SavedForecast.delete(at: url) }
19 try saved.save(to: url)
20 #expect(SavedForecast.load(from: url) == saved)
21 #expect(saved.isFor(Observer(latitude: 41.88, longitude: -87.63)))
22 #expect(!saved.isFor(Observer(latitude: 42.0, longitude: -87.63)))
23 SavedForecast.delete(at: url)
24 #expect(SavedForecast.load(from: url) == nil)
25}
Packages/MoonriseKit/Tests/SkyEngineTests/ConditionsTests.swift added +99
@@ -0,0 +1,99 @@
1import Foundation
2import Testing
3@testable import SkyEngine
4
5private let utcTime = Date.FormatStyle(date: .omitted, time: .shortened, locale: Locale(identifier: "en_GB"), timeZone: TimeZone(identifier: "UTC")!)
6private let fetched = utc("2026-10-20T12:00:00Z")
7private let dusk = utc("2026-10-21T00:00:00Z")
8
9/// Hourly samples from `dusk`, one total cover per hour; low cloud equals total unless `high` is set.
10private func forecast(_ covers: [Double], high: Bool = false, rain: Set<Int> = [], from start: Date = dusk) -> CloudForecast {
11 CloudForecast(fetched: fetched, hours: covers.enumerated().map { i, c in
12 HourSample(date: start.addingTimeInterval(Double(i) * 3600), cloudLow: high ? 0 : c, cloudMid: 0, cloudHigh: high ? c : 0,
13 cloudTotal: c, precipitationChance: rain.contains(i) ? 0.8 : 0, visibility: 20_000)
14 })
15}
16
17private func night(_ hours: Double) -> DateInterval { DateInterval(start: dusk, duration: hours * 3600) }
18
19@Test func clearMoonlessNightIsGo() {
20 let o = forecast([0.1, 0, 0.2, 0.1]).outlook(over: night(4), target: .faint, moonUp: [], moonIllumination: 0.9, now: fetched, time: utcTime)
21 #expect(o == Outlook(rating: .go, reason: "Clear throughout"))
22}
23
24@Test func overcastNightIsNo() {
25 let o = forecast([0.9, 1, 0.95]).outlook(over: night(3), target: .faint, moonUp: [], moonIllumination: 0, now: fetched, time: utcTime)
26 #expect(o == Outlook(rating: .no, reason: "90–100% cloud"))
27}
28
29@Test func moonlightAloneNeverMakesGo() {
30 // Clear all night with a 90% Moon up throughout: moonlit, so marginal, not go.
31 let o = forecast([0, 0, 0, 0]).outlook(over: night(4), target: .faint, moonUp: [night(4)], moonIllumination: 0.9, now: fetched, time: utcTime)
32 #expect(o == Outlook(rating: .marginal, reason: "Clear but moonlit"))
33}
34
35@Test func clearAfterMoonsetIsGo() {
36 let moon = DateInterval(start: dusk, duration: 2 * 3600)
37 let o = forecast([0, 0, 0, 0, 0]).outlook(over: night(5), target: .faint, moonUp: [moon], moonIllumination: 0.6, now: fetched, time: utcTime)
38 #expect(o == Outlook(rating: .go, reason: "Clear 2:00–5:00"))
39}
40
41@Test func oneGoodHourIsMarginal() {
42 let o = forecast([0.9, 0.1, 0.9, 0.8]).outlook(over: night(4), target: .faint, moonUp: [], moonIllumination: 0, now: fetched, time: utcTime)
43 #expect(o == Outlook(rating: .marginal, reason: "Clear 1:00–2:00, cloudy otherwise"))
44}
45
46@Test func partialCloudIsNotClear() {
47 let o = forecast([0.5, 0.5, 0.5]).outlook(over: night(3), target: .faint, moonUp: [], moonIllumination: 0, now: fetched, time: utcTime)
48 #expect(o?.rating == Rating.no)
49}
50
51@Test func rainOutweighsClearSky() {
52 let o = forecast([0, 0, 0], rain: [0, 1, 2]).outlook(over: night(3), target: .faint, moonUp: [], moonIllumination: 0, now: fetched, time: utcTime)
53 #expect(o == Outlook(rating: .no, reason: "Rain or fog likely"))
54}
55
56@Test func shortDarknessNeedsHalfOfIt() {
57 let o = forecast([0, 0.9]).outlook(over: night(1.5), target: .faint, moonUp: [], moonIllumination: 0, now: fetched, time: utcTime)
58 #expect(o?.rating == Rating.go)
59}
60
61@Test func noOutlookWhereTheForecastStops() {
62 #expect(forecast([0, 0]).outlook(over: night(3), target: .faint, moonUp: [], moonIllumination: 0, now: fetched) == nil)
63 #expect(forecast([0, 0]).outlook(at: dusk.addingTimeInterval(3 * 3600), target: .bright, now: fetched) == nil)
64}
65
66@Test func noRatingBeyond72Hours() {
67 let start = fetched.addingTimeInterval(80 * 3600)
68 let f = forecast([0.2, 0.4], from: start)
69 let o = f.outlook(over: DateInterval(start: start, duration: 2 * 3600), target: .faint, moonUp: [], moonIllumination: 0, now: fetched)
70 #expect(o == Outlook(rating: nil, reason: "20–40% cloud"))
71 #expect(f.outlook(at: start, target: .faint, now: fetched) == Outlook(rating: nil, reason: "20% cloud"))
72}
73
74@Test func noRatingFromAForecastOverADayOld() {
75 let o = forecast([0, 0, 0]).outlook(over: night(3), target: .faint, moonUp: [], moonIllumination: 0, now: fetched.addingTimeInterval(25 * 3600))
76 #expect(o == Outlook(rating: nil, reason: "0% cloud"))
77 #expect(!forecast([]).isStale(now: fetched.addingTimeInterval(6 * 3600)))
78 #expect(forecast([]).isStale(now: fetched.addingTimeInterval(6 * 3600 + 1)))
79}
80
81@Test func brightTargetsIgnoreHighCloud() {
82 let f = forecast([0.9], high: true)
83 let pass = dusk.addingTimeInterval(1200)
84 #expect(f.outlook(at: pass, target: .bright, now: fetched) == Outlook(rating: .go, reason: "0% low and mid cloud"))
85 #expect(f.outlook(at: pass, target: .faint, now: fetched) == Outlook(rating: .no, reason: "90% cloud"))
86 #expect(forecast([0.5]).outlook(at: pass, target: .bright, now: fetched)?.rating == Rating.marginal)
87}
88
89@Test func meteorShowerOutlookUsesItsNight() throws {
90 // Orionids peak night, 21–22 October 2026, from Chicago.
91 let event = try #require(SkyEngine.events(from: utc("2026-10-20T00:00:00Z"), days: 3, observer: chicago).first { $0.kind == .meteorShower })
92 let w = try #require(event.window)
93 let hours = (0..<24).map { i in
94 HourSample(date: w.start.addingTimeInterval(Double(i - 1) * 3600), cloudLow: 0, cloudMid: 0, cloudHigh: 0, cloudTotal: 0, precipitationChance: 0, visibility: 20_000)
95 }
96 let f = CloudForecast(fetched: w.start.addingTimeInterval(-6 * 3600), hours: hours)
97 let o = try #require(try SkyEngine.outlook(for: event, forecast: f, observer: chicago, now: f.fetched))
98 #expect(o.rating == Rating.go)
99}
server/src/privacy.ts +6 −3
@@ -17,13 +17,16 @@ h2 { font-weight: 500; font-size: 1.1em; margin-top: 1.8em; border-top: 1px soli
1717<body>
1818<h1>Moonrise privacy policy</h1>
1919<div class="rule"></div>
20<p>Last updated 18 October 2026.</p>
20<p>Last updated 20 October 2026.</p>
2121
2222<h2>Summary</h2>
23<p>Moonrise has no accounts, no advertising, no analytics and no tracking. If you turn on aurora alerts or news alerts, it sends our server four things needed to deliver them, described below. Nothing else is collected.</p>
23<p>Moonrise has no accounts, no advertising, no analytics and no tracking. Your location is never sent to our server. If you turn on aurora alerts or news alerts, it sends our server four things needed to deliver them, described below. If you turn on cloud forecasts, it sends a rounded location to Apple's weather service. Nothing else is collected.</p>
2424
2525<h2>Location</h2>
26<p>If you allow it, Moonrise uses your location to work out where the Sun, Moon, planets and stars are in your sky. This happens on your device. Your location is not sent to us or to anyone else. You can choose a city instead in Settings.</p>
26<p>If you allow it, Moonrise uses your location to work out where the Sun, Moon, planets and stars are in your sky. This happens on your device. Your location is never sent to us. You can choose a city instead in Settings.</p>
27
28<h2 id="cloud-forecasts">Cloud forecasts</h2>
29<p>Cloud forecasts are off until you turn them on in Settings. When they are on, the app asks Apple's weather service (WeatherKit) for an hourly forecast, sending your location or chosen city rounded to 0.1° of latitude and longitude, about 10 km. It asks at most once every three hours for each place, and only while the app is open. The request goes from your device to Apple, not through our server. Apple states that this location is used only to provide the forecast, is not associated with personally identifiable information and is not tracked between requests. The forecast is kept on your device. Turning cloud forecasts off deletes it.</p>
2730
2831<h2>Network requests</h2>
2932<p>To show live data, the app requests:</p>