Commit 8f340da1c6
Verified · cmc
Layout: unified · split
.qlty/.gitignore added +7
| @@ -0,0 +1,7 @@ | |||
| 1 | * | ||
| 2 | !configs | ||
| 3 | !configs/** | ||
| 4 | !hooks | ||
| 5 | !hooks/** | ||
| 6 | !qlty.toml | ||
| 7 | !.gitignore | ||
.qlty/qlty.toml added +50
| @@ -0,0 +1,50 @@ | |||
| 1 | config_version = "0" | ||
| 2 | |||
| 3 | exclude_patterns = [ | ||
| 4 | # Astronomy Engine, vendored (THIRD_PARTY.org). | ||
| 5 | "Packages/MoonriseKit/Sources/CAstronomy/**", | ||
| 6 | "**/vendor/**", | ||
| 7 | "**/node_modules/**", | ||
| 8 | "**/testdata/**", | ||
| 9 | "**/dist/**", | ||
| 10 | "**/.build/**", | ||
| 11 | "**/build/**", | ||
| 12 | "**/*.min.*", | ||
| 13 | "**/generated/**", | ||
| 14 | ".claude/**", | ||
| 15 | "**/Pods/**", | ||
| 16 | ] | ||
| 17 | |||
| 18 | test_patterns = [ | ||
| 19 | "**/test/**", | ||
| 20 | "**/tests/**", | ||
| 21 | "**/Tests/**", | ||
| 22 | "**/*_test.*", | ||
| 23 | "**/test_*.*", | ||
| 24 | "**/*.test.*", | ||
| 25 | "**/*Tests.swift", | ||
| 26 | "e2e/**", | ||
| 27 | ] | ||
| 28 | |||
| 29 | [[source]] | ||
| 30 | name = "default" | ||
| 31 | default = true | ||
| 32 | |||
| 33 | [[plugin]] | ||
| 34 | name = "osv-scanner" | ||
| 35 | |||
| 36 | [[plugin]] | ||
| 37 | name = "trufflehog" | ||
| 38 | |||
| 39 | # Early returns are guard clauses, which keep the happy path unindented. | ||
| 40 | [smells.return_statements] | ||
| 41 | enabled = false | ||
| 42 | |||
| 43 | # Total file complexity is the sum of its functions, which function_complexity | ||
| 44 | # already checks. | ||
| 45 | [smells.file_complexity] | ||
| 46 | enabled = false | ||
| 47 | |||
| 48 | # Exhaustive switch-over-enum lookup tables share shape but not content. | ||
| 49 | [language.swift.smells.duplication] | ||
| 50 | filter_patterns = ["(import_declaration _)", "(switch_statement _)"] | ||
App/Sources/EclipseDayScreen.swift +16 −10
| @@ -104,20 +104,26 @@ struct EclipseDayScreen: View { | |||
| 104 | if let cue = spoken, now.timeIntervalSince(cue.date) < 20 { | 104 | if let cue = spoken, now.timeIntervalSince(cue.date) < 20 { |
| 105 | Text(cue.text).font(.title3.weight(.medium)).foregroundStyle(cue.warning ? accent : ink) | 105 | Text(cue.text).font(.title3.weight(.medium)).foregroundStyle(cue.warning ? accent : ink) |
| 106 | } | 106 | } |
| 107 | let upcoming = t.cues.filter { $0.date > now && Int($0.text) == nil }.prefix(3) | 107 | upcomingCues(t, at: now) |
| 108 | if !upcoming.isEmpty { | 108 | } |
| 109 | VStack(alignment: .leading, spacing: 4) { | 109 | .accessibilityElement(children: .combine) |
| 110 | ForEach(upcoming, id: \.date) { c in | 110 | } |
| 111 | HStack(alignment: .firstTextBaseline) { | 111 | |
| 112 | Text("in \(clock(c.date.timeIntervalSince(now)))").monospacedDigit().dimmed(0.6).frame(width: 90, alignment: .leading) | 112 | /// The next three spoken cues that are not a count, each with the time until it. |
| 113 | Text(c.text).foregroundStyle(c.warning ? accent : ink).lineLimit(2) | 113 | @ViewBuilder |
| 114 | } | 114 | private func upcomingCues(_ t: EclipseTimeline, at now: Date) -> some View { |
| 115 | let upcoming = t.cues.filter { $0.date > now && Int($0.text) == nil }.prefix(3) | ||
| 116 | if !upcoming.isEmpty { | ||
| 117 | VStack(alignment: .leading, spacing: 4) { | ||
| 118 | ForEach(upcoming, id: \.date) { c in | ||
| 119 | HStack(alignment: .firstTextBaseline) { | ||
| 120 | Text("in \(clock(c.date.timeIntervalSince(now)))").monospacedDigit().dimmed(0.6).frame(width: 90, alignment: .leading) | ||
| 121 | Text(c.text).foregroundStyle(c.warning ? accent : ink).lineLimit(2) | ||
| 115 | } | 122 | } |
| 116 | } | 123 | } |
| 117 | .font(.footnote) | ||
| 118 | } | 124 | } |
| 125 | .font(.footnote) | ||
| 119 | } | 126 | } |
| 120 | .accessibilityElement(children: .combine) | ||
| 121 | } | 127 | } |
| 122 | 128 | ||
| 123 | private func label(_ contact: String, _ t: EclipseTimeline) -> String { | 129 | private func label(_ contact: String, _ t: EclipseTimeline) -> String { |
App/Sources/EventsScreen.swift +34 −24
| @@ -92,30 +92,9 @@ struct EventsScreen: View { | |||
| 92 | 92 | ||
| 93 | private func row(_ e: SkyEvent, link: Bool) -> some View { | 93 | private func row(_ e: SkyEvent, link: Bool) -> some View { |
| 94 | HStack(alignment: .top, spacing: 14) { | 94 | HStack(alignment: .top, spacing: 14) { |
| 95 | VStack(spacing: 0) { | 95 | dateColumn(e) |
| 96 | Text(e.date.formatted(.dateTime.day())).font(.title2.weight(.medium).monospacedDigit()) | 96 | details(e) |
| 97 | Text(e.date.formatted(.dateTime.weekday(.abbreviated))).font(.caption2).textCase(.uppercase).foregroundStyle(ink.opacity(0.6)) | 97 | .padding(.trailing, e.activityStart(now: .now) != nil ? 44 : 0) |
| 98 | } | ||
| 99 | .frame(width: 40) | ||
| 100 | VStack(alignment: .leading, spacing: 4) { | ||
| 101 | HStack(alignment: .firstTextBaseline, spacing: 6) { | ||
| 102 | Image(systemName: symbol(e.kind)).font(.subheadline).foregroundStyle(e.visibleHere == true ? accent : ink.opacity(0.7)) | ||
| 103 | .accessibilityHidden(true) | ||
| 104 | Text(e.title).font(.body.weight(.medium)) | ||
| 105 | } | ||
| 106 | Text(e.date.formatted(date: .omitted, time: .shortened)).font(.footnote.monospacedDigit()).foregroundStyle(ink.opacity(0.6)) | ||
| 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()) } | ||
| 109 | if let v = e.visibleHere { | ||
| 110 | HStack(spacing: 5) { | ||
| 111 | Circle().fill(v ? accent : ink.opacity(0.35)).frame(width: 6, height: 6) | ||
| 112 | Text(v ? "Visible from here" : "Not visible from here").font(.caption.weight(.medium)) | ||
| 113 | .foregroundStyle(v ? ink : ink.opacity(0.6)) | ||
| 114 | } | ||
| 115 | .padding(.top, 2) | ||
| 116 | } | ||
| 117 | } | ||
| 118 | .padding(.trailing, e.activityStart(now: .now) != nil ? 44 : 0) | ||
| 119 | Spacer(minLength: 0) | 98 | Spacer(minLength: 0) |
| 120 | if link { | 99 | if link { |
| 121 | Image(systemName: "chevron.right").font(.footnote.weight(.semibold)).foregroundStyle(ink.opacity(0.4)).padding(.top, 6) | 100 | Image(systemName: "chevron.right").font(.footnote.weight(.semibold)).foregroundStyle(ink.opacity(0.4)).padding(.top, 6) |
| @@ -130,6 +109,37 @@ struct EventsScreen: View { | |||
| 130 | } | 109 | } |
| 131 | } | 110 | } |
| 132 | 111 | ||
| 112 | private func dateColumn(_ e: SkyEvent) -> some View { | ||
| 113 | VStack(spacing: 0) { | ||
| 114 | Text(e.date.formatted(.dateTime.day())).font(.title2.weight(.medium).monospacedDigit()) | ||
| 115 | Text(e.date.formatted(.dateTime.weekday(.abbreviated))).font(.caption2).textCase(.uppercase).foregroundStyle(ink.opacity(0.6)) | ||
| 116 | } | ||
| 117 | .frame(width: 40) | ||
| 118 | } | ||
| 119 | |||
| 120 | private func details(_ e: SkyEvent) -> some View { | ||
| 121 | VStack(alignment: .leading, spacing: 4) { | ||
| 122 | HStack(alignment: .firstTextBaseline, spacing: 6) { | ||
| 123 | Image(systemName: symbol(e.kind)).font(.subheadline).foregroundStyle(e.visibleHere == true ? accent : ink.opacity(0.7)) | ||
| 124 | .accessibilityHidden(true) | ||
| 125 | Text(e.title).font(.body.weight(.medium)) | ||
| 126 | } | ||
| 127 | Text(e.date.formatted(date: .omitted, time: .shortened)).font(.footnote.monospacedDigit()).foregroundStyle(ink.opacity(0.6)) | ||
| 128 | if !e.detail.isEmpty { Text(e.detail).font(.footnote).foregroundStyle(ink.opacity(0.8)) } | ||
| 129 | if let o = outlooks[e.id] { OutlookLine(outlook: o).font(.footnote.monospacedDigit()) } | ||
| 130 | if let v = e.visibleHere { visibility(v) } | ||
| 131 | } | ||
| 132 | } | ||
| 133 | |||
| 134 | private func visibility(_ v: Bool) -> some View { | ||
| 135 | HStack(spacing: 5) { | ||
| 136 | Circle().fill(v ? accent : ink.opacity(0.35)).frame(width: 6, height: 6) | ||
| 137 | Text(v ? "Visible from here" : "Not visible from here").font(.caption.weight(.medium)) | ||
| 138 | .foregroundStyle(v ? ink : ink.opacity(0.6)) | ||
| 139 | } | ||
| 140 | .padding(.top, 2) | ||
| 141 | } | ||
| 142 | |||
| 133 | private func symbol(_ k: SkyEvent.Kind) -> String { | 143 | private func symbol(_ k: SkyEvent.Kind) -> String { |
| 134 | switch k { | 144 | switch k { |
| 135 | case .moonPhase: "moonphase.full.moon" | 145 | case .moonPhase: "moonphase.full.moon" |
App/Sources/SolarSystem3D.swift +29 −16
| @@ -785,26 +785,39 @@ struct SolarSystem3DView: View { | |||
| 785 | private func labels(size: CGSize) -> some View { | 785 | private func labels(size: CGSize) -> some View { |
| 786 | ZStack { | 786 | ZStack { |
| 787 | ForEach(labelled(size: size), id: \.marker.id) { item in | 787 | ForEach(labelled(size: size), id: \.marker.id) { item in |
| 788 | let m = item.marker | 788 | label(item.marker, radius: item.radius, showName: item.showName) |
| 789 | let isSelected = m.id == selected | 789 | .position(item.point) |
| 790 | let color: Color = isSelected ? accent : m.kind == .craft ? accent.opacity(0.9) : m.kind == .comet ? Color(red: 0.7, green: 0.85, blue: 1) : ink.opacity(m.kind == .moon ? 0.7 : 0.85) | 790 | } |
| 791 | ZStack { | 791 | } |
| 792 | if item.radius < 3, m.kind != .craft, m.kind != .comet { | 792 | } |
| 793 | Circle().stroke(isSelected ? accent : ink.opacity(0.6), lineWidth: 1.2).frame(width: 10, height: 10) | 793 | |
| 794 | } | 794 | /// A ring for a body too small to see, and its name when there is room for it. |
| 795 | if item.showName { | 795 | private func label(_ m: SolarMarker, radius: CGFloat, showName: Bool) -> some View { |
| 796 | Text(m.name).font(.caption2.weight(isSelected ? .semibold : .regular)) | 796 | let isSelected = m.id == selected |
| 797 | .foregroundStyle(color) | 797 | return ZStack { |
| 798 | .shadow(color: .black, radius: 2) | 798 | if radius < 3, m.kind != .craft, m.kind != .comet { |
| 799 | .fixedSize() | 799 | Circle().stroke(isSelected ? accent : ink.opacity(0.6), lineWidth: 1.2).frame(width: 10, height: 10) |
| 800 | .offset(y: -max(item.radius, 5) - 9) | 800 | } |
| 801 | } | 801 | if showName { |
| 802 | } | 802 | Text(m.name).font(.caption2.weight(isSelected ? .semibold : .regular)) |
| 803 | .position(item.point) | 803 | .foregroundStyle(labelColor(m, isSelected: isSelected)) |
| 804 | .shadow(color: .black, radius: 2) | ||
| 805 | .fixedSize() | ||
| 806 | .offset(y: -max(radius, 5) - 9) | ||
| 804 | } | 807 | } |
| 805 | } | 808 | } |
| 806 | } | 809 | } |
| 807 | 810 | ||
| 811 | private func labelColor(_ m: SolarMarker, isSelected: Bool) -> Color { | ||
| 812 | if isSelected { return accent } | ||
| 813 | switch m.kind { | ||
| 814 | case .craft: return accent.opacity(0.9) | ||
| 815 | case .comet: return Color(red: 0.7, green: 0.85, blue: 1) | ||
| 816 | case .moon: return ink.opacity(0.7) | ||
| 817 | default: return ink.opacity(0.85) | ||
| 818 | } | ||
| 819 | } | ||
| 820 | |||
| 808 | private func tap(_ location: CGPoint, size: CGSize) { | 821 | private func tap(_ location: CGPoint, size: CGSize) { |
| 809 | let hit = screenPoints(size: size) | 822 | let hit = screenPoints(size: size) |
| 810 | .map { ($0.marker.id, hypot($0.point.x - location.x, $0.point.y - location.y) - max($0.radius, 0)) } | 823 | .map { ($0.marker.id, hypot($0.point.x - location.x, $0.point.y - location.y) - max($0.radius, 0)) } |
Packages/MoonriseKit/Sources/Feeds/SunSummary.swift +26 −10
| @@ -34,16 +34,8 @@ public enum SunSummary { | |||
| 34 | return "\(name(g)) storm (G\(g)) \(when), Kp \(String(format: "%.1f", b.kp)). Aurora possible low in the \(sky) sky." | 34 | return "\(name(g)) storm (G\(g)) \(when), Kp \(String(format: "%.1f", b.kp)). Aurora possible low in the \(sky) sky." |
| 35 | } | 35 | } |
| 36 | if current.g >= 1 { | 36 | if current.g >= 1 { |
| 37 | let needed = Geomagnetic.kpNeeded(geomagneticLatitude: geomagneticLatitude) | 37 | let note = auroraNote(geomagneticLatitude: geomagneticLatitude, kp: kp, bar: bar, night: night) |
| 38 | var text = "\(name(current.g)) storm (G\(current.g))\(asOf)." | 38 | return "\(name(current.g)) storm (G\(current.g))\(asOf).\(note)" |
| 39 | if needed > 9 { | ||
| 40 | text += " Aurora at your latitude would need more than Kp 9." | ||
| 41 | } else if needed > 5 { | ||
| 42 | text += " Aurora at your latitude needs Kp \(String(format: "%.1f", needed))." | ||
| 43 | } else if kp.contains(where: { overlaps($0.start, bar, night) }) { | ||
| 44 | text += " Kp is forecast below 5 after dark." | ||
| 45 | } | ||
| 46 | return text | ||
| 47 | } | 39 | } |
| 48 | 40 | ||
| 49 | // 2. Solar radiation storm. | 41 | // 2. Solar radiation storm. |
| @@ -60,6 +52,30 @@ public enum SunSummary { | |||
| 60 | } | 52 | } |
| 61 | 53 | ||
| 62 | // 4. Quiet. | 54 | // 4. Quiet. |
| 55 | return quietText(storms: storms, probabilities: probabilities, at: now, time: time) | ||
| 56 | } | ||
| 57 | |||
| 58 | /// What aurora at this latitude would take, during a storm already under way. | ||
| 59 | private static func auroraNote(geomagneticLatitude: Double, kp: [KpBar], bar: TimeInterval, night: DateInterval) -> String { | ||
| 60 | let needed = Geomagnetic.kpNeeded(geomagneticLatitude: geomagneticLatitude) | ||
| 61 | if needed > 9 { | ||
| 62 | return " Aurora at your latitude would need more than Kp 9." | ||
| 63 | } | ||
| 64 | if needed > 5 { | ||
| 65 | return " Aurora at your latitude needs Kp \(String(format: "%.1f", needed))." | ||
| 66 | } | ||
| 67 | if kp.contains(where: { overlaps($0.start, bar, night) }) { | ||
| 68 | return " Kp is forecast below 5 after dark." | ||
| 69 | } | ||
| 70 | return "" | ||
| 71 | } | ||
| 72 | |||
| 73 | private static func quietText( | ||
| 74 | storms: [KpBar], | ||
| 75 | probabilities: SolarProbabilities?, | ||
| 76 | at now: Date, | ||
| 77 | time: (Date) -> String | ||
| 78 | ) -> String { | ||
| 63 | if let next = storms.min(by: { $0.start < $1.start }), let g = SpaceWeather.gScale(next.kp) { | 79 | if let next = storms.min(by: { $0.start < $1.start }), let g = SpaceWeather.gScale(next.kp) { |
| 64 | return "Quiet now. \(name(g)) storm (G\(g)) forecast from \(time(next.start)), Kp \(String(format: "%.1f", next.kp))." | 80 | return "Quiet now. \(name(g)) storm (G\(g)) forecast from \(time(next.start)), Kp \(String(format: "%.1f", next.kp))." |
| 65 | } | 81 | } |
Packages/MoonriseKit/Sources/ObservingLog/Equipment.swift +1 −13
| @@ -103,19 +103,7 @@ public struct Equipment: Sendable, Identifiable, Equatable, Hashable { | |||
| 103 | public init?(org text: String) { | 103 | public init?(org text: String) { |
| 104 | let lines = text.components(separatedBy: "\n") | 104 | let lines = text.components(separatedBy: "\n") |
| 105 | guard let head = lines.first, head.hasPrefix("* ") else { return nil } | 105 | guard let head = lines.first, head.hasPrefix("* ") else { return nil } |
| 106 | var props: [String: String] = [:] | 106 | let (props, other, i) = OrgProperty.drawer(in: lines, at: 1, known: Self.knownKeys) |
| 107 | var other: [OrgProperty] = [] | ||
| 108 | var i = 1 | ||
| 109 | if i < lines.count, lines[i] == ":PROPERTIES:" { | ||
| 110 | i += 1 | ||
| 111 | while i < lines.count, lines[i] != ":END:" { | ||
| 112 | if let p = OrgProperty.parse(lines[i]) { | ||
| 113 | if !Self.knownKeys.contains(p.key) { other.append(p) } else if !p.value.isEmpty { props[p.key] = p.value } | ||
| 114 | } | ||
| 115 | i += 1 | ||
| 116 | } | ||
| 117 | i += 1 | ||
| 118 | } | ||
| 119 | guard let id = props[":ID:"] else { return nil } | 107 | guard let id = props[":ID:"] else { return nil } |
| 120 | func leadingNumber(_ key: String) -> Double? { | 108 | func leadingNumber(_ key: String) -> Double? { |
| 121 | props[key].flatMap { Double($0.prefix { $0.isNumber || $0 == "." }) } | 109 | props[key].flatMap { Double($0.prefix { $0.isNumber || $0 == "." }) } |
Packages/MoonriseKit/Sources/ObservingLog/Observation.swift +23 −13
| @@ -13,6 +13,28 @@ public struct OrgProperty: Sendable, Equatable, Hashable { | |||
| 13 | 13 | ||
| 14 | var line: String { value.isEmpty ? key : "\(key) \(value)" } | 14 | var line: String { value.isEmpty ? key : "\(key) \(value)" } |
| 15 | 15 | ||
| 16 | /// The `:PROPERTIES:` drawer at `lines[start]`, if there is one: values of the | ||
| 17 | /// `known` keys that are set, every other property in order, and the index | ||
| 18 | /// of the first line past the drawer. | ||
| 19 | static func drawer( | ||
| 20 | in lines: [String], | ||
| 21 | at start: Int, | ||
| 22 | known: Set<String> | ||
| 23 | ) -> (known: [String: String], other: [OrgProperty], next: Int) { | ||
| 24 | var props: [String: String] = [:] | ||
| 25 | var other: [OrgProperty] = [] | ||
| 26 | var i = start | ||
| 27 | guard i < lines.count, lines[i] == ":PROPERTIES:" else { return (props, other, i) } | ||
| 28 | i += 1 | ||
| 29 | while i < lines.count, lines[i] != ":END:" { | ||
| 30 | if let p = parse(lines[i]) { | ||
| 31 | if !known.contains(p.key) { other.append(p) } else if !p.value.isEmpty { props[p.key] = p.value } | ||
| 32 | } | ||
| 33 | i += 1 | ||
| 34 | } | ||
| 35 | return (props, other, i + 1) | ||
| 36 | } | ||
| 37 | |||
| 16 | /// Splits a drawer line into key and value; nil for lines that are not a property. | 38 | /// Splits a drawer line into key and value; nil for lines that are not a property. |
| 17 | static func parse(_ line: String) -> OrgProperty? { | 39 | static func parse(_ line: String) -> OrgProperty? { |
| 18 | let parts = line.split(separator: " ", maxSplits: 1).map(String.init) | 40 | let parts = line.split(separator: " ", maxSplits: 1).map(String.init) |
| @@ -102,19 +124,7 @@ public struct Observation: Sendable, Identifiable, Equatable { | |||
| 102 | let lines = text.components(separatedBy: "\n") | 124 | let lines = text.components(separatedBy: "\n") |
| 103 | guard let head = lines.first, head.hasPrefix("* "), | 125 | guard let head = lines.first, head.hasPrefix("* "), |
| 104 | lines.count > 1, lines[1].hasPrefix("["), lines[1].hasSuffix("]") else { return nil } | 126 | lines.count > 1, lines[1].hasPrefix("["), lines[1].hasSuffix("]") else { return nil } |
| 105 | var props: [String: String] = [:] | 127 | let (props, other, i) = OrgProperty.drawer(in: lines, at: 2, known: Self.knownKeys) |
| 106 | var other: [OrgProperty] = [] | ||
| 107 | var i = 2 | ||
| 108 | if i < lines.count, lines[i] == ":PROPERTIES:" { | ||
| 109 | i += 1 | ||
| 110 | while i < lines.count, lines[i] != ":END:" { | ||
| 111 | if let p = OrgProperty.parse(lines[i]) { | ||
| 112 | if !Self.knownKeys.contains(p.key) { other.append(p) } else if !p.value.isEmpty { props[p.key] = p.value } | ||
| 113 | } | ||
| 114 | i += 1 | ||
| 115 | } | ||
| 116 | i += 1 | ||
| 117 | } | ||
| 118 | let offset = props[":UTC_OFFSET:"].flatMap(Self.offset) | 128 | let offset = props[":UTC_OFFSET:"].flatMap(Self.offset) |
| 119 | guard let date = try? Date(String(lines[1].dropFirst().dropLast()), strategy: Self.orgDate(offset.flatMap(TimeZone.init(secondsFromGMT:)) ?? .current).parseStrategy) else { return nil } | 129 | guard let date = try? Date(String(lines[1].dropFirst().dropLast()), strategy: Self.orgDate(offset.flatMap(TimeZone.init(secondsFromGMT:)) ?? .current).parseStrategy) else { return nil } |
| 120 | let notes = lines.dropFirst(i).joined(separator: "\n").trimmingCharacters(in: .whitespacesAndNewlines) | 130 | let notes = lines.dropFirst(i).joined(separator: "\n").trimmingCharacters(in: .whitespacesAndNewlines) |
Packages/MoonriseKit/Sources/ObservingLog/Programs.swift +54 −25
| @@ -91,6 +91,18 @@ public struct ObservingProgram: Sendable, Identifiable, Equatable { | |||
| 91 | 91 | ||
| 92 | public var id: String { ids.first ?? CatalogResolver.fold(name) } | 92 | public var id: String { ids.first ?? CatalogResolver.fold(name) } |
| 93 | var keys: [String] { ids.isEmpty ? [id] : ids } | 93 | var keys: [String] { ids.isEmpty ? [id] : ids } |
| 94 | |||
| 95 | /// Applies one drawer property from a program file. | ||
| 96 | mutating func apply(_ p: OrgProperty) { | ||
| 97 | switch p.key { | ||
| 98 | case ":CATALOG:": | ||
| 99 | ids = p.value.split(separator: " ").map { CatalogResolver.designation(String($0)) ?? String($0) } | ||
| 100 | if CatalogResolver.designation(name) == nil { aliases = [name] } | ||
| 101 | case ":RA:": ra = Double(p.value) | ||
| 102 | case ":DEC:": dec = Double(p.value) | ||
| 103 | default: break | ||
| 104 | } | ||
| 105 | } | ||
| 94 | } | 106 | } |
| 95 | 107 | ||
| 96 | public var id: String | 108 | public var id: String |
| @@ -119,33 +131,12 @@ public struct ObservingProgram: Sendable, Identifiable, Equatable { | |||
| 119 | 131 | ||
| 120 | /// Parses a program file (format above). Names resolve against `resolver`. | 132 | /// Parses a program file (format above). Names resolve against `resolver`. |
| 121 | public init(org text: String, id: String, resolver: CatalogResolver = .messier) { | 133 | public init(org text: String, id: String, resolver: CatalogResolver = .messier) { |
| 122 | var title = id | 134 | var parser = ProgramFileParser(title: id, resolver: resolver) |
| 123 | var objects: [Object] = [] | ||
| 124 | var inDrawer = false | ||
| 125 | for line in text.components(separatedBy: "\n") { | 135 | for line in text.components(separatedBy: "\n") { |
| 126 | if line.lowercased().hasPrefix("#+title:") { | 136 | parser.read(line) |
| 127 | title = line.dropFirst(8).trimmingCharacters(in: .whitespaces) | ||
| 128 | } else if line.hasPrefix("* ") { | ||
| 129 | let name = line.dropFirst(2).trimmingCharacters(in: .whitespaces) | ||
| 130 | let id = resolver.id(for: name) | ||
| 131 | objects.append(Object(ids: id.map { [$0] } ?? [], name: name, aliases: [], detail: "")) | ||
| 132 | inDrawer = false | ||
| 133 | } else if !objects.isEmpty, line.trimmingCharacters(in: .whitespaces) == ":PROPERTIES:" { | ||
| 134 | inDrawer = true | ||
| 135 | } else if inDrawer, line.trimmingCharacters(in: .whitespaces) == ":END:" { | ||
| 136 | inDrawer = false | ||
| 137 | } else if inDrawer, let p = OrgProperty.parse(line.trimmingCharacters(in: .whitespaces)) { | ||
| 138 | let i = objects.count - 1 | ||
| 139 | switch p.key { | ||
| 140 | case ":CATALOG:": | ||
| 141 | objects[i].ids = p.value.split(separator: " ").map { CatalogResolver.designation(String($0)) ?? String($0) } | ||
| 142 | if CatalogResolver.designation(objects[i].name) == nil { objects[i].aliases = [objects[i].name] } | ||
| 143 | case ":RA:": objects[i].ra = Double(p.value) | ||
| 144 | case ":DEC:": objects[i].dec = Double(p.value) | ||
| 145 | default: break | ||
| 146 | } | ||
| 147 | } | ||
| 148 | } | 137 | } |
| 138 | let title = parser.title | ||
| 139 | var objects = parser.objects | ||
| 149 | for i in objects.indices where objects[i].ra == nil || objects[i].dec == nil { | 140 | for i in objects.indices where objects[i].ra == nil || objects[i].dec == nil { |
| 150 | if let m = Self.messier.objects.first(where: { $0.id == objects[i].id }) { | 141 | if let m = Self.messier.objects.first(where: { $0.id == objects[i].id }) { |
| 151 | objects[i].ra = m.ra | 142 | objects[i].ra = m.ra |
| @@ -188,3 +179,41 @@ public struct ProgramProgress: Sendable { | |||
| 188 | self.first = first | 179 | self.first = first |
| 189 | } | 180 | } |
| 190 | } | 181 | } |
| 182 | |||
| 183 | /// Reads a program file line by line: its title, its headings, and their drawers. | ||
| 184 | private struct ProgramFileParser { | ||
| 185 | var title: String | ||
| 186 | let resolver: CatalogResolver | ||
| 187 | var objects: [ObservingProgram.Object] = [] | ||
| 188 | var inDrawer = false | ||
| 189 | |||
| 190 | init(title: String, resolver: CatalogResolver) { | ||
| 191 | self.title = title | ||
| 192 | self.resolver = resolver | ||
| 193 | } | ||
| 194 | |||
| 195 | mutating func read(_ line: String) { | ||
| 196 | let trimmed = line.trimmingCharacters(in: .whitespaces) | ||
| 197 | if line.lowercased().hasPrefix("#+title:") { | ||
| 198 | title = line.dropFirst(8).trimmingCharacters(in: .whitespaces) | ||
| 199 | return | ||
| 200 | } | ||
| 201 | if line.hasPrefix("* ") { | ||
| 202 | let name = line.dropFirst(2).trimmingCharacters(in: .whitespaces) | ||
| 203 | let id = resolver.id(for: name) | ||
| 204 | objects.append(ObservingProgram.Object(ids: id.map { [$0] } ?? [], name: name, aliases: [], detail: "")) | ||
| 205 | inDrawer = false | ||
| 206 | return | ||
| 207 | } | ||
| 208 | if !objects.isEmpty, trimmed == ":PROPERTIES:" { | ||
| 209 | inDrawer = true | ||
| 210 | return | ||
| 211 | } | ||
| 212 | guard inDrawer else { return } | ||
| 213 | if trimmed == ":END:" { | ||
| 214 | inDrawer = false | ||
| 215 | } else if let p = OrgProperty.parse(trimmed) { | ||
| 216 | objects[objects.count - 1].apply(p) | ||
| 217 | } | ||
| 218 | } | ||
| 219 | } | ||
Packages/MoonriseKit/Sources/SkyEngine/Events.swift +52 −10
| @@ -90,9 +90,21 @@ extension SkyEngine { | |||
| 90 | lock.lock() | 90 | lock.lock() |
| 91 | defer { lock.unlock() } | 91 | defer { lock.unlock() } |
| 92 | let end = start.addingTimeInterval(days * 86_400) | 92 | let end = start.addingTimeInterval(days * 86_400) |
| 93 | var out: [SkyEvent] = [] | 93 | let kinds = [ |
| 94 | moonPhaseEvents(from: start, to: end, observer: observer), | ||
| 95 | lunarEclipseEvents(from: start, to: end, observer: observer), | ||
| 96 | solarEclipseEvents(from: start, to: end, observer: observer), | ||
| 97 | oppositionEvents(from: start, to: end, observer: observer), | ||
| 98 | elongationEvents(from: start, to: end, observer: observer), | ||
| 99 | seasonEvents(from: start, to: end, observer: observer), | ||
| 100 | meteorShowerEvents(from: start, to: end, observer: observer), | ||
| 101 | ] | ||
| 102 | return kinds.flatMap { $0 }.sorted { $0.date < $1.date } | ||
| 103 | } | ||
| 94 | 104 | ||
| 95 | // Full and new moons | 105 | /// Full and new moons. |
| 106 | private static func moonPhaseEvents(from start: Date, to end: Date, observer: Observer) -> [SkyEvent] { | ||
| 107 | var out: [SkyEvent] = [] | ||
| 96 | var t = time(start) | 108 | var t = time(start) |
| 97 | while true { | 109 | while true { |
| 98 | let q = Astronomy_SearchMoonQuarter(t) | 110 | let q = Astronomy_SearchMoonQuarter(t) |
| @@ -105,7 +117,12 @@ extension SkyEngine { | |||
| 105 | t = Astronomy_AddDays(q.time, 1) | 117 | t = Astronomy_AddDays(q.time, 1) |
| 106 | } | 118 | } |
| 107 | 119 | ||
| 108 | // Lunar eclipses | 120 | return out |
| 121 | } | ||
| 122 | |||
| 123 | /// Lunar eclipses. | ||
| 124 | private static func lunarEclipseEvents(from start: Date, to end: Date, observer: Observer) -> [SkyEvent] { | ||
| 125 | var out: [SkyEvent] = [] | ||
| 109 | var lunar = Astronomy_SearchLunarEclipse(time(start)) | 126 | var lunar = Astronomy_SearchLunarEclipse(time(start)) |
| 110 | while lunar.status == ASTRO_SUCCESS, date(lunar.peak) <= end { | 127 | while lunar.status == ASTRO_SUCCESS, date(lunar.peak) <= end { |
| 111 | var peak = lunar.peak | 128 | var peak = lunar.peak |
| @@ -118,7 +135,12 @@ extension SkyEngine { | |||
| 118 | lunar = Astronomy_NextLunarEclipse(lunar.peak) | 135 | lunar = Astronomy_NextLunarEclipse(lunar.peak) |
| 119 | } | 136 | } |
| 120 | 137 | ||
| 121 | // Solar eclipses: global, with local circumstances for the observer | 138 | return out |
| 139 | } | ||
| 140 | |||
| 141 | /// Solar eclipses: global, with local circumstances for the observer. | ||
| 142 | private static func solarEclipseEvents(from start: Date, to end: Date, observer: Observer) -> [SkyEvent] { | ||
| 143 | var out: [SkyEvent] = [] | ||
| 122 | var local: [Date: astro_local_solar_eclipse_t] = [:] | 144 | var local: [Date: astro_local_solar_eclipse_t] = [:] |
| 123 | var l = Astronomy_SearchLocalSolarEclipse(time(start), observer.astro) | 145 | var l = Astronomy_SearchLocalSolarEclipse(time(start), observer.astro) |
| 124 | while l.status == ASTRO_SUCCESS, date(l.peak.time) <= end { | 146 | while l.status == ASTRO_SUCCESS, date(l.peak.time) <= end { |
| @@ -146,14 +168,24 @@ extension SkyEngine { | |||
| 146 | solar = Astronomy_NextGlobalSolarEclipse(solar.peak) | 168 | solar = Astronomy_NextGlobalSolarEclipse(solar.peak) |
| 147 | } | 169 | } |
| 148 | 170 | ||
| 149 | // Oppositions of the outer planets | 171 | return out |
| 172 | } | ||
| 173 | |||
| 174 | /// Oppositions of the outer planets. | ||
| 175 | private static func oppositionEvents(from start: Date, to end: Date, observer: Observer) -> [SkyEvent] { | ||
| 176 | var out: [SkyEvent] = [] | ||
| 150 | for body in [Body.mars, .jupiter, .saturn, .uranus, .neptune] { | 177 | for body in [Body.mars, .jupiter, .saturn, .uranus, .neptune] { |
| 151 | let r = Astronomy_SearchRelativeLongitude(body.astro, 0, time(start)) | 178 | let r = Astronomy_SearchRelativeLongitude(body.astro, 0, time(start)) |
| 152 | guard r.status == ASTRO_SUCCESS, date(r.time) <= end else { continue } | 179 | guard r.status == ASTRO_SUCCESS, date(r.time) <= end else { continue } |
| 153 | out.append(SkyEvent(kind: .opposition, date: date(r.time), title: "\(body.rawValue.capitalized) at opposition", detail: "Opposite the Sun: up all night and at its closest and brightest for the year.", visibleHere: nil)) | 180 | out.append(SkyEvent(kind: .opposition, date: date(r.time), title: "\(body.rawValue.capitalized) at opposition", detail: "Opposite the Sun: up all night and at its closest and brightest for the year.", visibleHere: nil)) |
| 154 | } | 181 | } |
| 155 | 182 | ||
| 156 | // Greatest elongations of Mercury and Venus | 183 | return out |
| 184 | } | ||
| 185 | |||
| 186 | /// Greatest elongations of Mercury and Venus. | ||
| 187 | private static func elongationEvents(from start: Date, to end: Date, observer: Observer) -> [SkyEvent] { | ||
| 188 | var out: [SkyEvent] = [] | ||
| 157 | for body in [Body.mercury, .venus] { | 189 | for body in [Body.mercury, .venus] { |
| 158 | var from = time(start) | 190 | var from = time(start) |
| 159 | while true { | 191 | while true { |
| @@ -165,7 +197,12 @@ extension SkyEngine { | |||
| 165 | } | 197 | } |
| 166 | } | 198 | } |
| 167 | 199 | ||
| 168 | // Equinoxes and solstices | 200 | return out |
| 201 | } | ||
| 202 | |||
| 203 | /// Equinoxes and solstices. | ||
| 204 | private static func seasonEvents(from start: Date, to end: Date, observer: Observer) -> [SkyEvent] { | ||
| 205 | var out: [SkyEvent] = [] | ||
| 169 | let cal = Calendar(identifier: .gregorian) | 206 | let cal = Calendar(identifier: .gregorian) |
| 170 | let y0 = cal.component(.year, from: start) | 207 | let y0 = cal.component(.year, from: start) |
| 171 | for y in y0...(y0 + 1) { | 208 | for y in y0...(y0 + 1) { |
| @@ -177,7 +214,13 @@ extension SkyEngine { | |||
| 177 | } | 214 | } |
| 178 | } | 215 | } |
| 179 | 216 | ||
| 180 | // Meteor showers, with darkness and the Moon on the observer's night of the peak | 217 | return out |
| 218 | } | ||
| 219 | |||
| 220 | /// Meteor showers, with darkness and the Moon on the observer's night of the peak. | ||
| 221 | private static func meteorShowerEvents(from start: Date, to end: Date, observer: Observer) -> [SkyEvent] { | ||
| 222 | var out: [SkyEvent] = [] | ||
| 223 | let y0 = Calendar(identifier: .gregorian).component(.year, from: start) | ||
| 181 | var utc = Calendar(identifier: .gregorian) | 224 | var utc = Calendar(identifier: .gregorian) |
| 182 | utc.timeZone = TimeZone(identifier: "UTC")! | 225 | utc.timeZone = TimeZone(identifier: "UTC")! |
| 183 | for y in y0...(y0 + 1) { | 226 | for y in y0...(y0 + 1) { |
| @@ -196,7 +239,6 @@ extension SkyEngine { | |||
| 196 | zhr: m.zhr, moonIllumination: lit)) | 239 | zhr: m.zhr, moonIllumination: lit)) |
| 197 | } | 240 | } |
| 198 | } | 241 | } |
| 199 | 242 | return out | |
| 200 | return out.sorted { $0.date < $1.date } | ||
| 201 | } | 243 | } |
| 202 | } | 244 | } |
Packages/MoonriseKit/Sources/SkyEngine/Passes.swift +37 −15
| @@ -105,11 +105,42 @@ extension SkyEngine { | |||
| 105 | return (perp * perp).sum().squareRoot() > 6378.135 | 105 | return (perp * perp).sum().squareRoot() > 6378.135 |
| 106 | } | 106 | } |
| 107 | 107 | ||
| 108 | /// A pass from its rise to the latest sample above the horizon. | ||
| 109 | private struct OpenPass { | ||
| 110 | var rise: Date, riseAz: Double, peak: Date, maxAlt: Double | ||
| 111 | var visible = false | ||
| 112 | |||
| 113 | /// Records a sample above the horizon; `lit` is asked only while the pass has not yet been seen high enough. | ||
| 114 | mutating func observe(altitude: Double, at t: Date, minAltitude: Double, lit: () -> Bool) { | ||
| 115 | if altitude > maxAlt { maxAlt = altitude; peak = t } | ||
| 116 | if !visible, altitude >= minAltitude, lit() { visible = true } | ||
| 117 | } | ||
| 118 | |||
| 119 | func pass(of elements: OrbitalElements, set: Date, setAzimuth: Double) -> SatellitePass { | ||
| 120 | SatellitePass(name: elements.OBJECT_NAME, rise: rise, set: set, peak: peak, maxAltitude: maxAlt, riseAzimuth: riseAz, setAzimuth: setAzimuth, visible: visible, featured: elements.isFeatured) | ||
| 121 | } | ||
| 122 | } | ||
| 123 | |||
| 124 | /// 20 s samples to advance from `altitude`: further the further below the horizon (see `passes(of:)`). | ||
| 125 | private static func samplesToSkip(below altitude: Double) -> Int { | ||
| 126 | altitude > -8 ? 1 : altitude > -30 ? 3 : 9 | ||
| 127 | } | ||
| 128 | |||
| 129 | /// Whether a satellite at `r` is in sunlight while the observer's sky is past civil twilight. | ||
| 130 | private static func litInDarkSky(_ r: SIMD3<Double>, at t: Date, observer: Observer) -> Bool { | ||
| 131 | lock.lock() | ||
| 132 | defer { lock.unlock() } | ||
| 133 | var tt = time(t) | ||
| 134 | let sun = Astronomy_Equator(BODY_SUN, &tt, observer.astro, EQUATOR_OF_DATE, ABERRATION) | ||
| 135 | let sunAlt = Astronomy_Horizon(&tt, observer.astro, sun.ra, sun.dec, REFRACTION_NORMAL).altitude | ||
| 136 | return sunAlt < -6 && sunlit(r, sun: sunDirection(t)) | ||
| 137 | } | ||
| 138 | |||
| 108 | /// Passes above `minAltitude` in the next `hours`, sampled every 20 s from 8° below the horizon up. | 139 | /// Passes above `minAltitude` in the next `hours`, sampled every 20 s from 8° below the horizon up. |
| 109 | public static func passes(of elements: OrbitalElements, from start: Date, hours: Double = 72, observer: Observer, minAltitude: Double = 10) -> [SatellitePass] { | 140 | public static func passes(of elements: OrbitalElements, from start: Date, hours: Double = 72, observer: Observer, minAltitude: Double = 10) -> [SatellitePass] { |
| 110 | guard let sgp = try? SGP4(elements) else { return [] } | 141 | guard let sgp = try? SGP4(elements) else { return [] } |
| 111 | var out: [SatellitePass] = [] | 142 | var out: [SatellitePass] = [] |
| 112 | var current: (rise: Date, riseAz: Double, peak: Date, maxAlt: Double, visible: Bool)? | 143 | var current: OpenPass? |
| 113 | var lastAz = 0.0 | 144 | var lastAz = 0.0 |
| 114 | var i = 0 | 145 | var i = 0 |
| 115 | var t = start | 146 | var t = start |
| @@ -118,28 +149,19 @@ extension SkyEngine { | |||
| 118 | guard let r = sgp.position(at: t) else { break } | 149 | guard let r = sgp.position(at: t) else { break } |
| 119 | let h = lookAngles(teme: r, at: t, from: observer) | 150 | let h = lookAngles(teme: r, at: t, from: observer) |
| 120 | if h.altitude >= 0 { | 151 | if h.altitude >= 0 { |
| 121 | if current == nil { current = (t, h.azimuth, t, h.altitude, false) } | 152 | var c = current ?? OpenPass(rise: t, riseAz: h.azimuth, peak: t, maxAlt: h.altitude) |
| 122 | if h.altitude > current!.maxAlt { current!.maxAlt = h.altitude; current!.peak = t } | 153 | c.observe(altitude: h.altitude, at: t, minAltitude: minAltitude) { litInDarkSky(r, at: t, observer: observer) } |
| 123 | if !current!.visible, h.altitude >= minAltitude { | 154 | current = c |
| 124 | lock.lock() | ||
| 125 | var tt = time(t) | ||
| 126 | let sun = Astronomy_Equator(BODY_SUN, &tt, observer.astro, EQUATOR_OF_DATE, ABERRATION) | ||
| 127 | let sunAlt = Astronomy_Horizon(&tt, observer.astro, sun.ra, sun.dec, REFRACTION_NORMAL).altitude | ||
| 128 | if sunAlt < -6, sunlit(r, sun: sunDirection(t)) { current!.visible = true } | ||
| 129 | lock.unlock() | ||
| 130 | } | ||
| 131 | lastAz = h.azimuth | 155 | lastAz = h.azimuth |
| 132 | } else if let c = current { | 156 | } else if let c = current { |
| 133 | if c.maxAlt >= minAltitude { | 157 | if c.maxAlt >= minAltitude { out.append(c.pass(of: elements, set: t, setAzimuth: lastAz)) } |
| 134 | out.append(SatellitePass(name: elements.OBJECT_NAME, rise: c.rise, set: t, peak: c.peak, maxAltitude: c.maxAlt, riseAzimuth: c.riseAz, setAzimuth: lastAz, visible: c.visible, featured: elements.isFeatured)) | ||
| 135 | } | ||
| 136 | current = nil | 158 | current = nil |
| 137 | } | 159 | } |
| 138 | // Below the horizon altitude changes no faster than the satellite moves around Earth's centre relative to the | 160 | // Below the horizon altitude changes no faster than the satellite moves around Earth's centre relative to the |
| 139 | // observer: about 4°/min in low orbit, under 6.5°/min for any orbit above the surface. A 60 s step from below | 161 | // observer: about 4°/min in low orbit, under 6.5°/min for any orbit above the surface. A 60 s step from below |
| 140 | // -8° skips 40 s (at most 4.3°) and a 180 s step from below -30° skips 160 s (at most 17.3°), so no 20 s sample | 162 | // -8° skips 40 s (at most 4.3°) and a 180 s step from below -30° skips 160 s (at most 17.3°), so no 20 s sample |
| 141 | // at or above the horizon is skipped and the passes are those of plain 20 s steps. | 163 | // at or above the horizon is skipped and the passes are those of plain 20 s steps. |
| 142 | i += h.altitude > -8 ? 1 : h.altitude > -30 ? 3 : 9 | 164 | i += samplesToSkip(below: h.altitude) |
| 143 | t = start.addingTimeInterval(Double(i) * 20) | 165 | t = start.addingTimeInterval(Double(i) * 20) |
| 144 | } | 166 | } |
| 145 | return out | 167 | return out |
Packages/MoonriseKit/Sources/SkyEngine/SmallBody.swift +35 −27
| @@ -30,33 +30,7 @@ public struct SmallBody: Sendable, Equatable, Codable, Identifiable { | |||
| 30 | /// Heliocentric position in AU on J2000 ecliptic axes. | 30 | /// Heliocentric position in AU on J2000 ecliptic axes. |
| 31 | public func position(at date: Date) -> SIMD3<Double> { | 31 | public func position(at date: Date) -> SIMD3<Double> { |
| 32 | let dt = date.timeIntervalSince1970 / 86_400 + 2_440_587.5 - tp | 32 | let dt = date.timeIntervalSince1970 / 86_400 + 2_440_587.5 - tp |
| 33 | var x: Double, y: Double | 33 | let (x, y) = abs(e - 1) < 1e-4 ? nearParabolicPosition(dt) : e < 1 ? ellipticPosition(dt) : hyperbolicPosition(dt) |
| 34 | if abs(e - 1) < 1e-4 { | ||
| 35 | // Barker's equation: s + s³/3 = k Δt / √(2q³), s = tan(ν/2). | ||
| 36 | let w = 3 * Self.k * dt / (2 * q * q * q).squareRoot() | ||
| 37 | let c = cbrt(w / 2 + (w * w / 4 + 1).squareRoot()) | ||
| 38 | let s = c - 1 / c | ||
| 39 | (x, y) = (q * (1 - s * s), 2 * q * s) | ||
| 40 | } else if e < 1 { | ||
| 41 | let a = q / (1 - e), m = Self.k * dt / pow(a, 1.5) | ||
| 42 | let mm = remainder(m, 2 * .pi) | ||
| 43 | var E = e < 0.8 ? mm : .pi * (mm < 0 ? -1 : 1) | ||
| 44 | for _ in 0..<60 { | ||
| 45 | let d = (E - e * sin(E) - mm) / (1 - e * cos(E)) | ||
| 46 | E -= d | ||
| 47 | if abs(d) < 1e-13 { break } | ||
| 48 | } | ||
| 49 | (x, y) = (a * (cos(E) - e), a * (1 - e * e).squareRoot() * sin(E)) | ||
| 50 | } else { | ||
| 51 | let a = q / (e - 1), m = Self.k * dt / pow(a, 1.5) | ||
| 52 | var h = asinh(m / e) | ||
| 53 | for _ in 0..<60 { | ||
| 54 | let d = (e * sinh(h) - h - m) / (e * cosh(h) - 1) | ||
| 55 | h -= d | ||
| 56 | if abs(d) < 1e-13 { break } | ||
| 57 | } | ||
| 58 | (x, y) = (a * (e - cosh(h)), a * (e * e - 1).squareRoot() * sinh(h)) | ||
| 59 | } | ||
| 60 | let r = Double.pi / 180 | 34 | let r = Double.pi / 180 |
| 61 | let (cO, sO) = (cos(node * r), sin(node * r)), (cw, sw) = (cos(peri * r), sin(peri * r)), (ci, si) = (cos(i * r), sin(i * r)) | 35 | let (cO, sO) = (cos(node * r), sin(node * r)), (cw, sw) = (cos(peri * r), sin(peri * r)), (ci, si) = (cos(i * r), sin(i * r)) |
| 62 | return SIMD3( | 36 | return SIMD3( |
| @@ -66,6 +40,40 @@ public struct SmallBody: Sendable, Equatable, Codable, Identifiable { | |||
| 66 | ) | 40 | ) |
| 67 | } | 41 | } |
| 68 | 42 | ||
| 43 | /// In-plane position for an eccentricity near 1, by Barker's equation: | ||
| 44 | /// s + s³/3 = k Δt / √(2q³), s = tan(ν/2). | ||
| 45 | private func nearParabolicPosition(_ dt: Double) -> (x: Double, y: Double) { | ||
| 46 | let w = 3 * Self.k * dt / (2 * q * q * q).squareRoot() | ||
| 47 | let c = cbrt(w / 2 + (w * w / 4 + 1).squareRoot()) | ||
| 48 | let s = c - 1 / c | ||
| 49 | return (q * (1 - s * s), 2 * q * s) | ||
| 50 | } | ||
| 51 | |||
| 52 | /// In-plane position on an ellipse, solving Kepler's equation by Newton's method. | ||
| 53 | private func ellipticPosition(_ dt: Double) -> (x: Double, y: Double) { | ||
| 54 | let a = q / (1 - e), m = Self.k * dt / pow(a, 1.5) | ||
| 55 | let mm = remainder(m, 2 * .pi) | ||
| 56 | var E = e < 0.8 ? mm : .pi * (mm < 0 ? -1 : 1) | ||
| 57 | for _ in 0..<60 { | ||
| 58 | let d = (E - e * sin(E) - mm) / (1 - e * cos(E)) | ||
| 59 | E -= d | ||
| 60 | if abs(d) < 1e-13 { break } | ||
| 61 | } | ||
| 62 | return (a * (cos(E) - e), a * (1 - e * e).squareRoot() * sin(E)) | ||
| 63 | } | ||
| 64 | |||
| 65 | /// In-plane position on a hyperbola, solving the hyperbolic Kepler equation by Newton's method. | ||
| 66 | private func hyperbolicPosition(_ dt: Double) -> (x: Double, y: Double) { | ||
| 67 | let a = q / (e - 1), m = Self.k * dt / pow(a, 1.5) | ||
| 68 | var h = asinh(m / e) | ||
| 69 | for _ in 0..<60 { | ||
| 70 | let d = (e * sinh(h) - h - m) / (e * cosh(h) - 1) | ||
| 71 | h -= d | ||
| 72 | if abs(d) < 1e-13 { break } | ||
| 73 | } | ||
| 74 | return (a * (e - cosh(h)), a * (e * e - 1).squareRoot() * sinh(h)) | ||
| 75 | } | ||
| 76 | |||
| 69 | /// Astrometric J2000 right ascension and declination (degrees), distances (AU) and magnitude from Earth at `date`; | 77 | /// Astrometric J2000 right ascension and declination (degrees), distances (AU) and magnitude from Earth at `date`; |
| 70 | /// light time is ignored. | 78 | /// light time is ignored. |
| 71 | public func apparent(at date: Date) throws -> (ra: Double, dec: Double, r: Double, delta: Double, magnitude: Double) { | 79 | public func apparent(at date: Date) throws -> (ra: Double, dec: Double, r: Double, delta: Double, magnitude: Double) { |
scripts/check-library.py +27 −16
| @@ -30,31 +30,42 @@ def status(url, image=False): | |||
| 30 | return err | 30 | return err |
| 31 | 31 | ||
| 32 | 32 | ||
| 33 | def main(): | 33 | def load_pages(): |
| 34 | offline = "--offline" in sys.argv | 34 | """(file name, page) for every Library page, files in name order.""" |
| 35 | pages, problems = [], [] | 35 | return [(f.name, p) for f in sorted(PAGES.glob("*.json")) for p in json.loads(f.read_text())] |
| 36 | for f in sorted(PAGES.glob("*.json")): | 36 | |
| 37 | for p in json.loads(f.read_text()): | 37 | |
| 38 | pages.append((f.name, p)) | 38 | def url_checks(pages): |
| 39 | print(f"{len(pages)} pages in {len(list(PAGES.glob('*.json')))} files") | 39 | """(page id, what, URL, must be an image) for each source and image a page cites.""" |
| 40 | if offline: | ||
| 41 | return 0 | ||
| 42 | checks = [] | 40 | checks = [] |
| 43 | for name, p in pages: | 41 | for _, p in pages: |
| 44 | for s in p.get("sources", []): | 42 | for s in p.get("sources", []): |
| 45 | if not s["url"].startswith(SKIP): | 43 | if not s["url"].startswith(SKIP): |
| 46 | checks.append((p["id"], "source", s["url"], False)) | 44 | checks.append((p["id"], "source", s["url"], False)) |
| 47 | if p.get("image"): | 45 | if p.get("image"): |
| 48 | checks.append((p["id"], "image", p["image"]["url"], True)) | 46 | checks.append((p["id"], "image", p["image"]["url"], True)) |
| 49 | checks.append((p["id"], "image page", p["image"]["page"], False)) | 47 | checks.append((p["id"], "image page", p["image"]["page"], False)) |
| 48 | return checks | ||
| 49 | |||
| 50 | |||
| 51 | def problem(check, st): | ||
| 52 | """The report line for a failed check, or None when it passed.""" | ||
| 53 | pid, kind, url, _ = check | ||
| 54 | # Sites that refuse scripts (403/429) but load in a browser. | ||
| 55 | if st in (403, 429) and any(url.startswith(p) for p in BLOCKS_SCRIPTS): | ||
| 56 | return None | ||
| 57 | return None if st == 200 else f"{pid}: {kind} {st} {url}" | ||
| 58 | |||
| 59 | |||
| 60 | def main(): | ||
| 61 | pages = load_pages() | ||
| 62 | print(f"{len(pages)} pages in {len(list(PAGES.glob('*.json')))} files") | ||
| 63 | if "--offline" in sys.argv: | ||
| 64 | return 0 | ||
| 65 | checks = url_checks(pages) | ||
| 50 | with ThreadPoolExecutor(8) as pool: | 66 | with ThreadPoolExecutor(8) as pool: |
| 51 | results = list(pool.map(lambda c: (c, status(c[2], c[3])), checks)) | 67 | results = list(pool.map(lambda c: (c, status(c[2], c[3])), checks)) |
| 52 | for (pid, kind, url, _), st in results: | 68 | problems = [line for line in (problem(c, st) for c, st in results) if line] |
| 53 | # Sites that refuse scripts (403/429) but load in a browser. | ||
| 54 | if st in (403, 429) and any(url.startswith(p) for p in BLOCKS_SCRIPTS): | ||
| 55 | continue | ||
| 56 | if st != 200: | ||
| 57 | problems.append(f"{pid}: {kind} {st} {url}") | ||
| 58 | print(f"{len(checks)} URLs checked, {len(problems)} problems") | 69 | print(f"{len(checks)} URLs checked, {len(problems)} problems") |
| 59 | for line in problems: | 70 | for line in problems: |
| 60 | print(" " + line) | 71 | print(" " + line) |
scripts/make-clouds.py +36 −17
| @@ -40,8 +40,8 @@ def palette(): | |||
| 40 | return out | 40 | return out |
| 41 | 41 | ||
| 42 | 42 | ||
| 43 | def rgba(png): | 43 | def chunks(png): |
| 44 | """Pixels of an 8-bit RGBA, non-interlaced PNG, as rows of (r, g, b, a).""" | 44 | """Width, height and the concatenated IDAT data of an 8-bit RGBA PNG.""" |
| 45 | assert png[:8] == b"\x89PNG\r\n\x1a\n" | 45 | assert png[:8] == b"\x89PNG\r\n\x1a\n" |
| 46 | pos, data, width, height = 8, b"", 0, 0 | 46 | pos, data, width, height = 8, b"", 0, 0 |
| 47 | while pos < len(png): | 47 | while pos < len(png): |
| @@ -53,35 +53,54 @@ def rgba(png): | |||
| 53 | elif kind == b"IDAT": | 53 | elif kind == b"IDAT": |
| 54 | data += body | 54 | data += body |
| 55 | pos += 12 + length | 55 | pos += 12 + length |
| 56 | return width, height, data | ||
| 57 | |||
| 58 | |||
| 59 | def paeth(a, b, c): | ||
| 60 | p = a + b - c | ||
| 61 | pa, pb, pc = abs(p - a), abs(p - b), abs(p - c) | ||
| 62 | return a if pa <= pb and pa <= pc else b if pb <= pc else c | ||
| 63 | |||
| 64 | |||
| 65 | def unfilter(f, line, prev): | ||
| 66 | """Reverses PNG filter `f` on one scanline in place, given the previous unfiltered one (4 bytes a pixel).""" | ||
| 67 | for i in range(len(line)): | ||
| 68 | a = line[i - 4] if i >= 4 else 0 | ||
| 69 | b, c = prev[i], prev[i - 4] if i >= 4 else 0 | ||
| 70 | if f == 1: line[i] = (line[i] + a) & 255 | ||
| 71 | elif f == 2: line[i] = (line[i] + b) & 255 | ||
| 72 | elif f == 3: line[i] = (line[i] + (a + b) // 2) & 255 | ||
| 73 | elif f == 4: line[i] = (line[i] + paeth(a, b, c)) & 255 | ||
| 74 | |||
| 75 | |||
| 76 | def rgba(png): | ||
| 77 | """Pixels of an 8-bit RGBA, non-interlaced PNG, as rows of (r, g, b, a).""" | ||
| 78 | width, height, data = chunks(png) | ||
| 56 | raw, stride, rows, prev = zlib.decompress(data), width * 4, [], bytearray(width * 4) | 79 | raw, stride, rows, prev = zlib.decompress(data), width * 4, [], bytearray(width * 4) |
| 57 | for y in range(height): | 80 | for y in range(height): |
| 58 | f, line = raw[y * (stride + 1)], bytearray(raw[y * (stride + 1) + 1:(y + 1) * (stride + 1)]) | 81 | f, line = raw[y * (stride + 1)], bytearray(raw[y * (stride + 1) + 1:(y + 1) * (stride + 1)]) |
| 59 | for i in range(stride): | 82 | unfilter(f, line, prev) |
| 60 | a = line[i - 4] if i >= 4 else 0 | ||
| 61 | b, c = prev[i], prev[i - 4] if i >= 4 else 0 | ||
| 62 | if f == 1: line[i] = (line[i] + a) & 255 | ||
| 63 | elif f == 2: line[i] = (line[i] + b) & 255 | ||
| 64 | elif f == 3: line[i] = (line[i] + (a + b) // 2) & 255 | ||
| 65 | elif f == 4: | ||
| 66 | p = a + b - c | ||
| 67 | pa, pb, pc = abs(p - a), abs(p - b), abs(p - c) | ||
| 68 | line[i] = (line[i] + (a if pa <= pb and pa <= pc else b if pb <= pc else c)) & 255 | ||
| 69 | rows.append([tuple(line[x * 4:x * 4 + 4]) for x in range(width)]) | 83 | rows.append([tuple(line[x * 4:x * 4 + 4]) for x in range(width)]) |
| 70 | prev = line | 84 | prev = line |
| 71 | return rows | 85 | return rows |
| 72 | 86 | ||
| 73 | 87 | ||
| 88 | def accumulate(total, count, rows, colors): | ||
| 89 | """Adds each opaque pixel with a known colour to its cell.""" | ||
| 90 | for y, row in enumerate(rows): | ||
| 91 | for x, (r, g, b, a) in enumerate(row): | ||
| 92 | if a and (r, g, b) in colors: | ||
| 93 | total[y * 360 + x] += colors[(r, g, b)] | ||
| 94 | count[y * 360 + x] += 1 | ||
| 95 | |||
| 96 | |||
| 74 | def grid(month_day, colors): | 97 | def grid(month_day, colors): |
| 75 | month, day = (int(v) for v in month_day.split("-")) | 98 | month, day = (int(v) for v in month_day.split("-")) |
| 76 | total, count = [0] * 64800, [0] * 64800 | 99 | total, count = [0] * 64800, [0] * 64800 |
| 77 | for year in YEARS: | 100 | for year in YEARS: |
| 78 | for offset in OFFSETS: | 101 | for offset in OFFSETS: |
| 79 | d = datetime.date(year, month, day) + datetime.timedelta(days=offset) | 102 | d = datetime.date(year, month, day) + datetime.timedelta(days=offset) |
| 80 | for y, row in enumerate(rgba(get(WMS.format(layer=LAYER, day=d.isoformat())))): | 103 | accumulate(total, count, rgba(get(WMS.format(layer=LAYER, day=d.isoformat()))), colors) |
| 81 | for x, (r, g, b, a) in enumerate(row): | ||
| 82 | if a and (r, g, b) in colors: | ||
| 83 | total[y * 360 + x] += colors[(r, g, b)] | ||
| 84 | count[y * 360 + x] += 1 | ||
| 85 | time.sleep(1) | 104 | time.sleep(1) |
| 86 | return bytes(round(t / n) if n else 255 for t, n in zip(total, count)) | 105 | return bytes(round(t / n) if n else 255 for t, n in zip(total, count)) |
| 87 | 106 | ||
scripts/make-skycultures.py +53 −36
| @@ -51,14 +51,18 @@ def license_section(md): | |||
| 51 | return " ".join(out) | 51 | return " ".join(out) |
| 52 | 52 | ||
| 53 | 53 | ||
| 54 | def main(): | 54 | def load_hip(path): |
| 55 | """HIP number -> (RA, Dec, Vmag) from the VizieR TSV.""" | ||
| 55 | hip = {} | 56 | hip = {} |
| 56 | for line in open(sys.argv[1]): | 57 | for line in open(path): |
| 57 | p = line.rstrip("\n").split("\t") | 58 | p = line.rstrip("\n").split("\t") |
| 58 | if len(p) == 4 and p[0].strip().isdigit() and p[1].strip() and p[2].strip(): | 59 | if len(p) == 4 and p[0].strip().isdigit() and p[1].strip() and p[2].strip(): |
| 59 | hip[int(p[0])] = (float(p[1]), float(p[2]), float(p[3] or 99)) | 60 | hip[int(p[0])] = (float(p[1]), float(p[2]), float(p[3] or 99)) |
| 61 | return hip | ||
| 62 | |||
| 60 | 63 | ||
| 61 | bsc = json.load(open(RES / "bsc5.json")) | 64 | def hr_matcher(hip, bsc): |
| 65 | """A function from a HIP number to the BSC (HR) star within 0.05 degrees of it, or None.""" | ||
| 62 | cells = {} | 66 | cells = {} |
| 63 | for row in bsc: | 67 | for row in bsc: |
| 64 | cells.setdefault((int(row[2])), []).append(row) | 68 | cells.setdefault((int(row[2])), []).append(row) |
| @@ -76,40 +80,53 @@ def main(): | |||
| 76 | best = (sep, int(row[0])) | 80 | best = (sep, int(row[0])) |
| 77 | return best[1] if best else None | 81 | return best[1] if best else None |
| 78 | 82 | ||
| 79 | out = [] | 83 | return hr_for |
| 80 | for cid, name in CULTURES: | 84 | |
| 81 | index = json.loads(fetch(f"{BASE}/{cid}/index.json")) | 85 | |
| 82 | lic = license_section(fetch(f"{BASE}/{cid}/description.md")) | 86 | def segments(line, hr_for): |
| 83 | assert "BY-SA" in lic.replace("-BY SA", "BY-SA").replace("BY SA", "BY-SA"), (cid, lic) | 87 | """A Stellarium line as runs of matched HR stars, split at stars without a match.""" |
| 84 | constellations = [] | 88 | out, current = [], [] |
| 85 | for c in index.get("constellations", []): | 89 | for h in line: |
| 86 | segments = [] | 90 | hr = hr_for(h) if isinstance(h, int) else None |
| 87 | for line in c.get("lines", []): | 91 | if hr is None: |
| 88 | current = [] | 92 | if len(current) > 1: |
| 89 | for h in line: | 93 | out.append(current) |
| 90 | hr = hr_for(h) if isinstance(h, int) else None | 94 | current = [] |
| 91 | if hr is None: | 95 | else: |
| 92 | if len(current) > 1: | 96 | current.append(hr) |
| 93 | segments.append(current) | 97 | if len(current) > 1: |
| 94 | current = [] | 98 | out.append(current) |
| 95 | else: | 99 | return out |
| 96 | current.append(hr) | 100 | |
| 97 | if len(current) > 1: | 101 | |
| 98 | segments.append(current) | 102 | def constellation(c, hr_for): |
| 99 | if not segments: | 103 | """One figure for the app, or None when none of its lines survive matching.""" |
| 100 | continue | 104 | lines = [s for line in c.get("lines", []) for s in segments(line, hr_for)] |
| 101 | cn = c.get("common_name", {}) | 105 | if not lines: |
| 102 | entry = {"name": cn.get("english") or cn.get("native") or c["id"], "lines": segments} | 106 | return None |
| 103 | if cn.get("native") and cn.get("native") != entry["name"]: | 107 | cn = c.get("common_name", {}) |
| 104 | entry["native"] = cn["native"] | 108 | entry = {"name": cn.get("english") or cn.get("native") or c["id"], "lines": lines} |
| 105 | constellations.append(entry) | 109 | if cn.get("native") and cn.get("native") != entry["name"]: |
| 106 | out.append({ | 110 | entry["native"] = cn["native"] |
| 107 | "id": cid, "name": name, "region": index.get("region", ""), | 111 | return entry |
| 108 | "licence": lic, "source": f"https://github.com/Stellarium/stellarium-skycultures/tree/master/{cid}", | 112 | |
| 109 | "constellations": constellations, | 113 | |
| 110 | }) | 114 | def culture(cid, name, hr_for): |
| 111 | print(f"{cid}: {len(constellations)} of {len(index.get('constellations', []))} figures", file=sys.stderr) | 115 | index = json.loads(fetch(f"{BASE}/{cid}/index.json")) |
| 116 | lic = license_section(fetch(f"{BASE}/{cid}/description.md")) | ||
| 117 | assert "BY-SA" in lic.replace("-BY SA", "BY-SA").replace("BY SA", "BY-SA"), (cid, lic) | ||
| 118 | figures = [f for f in (constellation(c, hr_for) for c in index.get("constellations", [])) if f] | ||
| 119 | print(f"{cid}: {len(figures)} of {len(index.get('constellations', []))} figures", file=sys.stderr) | ||
| 120 | return { | ||
| 121 | "id": cid, "name": name, "region": index.get("region", ""), | ||
| 122 | "licence": lic, "source": f"https://github.com/Stellarium/stellarium-skycultures/tree/master/{cid}", | ||
| 123 | "constellations": figures, | ||
| 124 | } | ||
| 112 | 125 | ||
| 126 | |||
| 127 | def main(): | ||
| 128 | hr_for = hr_matcher(load_hip(sys.argv[1]), json.load(open(RES / "bsc5.json"))) | ||
| 129 | out = [culture(cid, name, hr_for) for cid, name in CULTURES] | ||
| 113 | (RES / "skycultures.json").write_text(json.dumps(out, ensure_ascii=False, separators=(",", ":"))) | 130 | (RES / "skycultures.json").write_text(json.dumps(out, ensure_ascii=False, separators=(",", ":"))) |
| 114 | 131 | ||
| 115 | 132 | ||
server/src/apns.ts +9 −2
| @@ -105,8 +105,15 @@ async function result(res: Response, idHeader: string): Promise<ApnsResult> { | |||
| 105 | return { status: res.status, apnsId: res.headers.get(idHeader), reason }; | 105 | return { status: res.status, apnsId: res.headers.get(idHeader), reason }; |
| 106 | } | 106 | } |
| 107 | 107 | ||
| 108 | /** A Live Activity update to every device listening on a broadcast channel. `expiration` is in Unix seconds. */ | 108 | /** How a broadcast is delivered. `expiration` is in Unix seconds. */ |
| 109 | export async function broadcast(config: ApnsConfig, channelId: string, payload: unknown, sandbox: boolean, priority: 5 | 10, expiration: number): Promise<ApnsResult> { | 109 | export interface BroadcastOptions { |
| 110 | sandbox: boolean; | ||
| 111 | priority: 5 | 10; | ||
| 112 | expiration: number; | ||
| 113 | } | ||
| 114 | |||
| 115 | /** A Live Activity update to every device listening on a broadcast channel. */ | ||
| 116 | export async function broadcast(config: ApnsConfig, channelId: string, payload: unknown, { sandbox, priority, expiration }: BroadcastOptions): Promise<ApnsResult> { | ||
| 110 | const host = sandbox ? "api.sandbox.push.apple.com" : "api.push.apple.com"; | 117 | const host = sandbox ? "api.sandbox.push.apple.com" : "api.push.apple.com"; |
| 111 | const res = await fetch(`https://${host}/4/broadcasts/apps/${config.topic}`, { | 118 | const res = await fetch(`https://${host}/4/broadcasts/apps/${config.topic}`, { |
| 112 | method: "POST", | 119 | method: "POST", |
server/src/appattest.ts +38 −17
| @@ -47,28 +47,49 @@ export const toBase64 = (b: Uint8Array) => btoa(String.fromCharCode(...b)); | |||
| 47 | // MARK: CBOR (major types 0–5 with definite lengths, which is all App Attest uses) | 47 | // MARK: CBOR (major types 0–5 with definite lengths, which is all App Attest uses) |
| 48 | 48 | ||
| 49 | export function cbor(bytes: Uint8Array): unknown { | 49 | export function cbor(bytes: Uint8Array): unknown { |
| 50 | let i = 0; | 50 | return new CborReader(bytes).item(); |
| 51 | const length = (info: number): number => { | 51 | } |
| 52 | if (info < 24) return info; | 52 | |
| 53 | const n = info === 24 ? 1 : info === 25 ? 2 : info === 26 ? 4 : fail("cbor length"); | 53 | class CborReader { |
| 54 | let v = 0; | 54 | private i = 0; |
| 55 | for (let k = 0; k < n; k++) v = v * 256 + bytes[i++]; | 55 | private readonly bytes: Uint8Array; |
| 56 | return v; | 56 | |
| 57 | }; | 57 | constructor(bytes: Uint8Array) { |
| 58 | const item = (): unknown => { | 58 | this.bytes = bytes; |
| 59 | if (i >= bytes.length) fail("cbor truncated"); | 59 | } |
| 60 | const head = bytes[i++], major = head >> 5, n = length(head & 31); | 60 | |
| 61 | item(): unknown { | ||
| 62 | const head = this.take(1)[0], major = head >> 5, n = this.length(head & 31); | ||
| 61 | switch (major) { | 63 | switch (major) { |
| 62 | case 0: return n; | 64 | case 0: return n; |
| 63 | case 1: return -1 - n; | 65 | case 1: return -1 - n; |
| 64 | case 2: { const v = bytes.slice(i, i + n); i += n; return v; } | 66 | case 2: return this.take(n); |
| 65 | case 3: { const v = new TextDecoder().decode(bytes.slice(i, i + n)); i += n; return v; } | 67 | case 3: return new TextDecoder().decode(this.take(n)); |
| 66 | case 4: return Array.from({ length: n }, item); | 68 | case 4: return Array.from({ length: n }, () => this.item()); |
| 67 | case 5: { const m = new Map<unknown, unknown>(); for (let k = 0; k < n; k++) m.set(item(), item()); return m; } | 69 | case 5: return this.map(n); |
| 68 | default: return fail("cbor type"); | 70 | default: return fail("cbor type"); |
| 69 | } | 71 | } |
| 70 | }; | 72 | } |
| 71 | return item(); | 73 | |
| 74 | private length(info: number): number { | ||
| 75 | if (info < 24) return info; | ||
| 76 | const n = info === 24 ? 1 : info === 25 ? 2 : info === 26 ? 4 : fail("cbor length"); | ||
| 77 | return this.take(n).reduce((v, byte) => v * 256 + byte, 0); | ||
| 78 | } | ||
| 79 | |||
| 80 | private map(n: number): Map<unknown, unknown> { | ||
| 81 | const m = new Map<unknown, unknown>(); | ||
| 82 | for (let k = 0; k < n; k++) m.set(this.item(), this.item()); | ||
| 83 | return m; | ||
| 84 | } | ||
| 85 | |||
| 86 | /** The next `n` bytes; failing rather than reading past the end. */ | ||
| 87 | private take(n: number): Uint8Array { | ||
| 88 | if (this.i + n > this.bytes.length) fail("cbor truncated"); | ||
| 89 | const v = this.bytes.slice(this.i, this.i + n); | ||
| 90 | this.i += n; | ||
| 91 | return v; | ||
| 92 | } | ||
| 72 | } | 93 | } |
| 73 | 94 | ||
| 74 | // MARK: DER | 95 | // MARK: DER |
server/src/celestrak.ts +17 −7
| @@ -83,10 +83,13 @@ export function parseSupGP(text: string): Row[] { | |||
| 83 | function complete(r: unknown): r is Row { | 83 | function complete(r: unknown): r is Row { |
| 84 | if (typeof r !== "object" || r === null) return false; | 84 | if (typeof r !== "object" || r === null) return false; |
| 85 | const o = r as Row; | 85 | const o = r as Row; |
| 86 | return typeof o.OBJECT_NAME === "string" && typeof o.OBJECT_ID === "string" && typeof o.EPOCH === "string" && !Number.isNaN(epoch(o)) && | 86 | return hasNames(o) && !Number.isNaN(epoch(o)) && KEYS.every((k) => k === "OBJECT_NAME" || k === "EPOCH" || finite(o[k])); |
| 87 | KEYS.every((k) => k === "OBJECT_NAME" || k === "EPOCH" || (typeof o[k] === "number" && Number.isFinite(o[k]))); | ||
| 88 | } | 87 | } |
| 89 | 88 | ||
| 89 | const hasNames = (o: Row) => typeof o.OBJECT_NAME === "string" && typeof o.OBJECT_ID === "string" && typeof o.EPOCH === "string"; | ||
| 90 | |||
| 91 | const finite = (v: unknown) => typeof v === "number" && Number.isFinite(v); | ||
| 92 | |||
| 90 | const epoch = (r: Row) => Date.parse(`${r.EPOCH}Z`); | 93 | const epoch = (r: Row) => Date.parse(`${r.EPOCH}Z`); |
| 91 | 94 | ||
| 92 | /** | 95 | /** |
| @@ -143,12 +146,9 @@ export function compose(visual: Row[], recent: Row[], launches: LaunchRef[], sup | |||
| 143 | const groups = new Map(gp); | 146 | const groups = new Map(gp); |
| 144 | const out: Record<string, LaunchElements> = {}; | 147 | const out: Record<string, LaunchElements> = {}; |
| 145 | for (const l of launches) { | 148 | for (const l of launches) { |
| 146 | const g = l.designator ? gp.get(l.designator) : undefined; | 149 | const { source, rows } = launchRows(l, gp, supgp); |
| 147 | const s = supgp[l.id]?.length ? supgp[l.id] : undefined; | ||
| 148 | const source = s && (!g || newest(s) > newest(g)) ? "supgp" : "gp"; | ||
| 149 | const rows = source === "supgp" ? s : g; | ||
| 150 | if (!rows) continue; | 150 | if (!rows) continue; |
| 151 | const label = l.mission?.startsWith("Starlink ") ? l.mission.slice(9) : (l.mission ?? l.designator ?? l.id); | 151 | const label = launchLabel(l); |
| 152 | if (l.designator) groups.delete(l.designator); | 152 | if (l.designator) groups.delete(l.designator); |
| 153 | if (source === "gp" || newest(rows) <= now.getTime()) groups.set(label, rows); | 153 | if (source === "gp" || newest(rows) <= now.getTime()) groups.set(label, rows); |
| 154 | out[l.id] = { source, elements: launchElements(rows, label) }; | 154 | out[l.id] = { source, elements: launchElements(rows, label) }; |
| @@ -156,6 +156,16 @@ export function compose(visual: Row[], recent: Row[], launches: LaunchRef[], sup | |||
| 156 | return { satellites: [...pick(visual), ...starlinkTrains(groups)], launches: out }; | 156 | return { satellites: [...pick(visual), ...starlinkTrains(groups)], launches: out }; |
| 157 | } | 157 | } |
| 158 | 158 | ||
| 159 | /** A launch's elements: SupGP when it has newer rows than GP, otherwise GP. */ | ||
| 160 | function launchRows(l: LaunchRef, gp: Map<string, Row[]>, supgp: Record<string, Row[]>): { source: "supgp" | "gp"; rows: Row[] | undefined } { | ||
| 161 | const g = l.designator ? gp.get(l.designator) : undefined; | ||
| 162 | const s = supgp[l.id]?.length ? supgp[l.id] : undefined; | ||
| 163 | return s && (!g || newest(s) > newest(g)) ? { source: "supgp", rows: s } : { source: "gp", rows: g }; | ||
| 164 | } | ||
| 165 | |||
| 166 | /** "Group 15-25" for a Starlink mission; otherwise the mission, designator or ID. */ | ||
| 167 | const launchLabel = (l: LaunchRef) => (l.mission?.startsWith("Starlink ") ? l.mission.slice(9) : (l.mission ?? l.designator ?? l.id)); | ||
| 168 | |||
| 159 | /** The 5-minute tick 33 minutes after each 2-hourly poll, which runs at minute 7 of even UTC hours. */ | 169 | /** The 5-minute tick 33 minutes after each 2-hourly poll, which runs at minute 7 of even UTC hours. */ |
| 160 | export const retryTick = (now: Date) => now.getUTCHours() % 2 === 0 && now.getUTCMinutes() === 40; | 170 | export const retryTick = (now: Date) => now.getUTCHours() % 2 === 0 && now.getUTCMinutes() === 40; |
| 161 | 171 | ||
server/src/index.ts +169 −112
| @@ -120,13 +120,26 @@ async function cached(request: Request, ctx: ExecutionContext | undefined, respo | |||
| 120 | /** How long clients may reuse each GET response, matched to how often its source is polled. */ | 120 | /** How long clients may reuse each GET response, matched to how often its source is polled. */ |
| 121 | export const MAX_AGE = { today: 60, launches: 300, satellites: 3600, live: 300, news: 600, sun: 1800, smallBodies: 3600 } as const; | 121 | export const MAX_AGE = { today: 60, launches: 300, satellites: 3600, live: 300, news: 600, sun: 1800, smallBodies: 3600 } as const; |
| 122 | 122 | ||
| 123 | /** An APNs device token: hex, 32 to 100 bytes. */ | ||
| 124 | function validToken(t: unknown): t is string { | ||
| 125 | return typeof t === "string" && /^[0-9a-f]{64,200}$/i.test(t); | ||
| 126 | } | ||
| 127 | |||
| 128 | function validEnvironment(e: unknown): e is DeviceRequest["environment"] { | ||
| 129 | return e === "sandbox" || e === "production"; | ||
| 130 | } | ||
| 131 | |||
| 132 | /** A latitude band: a multiple of 5 degrees. */ | ||
| 133 | function validBand(b: unknown): b is number { | ||
| 134 | return Number.isInteger(b) && Math.abs(b as number) <= 90 && (b as number) % 5 === 0; | ||
| 135 | } | ||
| 136 | |||
| 137 | function validUTCOffset(m: unknown): m is number { | ||
| 138 | return Number.isInteger(m) && Math.abs(m as number) <= 14 * 60; | ||
| 139 | } | ||
| 140 | |||
| 123 | function validDevice(d: Partial<DeviceRequest>): d is DeviceRequest { | 141 | function validDevice(d: Partial<DeviceRequest>): d is DeviceRequest { |
| 124 | return ( | 142 | return validToken(d.token) && validEnvironment(d.environment) && validBand(d.band) && validUTCOffset(d.utcOffsetMinutes); |
| 125 | typeof d.token === "string" && /^[0-9a-f]{64,200}$/i.test(d.token) && | ||
| 126 | (d.environment === "sandbox" || d.environment === "production") && | ||
| 127 | Number.isInteger(d.band) && Math.abs(d.band!) <= 90 && d.band! % 5 === 0 && | ||
| 128 | Number.isInteger(d.utcOffsetMinutes) && Math.abs(d.utcOffsetMinutes!) <= 14 * 60 | ||
| 129 | ); | ||
| 130 | } | 143 | } |
| 131 | 144 | ||
| 132 | async function today(env: Env, now: Date): Promise<Response> { | 145 | async function today(env: Env, now: Date): Promise<Response> { |
| @@ -155,54 +168,25 @@ export default { | |||
| 155 | const now = new Date(); | 168 | const now = new Date(); |
| 156 | if (request.method === "GET" && API.has(url.pathname)) return cached(request, ctx, () => api(url, env, now)); | 169 | if (request.method === "GET" && API.has(url.pathname)) return cached(request, ctx, () => api(url, env, now)); |
| 157 | 170 | ||
| 158 | if (request.method === "GET" && url.pathname === "/healthz") { | 171 | if (request.method === "GET" && url.pathname === "/healthz") return health(env); |
| 159 | const rows = await env.DB.prepare("SELECT feed, fetched_at, ok FROM feed_snapshots").all(); | ||
| 160 | return json({ ok: true, feeds: rows.results }); | ||
| 161 | } | ||
| 162 | // The policy lives on krz.sh; older builds link here. | 172 | // The policy lives on krz.sh; older builds link here. |
| 163 | if (request.method === "GET" && url.pathname === "/privacy") return Response.redirect(PRIVACY_URL, 301); | 173 | if (request.method === "GET" && url.pathname === "/privacy") return Response.redirect(PRIVACY_URL, 301); |
| 164 | 174 | ||
| 165 | if (request.method === "POST" && url.pathname === "/v1/challenge") { | 175 | if (request.method === "POST" && url.pathname === "/v1/challenge") return issueChallenge(env, now); |
| 166 | const challenge = toBase64(crypto.getRandomValues(new Uint8Array(32))); | ||
| 167 | await env.DB.prepare("INSERT INTO attest_challenges (challenge, expires_at) VALUES (?1, ?2)").bind(challenge, new Date(now.getTime() + CHALLENGE_MS).toISOString()).run(); | ||
| 168 | return json({ challenge }); | ||
| 169 | } | ||
| 170 | 176 | ||
| 171 | if (request.method === "POST" && url.pathname === "/v1/attest") return attest(request, env, now); | 177 | if (request.method === "POST" && url.pathname === "/v1/attest") return attest(request, env, now); |
| 172 | 178 | ||
| 173 | if (request.method === "POST" && url.pathname === "/v1/devices") { | 179 | if (request.method === "POST" && url.pathname === "/v1/devices") return registerDevice(request, env, now); |
| 174 | const body = new Uint8Array(await request.arrayBuffer()); | ||
| 175 | let d: Partial<DeviceRequest>; | ||
| 176 | try { | ||
| 177 | d = JSON.parse(new TextDecoder().decode(body)); | ||
| 178 | } catch { | ||
| 179 | d = {}; | ||
| 180 | } | ||
| 181 | if (!validDevice(d)) return json({ error: "invalid device" }, 400); | ||
| 182 | const refused = await checkAssertion(env, request, body, d.challenge, now); | ||
| 183 | if (refused) return refused; | ||
| 184 | await env.DB.prepare( | ||
| 185 | `INSERT INTO devices (token, environment, band, utc_offset_minutes, aurora, news, last_seen) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7) | ||
| 186 | ON CONFLICT (token) DO UPDATE SET environment = ?2, band = ?3, utc_offset_minutes = ?4, aurora = ?5, news = ?6, last_seen = ?7`, | ||
| 187 | ).bind(d.token.toLowerCase(), d.environment, d.band, d.utcOffsetMinutes, d.aurora === false ? 0 : 1, d.news === true ? 1 : 0, now.toISOString()).run(); | ||
| 188 | return json({ ok: true }); | ||
| 189 | } | ||
| 190 | 180 | ||
| 191 | const test = url.pathname.match(/^\/v1\/devices\/([0-9a-f]{64,200})\/test$/i); | 181 | const test = url.pathname.match(/^\/v1\/devices\/([0-9a-f]{64,200})\/test$/i); |
| 192 | if (request.method === "POST" && test) return sendTest(env, test[1].toLowerCase(), now); | 182 | if (request.method === "POST" && test) return sendTest(env, test[1].toLowerCase(), now); |
| 193 | 183 | ||
| 194 | if (request.method === "POST" && url.pathname === "/v1/launch-starts") return registerLaunchStarts(request, env, now); | 184 | if (request.method === "POST" && url.pathname === "/v1/launch-starts") return registerLaunchStarts(request, env, now); |
| 195 | const delStarts = url.pathname.match(/^\/v1\/launch-starts\/([0-9a-f]{64,200})$/i); | 185 | const delStarts = url.pathname.match(/^\/v1\/launch-starts\/([0-9a-f]{64,200})$/i); |
| 196 | if (request.method === "DELETE" && delStarts) { | 186 | if (request.method === "DELETE" && delStarts) return deleteRow(env, "DELETE FROM launch_starts WHERE token = ?1", delStarts[1].toLowerCase()); |
| 197 | await env.DB.prepare("DELETE FROM launch_starts WHERE token = ?1").bind(delStarts[1].toLowerCase()).run(); | ||
| 198 | return json({ ok: true }); | ||
| 199 | } | ||
| 200 | 187 | ||
| 201 | const del = url.pathname.match(/^\/v1\/devices\/([0-9a-f]{64,200})$/i); | 188 | const del = url.pathname.match(/^\/v1\/devices\/([0-9a-f]{64,200})$/i); |
| 202 | if (request.method === "DELETE" && del) { | 189 | if (request.method === "DELETE" && del) return deleteRow(env, "DELETE FROM devices WHERE token = ?1", del[1]); |
| 203 | await env.DB.prepare("DELETE FROM devices WHERE token = ?1").bind(del[1]).run(); | ||
| 204 | return json({ ok: true }); | ||
| 205 | } | ||
| 206 | 190 | ||
| 207 | return json({ error: "not found" }, 404); | 191 | return json({ error: "not found" }, 404); |
| 208 | }, | 192 | }, |
| @@ -218,6 +202,137 @@ export default { | |||
| 218 | }, | 202 | }, |
| 219 | } satisfies ExportedHandler<Env>; | 203 | } satisfies ExportedHandler<Env>; |
| 220 | 204 | ||
| 205 | async function health(env: Env): Promise<Response> { | ||
| 206 | const rows = await env.DB.prepare("SELECT feed, fetched_at, ok FROM feed_snapshots").all(); | ||
| 207 | return json({ ok: true, feeds: rows.results }); | ||
| 208 | } | ||
| 209 | |||
| 210 | async function issueChallenge(env: Env, now: Date): Promise<Response> { | ||
| 211 | const challenge = toBase64(crypto.getRandomValues(new Uint8Array(32))); | ||
| 212 | await env.DB.prepare("INSERT INTO attest_challenges (challenge, expires_at) VALUES (?1, ?2)").bind(challenge, new Date(now.getTime() + CHALLENGE_MS).toISOString()).run(); | ||
| 213 | return json({ challenge }); | ||
| 214 | } | ||
| 215 | |||
| 216 | async function registerDevice(request: Request, env: Env, now: Date): Promise<Response> { | ||
| 217 | const body = new Uint8Array(await request.arrayBuffer()); | ||
| 218 | let d: Partial<DeviceRequest>; | ||
| 219 | try { | ||
| 220 | d = JSON.parse(new TextDecoder().decode(body)); | ||
| 221 | } catch { | ||
| 222 | d = {}; | ||
| 223 | } | ||
| 224 | if (!validDevice(d)) return json({ error: "invalid device" }, 400); | ||
| 225 | const refused = await checkAssertion(env, request, body, d.challenge, now); | ||
| 226 | if (refused) return refused; | ||
| 227 | await env.DB.prepare( | ||
| 228 | `INSERT INTO devices (token, environment, band, utc_offset_minutes, aurora, news, last_seen) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7) | ||
| 229 | ON CONFLICT (token) DO UPDATE SET environment = ?2, band = ?3, utc_offset_minutes = ?4, aurora = ?5, news = ?6, last_seen = ?7`, | ||
| 230 | ).bind(d.token.toLowerCase(), d.environment, d.band, d.utcOffsetMinutes, d.aurora === false ? 0 : 1, d.news === true ? 1 : 0, now.toISOString()).run(); | ||
| 231 | return json({ ok: true }); | ||
| 232 | } | ||
| 233 | |||
| 234 | async function deleteRow(env: Env, sql: string, token: string): Promise<Response> { | ||
| 235 | await env.DB.prepare(sql).bind(token).run(); | ||
| 236 | return json({ ok: true }); | ||
| 237 | } | ||
| 238 | |||
| 239 | const apnsConfig = (env: Env): ApnsConfig => ({ keyId: env.APNS_KEY_ID, teamId: env.APNS_TEAM_ID, privateKey: env.APNS_KEY, topic: env.APNS_TOPIC }); | ||
| 240 | |||
| 241 | /** A Live Activity push to a channel, kept by APNs for 8 hours. */ | ||
| 242 | function broadcastPush(config: ApnsConfig, c: { channel_id: string; environment: string }, push: { payload: unknown; priority: 5 | 10 }, now: Date) { | ||
| 243 | return broadcast(config, c.channel_id, push.payload, { | ||
| 244 | sandbox: c.environment === "sandbox", | ||
| 245 | priority: push.priority, | ||
| 246 | expiration: Math.floor(now.getTime() / 1000) + 8 * 3600, | ||
| 247 | }); | ||
| 248 | } | ||
| 249 | |||
| 250 | /** Deletes the channels in `table` whose stored end message has expired. */ | ||
| 251 | async function deleteEndedChannels(env: Env, config: ApnsConfig, table: "launch_channels" | "storm_channels", now: Date): Promise<void> { | ||
| 252 | const done = await env.DB.prepare(`SELECT channel_id, environment FROM ${table} WHERE ended_at < ?1`) | ||
| 253 | .bind(new Date(now.getTime() - 8 * 3600_000).toISOString()).all<{ channel_id: string; environment: string }>(); | ||
| 254 | const label = table === "storm_channels" ? "apns storm channel delete" : "apns channel delete"; | ||
| 255 | for (const c of done.results) { | ||
| 256 | const r = await deleteChannel(config, c.channel_id, c.environment === "sandbox"); | ||
| 257 | if (r.status === 204 || r.status === 404) await env.DB.prepare(`DELETE FROM ${table} WHERE channel_id = ?1`).bind(c.channel_id).run(); | ||
| 258 | else console.error(label, r.status, r.reason); | ||
| 259 | } | ||
| 260 | } | ||
| 261 | |||
| 262 | /** A channel per environment for each launch that needs one: from the pool, or created when channels are managed here. */ | ||
| 263 | async function assignLaunchChannels(env: Env, config: ApnsConfig, manage: boolean, near: Near[], now: Date): Promise<void> { | ||
| 264 | const assigned = await env.DB.prepare("SELECT launch_id, environment FROM launch_channels WHERE launch_id IS NOT NULL").all<{ launch_id: string; environment: string }>(); | ||
| 265 | const has = new Set(assigned.results.map((c) => `${c.launch_id}:${c.environment}`)); | ||
| 266 | for (const l of near.filter((l) => needsChannel(l, now))) { | ||
| 267 | for (const environment of ["sandbox", "production"]) { | ||
| 268 | if (!has.has(`${l.id}:${environment}`)) await assignLaunchChannel(env, manage ? config : null, l, environment, now); | ||
| 269 | } | ||
| 270 | } | ||
| 271 | } | ||
| 272 | |||
| 273 | /** Takes a pooled channel for a launch in one environment, or creates one when `creator` may. */ | ||
| 274 | async function assignLaunchChannel(env: Env, creator: ApnsConfig | null, l: Near, environment: string, now: Date): Promise<void> { | ||
| 275 | const pooled = await env.DB.prepare( | ||
| 276 | `UPDATE launch_channels SET launch_id = ?1, net = ?2, status = ?3 | ||
| 277 | WHERE channel_id = (SELECT channel_id FROM launch_channels WHERE launch_id IS NULL AND environment = ?4 ORDER BY created_at LIMIT 1)`, | ||
| 278 | ).bind(l.id, l.net, l.status, environment).run(); | ||
| 279 | if (pooled.meta.changes) return; | ||
| 280 | if (!creator) { | ||
| 281 | console.error("launch channel pool empty", environment); | ||
| 282 | return; | ||
| 283 | } | ||
| 284 | const c = await createChannel(creator, environment === "sandbox"); | ||
| 285 | if (!c.channelId) { | ||
| 286 | console.error("apns channel", c.status, c.reason); | ||
| 287 | return; | ||
| 288 | } | ||
| 289 | await env.DB.prepare("INSERT INTO launch_channels (channel_id, environment, launch_id, net, status, created_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6)") | ||
| 290 | .bind(c.channelId, environment, l.id, l.net, l.status, now.toISOString()).run(); | ||
| 291 | } | ||
| 292 | |||
| 293 | /** An open storm channel and what it last broadcast. */ | ||
| 294 | interface StormChannelRow { | ||
| 295 | channel_id: string; | ||
| 296 | environment: string; | ||
| 297 | active_at: string; | ||
| 298 | sent: string | null; | ||
| 299 | sent_at: string | null; | ||
| 300 | } | ||
| 301 | |||
| 302 | /** One new storm channel per environment, recorded as open. */ | ||
| 303 | async function openStormChannels(env: Env, config: ApnsConfig, iso: string): Promise<StormChannelRow[]> { | ||
| 304 | const open: StormChannelRow[] = []; | ||
| 305 | for (const environment of ["sandbox", "production"]) { | ||
| 306 | const c = await createChannel(config, environment === "sandbox"); | ||
| 307 | if (!c.channelId) { | ||
| 308 | console.error("apns storm channel", c.status, c.reason); | ||
| 309 | continue; | ||
| 310 | } | ||
| 311 | await env.DB.prepare("INSERT INTO storm_channels (channel_id, environment, started_at, active_at) VALUES (?1, ?2, ?3, ?3)").bind(c.channelId, environment, iso).run(); | ||
| 312 | open.push({ channel_id: c.channelId, environment, active_at: iso, sent: null, sent_at: null }); | ||
| 313 | } | ||
| 314 | return open; | ||
| 315 | } | ||
| 316 | |||
| 317 | /** Pushes the storm's change to one open channel, ending it once the storm has been calm long enough. */ | ||
| 318 | async function updateStormChannel(env: Env, config: ApnsConfig, c: StormChannelRow, state: StormState, now: Date): Promise<void> { | ||
| 319 | const iso = now.toISOString(); | ||
| 320 | const active = stormActive(state); | ||
| 321 | const end = !active && now.getTime() - Date.parse(c.active_at) >= CALM_MS; | ||
| 322 | const push: StormPush | null = end ? stormEnd(state, now) | ||
| 323 | : stormUpdate(c.sent && c.sent_at ? { state: JSON.parse(c.sent), at: new Date(c.sent_at) } : null, state, now); | ||
| 324 | if (active) await env.DB.prepare("UPDATE storm_channels SET active_at = ?2 WHERE channel_id = ?1").bind(c.channel_id, iso).run(); | ||
| 325 | if (!push) return; | ||
| 326 | const r = await broadcastPush(config, c, push, now) | ||
| 327 | .catch((e) => ({ status: 0, reason: String(e) })); | ||
| 328 | if (r.status !== 200) { | ||
| 329 | console.error("apns storm broadcast", r.status, r.reason); | ||
| 330 | return; | ||
| 331 | } | ||
| 332 | await env.DB.prepare("UPDATE storm_channels SET sent = ?2, sent_at = ?3, ended_at = ?4 WHERE channel_id = ?1") | ||
| 333 | .bind(c.channel_id, JSON.stringify(state), iso, end ? iso : null).run(); | ||
| 334 | } | ||
| 335 | |||
| 221 | const appId = (env: Env) => `${env.APNS_TEAM_ID}.${env.APNS_TOPIC}`; | 336 | const appId = (env: Env) => `${env.APNS_TEAM_ID}.${env.APNS_TOPIC}`; |
| 222 | 337 | ||
| 223 | /** Deletes a challenge and says whether it was there and unexpired. */ | 338 | /** Deletes a challenge and says whether it was there and unexpired. */ |
| @@ -274,7 +389,7 @@ async function sendTest(env: Env, token: string, now: Date): Promise<Response> { | |||
| 274 | const claimed = await env.DB.prepare("INSERT OR IGNORE INTO alerts_sent (kind, band, event, sent_at) VALUES ('test', 0, ?1, ?2)") | 389 | const claimed = await env.DB.prepare("INSERT OR IGNORE INTO alerts_sent (kind, band, event, sent_at) VALUES ('test', 0, ?1, ?2)") |
| 275 | .bind(window, now.toISOString()).run(); | 390 | .bind(window, now.toISOString()).run(); |
| 276 | if (!claimed.meta.changes) return json({ error: "try again in a few minutes" }, 429); | 391 | if (!claimed.meta.changes) return json({ error: "try again in a few minutes" }, 429); |
| 277 | const config: ApnsConfig = { keyId: env.APNS_KEY_ID, teamId: env.APNS_TEAM_ID, privateKey: env.APNS_KEY, topic: env.APNS_TOPIC }; | 392 | const config = apnsConfig(env); |
| 278 | const payload = { aps: { alert: { title: "Moonrise test alert", body: "Alerts reach this device." }, sound: "default" } }; | 393 | const payload = { aps: { alert: { title: "Moonrise test alert", body: "Alerts reach this device." }, sound: "default" } }; |
| 279 | const r = await send(config, token, payload, device.environment === "sandbox"); | 394 | const r = await send(config, token, payload, device.environment === "sandbox"); |
| 280 | if (r.status === 410) await env.DB.prepare("DELETE FROM devices WHERE token = ?1").bind(token).run(); | 395 | if (r.status === 410) await env.DB.prepare("DELETE FROM devices WHERE token = ?1").bind(token).run(); |
| @@ -385,7 +500,7 @@ async function registerLaunchStarts(request: Request, env: Env, now: Date): Prom | |||
| 385 | } catch { | 500 | } catch { |
| 386 | d = {}; | 501 | d = {}; |
| 387 | } | 502 | } |
| 388 | if (typeof d.token !== "string" || !/^[0-9a-f]{64,200}$/i.test(d.token) || (d.environment !== "sandbox" && d.environment !== "production") || !RULE(d.rockets) || !RULE(d.providers)) { | 503 | if (!validToken(d.token) || !validEnvironment(d.environment) || !RULE(d.rockets) || !RULE(d.providers)) { |
| 389 | return json({ error: "invalid registration" }, 400); | 504 | return json({ error: "invalid registration" }, 400); |
| 390 | } | 505 | } |
| 391 | const refused = await checkAssertion(env, request, body, d.challenge, now); | 506 | const refused = await checkAssertion(env, request, body, d.challenge, now); |
| @@ -413,7 +528,7 @@ async function startLaunches(env: Env, now: Date): Promise<void> { | |||
| 413 | // A minute either side: LL2 writes "…:00Z" and toISOString "…:00.000Z", which compare unequal as text. startDue decides. | 528 | // A minute either side: LL2 writes "…:00Z" and toISOString "…:00.000Z", which compare unequal as text. startDue decides. |
| 414 | ).bind(new Date(now.getTime() - 60_000).toISOString(), new Date(now.getTime() + 61 * 60_000).toISOString()).all<StartLaunch>()).results.filter((l) => startDue(l, now)); | 529 | ).bind(new Date(now.getTime() - 60_000).toISOString(), new Date(now.getTime() + 61 * 60_000).toISOString()).all<StartLaunch>()).results.filter((l) => startDue(l, now)); |
| 415 | if (!due.length) return; | 530 | if (!due.length) return; |
| 416 | const config: ApnsConfig = { keyId: env.APNS_KEY_ID, teamId: env.APNS_TEAM_ID, privateKey: env.APNS_KEY, topic: env.APNS_TOPIC }; | 531 | const config = apnsConfig(env); |
| 417 | for (const l of due) { | 532 | for (const l of due) { |
| 418 | const channels = Object.fromEntries((await env.DB.prepare("SELECT environment, channel_id FROM launch_channels WHERE launch_id = ?1 AND ended_at IS NULL") | 533 | const channels = Object.fromEntries((await env.DB.prepare("SELECT environment, channel_id FROM launch_channels WHERE launch_id = ?1 AND ended_at IS NULL") |
| 419 | .bind(l.id).all<{ environment: string; channel_id: string }>()).results.map((c) => [c.environment, c.channel_id])); | 534 | .bind(l.id).all<{ environment: string; channel_id: string }>()).results.map((c) => [c.environment, c.channel_id])); |
| @@ -517,33 +632,11 @@ function upsertLaunches(env: Env, list: Launch[]): D1PreparedStatement[] { | |||
| 517 | * retires a channel once its launch is over. Nothing about who follows a launch reaches the server. | 632 | * retires a channel once its launch is over. Nothing about who follows a launch reaches the server. |
| 518 | */ | 633 | */ |
| 519 | async function launchChannels(env: Env, near: Near[], now: Date): Promise<void> { | 634 | async function launchChannels(env: Env, near: Near[], now: Date): Promise<void> { |
| 520 | const config: ApnsConfig = { keyId: env.APNS_KEY_ID, teamId: env.APNS_TEAM_ID, privateKey: env.APNS_KEY, topic: env.APNS_TOPIC }; | 635 | const config = apnsConfig(env); |
| 521 | const manage = env.APNS_MANAGE_CHANNELS === "1"; | 636 | const manage = env.APNS_MANAGE_CHANNELS === "1"; |
| 522 | const iso = now.toISOString(); | 637 | const iso = now.toISOString(); |
| 523 | 638 | ||
| 524 | const assigned = await env.DB.prepare("SELECT launch_id, environment FROM launch_channels WHERE launch_id IS NOT NULL").all<{ launch_id: string; environment: string }>(); | 639 | await assignLaunchChannels(env, config, manage, near, now); |
| 525 | const has = new Set(assigned.results.map((c) => `${c.launch_id}:${c.environment}`)); | ||
| 526 | for (const l of near.filter((l) => needsChannel(l, now))) { | ||
| 527 | for (const environment of ["sandbox", "production"]) { | ||
| 528 | if (has.has(`${l.id}:${environment}`)) continue; | ||
| 529 | const pooled = await env.DB.prepare( | ||
| 530 | `UPDATE launch_channels SET launch_id = ?1, net = ?2, status = ?3 | ||
| 531 | WHERE channel_id = (SELECT channel_id FROM launch_channels WHERE launch_id IS NULL AND environment = ?4 ORDER BY created_at LIMIT 1)`, | ||
| 532 | ).bind(l.id, l.net, l.status, environment).run(); | ||
| 533 | if (pooled.meta.changes) continue; | ||
| 534 | if (!manage) { | ||
| 535 | console.error("launch channel pool empty", environment); | ||
| 536 | continue; | ||
| 537 | } | ||
| 538 | const c = await createChannel(config, environment === "sandbox"); | ||
| 539 | if (!c.channelId) { | ||
| 540 | console.error("apns channel", c.status, c.reason); | ||
| 541 | continue; | ||
| 542 | } | ||
| 543 | await env.DB.prepare("INSERT INTO launch_channels (channel_id, environment, launch_id, net, status, created_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6)") | ||
| 544 | .bind(c.channelId, environment, l.id, l.net, l.status, iso).run(); | ||
| 545 | } | ||
| 546 | } | ||
| 547 | 640 | ||
| 548 | await broadcastChanges(env, now); | 641 | await broadcastChanges(env, now); |
| 549 | 642 | ||
| @@ -552,18 +645,12 @@ async function launchChannels(env: Env, near: Near[], now: Date): Promise<void> | |||
| 552 | .bind(iso, new Date(now.getTime() - 86400_000).toISOString()).run(); | 645 | .bind(iso, new Date(now.getTime() - 86400_000).toISOString()).run(); |
| 553 | if (!manage) return; | 646 | if (!manage) return; |
| 554 | // Deleted once the stored end message has expired. | 647 | // Deleted once the stored end message has expired. |
| 555 | const done = await env.DB.prepare("SELECT channel_id, environment FROM launch_channels WHERE ended_at < ?1") | 648 | await deleteEndedChannels(env, config, "launch_channels", now); |
| 556 | .bind(new Date(now.getTime() - 8 * 3600_000).toISOString()).all<{ channel_id: string; environment: string }>(); | ||
| 557 | for (const c of done.results) { | ||
| 558 | const r = await deleteChannel(config, c.channel_id, c.environment === "sandbox"); | ||
| 559 | if (r.status === 204 || r.status === 404) await env.DB.prepare("DELETE FROM launch_channels WHERE channel_id = ?1").bind(c.channel_id).run(); | ||
| 560 | else console.error("apns channel delete", r.status, r.reason); | ||
| 561 | } | ||
| 562 | } | 649 | } |
| 563 | 650 | ||
| 564 | /** Each change of status or NET since the last broadcast on a channel. */ | 651 | /** Each change of status or NET since the last broadcast on a channel. */ |
| 565 | async function broadcastChanges(env: Env, now: Date): Promise<void> { | 652 | async function broadcastChanges(env: Env, now: Date): Promise<void> { |
| 566 | const config: ApnsConfig = { keyId: env.APNS_KEY_ID, teamId: env.APNS_TEAM_ID, privateKey: env.APNS_KEY, topic: env.APNS_TOPIC }; | 653 | const config = apnsConfig(env); |
| 567 | const changed = await env.DB.prepare( | 654 | const changed = await env.DB.prepare( |
| 568 | `SELECT c.channel_id, c.environment, c.net AS sent_net, c.status AS sent_status, l.net, l.status | 655 | `SELECT c.channel_id, c.environment, c.net AS sent_net, c.status AS sent_status, l.net, l.status |
| 569 | FROM launch_channels c JOIN launches l ON l.id = c.launch_id WHERE c.ended_at IS NULL AND (c.net != l.net OR c.status != l.status)`, | 656 | FROM launch_channels c JOIN launches l ON l.id = c.launch_id WHERE c.ended_at IS NULL AND (c.net != l.net OR c.status != l.status)`, |
| @@ -571,7 +658,7 @@ async function broadcastChanges(env: Env, now: Date): Promise<void> { | |||
| 571 | for (const c of changed.results) { | 658 | for (const c of changed.results) { |
| 572 | const push = activityPush({ net: c.sent_net, status: c.sent_status }, c, now)!; | 659 | const push = activityPush({ net: c.sent_net, status: c.sent_status }, c, now)!; |
| 573 | // APNs keeps the latest message for devices that are offline, for at most 8 hours. | 660 | // APNs keeps the latest message for devices that are offline, for at most 8 hours. |
| 574 | const r = await broadcast(config, c.channel_id, push.payload, c.environment === "sandbox", push.priority, Math.floor(now.getTime() / 1000) + 8 * 3600) | 661 | const r = await broadcastPush(config, c, push, now) |
| 575 | .catch((e) => ({ status: 0, reason: String(e) })); | 662 | .catch((e) => ({ status: 0, reason: String(e) })); |
| 576 | if (r.status !== 200) { | 663 | if (r.status !== 200) { |
| 577 | console.error("apns broadcast", r.status, r.reason); | 664 | console.error("apns broadcast", r.status, r.reason); |
| @@ -662,45 +749,15 @@ async function pollSpaceWeather(env: Env, now: Date): Promise<void> { | |||
| 662 | */ | 749 | */ |
| 663 | async function stormChannels(env: Env, state: StormState, now: Date): Promise<void> { | 750 | async function stormChannels(env: Env, state: StormState, now: Date): Promise<void> { |
| 664 | if (!env.APNS_KEY) return; | 751 | if (!env.APNS_KEY) return; |
| 665 | const config: ApnsConfig = { keyId: env.APNS_KEY_ID, teamId: env.APNS_TEAM_ID, privateKey: env.APNS_KEY, topic: env.APNS_TOPIC }; | 752 | const config = apnsConfig(env); |
| 666 | const iso = now.toISOString(); | 753 | const iso = now.toISOString(); |
| 667 | const active = stormActive(state); | 754 | const active = stormActive(state); |
| 668 | let open = (await env.DB.prepare("SELECT channel_id, environment, active_at, sent, sent_at FROM storm_channels WHERE ended_at IS NULL") | 755 | let open = (await env.DB.prepare("SELECT channel_id, environment, active_at, sent, sent_at FROM storm_channels WHERE ended_at IS NULL") |
| 669 | .all<{ channel_id: string; environment: string; active_at: string; sent: string | null; sent_at: string | null }>()).results; | 756 | .all<StormChannelRow>()).results; |
| 670 | if (!open.length && active && env.APNS_MANAGE_CHANNELS === "1") { | 757 | if (!open.length && active && env.APNS_MANAGE_CHANNELS === "1") open = await openStormChannels(env, config, iso); |
| 671 | for (const environment of ["sandbox", "production"]) { | 758 | for (const c of open) await updateStormChannel(env, config, c, state, now); |
| 672 | const c = await createChannel(config, environment === "sandbox"); | ||
| 673 | if (!c.channelId) { | ||
| 674 | console.error("apns storm channel", c.status, c.reason); | ||
| 675 | continue; | ||
| 676 | } | ||
| 677 | await env.DB.prepare("INSERT INTO storm_channels (channel_id, environment, started_at, active_at) VALUES (?1, ?2, ?3, ?3)").bind(c.channelId, environment, iso).run(); | ||
| 678 | open.push({ channel_id: c.channelId, environment, active_at: iso, sent: null, sent_at: null }); | ||
| 679 | } | ||
| 680 | } | ||
| 681 | for (const c of open) { | ||
| 682 | const end = !active && now.getTime() - Date.parse(c.active_at) >= CALM_MS; | ||
| 683 | const push: StormPush | null = end ? stormEnd(state, now) | ||
| 684 | : stormUpdate(c.sent && c.sent_at ? { state: JSON.parse(c.sent), at: new Date(c.sent_at) } : null, state, now); | ||
| 685 | if (active) await env.DB.prepare("UPDATE storm_channels SET active_at = ?2 WHERE channel_id = ?1").bind(c.channel_id, iso).run(); | ||
| 686 | if (!push) continue; | ||
| 687 | const r = await broadcast(config, c.channel_id, push.payload, c.environment === "sandbox", push.priority, Math.floor(now.getTime() / 1000) + 8 * 3600) | ||
| 688 | .catch((e) => ({ status: 0, reason: String(e) })); | ||
| 689 | if (r.status !== 200) { | ||
| 690 | console.error("apns storm broadcast", r.status, r.reason); | ||
| 691 | continue; | ||
| 692 | } | ||
| 693 | await env.DB.prepare("UPDATE storm_channels SET sent = ?2, sent_at = ?3, ended_at = ?4 WHERE channel_id = ?1") | ||
| 694 | .bind(c.channel_id, JSON.stringify(state), iso, end ? iso : null).run(); | ||
| 695 | } | ||
| 696 | if (env.APNS_MANAGE_CHANNELS !== "1") return; | 759 | if (env.APNS_MANAGE_CHANNELS !== "1") return; |
| 697 | const done = await env.DB.prepare("SELECT channel_id, environment FROM storm_channels WHERE ended_at < ?1") | 760 | await deleteEndedChannels(env, config, "storm_channels", now); |
| 698 | .bind(new Date(now.getTime() - 8 * 3600_000).toISOString()).all<{ channel_id: string; environment: string }>(); | ||
| 699 | for (const c of done.results) { | ||
| 700 | const r = await deleteChannel(config, c.channel_id, c.environment === "sandbox"); | ||
| 701 | if (r.status === 204 || r.status === 404) await env.DB.prepare("DELETE FROM storm_channels WHERE channel_id = ?1").bind(c.channel_id).run(); | ||
| 702 | else console.error("apns storm channel delete", r.status, r.reason); | ||
| 703 | } | ||
| 704 | } | 761 | } |
| 705 | 762 | ||
| 706 | /** RTSW, reduced; the last good copy is kept on failure, and null is returned so no alert rests on old wind. */ | 763 | /** RTSW, reduced; the last good copy is kept on failure, and null is returned so no alert rests on old wind. */ |
| @@ -804,7 +861,7 @@ interface Recipient { | |||
| 804 | * alerts_sent and drops devices it reports gone (410). Retryable failures are not recorded, so a later run tries again. | 861 | * alerts_sent and drops devices it reports gone (410). Retryable failures are not recorded, so a later run tries again. |
| 805 | */ | 862 | */ |
| 806 | async function sendAlerts(env: Env, kind: string, recipients: Recipient[], now: Date, payload: (r: Recipient) => unknown): Promise<void> { | 863 | async function sendAlerts(env: Env, kind: string, recipients: Recipient[], now: Date, payload: (r: Recipient) => unknown): Promise<void> { |
| 807 | const config: ApnsConfig = { keyId: env.APNS_KEY_ID, teamId: env.APNS_TEAM_ID, privateKey: env.APNS_KEY, topic: env.APNS_TOPIC }; | 864 | const config = apnsConfig(env); |
| 808 | const slice = recipients.slice(0, PUSH_SLICE); | 865 | const slice = recipients.slice(0, PUSH_SLICE); |
| 809 | const results = await sendAll(config, slice.map((r) => ({ token: r.token, payload: payload(r), sandbox: r.environment === "sandbox" })), PUSH_CONCURRENCY); | 866 | const results = await sendAll(config, slice.map((r) => ({ token: r.token, payload: payload(r), sandbox: r.environment === "sandbox" })), PUSH_CONCURRENCY); |
| 810 | const sent = env.DB.prepare("INSERT OR IGNORE INTO alerts_sent (kind, band, event, sent_at) VALUES (?1, ?2, ?3, ?4)"); | 867 | const sent = env.DB.prepare("INSERT OR IGNORE INTO alerts_sent (kind, band, event, sent_at) VALUES (?1, ?2, ?3, ?4)"); |
server/src/solarwind.ts +23 −11
| @@ -29,38 +29,50 @@ const HOURS = 6; | |||
| 29 | const mean = (xs: number[]) => (xs.length ? Math.round((xs.reduce((a, b) => a + b, 0) / xs.length) * 10) / 10 : null); | 29 | const mean = (xs: number[]) => (xs.length ? Math.round((xs.reduce((a, b) => a + b, 0) / xs.length) * 10) / 10 : null); |
| 30 | const ok = (v: number | null | undefined): v is number => typeof v === "number" && Number.isFinite(v); | 30 | const ok = (v: number | null | undefined): v is number => typeof v === "number" && Number.isFinite(v); |
| 31 | 31 | ||
| 32 | interface Bin { speed: number[]; density: number[]; bz: number[]; bt: number[] } | ||
| 33 | type Binner = (tag: string) => Bin | undefined; | ||
| 34 | |||
| 32 | export function reduce(mag: MagRow[], wind: WindRow[], now: Date): SolarWind | null { | 35 | export function reduce(mag: MagRow[], wind: WindRow[], now: Date): SolarWind | null { |
| 33 | const start = Math.floor((now.getTime() - HOURS * 3600_000) / BIN) * BIN; | 36 | const start = Math.floor((now.getTime() - HOURS * 3600_000) / BIN) * BIN; |
| 34 | const bins = new Map<number, { speed: number[]; density: number[]; bz: number[]; bt: number[] }>(); | 37 | const bins = new Map<number, Bin>(); |
| 35 | const bin = (tag: string) => { | 38 | const bin: Binner = (tag) => { |
| 36 | const t = Date.parse(tag + "Z"); | 39 | const t = Date.parse(tag + "Z"); |
| 37 | if (!(t >= start)) return undefined; | 40 | if (!(t >= start)) return undefined; |
| 38 | const k = Math.floor(t / BIN) * BIN; | 41 | const k = Math.floor(t / BIN) * BIN; |
| 39 | if (!bins.has(k)) bins.set(k, { speed: [], density: [], bz: [], bt: [] }); | 42 | if (!bins.has(k)) bins.set(k, { speed: [], density: [], bz: [], bt: [] }); |
| 40 | return bins.get(k)!; | 43 | return bins.get(k)!; |
| 41 | }; | 44 | }; |
| 45 | const latest = binMagnetometer(mag, bin); | ||
| 46 | binPlasma(wind, bin); | ||
| 47 | if (!bins.size) return null; | ||
| 48 | const series = [...bins.entries()].sort((a, b) => a[0] - b[0]).map(([k, b]) => ({ | ||
| 49 | t: new Date(k).toISOString(), speed: mean(b.speed), density: mean(b.density), bz: mean(b.bz), bt: mean(b.bt), | ||
| 50 | })); | ||
| 51 | return { observedAt: new Date(latest.observed).toISOString(), source: latest.source, series }; | ||
| 52 | } | ||
| 53 | |||
| 54 | /** Bins the active spacecraft's field readings; returns the time and source of the latest. */ | ||
| 55 | function binMagnetometer(mag: MagRow[], bin: Binner): { observed: number; source: string } { | ||
| 42 | let observed = 0, source = ""; | 56 | let observed = 0, source = ""; |
| 43 | for (const r of mag) { | 57 | for (const r of mag) { |
| 44 | if (!r.active) continue; | 58 | const b = r.active ? bin(r.time_tag) : undefined; |
| 45 | const b = bin(r.time_tag); | ||
| 46 | if (!b) continue; | 59 | if (!b) continue; |
| 47 | if (ok(r.bz_gsm)) b.bz.push(r.bz_gsm); | 60 | if (ok(r.bz_gsm)) b.bz.push(r.bz_gsm); |
| 48 | if (ok(r.bt)) b.bt.push(r.bt); | 61 | if (ok(r.bt)) b.bt.push(r.bt); |
| 49 | const t = Date.parse(r.time_tag + "Z"); | 62 | const t = Date.parse(r.time_tag + "Z"); |
| 50 | if (t > observed) { observed = t; source = r.source; } | 63 | if (t > observed) { observed = t; source = r.source; } |
| 51 | } | 64 | } |
| 65 | return { observed, source }; | ||
| 66 | } | ||
| 67 | |||
| 68 | /** Bins the active spacecraft's plasma readings. */ | ||
| 69 | function binPlasma(wind: WindRow[], bin: Binner): void { | ||
| 52 | for (const r of wind) { | 70 | for (const r of wind) { |
| 53 | if (!r.active) continue; | 71 | const b = r.active ? bin(r.time_tag) : undefined; |
| 54 | const b = bin(r.time_tag); | ||
| 55 | if (!b) continue; | 72 | if (!b) continue; |
| 56 | if (ok(r.proton_speed)) b.speed.push(r.proton_speed); | 73 | if (ok(r.proton_speed)) b.speed.push(r.proton_speed); |
| 57 | if (ok(r.proton_density)) b.density.push(r.proton_density); | 74 | if (ok(r.proton_density)) b.density.push(r.proton_density); |
| 58 | } | 75 | } |
| 59 | if (!bins.size) return null; | ||
| 60 | const series = [...bins.entries()].sort((a, b) => a[0] - b[0]).map(([k, b]) => ({ | ||
| 61 | t: new Date(k).toISOString(), speed: mean(b.speed), density: mean(b.density), bz: mean(b.bz), bt: mean(b.bt), | ||
| 62 | })); | ||
| 63 | return { observedAt: new Date(observed).toISOString(), source, series }; | ||
| 64 | } | 76 | } |
| 65 | 77 | ||
| 66 | /** | 78 | /** |
server/test/apns.test.ts +1 −1
| @@ -45,7 +45,7 @@ test("broadcast goes to the standard host with the channel, Live Activity type, | |||
| 45 | const real = globalThis.fetch; | 45 | const real = globalThis.fetch; |
| 46 | globalThis.fetch = fetcher; | 46 | globalThis.fetch = fetcher; |
| 47 | try { | 47 | try { |
| 48 | const r = await broadcast(await config(), "dHN0LXNyY2gtY2hubA==", { aps: { event: "update" } }, false, 5, 1_792_230_000); | 48 | const r = await broadcast(await config(), "dHN0LXNyY2gtY2hubA==", { aps: { event: "update" } }, { sandbox: false, priority: 5, expiration: 1_792_230_000 }); |
| 49 | assert.deepEqual(r, { status: 200, apnsId: "r", reason: null }); | 49 | assert.deepEqual(r, { status: 200, apnsId: "r", reason: null }); |
| 50 | } finally { | 50 | } finally { |
| 51 | globalThis.fetch = real; | 51 | globalThis.fetch = real; |