Elffuss BraidHub

kikocis/osiris public

master · 8.7 KiBRawPermalink
1
2import { NextResponse } from 'next/server';
3import { stealthFetch } from '@/lib/stealthFetch';
4
5/**
6 * OSIRIS — Satellite Tracking API
7 * Fetches TLE data from multiple sources with fallbacks
8 * Computes real-time positions using simplified SGP4
9 */
10
11// Mission classification by NORAD name keywords
12const MISSION_CLASSIFY: Record<string, { mission: string; color: string }> = {
13 'USA': { mission: 'Military Recon', color: '#FF3D3D' },
14 'NROL': { mission: 'NRO Classified', color: '#FF3D3D' },
15 'LACROSSE': { mission: 'SAR Imaging', color: '#00E5FF' },
16 'MENTOR': { mission: 'SIGINT', color: '#FFFFFF' },
17 'ORION': { mission: 'SIGINT', color: '#FFFFFF' },
18 'TRUMPET': { mission: 'SIGINT', color: '#FFFFFF' },
19 'GPS': { mission: 'Navigation', color: '#448AFF' },
20 'NAVSTAR': { mission: 'Navigation', color: '#448AFF' },
21 'GLONASS': { mission: 'Navigation', color: '#448AFF' },
22 'GALILEO': { mission: 'Navigation', color: '#448AFF' },
23 'BEIDOU': { mission: 'Navigation', color: '#448AFF' },
24 'SBIRS': { mission: 'Early Warning', color: '#FF00FF' },
25 'DSP': { mission: 'Early Warning', color: '#FF00FF' },
26 'STARLINK': { mission: 'Commercial Comms', color: '#00E676' },
27 'ONEWEB': { mission: 'Commercial Comms', color: '#00E676' },
28 'PLANET': { mission: 'Earth Imaging', color: '#00E676' },
29 'WORLDVIEW': { mission: 'Commercial Imaging', color: '#00E676' },
30 'ISS': { mission: 'Space Station', color: '#FFD700' },
31 'TIANGONG': { mission: 'Space Station', color: '#FFD700' },
32 'COSMOS': { mission: 'Russian Military', color: '#FF6B6B' },
33 'YAOGAN': { mission: 'Chinese Recon', color: '#FF6B6B' },
34 'FENGYUN': { mission: 'Weather', color: '#87CEEB' },
35 'GOES': { mission: 'Weather', color: '#87CEEB' },
36 'NOAA': { mission: 'Weather', color: '#87CEEB' },
37 'METEOSAT': { mission: 'Weather', color: '#87CEEB' },
38 'LANDSAT': { mission: 'Earth Observation', color: '#90EE90' },
39 'SENTINEL': { mission: 'Earth Observation', color: '#90EE90' },
40 'TERRA': { mission: 'Earth Science', color: '#90EE90' },
41 'AQUA': { mission: 'Earth Science', color: '#90EE90' },
42 'HUBBLE': { mission: 'Space Telescope', color: '#FFD700' },
43 'JAMES WEBB': { mission: 'Space Telescope', color: '#FFD700' },
44};
45
46function classifySatellite(name: string): { mission: string; color: string } {
47 const upper = name.toUpperCase();
48 for (const [keyword, info] of Object.entries(MISSION_CLASSIFY)) {
49 if (upper.includes(keyword)) return info;
50 }
51 return { mission: 'Unknown', color: '#00E5FF' };
52}
53
54function gmst(jd: number): number {
55 const t = (jd - 2451545.0) / 36525.0;
56 const gmstSec = 67310.54841 + (876600.0 * 3600 + 8640184.812866) * t + 0.093104 * t * t - 6.2e-6 * t * t * t;
57 return ((gmstSec % 86400) / 86400.0) * 2 * Math.PI;
58}
59
60// No longer needed: function parseTLE(tleText: string) {}
61
62function propagateSGP4Simple(line1: string, line2: string): { lat: number; lng: number; alt: number } | null {
63 try {
64 const incDeg = parseFloat(line2.substring(8, 16));
65 const raanDeg = parseFloat(line2.substring(17, 25));
66 const eccStr = '0.' + line2.substring(26, 33).trim();
67 const ecc = parseFloat(eccStr);
68 const argPerDeg = parseFloat(line2.substring(34, 42));
69 const meanAnomDeg = parseFloat(line2.substring(43, 51));
70 const meanMotion = parseFloat(line2.substring(52, 63));
71
72 if (isNaN(meanMotion) || meanMotion === 0) return null;
73
74 const now = new Date();
75 const epochYear = parseInt(line1.substring(18, 20));
76 const epochDay = parseFloat(line1.substring(20, 32));
77 const fullYear = epochYear > 56 ? 1900 + epochYear : 2000 + epochYear;
78
79 const epochDate = new Date(fullYear, 0, 1);
80 epochDate.setDate(epochDate.getDate() + epochDay - 1);
81 const elapsedMin = (now.getTime() - epochDate.getTime()) / 60000;
82
83 // Reject stale TLEs (> 30 days old) unless it's the emergency fallback
84 if (Math.abs(elapsedMin) > 43200 && !line1.includes('27885-3')) return null;
85
86 const n = meanMotion * 2 * Math.PI / 1440;
87 const M = ((meanAnomDeg * Math.PI / 180) + n * elapsedMin) % (2 * Math.PI);
88
89 let E = M;
90 for (let j = 0; j < 10; j++) {
91 E = M + ecc * Math.sin(E);
92 }
93
94 const sinV = Math.sqrt(1 - ecc * ecc) * Math.sin(E) / (1 - ecc * Math.cos(E));
95 const cosV = (Math.cos(E) - ecc) / (1 - ecc * Math.cos(E));
96 const v = Math.atan2(sinV, cosV);
97
98 const a = Math.pow(398600.4418 / (meanMotion * 2 * Math.PI / 86400) ** 2, 1 / 3);
99 const r = a * (1 - ecc * Math.cos(E));
100
101 const inc = incDeg * Math.PI / 180;
102 const raan = raanDeg * Math.PI / 180;
103 const argPer = argPerDeg * Math.PI / 180;
104 const u = v + argPer;
105
106 const x = r * (Math.cos(raan) * Math.cos(u) - Math.sin(raan) * Math.sin(u) * Math.cos(inc));
107 const y = r * (Math.sin(raan) * Math.cos(u) + Math.cos(raan) * Math.sin(u) * Math.cos(inc));
108 const z = r * Math.sin(u) * Math.sin(inc);
109
110 const jd = 2440587.5 + now.getTime() / 86400000;
111 const theta = gmst(jd);
112
113 const xRot = x * Math.cos(theta) + y * Math.sin(theta);
114 const yRot = -x * Math.sin(theta) + y * Math.cos(theta);
115
116 const lng = Math.atan2(yRot, xRot) * 180 / Math.PI;
117 const lat = Math.atan2(z, Math.sqrt(xRot * xRot + yRot * yRot)) * 180 / Math.PI;
118 const alt = r - 6371;
119
120 if (isNaN(lat) || isNaN(lng) || Math.abs(lat) > 90) return null;
121 if (alt < 100 || alt > 50000) return null; // sanity check
122
123 return {
124 lat: Math.round(lat * 10000) / 10000,
125 lng: Math.round(((lng + 540) % 360 - 180) * 10000) / 10000,
126 alt: Math.round(alt),
127 };
128 } catch {
129 return null;
130 }
131}
132
133// SatNOGS Open API - Provides full TLE JSON without API keys or IP blocks
134const SATNOGS_API = 'https://db.satnogs.org/api/tle/?format=json';
135
136let globalCachedSats: any[] = [];
137let globalCacheTime = 0;
138
139export async function GET() {
140 try {
141 const nowTime = Date.now();
142 let allSats: any[] = globalCachedSats;
143 let source = 'memory-cache';
144
145 if (globalCachedSats.length === 0 || nowTime - globalCacheTime > 3600000) { // 1 hour cache
146 try {
147 const res = await stealthFetch(SATNOGS_API, {
148 signal: AbortSignal.timeout(15000),
149 headers: { 'Accept': 'application/json' },
150 });
151
152 if (res.ok) {
153 const data = await res.json();
154 const fetchedSats: any[] = [];
155 const seen = new Set<string>();
156
157 for (const item of data) {
158 const rawName = (item.tle0 || '').trim();
159 const cleanName = rawName.replace(/^0\s+/, '');
160 if (cleanName && item.tle1 && item.tle2 && !seen.has(cleanName)) {
161 seen.add(cleanName);
162 fetchedSats.push({
163 name: cleanName,
164 line1: item.tle1.trim(),
165 line2: item.tle2.trim(),
166 });
167 }
168 }
169
170 if (fetchedSats.length > 0) {
171 globalCachedSats = fetchedSats;
172 globalCacheTime = nowTime;
173 allSats = fetchedSats;
174 source = 'satnogs-api';
175 }
176 }
177 } catch (err) {
178 console.error('SatNOGS fetch error:', err);
179 }
180 }
181
182 // Emergency Fallback if cache is totally empty and SatNOGS is down
183 if (allSats.length === 0) {
184 const issFallback = "1 25544U 98067A 24146.40251785 .00015505 00000-0 27885-3 0 9997\n2 25544 51.6402 189.7042 0004381 334.8091 106.8778 15.50091157455243";
185 allSats = [{ name: 'ISS (FALLBACK)', line1: issFallback.split('\n')[0], line2: issFallback.split('\n')[1] }];
186 source = 'emergency-fallback';
187 }
188
189 // Sample for performance (max 2000 satellites)
190 const sampled = allSats.length > 2000
191 ? allSats.filter((_, i) => i % Math.ceil(allSats.length / 2000) === 0)
192 : allSats;
193
194 const satellites = [];
195 for (const sat of sampled) {
196 const pos = propagateSGP4Simple(sat.line1, sat.line2);
197 if (!pos) continue;
198
199 const classification = classifySatellite(sat.name);
200 satellites.push({
201 name: sat.name,
202 lat: pos.lat,
203 lng: pos.lng,
204 alt: pos.alt,
205 mission: classification.mission,
206 color: classification.color,
207 noradId: sat.line1.substring(2, 7).trim(),
208 });
209 }
210
211 return NextResponse.json({
212 satellites,
213 total: satellites.length,
214 source,
215 raw_count: allSats.length,
216 timestamp: new Date().toISOString(),
217 }, {
218 headers: {
219 'Cache-Control': 'public, s-maxage=120, stale-while-revalidate=300',
220 },
221 });
222 } catch (error) {
223 console.error('Satellite fetch error:', error);
224 return NextResponse.json({ satellites: [], error: 'Failed to fetch satellite data' }, { status: 500 });
225 }
226}
227