Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
1714 lines (1473 loc) · 66.9 KB
/
Copy pathserver.js
File metadata and controls
1714 lines (1473 loc) · 66.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
require('dotenv').config();
const express = require('express');
const cors = require('cors');
const axios = require('axios');
const xml2js = require('xml2js');
const path = require('path');
const cookieParser = require('cookie-parser');
const bcrypt = require('bcryptjs');
const crypto = require('crypto');
const app = express();
const PORT = process.env.PORT || 3003;
// Cookie secret for signing
const COOKIE_SECRET = process.env.SESSION_SECRET || 'ifrc-emergency-response-secret-key-change-this';
app.use(cors({
origin: true,
credentials: true
}));
app.use(express.json());
app.use(cookieParser(COOKIE_SECRET));
// Authentication middleware
function requireAuth(req, res, next) {
const authToken = req.signedCookies.auth_token;
if (authToken && authToken === 'authenticated') {
return next();
}
// If not authenticated, redirect to login or send 401
if (req.path.startsWith('/api/')) {
return res.status(401).json({ error: 'Authentication required' });
}
res.redirect('/login.html');
}
// Login endpoint
app.post('/api/login', async (req, res) => {
try {
const { password } = req.body;
if (!password) {
return res.status(400).json({
success: false,
error: 'Password is required'
});
}
// Get password hash from environment variable
const passwordHash = process.env.APP_PASSWORD_HASH;
if (!passwordHash) {
console.error('APP_PASSWORD_HASH not set in environment variables');
return res.status(500).json({
success: false,
error: 'Authentication not configured'
});
}
// Compare password with hash
const isValid = await bcrypt.compare(password, passwordHash);
if (isValid) {
// Set a signed cookie for authentication
res.cookie('auth_token', 'authenticated', {
signed: true,
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
maxAge: 60 * 60 * 1000, // 1 hour
sameSite: 'lax'
});
return res.json({
success: true,
message: 'Login successful'
});
} else {
return res.status(401).json({
success: false,
error: 'Invalid password'
});
}
} catch (error) {
console.error('Login error:', error);
return res.status(500).json({
success: false,
error: 'Login failed'
});
}
});
// Logout endpoint
app.post('/api/logout', (req, res) => {
res.clearCookie('auth_token');
res.json({ success: true, message: 'Logged out successfully' });
});
// Public routes (no authentication required)
app.get('/login.html', (req, res) => {
res.sendFile(path.join(__dirname, 'login.html'));
});
app.get('/IFRC-Logo.png', (req, res) => {
res.sendFile(path.join(__dirname, 'IFRC-Logo.png'));
});
// Authentication enabled - all routes below require login
// Serve JS modules with correct MIME type and no-cache headers BEFORE static middleware
app.get('/js/:filename', requireAuth, (req, res) => {
res.type('application/javascript');
res.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate');
res.setHeader('Pragma', 'no-cache');
res.setHeader('Expires', '0');
res.sendFile(path.join(__dirname, 'js', req.params.filename));
});
// Serve images (protected)
app.get('/images/:filename', requireAuth, (req, res) => {
res.sendFile(path.join(__dirname, 'images', req.params.filename));
});
// Explicit static file routes for Vercel deployment (all protected except already defined public ones)
app.get('/styles.css', requireAuth, (req, res) => {
res.sendFile(path.join(__dirname, 'styles.css'));
});
app.get('/script.js', requireAuth, (req, res) => {
res.sendFile(path.join(__dirname, 'script.js'));
});
app.get('/index.html', requireAuth, (req, res) => {
res.sendFile(path.join(__dirname, 'index.html'));
});
const parser = new xml2js.Parser();
class PopulationEstimator {
constructor() {
// Population density data for major regions (people per sq km)
this.populationDensityData = {
// High density regions
'asia-high': 500, // Bangladesh, India, China urban
'europe-high': 300, // Western Europe urban
'africa-high': 400, // Nigeria, Egypt urban
// Medium density regions
'asia-medium': 150, // Southeast Asia, rural China
'europe-medium': 100, // Eastern Europe, rural areas
'africa-medium': 80, // Central/East Africa
'americas-medium': 50, // US/Canada suburban
// Low density regions
'asia-low': 30, // Mongolia, Central Asia
'europe-low': 20, // Scandinavia, Russia rural
'africa-low': 15, // Sahara, rural areas
'americas-low': 5, // Alaska, rural Canada/US
'oceania-low': 3, // Australia outback
// Urban centers (major cities)
'urban-mega': 10000, // City centers
'urban-major': 5000, // Major cities
'urban-medium': 2000, // Medium cities
};
// Major population centers for more accurate estimates
this.populationCenters = [
// Asia
{ name: 'Delhi', lat: 28.7, lon: 77.1, population: 30000000, radius: 50 },
{ name: 'Tokyo', lat: 35.7, lon: 139.7, population: 38000000, radius: 60 },
{ name: 'Shanghai', lat: 31.2, lon: 121.5, population: 27000000, radius: 45 },
{ name: 'Beijing', lat: 39.9, lon: 116.4, population: 21500000, radius: 40 },
{ name: 'Mumbai', lat: 19.1, lon: 72.9, population: 20400000, radius: 35 },
{ name: 'Manila', lat: 14.6, lon: 121.0, population: 13500000, radius: 30 },
{ name: 'Jakarta', lat: -6.2, lon: 106.8, population: 10800000, radius: 25 },
{ name: 'Karachi', lat: 24.9, lon: 67.0, population: 16000000, radius: 30 },
{ name: 'Dhaka', lat: 23.8, lon: 90.4, population: 9000000, radius: 20 },
// Americas
{ name: 'New York', lat: 40.7, lon: -74.0, population: 8400000, radius: 25 },
{ name: 'Los Angeles', lat: 34.1, lon: -118.2, population: 4000000, radius: 30 },
{ name: 'Mexico City', lat: 19.4, lon: -99.1, population: 21800000, radius: 40 },
{ name: 'São Paulo', lat: -23.5, lon: -46.6, population: 12300000, radius: 30 },
{ name: 'Buenos Aires', lat: -34.6, lon: -58.4, population: 3000000, radius: 20 },
// Europe
{ name: 'London', lat: 51.5, lon: -0.1, population: 9000000, radius: 25 },
{ name: 'Paris', lat: 48.9, lon: 2.3, population: 2200000, radius: 15 },
{ name: 'Istanbul', lat: 41.0, lon: 28.9, population: 15500000, radius: 35 },
{ name: 'Moscow', lat: 55.8, lon: 37.6, population: 12500000, radius: 30 },
// Africa
{ name: 'Lagos', lat: 6.5, lon: 3.4, population: 15000000, radius: 30 },
{ name: 'Cairo', lat: 30.0, lon: 31.2, population: 20900000, radius: 35 },
{ name: 'Kinshasa', lat: -4.3, lon: 15.3, population: 14300000, radius: 25 },
];
}
// Calculate distance between two points in km
calculateDistance(lat1, lon1, lat2, lon2) {
const R = 6371; // Earth's radius in km
const dLat = (lat2 - lat1) * Math.PI / 180;
const dLon = (lon2 - lon1) * Math.PI / 180;
const a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
Math.sin(dLon/2) * Math.sin(dLon/2);
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
return R * c;
}
// Estimate population for a circular area around coordinates
estimatePopulationInRadius(lat, lon, radiusKm) {
let totalPopulation = 0;
let density = this.getRegionalDensity(lat, lon);
// Check if near major population centers
const nearbyCenter = this.findNearestPopulationCenter(lat, lon);
if (nearbyCenter && nearbyCenter.distance < 100) {
// Adjust density based on proximity to major city
const proximityFactor = Math.max(0.1, 1 - (nearbyCenter.distance / 100));
const cityInfluence = nearbyCenter.center.population / (Math.PI * Math.pow(nearbyCenter.center.radius, 2));
density = Math.max(density, cityInfluence * proximityFactor);
}
// Calculate population in circular area
const areaKm2 = Math.PI * Math.pow(radiusKm, 2);
totalPopulation = Math.round(density * areaKm2);
return {
estimatedPopulation: totalPopulation,
density: Math.round(density),
area: Math.round(areaKm2),
method: 'regional_density_estimation'
};
}
// Get regional population density based on coordinates
getRegionalDensity(lat, lon) {
// Asia
if (lon > 60 && lon < 150 && lat > 10 && lat < 55) {
if (lon > 70 && lon < 140 && lat > 20 && lat < 40) return this.populationDensityData['asia-high']; // China/India belt
return this.populationDensityData['asia-medium'];
}
// Europe
if (lon > -10 && lon < 40 && lat > 35 && lat < 70) {
if (lon > 0 && lon < 25 && lat > 45 && lat < 60) return this.populationDensityData['europe-high']; // Western Europe
return this.populationDensityData['europe-medium'];
}
// Africa
if (lon > -20 && lon < 55 && lat > -35 && lat < 35) {
if (lon > 30 && lon < 45 && lat > 25 && lat < 35) return this.populationDensityData['africa-high']; // Nile Valley
if (lon > -5 && lon < 15 && lat > 5 && lat < 15) return this.populationDensityData['africa-high']; // West Africa coastal
return this.populationDensityData['africa-medium'];
}
// North America
if (lon > -170 && lon < -50 && lat > 15 && lat < 70) {
if (lon > -125 && lon < -70 && lat > 25 && lat < 50) return this.populationDensityData['americas-medium']; // US/Canada populated
return this.populationDensityData['americas-low'];
}
// South America
if (lon > -85 && lon < -30 && lat > -55 && lat < 15) {
return this.populationDensityData['americas-medium'];
}
// Australia/Oceania
if (lon > 110 && lon < 180 && lat > -50 && lat < -10) {
return this.populationDensityData['oceania-low'];
}
// Default low density for remote areas
return this.populationDensityData['asia-low'];
}
// Find nearest major population center
findNearestPopulationCenter(lat, lon) {
let nearest = null;
let minDistance = Infinity;
for (const center of this.populationCenters) {
const distance = this.calculateDistance(lat, lon, center.lat, center.lon);
if (distance < minDistance) {
minDistance = distance;
nearest = { center, distance };
}
}
return nearest;
}
// Get country-level population estimate using REST Countries API
async getCountryPopulation(lat, lon) {
try {
// This is a simplified approach - in production you'd use a reverse geocoding service
const country = this.getCountryFromCoordinates(lat, lon);
if (country) {
const response = await axios.get(`https://restcountries.com/v3.1/name/${country}`, {
timeout: 5000
});
if (response.data && response.data[0] && response.data[0].population) {
return {
country: country,
population: response.data[0].population,
method: 'country_api'
};
}
}
} catch (error) {
console.warn('Country population lookup failed:', error.message);
}
return null;
}
// Simple country detection from coordinates (basic implementation)
getCountryFromCoordinates(lat, lon) {
const countries = [
{ name: 'China', bounds: { minLat: 15, maxLat: 54, minLon: 73, maxLon: 135 } },
{ name: 'India', bounds: { minLat: 8, maxLat: 37, minLon: 68, maxLon: 97 } },
{ name: 'United States', bounds: { minLat: 25, maxLat: 49, minLon: -125, maxLon: -66 } },
{ name: 'Indonesia', bounds: { minLat: -11, maxLat: 6, minLon: 95, maxLon: 141 } },
{ name: 'Brazil', bounds: { minLat: -34, maxLat: 5, minLon: -74, maxLon: -35 } },
{ name: 'Pakistan', bounds: { minLat: 24, maxLat: 37, minLon: 61, maxLon: 77 } },
{ name: 'Bangladesh', bounds: { minLat: 20, maxLat: 27, minLon: 88, maxLon: 93 } },
{ name: 'Nigeria', bounds: { minLat: 4, maxLat: 14, minLon: 2, maxLon: 15 } },
{ name: 'Russia', bounds: { minLat: 41, maxLat: 82, minLon: 19, maxLon: 169 } },
{ name: 'Japan', bounds: { minLat: 30, maxLat: 46, minLon: 129, maxLon: 146 } },
];
for (const country of countries) {
const bounds = country.bounds;
if (lat >= bounds.minLat && lat <= bounds.maxLat &&
lon >= bounds.minLon && lon <= bounds.maxLon) {
return country.name;
}
}
return null;
}
}
class GDACSProxy {
constructor() {
this.baseUrl = 'https://www.gdacs.org';
this.rssUrl = 'https://www.gdacs.org/xml/rss.xml';
this.populationEstimator = new PopulationEstimator();
}
async fetchGDACSData(source = 'ALL', alertLevel = '', fromDate = '', toDate = '') {
try {
console.log('📡 Fetching GDACS events from API...');
const url = 'https://www.gdacs.org/gdacsapi/api/events/geteventlist/SEARCH';
const response = await axios.get(url, {
timeout: 30000,
headers: {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
'Accept': 'application/json'
}
});
if (!response.data || !response.data.features) {
console.warn('No features in GDACS response');
return [];
}
console.log(`✅ Retrieved ${response.data.features.length} events from GDACS`);
// Calculate date 30 days ago for filtering recent events
const thirtyDaysAgo = new Date();
thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
// Transform GDACS GeoJSON to our format and filter
const allEvents = response.data.features
.filter(feature => {
const props = feature.properties;
// Include if: current OR recent (last 30 days)
const isCurrent = props.iscurrent === 'true' || props.iscurrent === true;
const isTemporary = props.istemporary === 'true' || props.istemporary === true;
// Check if event is recent (within last 30 days)
const eventDate = new Date(props.fromdate);
const isRecent = eventDate >= thirtyDaysAgo;
// Include current events, OR recent events that aren't temporary
return (isCurrent || isRecent) && !isTemporary;
})
.map(feature => {
const props = feature.properties;
const coords = feature.geometry.coordinates;
// Extract severity details if available
const severityText = props.severitydata?.severitytext || '';
const severityValue = props.severitydata?.severity || '';
const severityUnit = props.severitydata?.severityunit || '';
return {
id: `${props.eventtype}-${props.eventid}`,
title: props.name || props.eventname || 'Unnamed Event',
description: props.description || props.htmldescription || '',
type: this.mapEventType(props.eventtype),
alertLevel: this.normalizeAlertLevel(props.alertlevel),
coordinates: [coords[1], coords[0]], // GeoJSON is [lng, lat], we need [lat, lng]
severity: props.episodealertscore || 0,
affectedRadius: this.calculateRadius(props.eventtype, props.episodealertscore),
date: props.fromdate || new Date().toISOString(),
country: props.country || '',
source: 'GDACS',
severityText: severityText,
severityValue: severityValue,
severityUnit: severityUnit
};
});
// Filter by alert level and remove drought events
let filteredEvents = allEvents.filter(e => e.type !== 'Drought');
if (alertLevel && alertLevel !== '') {
filteredEvents = filteredEvents.filter(e => e.alertLevel === alertLevel);
}
console.log(`📊 Returning ${filteredEvents.length} disaster events (current or from last 30 days, excluded droughts)`);
return filteredEvents;
} catch (error) {
console.error('❌ Error fetching GDACS data:', error.message);
return [];
}
}
mapEventType(gdacsType) {
const typeMap = {
'EQ': 'Earthquake',
'TC': 'Cyclone',
'FL': 'Flood',
'VO': 'Volcanic Activity',
'DR': 'Drought',
'WF': 'Wildfire'
};
return typeMap[gdacsType] || 'Other';
}
normalizeAlertLevel(level) {
if (!level) return 'Green';
const normalized = level.charAt(0).toUpperCase() + level.slice(1).toLowerCase();
return ['Red', 'Orange', 'Green'].includes(normalized) ? normalized : 'Green';
}
calculateRadius(eventType, alertScore) {
const baseRadii = {
'Earthquake': 50,
'Flood': 30,
'Cyclone': 100,
'Wildfire': 20,
'Volcanic Activity': 25,
'Drought': 100,
'Other': 40
};
const base = baseRadii[eventType] || 40;
const multiplier = alertScore ? (alertScore / 2) : 1;
return base * multiplier;
}
async tryFloodDataFormat(src, format, alertLevel, fromDate, toDate, retries = 2) {
const url = `${this.baseUrl}/floodmerge/data_v2.aspx`;
const params = {
source: src,
type: format,
alertlevel: alertLevel,
from: fromDate,
to: toDate
};
for (let attempt = 1; attempt <= retries; attempt++) {
try {
console.log(`Trying ${src} in ${format} format (attempt ${attempt}):`, url, params);
const response = await axios.get(url, {
params,
timeout: 20000,
headers: {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
'Accept': format === 'json' ? 'application/json' : 'text/csv',
'Cache-Control': 'no-cache'
}
});
console.log(`${src} ${format} response status:`, response.status, 'Data length:', response.data ? response.data.length || 0 : 0);
if (format === 'json' && response.data && Array.isArray(response.data)) {
const events = this.transformFloodData(response.data, src);
console.log(`Successfully parsed ${events.length} events from ${src} JSON`);
return events;
} else if (format === 'csv' && response.data && typeof response.data === 'string') {
const events = this.parseCSVFloodData(response.data, src);
console.log(`Successfully parsed ${events.length} events from ${src} CSV`);
return events;
}
return [];
} catch (error) {
console.warn(`Attempt ${attempt} failed for ${src} ${format}:`, error.message);
if (attempt === retries) {
throw error;
}
// Wait before retry
await new Promise(resolve => setTimeout(resolve, 1000 * attempt));
}
}
return [];
}
parseCSVFloodData(csvData, source) {
try {
const lines = csvData.split('\n').filter(line => line.trim());
if (lines.length < 2) return [];
const headers = lines[0].split(';');
const events = [];
for (let i = 1; i < lines.length; i++) {
const values = lines[i].split(';');
const event = {};
headers.forEach((header, index) => {
event[header.trim()] = values[index] ? values[index].trim() : '';
});
if (event.lat && event.lon) {
events.push({
id: event.areaid || `${source}_${i}`,
title: `${this.getSourceName(source)} Alert - ${event.sitename || `Area ${event.areaid}`}`,
type: this.getDisasterType(source),
alertLevel: this.normalizeAlertLevel(event.alertlevel),
latitude: parseFloat(event.lat),
longitude: parseFloat(event.lon),
magnitude: parseFloat(event.signal) || 0,
date: event.date || new Date().toISOString().split('T')[0],
description: `Signal: ${event.signal || 'N/A'}, Area: ${event.sitename || 'Unknown'}`,
source: source,
raw: event
});
}
}
return events;
} catch (error) {
console.error('Error parsing CSV data:', error.message);
return [];
}
}
async fetchRSSData(fromDate = '', toDate = '') {
try {
console.log('Fetching RSS data from:', this.rssUrl);
const response = await axios.get(this.rssUrl, {
timeout: 15000,
headers: {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
}
});
const result = await parser.parseStringPromise(response.data);
let events = await this.transformRSSData(result);
// Filter events by date range if provided
if (fromDate || toDate) {
const fromDateObj = fromDate ? new Date(fromDate) : null;
const toDateObj = toDate ? new Date(toDate) : null;
events = events.filter(event => {
const eventDate = new Date(event.date);
if (fromDateObj && eventDate < fromDateObj) return false;
if (toDateObj && eventDate > toDateObj) return false;
return true;
});
console.log(`Filtered ${events.length} events within date range ${fromDate || 'any'} to ${toDate || 'any'}`);
}
console.log(`Successfully parsed ${events.length} events from RSS with population estimates`);
return events;
} catch (error) {
console.error('Error fetching RSS data:', error.message);
throw error;
}
}
transformFloodData(data, source) {
return data.map((item, index) => ({
id: item.areaid || `${source}_${index}`,
title: `${this.getSourceName(source)} Alert - ${item.sitename || `Area ${item.areaid}`}`,
type: this.getDisasterType(source),
alertLevel: this.normalizeAlertLevel(item.alertlevel),
latitude: parseFloat(item.lat) || 0,
longitude: parseFloat(item.lon) || 0,
magnitude: parseFloat(item.signal) || 0,
date: item.date || new Date().toISOString().split('T')[0],
description: `Signal: ${item.signal || 'N/A'}, Area: ${item.sitename || 'Unknown'}`,
source: source,
raw: item
})).filter(event => event.latitude !== 0 && event.longitude !== 0);
}
async transformRSSData(rssData) {
if (!rssData || !rssData.rss || !rssData.rss.channel || !rssData.rss.channel[0].item) {
console.log('No RSS items found');
return [];
}
const items = rssData.rss.channel[0].item;
console.log(`Processing ${items.length} RSS items`);
const events = [];
for (let index = 0; index < items.length; index++) {
const item = items[index];
const title = item.title && item.title[0] ? item.title[0] : `Event ${index + 1}`;
const description = item.description && item.description[0] ? item.description[0] : '';
const pubDate = item.pubDate && item.pubDate[0] ? item.pubDate[0] : '';
const link = item.link && item.link[0] ? item.link[0] : '';
// Extract GDACS-specific data from georss and gdacs namespaces
const coordinates = this.extractGDACSCoordinates(item);
const alertLevel = this.extractGDACSAlertLevel(item, title);
const disasterType = this.extractGDACSDisasterType(item, title);
const magnitude = this.extractGDACSMagnitude(item, description);
// Use async population estimation
const areaInfo = await this.extractAffectedAreaInfo(item, title, description, coordinates);
const event = {
id: `gdacs_${index}`,
title: title,
type: disasterType,
alertLevel: alertLevel,
coordinates: [coordinates.lat, coordinates.lon], // Add coordinates array for frontend
latitude: coordinates.lat,
longitude: coordinates.lon,
magnitude: magnitude,
date: pubDate ? new Date(pubDate).toISOString().split('T')[0] : new Date().toISOString().split('T')[0],
description: description.length > 300 ? description.substring(0, 300) + '...' : description,
source: 'GDACS-RSS',
link: link,
affectedRadius: areaInfo.affectedRadius || areaInfo.estimatedRadius,
affectedPopulation: areaInfo.estimatedPopulation || areaInfo.affectedPopulation,
impactDescription: areaInfo.impactDescription,
estimatedRadius: areaInfo.estimatedRadius,
populationData: areaInfo.populationData
};
if (event.latitude !== 0 && event.longitude !== 0) {
events.push(event);
console.log(`Parsed event: ${event.title} at ${event.latitude}, ${event.longitude}`);
}
}
return events;
}
extractGDACSCoordinates(item) {
let lat = 0, lon = 0;
// Try georss:point first
if (item['georss:point'] && item['georss:point'][0]) {
const coords = item['georss:point'][0].split(' ');
if (coords.length === 2) {
lat = parseFloat(coords[0]);
lon = parseFloat(coords[1]);
}
}
// Try gdacs specific coordinates
if (lat === 0 && lon === 0) {
if (item['gdacs:lat'] && item['gdacs:lat'][0]) {
lat = parseFloat(item['gdacs:lat'][0]);
}
if (item['gdacs:lon'] && item['gdacs:lon'][0]) {
lon = parseFloat(item['gdacs:lon'][0]);
}
}
// Fallback to description parsing
if (lat === 0 && lon === 0) {
const description = item.description && item.description[0] ? item.description[0] : '';
const link = item.link && item.link[0] ? item.link[0] : '';
const coords = this.extractCoordinatesFromDescription(description, link);
lat = coords.lat;
lon = coords.lon;
}
return { lat, lon };
}
extractGDACSAlertLevel(item, title) {
// Try GDACS-specific alert level
if (item['gdacs:alertlevel'] && item['gdacs:alertlevel'][0]) {
return item['gdacs:alertlevel'][0].toUpperCase();
}
// Extract from title
return this.extractAlertLevelFromTitle(title);
}
extractGDACSDisasterType(item, title) {
// Try GDACS-specific event type
if (item['gdacs:eventtype'] && item['gdacs:eventtype'][0]) {
const eventType = item['gdacs:eventtype'][0].toLowerCase();
const typeMap = {
'eq': 'Earthquake',
'tc': 'Cyclone',
'fl': 'Flood',
'vo': 'Volcano',
'wf': 'Wildfire',
'dr': 'Drought'
};
return typeMap[eventType] || eventType;
}
// Fallback to title parsing
return this.extractDisasterTypeFromTitle(title);
}
extractGDACSMagnitude(item, description) {
// Try GDACS-specific magnitude
if (item['gdacs:severity'] && item['gdacs:severity'][0]) {
return parseFloat(item['gdacs:severity'][0]);
}
// Extract magnitude from description
const magMatch = description.match(/magnitude[:\s]*([0-9.]+)/i) ||
description.match(/m([0-9.]+)/i) ||
description.match(/([0-9.]+)m/i);
return magMatch ? parseFloat(magMatch[1]) : 0;
}
async extractAffectedAreaInfo(item, title, description, coordinates) {
const areaInfo = {
affectedRadius: 0,
affectedPopulation: 0,
estimatedPopulation: 0,
impactDescription: '',
estimatedRadius: 0,
populationData: null
};
// Extract population affected from GDACS description first
const popMatches = [
description.match(/(\d+(?:\.\d+)?)\s*million/i),
description.match(/(\d+(?:,\d+)*)\s*thousand/i),
description.match(/affecting\s*(\d+(?:,\d+)*)/i)
];
if (popMatches[0]) {
areaInfo.affectedPopulation = parseFloat(popMatches[0][1]) * 1000000;
} else if (popMatches[1]) {
areaInfo.affectedPopulation = parseFloat(popMatches[1][1].replace(/,/g, '')) * 1000;
} else if (popMatches[2]) {
areaInfo.affectedPopulation = parseFloat(popMatches[2][1].replace(/,/g, ''));
}
// Extract radius information from GDACS description
const radiusMatch = description.match(/(\d+)\s*km/i);
if (radiusMatch) {
areaInfo.affectedRadius = parseFloat(radiusMatch[1]);
}
// Calculate estimated impact radius based on event type and magnitude
const eventType = this.extractGDACSDisasterType(item, title);
const magnitude = this.extractGDACSMagnitude(item, description);
areaInfo.estimatedRadius = this.calculateImpactRadius(eventType, magnitude, areaInfo.affectedPopulation);
// Use population estimator to get more accurate population data
if (coordinates && coordinates.lat !== 0 && coordinates.lon !== 0) {
try {
const populationEstimate = this.populationEstimator.estimatePopulationInRadius(
coordinates.lat,
coordinates.lon,
areaInfo.estimatedRadius
);
areaInfo.populationData = populationEstimate;
// If GDACS didn't provide population data, use our estimate
if (areaInfo.affectedPopulation === 0) {
areaInfo.estimatedPopulation = populationEstimate.estimatedPopulation;
} else {
areaInfo.estimatedPopulation = areaInfo.affectedPopulation;
}
console.log(`Population estimate for ${title}: ${populationEstimate.estimatedPopulation.toLocaleString()} people in ${areaInfo.estimatedRadius}km radius (density: ${populationEstimate.density}/km²)`);
} catch (error) {
console.warn('Population estimation failed:', error.message);
areaInfo.estimatedPopulation = areaInfo.affectedPopulation || 0;
}
} else {
areaInfo.estimatedPopulation = areaInfo.affectedPopulation || 0;
}
areaInfo.impactDescription = this.generateImpactDescription(eventType, magnitude, areaInfo.estimatedPopulation);
return areaInfo;
}
calculateImpactRadius(eventType, magnitude, population) {
switch (eventType.toLowerCase()) {
case 'earthquake':
// Earthquake impact radius based on magnitude
if (magnitude >= 7) return 200; // Major earthquake
if (magnitude >= 6) return 100; // Strong earthquake
if (magnitude >= 5) return 50; // Moderate earthquake
if (magnitude >= 4) return 25; // Light earthquake
return 10;
case 'cyclone':
case 'hurricane':
case 'typhoon':
// Cyclone impact radius based on intensity
if (magnitude >= 4) return 300; // Category 4-5
if (magnitude >= 3) return 200; // Category 3
if (magnitude >= 2) return 150; // Category 2
if (magnitude >= 1) return 100; // Category 1
return 75; // Tropical storm
case 'volcano':
// Volcanic impact radius
if (magnitude >= 4) return 100; // Major eruption
if (magnitude >= 3) return 50; // Moderate eruption
return 25; // Minor activity
case 'wildfire':
// Wildfire impact - varies widely
return 20;
case 'flood':
// Flood impact based on population affected
if (population > 1000000) return 150;
if (population > 100000) return 75;
if (population > 10000) return 40;
return 20;
case 'drought':
// Drought affects large areas
return 200;
default:
// Default radius based on population
if (population > 1000000) return 100;
if (population > 100000) return 50;
if (population > 10000) return 25;
return 15;
}
}
generateImpactDescription(eventType, magnitude, population) {
let desc = '';
if (population > 0) {
if (population >= 1000000) {
desc += `${(population / 1000000).toFixed(1)}M people affected`;
} else if (population >= 1000) {
desc += `${(population / 1000).toFixed(0)}K people affected`;
} else {
desc += `${population} people affected`;
}
}
if (magnitude > 0) {
if (desc) desc += ', ';
if (eventType.toLowerCase() === 'earthquake') {
desc += `Magnitude ${magnitude}`;
} else {
desc += `Intensity ${magnitude}`;
}
}
return desc;
}
extractCoordinatesFromDescription(description, link) {
let lat = 0, lon = 0;
const text = (description + ' ' + link).toLowerCase();
const latRegex = /lat[:\s=]*([+-]?\d+\.?\d*)/i;
const lonRegex = /lon[:\s=]*([+-]?\d+\.?\d*)/i;
const latMatch = text.match(latRegex);
const lonMatch = text.match(lonRegex);
if (latMatch) lat = parseFloat(latMatch[1]);
if (lonMatch) lon = parseFloat(lonMatch[1]);
if (lat === 0 && lon === 0) {
const coordRegex = /(-?\d+\.?\d*),\s*(-?\d+\.?\d*)/;
const coordMatch = text.match(coordRegex);
if (coordMatch) {
lat = parseFloat(coordMatch[1]);
lon = parseFloat(coordMatch[2]);
}
}
if (lat === 0 && lon === 0) {
const geoRegex = /(\d+\.?\d*)[°\s]*([ns])[,\s]*(\d+\.?\d*)[°\s]*([ew])/i;
const geoMatch = text.match(geoRegex);
if (geoMatch) {
lat = parseFloat(geoMatch[1]) * (geoMatch[2].toLowerCase() === 's' ? -1 : 1);
lon = parseFloat(geoMatch[3]) * (geoMatch[4].toLowerCase() === 'w' ? -1 : 1);
}
}
return { lat: lat || 0, lon: lon || 0 };
}
extractAlertLevelFromTitle(title) {
const upperTitle = title.toUpperCase();
if (upperTitle.includes('RED')) return 'RED';
if (upperTitle.includes('ORANGE')) return 'ORANGE';
if (upperTitle.includes('GREEN')) return 'GREEN';
return 'GREEN';
}
extractDisasterTypeFromTitle(title) {
const lowerTitle = title.toLowerCase();
if (lowerTitle.includes('flood')) return 'Flood';
if (lowerTitle.includes('earthquake')) return 'Earthquake';
if (lowerTitle.includes('cyclone') || lowerTitle.includes('hurricane') || lowerTitle.includes('typhoon')) return 'Cyclone';
if (lowerTitle.includes('volcano')) return 'Volcano';
if (lowerTitle.includes('wildfire') || lowerTitle.includes('fire')) return 'Wildfire';
if (lowerTitle.includes('drought')) return 'Drought';
if (lowerTitle.includes('tsunami')) return 'Tsunami';
return 'Disaster Event';
}
getSourceName(source) {
const names = {
'DFO': 'Dartmouth Flood Observatory',
'GPM': 'Global Precipitation Measurement',
'DFOMERGE': 'DFO Merged Analysis'
};
return names[source] || source;
}
getDisasterType(source) {
const types = {
'DFO': 'Flood',
'GPM': 'Precipitation',
'DFOMERGE': 'Flood Analysis'
};
return types[source] || 'Disaster Event';
}
normalizeAlertLevel(level) {
if (!level) return 'GREEN';
const upper = level.toString().toUpperCase();
if (['RED', 'ORANGE', 'GREEN'].includes(upper)) {
return upper;
}
return 'GREEN';
}
getSampleData() {
return [
{
id: 'gdacs_sample_1',
title: 'Flood Alert - Bangladesh (Brahmaputra River)',
type: 'Flood',
alertLevel: 'RED',
latitude: 25.2677,
longitude: 89.9376,
date: new Date().toISOString().split('T')[0],
description: 'Severe flooding along Brahmaputra River affecting multiple districts in northern Bangladesh.',
source: 'DFO',
magnitude: 8.5,
affectedRadius: 150,
affectedPopulation: 10000000,
impactDescription: '10.0M people affected, Intensity 8.5'
},
{
id: 'gdacs_sample_2',
title: 'Earthquake M6.2 - Turkey (Eastern Anatolia)',
type: 'Earthquake',
alertLevel: 'ORANGE',
latitude: 38.7312,
longitude: 35.4826,
date: new Date(Date.now() - 86400000).toISOString().split('T')[0],
description: 'Moderate earthquake in Eastern Anatolia region with potential for aftershocks.',
source: 'RSS',