Elffuss BraidHub

kikocis/osiris public

master · 4.2 KiBRawPermalink
1
2import { NextResponse } from 'next/server';
3
4export const dynamic = 'force-dynamic';
5
6/**
7 * OSIRIS — Active Fire & Wildfire Tracking
8 * Multi-source: NASA FIRMS Open Data (primary for global fires), NASA EONET (volcanoes)
9 */
10
11export async function GET() {
12 try {
13 let fires: any[] = [];
14 let source = '';
15
16 // Source 1: NASA FIRMS Open Data (Global 24h CSV) - no API key needed
17 const firmsSources = [
18 'https://firms.modaps.eosdis.nasa.gov/data/active_fire/suomi-npp-viirs-c2/csv/SUOMI_VIIRS_C2_Global_24h.csv',
19 'https://firms.modaps.eosdis.nasa.gov/data/active_fire/modis-c6.1/csv/MODIS_C6_1_Global_24h.csv'
20 ];
21
22 for (const url of firmsSources) {
23 try {
24 const res = await fetch(url, {
25 signal: AbortSignal.timeout(15000),
26 headers: { 'User-Agent': 'OSIRIS-Intelligence-Platform/3.5' },
27 });
28 if (res.ok) {
29 const text = await res.text();
30 if (text && text.includes('latitude') && text.length > 200) {
31 const parsed = parseCSV(text);
32 if (parsed.length > 0) {
33 fires = parsed;
34 source = url.includes('SUOMI') ? 'NASA-FIRMS (VIIRS)' : 'NASA-FIRMS (MODIS)';
35 break;
36 }
37 }
38 }
39 } catch { continue; }
40 }
41
42 // Source 2: Pull volcanoes from EONET for richer data
43 try {
44 const volcRes = await fetch('https://eonet.gsfc.nasa.gov/api/v3/events?status=open&category=volcanoes&limit=50', {
45 signal: AbortSignal.timeout(10000),
46 });
47 if (volcRes.ok) {
48 const volcData = await volcRes.json();
49 const volcanoes = (volcData.events || []).map((e: any) => {
50 const geo = e.geometry?.[e.geometry.length - 1];
51 if (!geo?.coordinates) return null;
52 return {
53 lat: geo.coordinates[1],
54 lng: geo.coordinates[0],
55 brightness: 500,
56 confidence: 'high',
57 date: geo.date?.split('T')[0] || '',
58 time: '',
59 frp: 100,
60 title: `[VOLCANO] ${e.title}`,
61 type: 'volcano',
62 };
63 }).filter(Boolean);
64 fires = [...fires, ...volcanoes];
65 if (!source) source = 'NASA-EONET';
66 }
67 } catch (e) { console.warn('[OSIRIS] Suppressed EONET error:', e instanceof Error ? e.message : e); }
68
69 return NextResponse.json({
70 fires,
71 total: fires.length,
72 source: source || 'Unknown',
73 timestamp: new Date().toISOString(),
74 }, {
75 headers: {
76 'Cache-Control': 'public, s-maxage=600, stale-while-revalidate=1200',
77 },
78 });
79 } catch (error) {
80 console.error('Fire fetch error:', error);
81 return NextResponse.json({ fires: [], error: 'Failed to fetch fire data' }, { status: 500 });
82 }
83}
84
85function parseCSV(csv: string): any[] {
86 const lines = csv.trim().split('\n');
87 if (lines.length < 2) return [];
88
89 const header = lines[0].split(',');
90 const latIdx = header.indexOf('latitude');
91 const lngIdx = header.indexOf('longitude');
92 const brightIdx = header.indexOf('bright_ti4') !== -1 ? header.indexOf('bright_ti4') : header.indexOf('brightness');
93 const confIdx = header.indexOf('confidence');
94 const dateIdx = header.indexOf('acq_date');
95 const timeIdx = header.indexOf('acq_time');
96 const frpIdx = header.indexOf('frp');
97
98 const fires: any[] = [];
99 // Sample the data if there are too many rows to avoid browser lag. Limit to ~2000 points globally.
100 const maxPoints = 2000;
101 const step = lines.length > maxPoints ? Math.ceil(lines.length / maxPoints) : 1;
102
103 for (let i = 1; i < lines.length; i += step) {
104 const cols = lines[i].split(',');
105 const lat = parseFloat(cols[latIdx]);
106 const lng = parseFloat(cols[lngIdx]);
107 if (isNaN(lat) || isNaN(lng)) continue;
108
109 fires.push({
110 lat: Math.round(lat * 1000) / 1000,
111 lng: Math.round(lng * 1000) / 1000,
112 brightness: parseFloat(cols[brightIdx]) || 0,
113 confidence: cols[confIdx] || 'unknown',
114 date: cols[dateIdx] || '',
115 time: cols[timeIdx] || '',
116 frp: parseFloat(cols[frpIdx]) || 0,
117 type: 'fire'
118 });
119 }
120
121 return fires;
122}
123