Commit e601dfc47e
Unsigned
Layout: unified · split
App/Sources/CloudViews.swift added +100
| @@ -0,0 +1,100 @@ | |||
| 1 | import Feeds | ||
| 2 | import SkyEngine | ||
| 3 | import SwiftUI | ||
| 4 | |||
| 5 | /// The rating word, set like a section label, then its reason: "GO Clear 22:00–4:00". | ||
| 6 | struct 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. | ||
| 21 | struct 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. | ||
| 81 | struct 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 @@ | |||
| 1 | import Feeds | ||
| 1 | import SkyEngine | 2 | import SkyEngine |
| 2 | import SwiftUI | 3 | import SwiftUI |
| 3 | 4 | ||
| @@ -5,7 +6,11 @@ import SwiftUI | |||
| 5 | struct EventsScreen: View { | 6 | struct EventsScreen: View { |
| 6 | var observer: Observer | 7 | var observer: Observer |
| 7 | var placeName: String | 8 | var placeName: String |
| 9 | /// Cloud forecast, when cloud forecasts are on. | ||
| 10 | var forecast: SavedForecast? | ||
| 8 | @State private var events: [SkyEvent] = [] | 11 | @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] = [:] | ||
| 9 | @State private var filter = "notable" | 14 | @State private var filter = "notable" |
| 10 | @State private var eclipse: SkyEvent? | 15 | @State private var eclipse: SkyEvent? |
| 11 | @Environment(\.dismiss) private var dismiss | 16 | @Environment(\.dismiss) private var dismiss |
| @@ -36,6 +41,7 @@ struct EventsScreen: View { | |||
| 36 | } | 41 | } |
| 37 | .pickerStyle(.segmented) | 42 | .pickerStyle(.segmented) |
| 38 | .padding(.vertical, 16) | 43 | .padding(.vertical, 16) |
| 44 | if let forecast, !outlooks.isEmpty { WeatherCreditLine(saved: forecast).padding(.bottom, 4) } | ||
| 39 | 45 | ||
| 40 | if events.isEmpty { | 46 | if events.isEmpty { |
| 41 | ProgressView().tint(ink).frame(maxWidth: .infinity).padding(.top, 40) | 47 | ProgressView().tint(ink).frame(maxWidth: .infinity).padding(.top, 40) |
| @@ -72,8 +78,15 @@ struct EventsScreen: View { | |||
| 72 | .foregroundStyle(ink) | 78 | .foregroundStyle(ink) |
| 73 | .tint(accent) | 79 | .tint(accent) |
| 74 | .task { | 80 | .task { |
| 75 | let observer = observer | 81 | let observer = observer, forecast = forecast?.forecast |
| 76 | events = await Task.detached { SkyEngine.events(from: .now, observer: observer) }.value | 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 | ||
| 77 | } | 90 | } |
| 78 | } | 91 | } |
| 79 | 92 | ||
| @@ -92,6 +105,7 @@ struct EventsScreen: View { | |||
| 92 | } | 105 | } |
| 93 | Text(e.date.formatted(date: .omitted, time: .shortened)).font(.footnote.monospacedDigit()).foregroundStyle(ink.opacity(0.6)) | 106 | Text(e.date.formatted(date: .omitted, time: .shortened)).font(.footnote.monospacedDigit()).foregroundStyle(ink.opacity(0.6)) |
| 94 | if !e.detail.isEmpty { Text(e.detail).font(.footnote).foregroundStyle(ink.opacity(0.8)) } | 107 | 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()) } | ||
| 95 | if let v = e.visibleHere { | 109 | if let v = e.visibleHere { |
| 96 | HStack(spacing: 5) { | 110 | HStack(spacing: 5) { |
| 97 | Circle().fill(v ? accent : ink.opacity(0.35)).frame(width: 6, height: 6) | 111 | Circle().fill(v ? accent : ink.opacity(0.35)).frame(width: 6, height: 6) |
App/Sources/Moonrise.entitlements +2
| @@ -4,5 +4,7 @@ | |||
| 4 | <dict> | 4 | <dict> |
| 5 | <key>aps-environment</key> | 5 | <key>aps-environment</key> |
| 6 | <string>development</string> | 6 | <string>development</string> |
| 7 | <key>com.apple.developer.weatherkit</key> | ||
| 8 | <true/> | ||
| 7 | </dict> | 9 | </dict> |
| 8 | </plist> | 10 | </plist> |
App/Sources/SettingsScreen.swift +10
| @@ -1,3 +1,4 @@ | |||
| 1 | import Feeds | ||
| 1 | import Library | 2 | import Library |
| 2 | import SkyRenderer | 3 | import SkyRenderer |
| 3 | import SwiftUI | 4 | import SwiftUI |
| @@ -20,6 +21,8 @@ enum SettingsKey { | |||
| 20 | static let dailySummaryMinutes = "dailySummaryMinutes" | 21 | static let dailySummaryMinutes = "dailySummaryMinutes" |
| 21 | /// Messier objects on the sky chart. | 22 | /// Messier objects on the sky chart. |
| 22 | static let showDeepSky = "showDeepSky" | 23 | static let showDeepSky = "showDeepSky" |
| 24 | /// Cloud forecasts from Apple Weather; off unless turned on. | ||
| 25 | static let cloudForecast = "cloudForecast" | ||
| 23 | } | 26 | } |
| 24 | 27 | ||
| 25 | struct City: Hashable, Identifiable { | 28 | struct City: Hashable, Identifiable { |
| @@ -74,6 +77,7 @@ struct SettingsScreen: View { | |||
| 74 | @AppStorage(SettingsKey.dailySummary) private var dailySummary = false | 77 | @AppStorage(SettingsKey.dailySummary) private var dailySummary = false |
| 75 | @AppStorage(SettingsKey.dailySummaryMinutes) private var dailySummaryMinutes = DailySummaryNotifications.defaultMinutes | 78 | @AppStorage(SettingsKey.dailySummaryMinutes) private var dailySummaryMinutes = DailySummaryNotifications.defaultMinutes |
| 76 | @State private var summaryStatus: String? | 79 | @State private var summaryStatus: String? |
| 80 | @AppStorage(SettingsKey.cloudForecast) private var cloudForecast = false | ||
| 77 | var onChange: () -> Void | 81 | var onChange: () -> Void |
| 78 | 82 | ||
| 79 | var body: some View { | 83 | var body: some View { |
| @@ -124,6 +128,11 @@ struct SettingsScreen: View { | |||
| 124 | } footer: { | 128 | } footer: { |
| 125 | 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.") | 129 | 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.") |
| 126 | } | 130 | } |
| 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 | } | ||
| 127 | Section { | 136 | Section { |
| 128 | Picker("Constellations", selection: $skyCulture) { | 137 | Picker("Constellations", selection: $skyCulture) { |
| 129 | Text("Western (IAU)").tag("western") | 138 | Text("Western (IAU)").tag("western") |
| @@ -167,6 +176,7 @@ struct SettingsScreen: View { | |||
| 167 | onChange() | 176 | onChange() |
| 168 | } | 177 | } |
| 169 | .onChange(of: locationMode) { onChange() } | 178 | .onChange(of: locationMode) { onChange() } |
| 179 | .onChange(of: cloudForecast) { if !cloudForecast { SavedForecast.delete() } } | ||
| 170 | } | 180 | } |
| 171 | } | 181 | } |
| 172 | 182 | ||
App/Sources/SkyModel.swift +25
| @@ -58,6 +58,8 @@ final class SkyModel: NSObject, CLLocationManagerDelegate { | |||
| 58 | private var elementsFetched: Date? | 58 | private var elementsFetched: Date? |
| 59 | private var passesComputed: (at: Date, observer: Observer, elementsFetched: Date?)? | 59 | private var passesComputed: (at: Date, observer: Observer, elementsFetched: Date?)? |
| 60 | private var weatherFetched: Date? | 60 | private var weatherFetched: Date? |
| 61 | private var savedForecast: SavedForecast? | ||
| 62 | private var fetchingForecast = false | ||
| 61 | /// Hours from now shown by the time scrubber. | 63 | /// Hours from now shown by the time scrubber. |
| 62 | var offsetHours = 0.0 { didSet { refresh() } } | 64 | var offsetHours = 0.0 { didSet { refresh() } } |
| 63 | /// Year shown instead of this one (astronomical numbering: 0 is 1 BCE), or nil for now. | 65 | /// 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 { | |||
| 181 | } | 183 | } |
| 182 | } | 184 | } |
| 183 | 185 | ||
| 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 | |||
| 184 | func details(of body: Body) async -> BodyDetails? { | 209 | func details(of body: Body) async -> BodyDetails? { |
| 185 | try? await astronomer.details(of: body, at: displayedDate, from: observer) | 210 | try? await astronomer.details(of: body, at: displayedDate, from: observer) |
| 186 | } | 211 | } |
App/Sources/SkyScreen.swift +1 −1
| @@ -94,7 +94,7 @@ struct SkyScreen: View { | |||
| 94 | ObservationEditor(observation: o) {}.preferredColorScheme(.dark).tint(.blue) | 94 | ObservationEditor(observation: o) {}.preferredColorScheme(.dark).tint(.blue) |
| 95 | } | 95 | } |
| 96 | .sheet(isPresented: $showEvents) { | 96 | .sheet(isPresented: $showEvents) { |
| 97 | EventsScreen(observer: model.observer, placeName: model.placeName) | 97 | EventsScreen(observer: model.observer, placeName: model.placeName, forecast: model.forecast) |
| 98 | .preferredColorScheme(.dark) | 98 | .preferredColorScheme(.dark) |
| 99 | } | 99 | } |
| 100 | .sheet(isPresented: $showTours) { | 100 | .sheet(isPresented: $showTours) { |
App/Sources/TodaySheet.swift +35 −4
| @@ -12,7 +12,7 @@ struct TodaySheet: View { | |||
| 12 | ScrollView { | 12 | ScrollView { |
| 13 | VStack(alignment: .leading, spacing: 0) { | 13 | VStack(alignment: .leading, spacing: 0) { |
| 14 | if let t = model.tonight { | 14 | if let t = model.tonight { |
| 15 | section("Tonight") { Text(t.moonAndDarkness()).font(.subheadline.monospacedDigit()) } | 15 | section("Tonight") { tonight(t) } |
| 16 | section("Moon") { moon(t) } | 16 | section("Moon") { moon(t) } |
| 17 | section("Planets tonight") { planets(t) } | 17 | section("Planets tonight") { planets(t) } |
| 18 | section("Sun") { sun(t) } | 18 | section("Sun") { sun(t) } |
| @@ -28,6 +28,7 @@ struct TodaySheet: View { | |||
| 28 | .foregroundStyle(ink) | 28 | .foregroundStyle(ink) |
| 29 | .presentationBackground(background) | 29 | .presentationBackground(background) |
| 30 | .task { await model.refreshPasses() } | 30 | .task { await model.refreshPasses() } |
| 31 | .task { await model.refreshForecast() } | ||
| 31 | } | 32 | } |
| 32 | 33 | ||
| 33 | private func section(_ title: String, @ViewBuilder content: () -> some View) -> some View { | 34 | private func section(_ title: String, @ViewBuilder content: () -> some View) -> some View { |
| @@ -40,6 +41,31 @@ struct TodaySheet: View { | |||
| 40 | .overlay(alignment: .top) { Rectangle().fill(ink.opacity(0.25)).frame(height: 0.5) } | 41 | .overlay(alignment: .top) { Rectangle().fill(ink.opacity(0.25)).frame(height: 0.5) } |
| 41 | } | 42 | } |
| 42 | 43 | ||
| 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 | |||
| 43 | private func moon(_ t: Tonight) -> some View { | 69 | private func moon(_ t: Tonight) -> some View { |
| 44 | let quarter = switch t.nextQuarter.quarter { | 70 | let quarter = switch t.nextQuarter.quarter { |
| 45 | case .new: "New moon" | 71 | case .new: "New moon" |
| @@ -88,6 +114,7 @@ struct TodaySheet: View { | |||
| 88 | } else { | 114 | } else { |
| 89 | VStack(alignment: .leading, spacing: 10) { | 115 | VStack(alignment: .leading, spacing: 10) { |
| 90 | ForEach(Array(shown)) { p in | 116 | ForEach(Array(shown)) { p in |
| 117 | let cloud = cloudAtPeak(p) | ||
| 91 | VStack(alignment: .leading, spacing: 2) { | 118 | VStack(alignment: .leading, spacing: 2) { |
| 92 | HStack { | 119 | HStack { |
| 93 | Text(p.displayName).font(.subheadline.weight(.medium)) | 120 | Text(p.displayName).font(.subheadline.weight(.medium)) |
| @@ -97,9 +124,10 @@ struct TodaySheet: View { | |||
| 97 | } | 124 | } |
| 98 | } | 125 | } |
| 99 | Text(p.rise.formatted(.dateTime.weekday(.abbreviated).hour().minute()) + String(format: " · rises %@, highest %.0f°, sets %@", compass(p.riseAzimuth), p.maxAltitude, compass(p.setAzimuth)) | 126 | 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)" } ?? "")) |
| 101 | .font(.footnote.monospacedDigit()).dimmed(0.8) | 128 | .font(.footnote.monospacedDigit()).dimmed(0.8) |
| 102 | } | 129 | } |
| 130 | .dimmed(cloud?.rating == .no ? 0.5 : 1) | ||
| 103 | .accessibilityElement(children: .combine) | 131 | .accessibilityElement(children: .combine) |
| 104 | .frame(maxWidth: .infinity, alignment: .leading) | 132 | .frame(maxWidth: .infinity, alignment: .leading) |
| 105 | .padding(.trailing, 44) | 133 | .padding(.trailing, 44) |
| @@ -109,8 +137,10 @@ struct TodaySheet: View { | |||
| 109 | if !others.isEmpty { | 137 | if !others.isEmpty { |
| 110 | Text("Also visible tonight").font(.caption2.weight(.medium)).textCase(.uppercase).tracking(0.8).dimmed(0.6).padding(.top, 6) | 138 | Text("Also visible tonight").font(.caption2.weight(.medium)).textCase(.uppercase).tracking(0.8).dimmed(0.6).padding(.top, 6) |
| 111 | ForEach(others) { p in | 139 | 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)" } ?? "")) | 140 | let cloud = cloudAtPeak(p) |
| 113 | .font(.footnote.monospacedDigit()).dimmed(0.8) | 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) | ||
| 114 | } | 144 | } |
| 115 | } | 145 | } |
| 116 | Text("Visible means sunlit while your sky is dark. Orbits: CelesTrak.").font(.caption2).dimmed(0.6) | 146 | Text("Visible means sunlit while your sky is dark. Orbits: CelesTrak.").font(.caption2).dimmed(0.6) |
| @@ -188,6 +218,7 @@ struct TodayBar: View { | |||
| 188 | .task { | 218 | .task { |
| 189 | while !Task.isCancelled { | 219 | while !Task.isCancelled { |
| 190 | await model.refreshSpaceWeather() | 220 | await model.refreshSpaceWeather() |
| 221 | await model.refreshForecast() | ||
| 191 | try? await Task.sleep(for: .seconds(600)) | 222 | try? await Task.sleep(for: .seconds(600)) |
| 192 | } | 223 | } |
| 193 | } | 224 | } |
App/project.yml +1
| @@ -38,6 +38,7 @@ targets: | |||
| 38 | path: Sources/Moonrise.entitlements | 38 | path: Sources/Moonrise.entitlements |
| 39 | properties: | 39 | properties: |
| 40 | aps-environment: development | 40 | aps-environment: development |
| 41 | com.apple.developer.weatherkit: true | ||
| 41 | info: | 42 | info: |
| 42 | path: Sources/Info.plist | 43 | path: Sources/Info.plist |
| 43 | properties: | 44 | properties: |
Packages/MoonriseKit/Sources/Feeds/CloudForecast.swift added +59
| @@ -0,0 +1,59 @@ | |||
| 1 | import CoreLocation | ||
| 2 | import Foundation | ||
| 3 | import SkyEngine | ||
| 4 | import WeatherKit | ||
| 5 | |||
| 6 | /// The Apple Weather mark and legal page, which WeatherKit's terms require wherever its data is shown. | ||
| 7 | public 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. | ||
| 14 | public 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 @@ | |||
| 1 | import Foundation | ||
| 2 | |||
| 3 | /// One hour of a weather forecast, from `date` to an hour later. Cover and chance run from 0 to 1. | ||
| 4 | public 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. | ||
| 36 | public enum SkyTarget: Sendable { | ||
| 37 | case bright, faint | ||
| 38 | } | ||
| 39 | |||
| 40 | public 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. | ||
| 45 | public 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`. | ||
| 52 | public 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 | |||
| 142 | extension 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 { | |||
| 12 | public var detail: String | 12 | public var detail: String |
| 13 | /// Whether it can be seen from the observer's location; nil when that does not apply. | 13 | /// Whether it can be seen from the observer's location; nil when that does not apply. |
| 14 | public var visibleHere: Bool? | 14 | 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? | ||
| 15 | public var id: String { "\(kind.rawValue)-\(title)-\(Int(date.timeIntervalSince1970))" } | 18 | public var id: String { "\(kind.rawValue)-\(title)-\(Int(date.timeIntervalSince1970))" } |
| 16 | } | 19 | } |
| 17 | 20 | ||
| @@ -75,7 +78,8 @@ extension SkyEngine { | |||
| 75 | let alt = Astronomy_Horizon(&peak, observer.astro, moon.ra, moon.dec, REFRACTION_NORMAL).altitude | 78 | let alt = Astronomy_Horizon(&peak, observer.astro, moon.ra, moon.dec, REFRACTION_NORMAL).altitude |
| 76 | let minutes = lunar.sd_total > 0 ? lunar.sd_total * 2 : lunar.sd_partial * 2 | 79 | let minutes = lunar.sd_total > 0 ? lunar.sd_total * 2 : lunar.sd_partial * 2 |
| 77 | let length = minutes > 0 ? String(format: " %@ phase lasts %.0f minutes.", lunar.sd_total > 0 ? "Total" : "Partial", minutes) : "" | 80 | 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)) | ||
| 79 | lunar = Astronomy_NextLunarEclipse(lunar.peak) | 83 | lunar = Astronomy_NextLunarEclipse(lunar.peak) |
| 80 | } | 84 | } |
| 81 | 85 | ||
| @@ -92,8 +96,10 @@ extension SkyEngine { | |||
| 92 | let here = local.first { abs($0.key.timeIntervalSince(peakDate)) < 6 * 3600 }?.value | 96 | let here = local.first { abs($0.key.timeIntervalSince(peakDate)) < 6 * 3600 }?.value |
| 93 | var detail: String | 97 | var detail: String |
| 94 | var visible = false | 98 | var visible = false |
| 99 | var window: DateInterval? | ||
| 95 | if let here, here.peak.altitude > 0 { | 100 | if let here, here.peak.altitude > 0 { |
| 96 | visible = true | 101 | visible = true |
| 102 | window = DateInterval(start: date(here.peak.time), duration: 0) | ||
| 97 | 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)) | 103 | 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)) |
| 98 | } else { | 104 | } else { |
| 99 | detail = "Not visible from here." | 105 | detail = "Not visible from here." |
| @@ -101,7 +107,7 @@ extension SkyEngine { | |||
| 101 | if solar.kind == ECLIPSE_TOTAL || solar.kind == ECLIPSE_ANNULAR { | 107 | if solar.kind == ECLIPSE_TOTAL || solar.kind == ECLIPSE_ANNULAR { |
| 102 | detail += String(format: " Greatest eclipse at %.1f°%@, %.1f°%@.", abs(solar.latitude), solar.latitude >= 0 ? "N" : "S", abs(solar.longitude), solar.longitude >= 0 ? "E" : "W") | 108 | detail += String(format: " Greatest eclipse at %.1f°%@, %.1f°%@.", abs(solar.latitude), solar.latitude >= 0 ? "N" : "S", abs(solar.longitude), solar.longitude >= 0 ? "E" : "W") |
| 103 | } | 109 | } |
| 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)) |
| 105 | solar = Astronomy_NextGlobalSolarEclipse(solar.peak) | 111 | solar = Astronomy_NextGlobalSolarEclipse(solar.peak) |
| 106 | } | 112 | } |
| 107 | 113 | ||
| @@ -148,9 +154,10 @@ extension SkyEngine { | |||
| 148 | let noon = midnight.addingTimeInterval(-12 * 3600) | 154 | let noon = midnight.addingTimeInterval(-12 * 3600) |
| 149 | let sunset = riseSet(.sun, after: noon, from: observer).set ?? noon | 155 | let sunset = riseSet(.sun, after: noon, from: observer).set ?? noon |
| 150 | let night = DateInterval(start: sunset, end: riseSet(.sun, after: sunset, from: observer).rise ?? sunset.addingTimeInterval(12 * 3600)) | 156 | 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, | ||
| 152 | moonUp: (try? moonUp(from: night.start, to: night.end, observer: observer)) ?? [], moonIllumination: lit) | 159 | 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)) |
| 154 | } | 161 | } |
| 155 | } | 162 | } |
| 156 | 163 | ||
Packages/MoonriseKit/Tests/FeedsTests/CloudForecastTests.swift added +25
| @@ -0,0 +1,25 @@ | |||
| 1 | import Foundation | ||
| 2 | import SkyEngine | ||
| 3 | import 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 @@ | |||
| 1 | import Foundation | ||
| 2 | import Testing | ||
| 3 | @testable import SkyEngine | ||
| 4 | |||
| 5 | private let utcTime = Date.FormatStyle(date: .omitted, time: .shortened, locale: Locale(identifier: "en_GB"), timeZone: TimeZone(identifier: "UTC")!) | ||
| 6 | private let fetched = utc("2026-10-20T12:00:00Z") | ||
| 7 | private 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. | ||
| 10 | private 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 | |||
| 17 | private 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 | |||
| 17 | <body> | 17 | <body> |
| 18 | <h1>Moonrise privacy policy</h1> | 18 | <h1>Moonrise privacy policy</h1> |
| 19 | <div class="rule"></div> | 19 | <div class="rule"></div> |
| 20 | <p>Last updated 18 October 2026.</p> | 20 | <p>Last updated 20 October 2026.</p> |
| 21 | 21 | ||
| 22 | <h2>Summary</h2> | 22 | <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> |
| 24 | 24 | ||
| 25 | <h2>Location</h2> | 25 | <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> | ||
| 27 | 30 | ||
| 28 | <h2>Network requests</h2> | 31 | <h2>Network requests</h2> |
| 29 | <p>To show live data, the app requests:</p> | 32 | <p>To show live data, the app requests:</p> |