Elffuss BraidHub

kikocis/osiris public

c867dff8b92f · 10.1 KiBRawPermalink
1
2import { NextResponse } from 'next/server';
3
4/**
5 * OSIRIS — Satellite Tracking API
6 * Fetches TLE data from multiple sources with fallbacks
7 * Computes real-time positions using simplified SGP4
8 */
9
10// Mission classification by NORAD name keywords
11const MISSION_CLASSIFY: Record<string, { mission: string; color: string }> = {
12 'USA': { mission: 'Military Recon', color: '#FF3D3D' },
13 'NROL': { mission: 'NRO Classified', color: '#FF3D3D' },
14 'LACROSSE': { mission: 'SAR Imaging', color: '#00E5FF' },
15 'MENTOR': { mission: 'SIGINT', color: '#FFFFFF' },
16 'ORION': { mission: 'SIGINT', color: '#FFFFFF' },
17 'TRUMPET': { mission: 'SIGINT', color: '#FFFFFF' },
18 'GPS': { mission: 'Navigation', color: '#448AFF' },
19 'NAVSTAR': { mission: 'Navigation', color: '#448AFF' },
20 'GLONASS': { mission: 'Navigation', color: '#448AFF' },
21 'GALILEO': { mission: 'Navigation', color: '#448AFF' },
22 'BEIDOU': { mission: 'Navigation', color: '#448AFF' },
23 'SBIRS': { mission: 'Early Warning', color: '#FF00FF' },
24 'DSP': { mission: 'Early Warning', color: '#FF00FF' },
25 'STARLINK': { mission: 'Commercial Comms', color: '#00E676' },
26 'ONEWEB': { mission: 'Commercial Comms', color: '#00E676' },
27 'PLANET': { mission: 'Earth Imaging', color: '#00E676' },
28 'WORLDVIEW': { mission: 'Commercial Imaging', color: '#00E676' },
29 'ISS': { mission: 'Space Station', color: '#FFD700' },
30 'TIANGONG': { mission: 'Space Station', color: '#FFD700' },
31 'COSMOS': { mission: 'Russian Military', color: '#FF6B6B' },
32 'YAOGAN': { mission: 'Chinese Recon', color: '#FF6B6B' },
33 'FENGYUN': { mission: 'Weather', color: '#87CEEB' },
34 'GOES': { mission: 'Weather', color: '#87CEEB' },
35 'NOAA': { mission: 'Weather', color: '#87CEEB' },
36 'METEOSAT': { mission: 'Weather', color: '#87CEEB' },
37 'LANDSAT': { mission: 'Earth Observation', color: '#90EE90' },
38 'SENTINEL': { mission: 'Earth Observation', color: '#90EE90' },
39 'TERRA': { mission: 'Earth Science', color: '#90EE90' },
40 'AQUA': { mission: 'Earth Science', color: '#90EE90' },
41 'HUBBLE': { mission: 'Space Telescope', color: '#FFD700' },
42 'JAMES WEBB': { mission: 'Space Telescope', color: '#FFD700' },
43};
44
45function classifySatellite(name: string): { mission: string; color: string } {
46 const upper = name.toUpperCase();
47 for (const [keyword, info] of Object.entries(MISSION_CLASSIFY)) {
48 if (upper.includes(keyword)) return info;
49 }
50 return { mission: 'Unknown', color: '#808080' };
51}
52
53function gmst(jd: number): number {
54 const t = (jd - 2451545.0) / 36525.0;
55 const gmstSec = 67310.54841 + (876600.0 * 3600 + 8640184.812866) * t + 0.093104 * t * t - 6.2e-6 * t * t * t;
56 return ((gmstSec % 86400) / 86400.0) * 2 * Math.PI;
57}
58
59function parseTLE(tleText: string) {
60 const lines = tleText.trim().split('\n').map(l => l.trim()).filter(l => l.length > 0);
61 const satellites: any[] = [];
62
63 for (let i = 0; i < lines.length - 2; i++) {
64 // Find name + line1 + line2 pattern
65 const name = lines[i];
66 const line1 = lines[i + 1];
67 const line2 = lines[i + 2];
68
69 if (!line1?.startsWith('1 ') || !line2?.startsWith('2 ')) continue;
70 if (name.startsWith('1 ') || name.startsWith('2 ')) continue;
71
72 satellites.push({ name, line1, line2 });
73 i += 2; // skip the TLE lines
74 }
75 return satellites;
76}
77
78function propagateSGP4Simple(line1: string, line2: string): { lat: number; lng: number; alt: number } | null {
79 try {
80 const incDeg = parseFloat(line2.substring(8, 16));
81 const raanDeg = parseFloat(line2.substring(17, 25));
82 const eccStr = '0.' + line2.substring(26, 33).trim();
83 const ecc = parseFloat(eccStr);
84 const argPerDeg = parseFloat(line2.substring(34, 42));
85 const meanAnomDeg = parseFloat(line2.substring(43, 51));
86 const meanMotion = parseFloat(line2.substring(52, 63));
87
88 if (isNaN(meanMotion) || meanMotion === 0) return null;
89
90 const now = new Date();
91 const epochYear = parseInt(line1.substring(18, 20));
92 const epochDay = parseFloat(line1.substring(20, 32));
93 const fullYear = epochYear > 56 ? 1900 + epochYear : 2000 + epochYear;
94
95 const epochDate = new Date(fullYear, 0, 1);
96 epochDate.setDate(epochDate.getDate() + epochDay - 1);
97 const elapsedMin = (now.getTime() - epochDate.getTime()) / 60000;
98
99 // Reject stale TLEs (> 30 days old)
100 if (Math.abs(elapsedMin) > 43200) return null;
101
102 const n = meanMotion * 2 * Math.PI / 1440;
103 const M = ((meanAnomDeg * Math.PI / 180) + n * elapsedMin) % (2 * Math.PI);
104
105 let E = M;
106 for (let j = 0; j < 10; j++) {
107 E = M + ecc * Math.sin(E);
108 }
109
110 const sinV = Math.sqrt(1 - ecc * ecc) * Math.sin(E) / (1 - ecc * Math.cos(E));
111 const cosV = (Math.cos(E) - ecc) / (1 - ecc * Math.cos(E));
112 const v = Math.atan2(sinV, cosV);
113
114 const a = Math.pow(398600.4418 / (meanMotion * 2 * Math.PI / 86400) ** 2, 1 / 3);
115 const r = a * (1 - ecc * Math.cos(E));
116
117 const inc = incDeg * Math.PI / 180;
118 const raan = raanDeg * Math.PI / 180;
119 const argPer = argPerDeg * Math.PI / 180;
120 const u = v + argPer;
121
122 const x = r * (Math.cos(raan) * Math.cos(u) - Math.sin(raan) * Math.sin(u) * Math.cos(inc));
123 const y = r * (Math.sin(raan) * Math.cos(u) + Math.cos(raan) * Math.sin(u) * Math.cos(inc));
124 const z = r * Math.sin(u) * Math.sin(inc);
125
126 const jd = 2440587.5 + now.getTime() / 86400000;
127 const theta = gmst(jd);
128
129 const xRot = x * Math.cos(theta) + y * Math.sin(theta);
130 const yRot = -x * Math.sin(theta) + y * Math.cos(theta);
131
132 const lng = Math.atan2(yRot, xRot) * 180 / Math.PI;
133 const lat = Math.atan2(z, Math.sqrt(xRot * xRot + yRot * yRot)) * 180 / Math.PI;
134 const alt = r - 6371;
135
136 if (isNaN(lat) || isNaN(lng) || Math.abs(lat) > 90) return null;
137 if (alt < 100 || alt > 50000) return null; // sanity check
138
139 return {
140 lat: Math.round(lat * 10000) / 10000,
141 lng: Math.round(((lng + 540) % 360 - 180) * 10000) / 10000,
142 alt: Math.round(alt),
143 };
144 } catch {
145 return null;
146 }
147}
148
149// Multiple TLE sources — individual groups fetched in parallel for resilience
150// NOTE: The full 'active' catalog often returns empty from cloud/serverless IPs
151// due to Celestrak rate-limiting. Individual groups are smaller and more reliable.
152const TLE_SOURCES = [
153 { url: 'https://celestrak.org/NORAD/elements/gp.php?GROUP=stations&FORMAT=tle', group: 'stations' },
154 { url: 'https://celestrak.org/NORAD/elements/gp.php?GROUP=visual&FORMAT=tle', group: 'visual' },
155 { url: 'https://celestrak.org/NORAD/elements/gp.php?GROUP=weather&FORMAT=tle', group: 'weather' },
156 { url: 'https://celestrak.org/NORAD/elements/gp.php?GROUP=resource&FORMAT=tle', group: 'resource' },
157 { url: 'https://celestrak.org/NORAD/elements/gp.php?GROUP=sarsat&FORMAT=tle', group: 'sarsat' },
158 { url: 'https://celestrak.org/NORAD/elements/gp.php?GROUP=gps-ops&FORMAT=tle', group: 'gps' },
159 { url: 'https://celestrak.org/NORAD/elements/gp.php?GROUP=glo-ops&FORMAT=tle', group: 'glonass' },
160 { url: 'https://celestrak.org/NORAD/elements/gp.php?GROUP=galileo&FORMAT=tle', group: 'galileo' },
161 { url: 'https://celestrak.org/NORAD/elements/gp.php?GROUP=beidou&FORMAT=tle', group: 'beidou' },
162 { url: 'https://celestrak.org/NORAD/elements/gp.php?GROUP=military&FORMAT=tle', group: 'military' },
163 { url: 'https://celestrak.org/NORAD/elements/gp.php?GROUP=science&FORMAT=tle', group: 'science' },
164 { url: 'https://celestrak.org/NORAD/elements/gp.php?GROUP=geodetic&FORMAT=tle', group: 'geodetic' },
165 { url: 'https://celestrak.org/NORAD/elements/gp.php?GROUP=engineering&FORMAT=tle', group: 'engineering' },
166 { url: 'https://celestrak.org/NORAD/elements/gp.php?GROUP=education&FORMAT=tle', group: 'education' },
167 { url: 'https://celestrak.org/NORAD/elements/gp.php?GROUP=starlink&FORMAT=tle', group: 'starlink' },
168 { url: 'https://celestrak.org/NORAD/elements/gp.php?GROUP=active&FORMAT=tle', group: 'active-fallback' },
169];
170
171async function fetchTLEFromSource(source: typeof TLE_SOURCES[0]): Promise<string | null> {
172 try {
173 const res = await fetch(source.url, {
174 signal: AbortSignal.timeout(12000),
175 headers: { 'User-Agent': 'OSIRIS-Intelligence-Platform/3.4' },
176 });
177 if (!res.ok) return null;
178 const text = await res.text();
179 if (text.length < 100 || text.includes('<!DOCTYPE') || text.includes('<html')) return null;
180 return text;
181 } catch {
182 return null;
183 }
184}
185
186export async function GET() {
187 try {
188 // Fetch all groups in parallel for maximum speed & resilience
189 const results = await Promise.allSettled(
190 TLE_SOURCES.map(src => fetchTLEFromSource(src))
191 );
192
193 const allSats: any[] = [];
194 const seen = new Set<string>();
195
196 for (const result of results) {
197 if (result.status === 'fulfilled' && result.value) {
198 const parsed = parseTLE(result.value);
199 for (const sat of parsed) {
200 if (!seen.has(sat.name)) {
201 seen.add(sat.name);
202 allSats.push(sat);
203 }
204 }
205 }
206 }
207
208 const source = allSats.length > 0 ? 'celestrak-groups' : 'none';
209
210 // Sample for performance (max 2000 satellites)
211 const sampled = allSats.length > 2000
212 ? allSats.filter((_, i) => i % Math.ceil(allSats.length / 2000) === 0)
213 : allSats;
214
215 const satellites = [];
216 for (const sat of sampled) {
217 const pos = propagateSGP4Simple(sat.line1, sat.line2);
218 if (!pos) continue;
219
220 const classification = classifySatellite(sat.name);
221 satellites.push({
222 name: sat.name,
223 lat: pos.lat,
224 lng: pos.lng,
225 alt: pos.alt,
226 mission: classification.mission,
227 color: classification.color,
228 });
229 }
230
231 return NextResponse.json({
232 satellites,
233 total: satellites.length,
234 source,
235 raw_count: allSats.length,
236 timestamp: new Date().toISOString(),
237 }, {
238 headers: {
239 'Cache-Control': 'public, s-maxage=120, stale-while-revalidate=300',
240 },
241 });
242 } catch (error) {
243 console.error('Satellite fetch error:', error);
244 return NextResponse.json({ satellites: [], error: 'Failed to fetch satellite data' }, { status: 500 });
245 }
246}
247