-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver-enhanced.js
More file actions
371 lines (321 loc) · 15.4 KB
/
Copy pathserver-enhanced.js
File metadata and controls
371 lines (321 loc) · 15.4 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
const express = require('express');
const axios = require('axios');
const PDFDocument = require('pdfkit');
const cors = require('cors');
const path = require('path');
const fs = require('fs');
const fetch = require('node-fetch');
const app = express();
const PORT = 3000;
app.use(cors());
app.use(express.json({ limit: '50mb' }));
app.use(express.static('public'));
// =====================================================
// AIRPORTS DATABASE WITH CACHING
// =====================================================
let airportsCache = null;
let airportsCacheTime = null;
const CACHE_DURATION = 3600000; // 1 hour
async function loadAirportsDatabase() {
if (airportsCache && airportsCacheTime && (Date.now() - airportsCacheTime < CACHE_DURATION)) {
return airportsCache;
}
try {
console.log('Loading worldwide airports database...');
const response = await fetch('https://davidmegginson.github.io/ourairports-data/airports.csv');
const csvText = await response.text();
const airports = [];
const lines = csvText.split('\n');
for (let i = 1; i < lines.length; i++) {
const line = lines[i];
if (!line.trim()) continue;
const parts = line.match(/(".*?"|[^",]+)(?=\s*,|\s*$)/g);
if (!parts || parts.length < 10) continue;
const clean = (str) => str ? str.replace(/^"|"$/g, '').trim() : '';
const type = clean(parts[2]);
if (type === 'large_airport' || type === 'medium_airport' || type === 'small_airport') {
const icao = clean(parts[1]) || clean(parts[12]);
if (icao && icao.length >= 3) {
airports.push({
icao: icao,
iata: clean(parts[13]),
name: clean(parts[3]),
city: clean(parts[10]),
country: clean(parts[8]),
lat: parseFloat(clean(parts[4])) || 0,
lon: parseFloat(clean(parts[5])) || 0,
elevation: parseInt(clean(parts[6])) || 0,
type: type
});
}
}
}
airportsCache = airports;
airportsCacheTime = Date.now();
console.log(`✓ Loaded ${airports.length} airports into database`);
return airports;
} catch (error) {
console.error('Failed to load airports database:', error);
return getBuiltInAirports();
}
}
function getBuiltInAirports() {
return [
{ icao: 'KJFK', iata: 'JFK', name: 'John F Kennedy Intl', city: 'New York', country: 'US', lat: 40.6398, lon: -73.7789, elevation: 13, type: 'large_airport' },
{ icao: 'EGLL', iata: 'LHR', name: 'London Heathrow', city: 'London', country: 'GB', lat: 51.4706, lon: -0.4619, elevation: 83, type: 'large_airport' },
{ icao: 'LFPG', iata: 'CDG', name: 'Paris Charles de Gaulle', city: 'Paris', country: 'FR', lat: 49.0097, lon: 2.5479, elevation: 392, type: 'large_airport' },
{ icao: 'EDDF', iata: 'FRA', name: 'Frankfurt am Main', city: 'Frankfurt', country: 'DE', lat: 50.0333, lon: 8.5706, elevation: 364, type: 'large_airport' },
{ icao: 'LTFM', iata: 'IST', name: 'Istanbul Airport', city: 'Istanbul', country: 'TR', lat: 41.2619, lon: 28.7414, elevation: 325, type: 'large_airport' },
{ icao: 'LTBA', iata: 'ISL', name: 'Istanbul Ataturk', city: 'Istanbul', country: 'TR', lat: 40.9769, lon: 28.8146, elevation: 163, type: 'large_airport' },
{ icao: 'OMDB', iata: 'DXB', name: 'Dubai Intl', city: 'Dubai', country: 'AE', lat: 25.2528, lon: 55.3644, elevation: 62, type: 'large_airport' },
{ icao: 'KLAX', iata: 'LAX', name: 'Los Angeles Intl', city: 'Los Angeles', country: 'US', lat: 33.9425, lon: -118.408, elevation: 125, type: 'large_airport' }
];
}
// =====================================================
// API ENDPOINTS
// =====================================================
// Search airports
app.get('/api/airports/search', async (req, res) => {
try {
const query = req.query.q?.toUpperCase() || '';
if (query.length < 2) {
return res.json([]);
}
const airports = await loadAirportsDatabase();
const results = airports
.filter(apt => {
const searchStr = `${apt.icao} ${apt.iata} ${apt.name} ${apt.city}`.toUpperCase();
return searchStr.includes(query);
})
.slice(0, 100)
.map(apt => ({
...apt,
label: `${apt.icao}${apt.iata ? ' / ' + apt.iata : ''} - ${apt.name}`,
sublabel: `${apt.city}, ${apt.country}`
}));
res.json(results);
} catch (error) {
console.error('Airport search error:', error);
res.status(500).json({ error: 'Search failed' });
}
});
// Get airport details
app.get('/api/airports/:icao', async (req, res) => {
try {
const icao = req.params.icao.toUpperCase();
const airports = await loadAirportsDatabase();
const airport = airports.find(apt => apt.icao === icao);
if (airport) {
res.json(airport);
} else {
res.status(404).json({ error: 'Airport not found' });
}
} catch (error) {
res.status(500).json({ error: 'Failed to fetch airport' });
}
});
// Weather - METAR
app.get('/api/weather/metar/:icao', async (req, res) => {
try {
const icao = req.params.icao.toUpperCase();
const response = await axios.get(`https://aviationweather.gov/api/data/metar?ids=${icao}&format=json`, { timeout: 5000 });
res.json(response.data);
} catch (error) {
res.json([{ rawOb: `No METAR available for ${req.params.icao}` }]);
}
});
// Weather - TAF
app.get('/api/weather/taf/:icao', async (req, res) => {
try {
const icao = req.params.icao.toUpperCase();
const response = await axios.get(`https://aviationweather.gov/api/data/taf?ids=${icao}&format=json`, { timeout: 5000 });
res.json(response.data);
} catch (error) {
res.json([]);
}
});
// Calculate route
app.post('/api/route/calculate', async (req, res) => {
try {
const { departure, arrival, cruiseAltitude, cruiseSpeed, aircraft } = req.body;
const airports = await loadAirportsDatabase();
const depAirport = airports.find(a => a.icao === departure);
const arrAirport = airports.find(a => a.icao === arrival);
if (!depAirport || !arrAirport) {
return res.status(400).json({ error: 'Airport not found' });
}
const distance = calculateGreatCircleDistance(
depAirport.lat, depAirport.lon,
arrAirport.lat, arrAirport.lon
);
const heading = calculateBearing(
depAirport.lat, depAirport.lon,
arrAirport.lat, arrAirport.lon
);
const waypoints = generateWaypoints(
depAirport.lat, depAirport.lon,
arrAirport.lat, arrAirport.lon,
Math.min(Math.floor(distance / 200), 10)
);
const flightTime = (distance / cruiseSpeed) * 60;
const fuelRequired = calculateFuel(aircraft, distance, cruiseAltitude);
res.json({
departure: depAirport,
arrival: arrAirport,
distance,
heading,
cruiseAltitude,
cruiseSpeed,
aircraft,
flightTime,
fuelRequired,
waypoints
});
} catch (error) {
console.error('Route calculation error:', error);
res.status(500).json({ error: 'Calculation failed' });
}
});
// Export formats
app.post('/api/export/pmdg', (req, res) => {
const { flightPlan } = req.body;
let content = `${flightPlan.departure.icao} ${flightPlan.waypoints.map(w => w.name).join(' ')} ${flightPlan.arrival.icao}\n`;
content += `FL${Math.floor(flightPlan.cruiseAltitude / 100)} ${flightPlan.aircraft.icao}\n`;
res.setHeader('Content-Type', 'text/plain');
res.setHeader('Content-Disposition', `attachment; filename=${flightPlan.departure.icao}${flightPlan.arrival.icao}.rte`);
res.send(content);
});
app.post('/api/export/msfs', (req, res) => {
const { flightPlan } = req.body;
let xml = `<?xml version="1.0"?>\n<SimBase.Document Type="AceXML" version="1,0">\n<FlightPlan.FlightPlan>\n`;
xml += `<Title>${flightPlan.departure.icao} to ${flightPlan.arrival.icao}</Title>\n`;
xml += `<FPType>IFR</FPType>\n`;
xml += `<CruisingAlt>${flightPlan.cruiseAltitude}</CruisingAlt>\n`;
xml += `<DepartureID>${flightPlan.departure.icao}</DepartureID>\n`;
xml += `<DestinationID>${flightPlan.arrival.icao}</DestinationID>\n`;
xml += `</FlightPlan.FlightPlan>\n</SimBase.Document>`;
res.setHeader('Content-Type', 'application/xml');
res.setHeader('Content-Disposition', `attachment; filename=${flightPlan.departure.icao}${flightPlan.arrival.icao}.pln`);
res.send(xml);
});
app.post('/api/export/xplane', (req, res) => {
const { flightPlan } = req.body;
let content = `I\n1100 Version\nCYCLE 2401\n`;
content += `ADEP ${flightPlan.departure.icao}\nADES ${flightPlan.arrival.icao}\n`;
content += `NUMENR ${flightPlan.waypoints.length + 2}\n`;
content += `1 ${flightPlan.departure.icao} 0 ${flightPlan.departure.lat} ${flightPlan.departure.lon}\n`;
flightPlan.waypoints.forEach(wp => {
content += `11 ${wp.name} 0 ${wp.lat} ${wp.lon}\n`;
});
content += `1 ${flightPlan.arrival.icao} 0 ${flightPlan.arrival.lat} ${flightPlan.arrival.lon}\n`;
res.setHeader('Content-Type', 'text/plain');
res.setHeader('Content-Disposition', `attachment; filename=${flightPlan.departure.icao}${flightPlan.arrival.icao}.fms`);
res.send(content);
});
// PDF Export - Enhanced
app.post('/api/export/pdf', async (req, res) => {
const { flightPlan } = req.body;
const doc = new PDFDocument({ margin: 50 });
res.setHeader('Content-Type', 'application/pdf');
res.setHeader('Content-Disposition', `attachment; filename=OFP-${flightPlan.departure.icao}${flightPlan.arrival.icao}.pdf`);
doc.pipe(res);
// Header
doc.fontSize(20).font('Helvetica-Bold').text('OPERATIONAL FLIGHT PLAN', { align: 'center' });
doc.fontSize(10).font('Helvetica').text(`Flight Planner Pro - ${new Date().toUTCString()}`, { align: 'center' });
doc.moveDown(2);
// Flight Info
doc.fontSize(14).font('Helvetica-Bold').text('FLIGHT INFORMATION');
doc.fontSize(10).font('Helvetica');
doc.text(`From: ${flightPlan.departure.icao} - ${flightPlan.departure.name}`);
doc.text(`To: ${flightPlan.arrival.icao} - ${flightPlan.arrival.name}`);
doc.text(`Aircraft: ${flightPlan.aircraft.name} (${flightPlan.aircraft.icao})`);
doc.text(`Distance: ${Math.round(flightPlan.distance)} NM`);
doc.text(`Cruise: FL${Math.floor(flightPlan.cruiseAltitude / 100)} / ${flightPlan.cruiseSpeed} kts`);
doc.text(`ETE: ${Math.floor(flightPlan.flightTime / 60)}:${String(Math.round(flightPlan.flightTime % 60)).padStart(2, '0')}`);
doc.text(`Fuel: ${Math.round(flightPlan.fuelRequired)} lbs`);
doc.moveDown();
// Weather
if (flightPlan.weather) {
doc.fontSize(14).font('Helvetica-Bold').text('WEATHER');
doc.fontSize(9).font('Courier');
if (flightPlan.weather.departure && flightPlan.weather.departure[0]) {
doc.text(`DEP: ${flightPlan.weather.departure[0].rawOb || 'N/A'}`);
}
if (flightPlan.weather.arrival && flightPlan.weather.arrival[0]) {
doc.text(`ARR: ${flightPlan.weather.arrival[0].rawOb || 'N/A'}`);
}
doc.moveDown();
}
// Route
doc.fontSize(14).font('Helvetica-Bold').text('ROUTE');
doc.fontSize(10).font('Helvetica');
const route = [flightPlan.departure.icao, ...flightPlan.waypoints.map(w => w.name), flightPlan.arrival.icao].join(' ');
doc.text(route);
doc.end();
});
// Aircraft database
app.get('/api/aircraft', (req, res) => {
res.json(getAircraftDatabase());
});
// =====================================================
// HELPER FUNCTIONS
// =====================================================
function calculateGreatCircleDistance(lat1, lon1, lat2, lon2) {
const R = 3440.065;
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;
}
function calculateBearing(lat1, lon1, lat2, lon2) {
const dLon = (lon2 - lon1) * Math.PI / 180;
const y = Math.sin(dLon) * Math.cos(lat2 * Math.PI / 180);
const x = Math.cos(lat1 * Math.PI / 180) * Math.sin(lat2 * Math.PI / 180) -
Math.sin(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) * Math.cos(dLon);
return (Math.atan2(y, x) * 180 / Math.PI + 360) % 360;
}
function generateWaypoints(lat1, lon1, lat2, lon2, count) {
const waypoints = [];
for (let i = 1; i <= count; i++) {
const f = i / (count + 1);
waypoints.push({
name: `WP${String(i).padStart(2, '0')}`,
lat: lat1 + (lat2 - lat1) * f,
lon: lon1 + (lon2 - lon1) * f
});
}
return waypoints;
}
function calculateFuel(aircraft, distance, altitude) {
const hours = distance / (aircraft.cruiseSpeed || 450);
return (aircraft.fuelBurn || 5000) * hours * 1.15;
}
function getAircraftDatabase() {
return {
boeing: [
{ icao: 'B738', name: 'Boeing 737-800', cruiseSpeed: 450, fuelBurn: 5000, maxAltitude: 41000, simulator: ['MSFS2020', 'X-Plane 12', 'Prepar3D', 'FSX', 'PMDG'] },
{ icao: 'B789', name: 'Boeing 787-9 Dreamliner', cruiseSpeed: 490, fuelBurn: 8500, maxAltitude: 43000, simulator: ['MSFS2020', 'X-Plane 12', 'PMDG'] },
{ icao: 'B77W', name: 'Boeing 777-300ER', cruiseSpeed: 490, fuelBurn: 10000, maxAltitude: 43000, simulator: ['MSFS2020', 'X-Plane 12', 'PMDG'] },
],
airbus: [
{ icao: 'A20N', name: 'Airbus A320neo', cruiseSpeed: 450, fuelBurn: 4300, maxAltitude: 39800, simulator: ['MSFS2020', 'X-Plane 12', 'FlyByWire'] },
{ icao: 'A359', name: 'Airbus A350-900', cruiseSpeed: 490, fuelBurn: 8500, maxAltitude: 43000, simulator: ['MSFS2020', 'X-Plane 12'] },
{ icao: 'A388', name: 'Airbus A380-800', cruiseSpeed: 490, fuelBurn: 14000, maxAltitude: 43000, simulator: ['MSFS2020', 'X-Plane 12'] },
]
};
}
// Start server
app.listen(PORT, () => {
console.log(`\n╔════════════════════════════════════════════════╗`);
console.log(`║ Flight Planner Pro - Dispatch Office v2.0 ║`);
console.log(`╚════════════════════════════════════════════════╝`);
console.log(`\n🌐 Server: http://localhost:${PORT}`);
console.log(`📊 Status: ONLINE`);
console.log(`\nInitializing airports database...`);
loadAirportsDatabase().then(() => {
console.log(`✓ Ready for flight planning!\n`);
});
});