| 1 | import { writeFileSync } from 'fs'; |
| 2 | import { join } |
| 3 | import { prisma } |
| 4 | import { FlightAwareService } |
| 5 | |
| 6 | import { HttpException, HttpStatus |
| 7 | import { ConfigService } |
| 8 | import { Prisma } |
| 9 | |
| 10 | import { GetAirlineDTO } |
| 11 | import { GetFlightsBoundsDTO } |
| 12 | import { GetFlightsDTO } |
| 13 | |
| 14 | @Injectable() |
| 15 | export class FlightsService |
| 16 | constructor( |
| 17 | private configService: |
| 18 | private flightAwareService: |
| 19 | ) {} |
| 20 | |
| 21 | async getAirline(body |
| 22 | const airline = |
| 23 | where: { |
| 24 | OR: [ |
| 25 | { |
| 26 | iata: { |
| 27 | equals: body.search |
| 28 | mode: 'insensitive', |
| 29 | }, |
| 30 | icao: { |
| 31 | equals: body.search |
| 32 | mode: 'insensitive', |
| 33 | }, |
| 34 | }, |
| 35 | ], |
| 36 | }, |
| 37 | }); |
| 38 | if (!airline) |
| 39 | throw new HttpException( |
| 40 | return airline; |
| 41 | } |
| 42 | |
| 43 | async getFlightsBetweenTwoAirports(query |
| 44 | const { from, |
| 45 | const apiKey = |
| 46 | 'AVIATION_STACK_API_KEY', |
| 47 | ); |
| 48 | |
| 49 | if (!apiKey) |
| 50 | throw new HttpException( |
| 51 | 'Internal Server Error', |
| 52 | HttpStatus.INTERNAL_SERVER_ERROR, |
| 53 | ); |
| 54 | } |
| 55 | |
| 56 | // Normalize date to start of day to ensure cache hits |
| 57 | const _date = |
| 58 | _date.setUTCHours(0, |
| 59 | |
| 60 | const dayEndDate = |
| 61 | dayEndDate.setDate(_date |
| 62 | |
| 63 | // First check in database |
| 64 | try { |
| 65 | const existingFlights = |
| 66 | where: { |
| 67 | AND: [ |
| 68 | { |
| 69 | arrival: { |
| 70 | path: ['iataCode'], |
| 71 | string_contains: to, |
| 72 | }, |
| 73 | departure: { |
| 74 | path: ['iataCode'], |
| 75 | string_contains: from, |
| 76 | }, |
| 77 | }, |
| 78 | { |
| 79 | date: { |
| 80 | gte: _date, |
| 81 | lt: dayEndDate, |
| 82 | }, |
| 83 | }, |
| 84 | ], |
| 85 | }, |
| 86 | orderBy: { |
| 87 | createdAt: 'desc', |
| 88 | }, |
| 89 | }); |
| 90 | if (existingFlights.length |
| 91 | console.log( |
| 92 | `Cache HIT: Found ${existingFlights.length} |
| 93 | ); |
| 94 | return { |
| 95 | success: true, |
| 96 | date, |
| 97 | route: { from, |
| 98 | flightCount: existingFlights.length, |
| 99 | flights: existingFlights, |
| 100 | }; |
| 101 | } |
| 102 | console.log( |
| 103 | `Cache MISS: No flights found for ${from} to ${ |
| 104 | ); |
| 105 | } catch (error) |
| 106 | console.error('Database query error: |
| 107 | } |
| 108 | |
| 109 | try { |
| 110 | const apiUrl = |
| 111 | apiUrl.searchParams.append |
| 112 | apiUrl.searchParams.append |
| 113 | apiUrl.searchParams.append |
| 114 | |
| 115 | const response = |
| 116 | |
| 117 | if (!response.ok |
| 118 | console.log(await |
| 119 | throw new Error( |
| 120 | } |
| 121 | |
| 122 | const flights = |
| 123 | |
| 124 | // Use upsert to prevent duplicate records |
| 125 | await Promise.all |
| 126 | flights.data.map |
| 127 | // Create a unique identifier for this flight |
| 128 | const uniqueId = |
| 129 | |
| 130 | return prisma.flights |
| 131 | where: { |
| 132 | id: uniqueId, |
| 133 | }, |
| 134 | update: { |
| 135 | airline: flight.airline |
| 136 | arrival: flight.arrival |
| 137 | codeshared: flight.codeshared |
| 138 | flight: flight.flight |
| 139 | departure: flight.departure |
| 140 | type: flight.type |
| 141 | status: flight.status |
| 142 | }, |
| 143 | create: { |
| 144 | id: uniqueId, |
| 145 | date: _date, |
| 146 | airline: flight.airline |
| 147 | arrival: flight.arrival |
| 148 | codeshared: flight.codeshared |
| 149 | flight: flight.flight |
| 150 | departure: flight.departure |
| 151 | type: flight.type |
| 152 | status: flight.status |
| 153 | }, |
| 154 | }); |
| 155 | }), |
| 156 | ); |
| 157 | |
| 158 | console.log( |
| 159 | `Cached ${flights.data |
| 160 | ); |
| 161 | |
| 162 | const routeFlights = |
| 163 | (flight) => |
| 164 | flight.departure?.iataCode |
| 165 | flight.arrival?.iataCode |
| 166 | ); |
| 167 | |
| 168 | return { |
| 169 | success: true, |
| 170 | date, |
| 171 | route: { from, |
| 172 | flightCount: routeFlights.length, |
| 173 | flights: routeFlights, |
| 174 | }; |
| 175 | } catch (error) |
| 176 | console.error('Error fetching flights: |
| 177 | throw new HttpException( |
| 178 | 'Failed to fetch flight data', |
| 179 | HttpStatus.INTERNAL_SERVER_ERROR, |
| 180 | ); |
| 181 | } |
| 182 | } |
| 183 | |
| 184 | async getFlightsInBounds(query |
| 185 | const { minLat, |
| 186 | return { |
| 187 | success: true, |
| 188 | timestamp: new Date |
| 189 | bounds: { |
| 190 | minLat, |
| 191 | maxLat, |
| 192 | minLng, |
| 193 | maxLng, |
| 194 | }, |
| 195 | totalAircraft: 0, |
| 196 | airborneAircraft: 0, |
| 197 | flights: [], |
| 198 | }; |
| 199 | // try { |
| 200 | // // Validate bounds |
| 201 | // if (minLat >= maxLat) { |
| 202 | // throw new HttpException( |
| 203 | // 'Minimum latitude must be less than maximum latitude', |
| 204 | // HttpStatus.BAD_REQUEST, |
| 205 | // ); |
| 206 | // } |
| 207 | |
| 208 | // if (minLng >= maxLng) { |
| 209 | // throw new HttpException( |
| 210 | // 'Minimum longitude must be less than maximum longitude', |
| 211 | // HttpStatus.BAD_REQUEST, |
| 212 | // ); |
| 213 | // } |
| 214 | |
| 215 | // // Check if bounds are too large (prevent world-wide queries) |
| 216 | // const latSpan = maxLat - minLat; |
| 217 | // const lngSpan = maxLng - minLng; |
| 218 | // const maxAllowedSpan = 30; // degrees |
| 219 | |
| 220 | // if (latSpan > maxAllowedSpan || lngSpan > maxAllowedSpan) { |
| 221 | // throw new HttpException( |
| 222 | // `Bounds too large. Maximum allowed span is ${maxAllowedSpan} degrees. Current span: lat=${latSpan.toFixed(2)}, lng=${lngSpan.toFixed(2)}`, |
| 223 | // HttpStatus.BAD_REQUEST, |
| 224 | // ); |
| 225 | // } |
| 226 | |
| 227 | // // Get flights from FlightAware |
| 228 | // const flightAwareData = await this.flightAwareService.getFlightsInBounds( |
| 229 | // minLat, |
| 230 | // maxLat, |
| 231 | // minLng, |
| 232 | // maxLng, |
| 233 | // ); |
| 234 | |
| 235 | // // Filter and transform the data to a more user-friendly format |
| 236 | // const flights = flightAwareData.flights |
| 237 | // .filter((flight) => { |
| 238 | // // Only include flights with position data and that are airborne |
| 239 | // return ( |
| 240 | // flight.last_position && |
| 241 | // flight.last_position.latitude && |
| 242 | // flight.last_position.longitude && |
| 243 | // flight.status !== 'Cancelled' && |
| 244 | // flight.status !== 'Landed' |
| 245 | // ); |
| 246 | // }) |
| 247 | // .map((flight) => ({ |
| 248 | // ident_icao: flight.ident_icao || flight.ident, |
| 249 | // ident_iata: flight.ident_iata, |
| 250 | // callsign: flight.ident, |
| 251 | |
| 252 | // // Position and movement data |
| 253 | // latitude: flight.last_position?.latitude, |
| 254 | // longitude: flight.last_position?.longitude, |
| 255 | // altitude: flight.last_position?.altitude, |
| 256 | // velocity: flight.last_position?.groundspeed, |
| 257 | // heading: flight.last_position?.heading, |
| 258 | // verticalRate: |
| 259 | // flight.last_position?.altitude_change === 'C' |
| 260 | // ? 1 |
| 261 | // : flight.last_position?.altitude_change === 'D' |
| 262 | // ? -1 |
| 263 | // : 0, |
| 264 | // lastContact: |
| 265 | // flight.last_position?.timestamp || new Date().toISOString(), |
| 266 | // isOnGround: |
| 267 | // flight.status === 'Landed' || flight.status === 'On Ground', |
| 268 | |
| 269 | // // Aircraft details |
| 270 | // aircraftType: flight.aircraft_type, |
| 271 | // aircraftTypeFaa: flight.aircraft_type_faa, |
| 272 | // aircraftFamily: flight.aircraft_family, |
| 273 | // manufacturer: flight.manufacturer, |
| 274 | // model: flight.model, |
| 275 | // engineType: flight.engine_type, |
| 276 | // engineCount: flight.engine_count, |
| 277 | // wakeTurbulenceCategory: flight.wake_turbulence_category, |
| 278 | |
| 279 | // // Flight plan and registration |
| 280 | // aircraftId: flight.flight_plan?.aircraft_id, |
| 281 | // aircraftRegistration: flight.flight_plan?.owner || 'Unknown', |
| 282 | // ownerIcao: flight.flight_plan?.owner_icao, |
| 283 | // ownerIata: flight.flight_plan?.owner_iata, |
| 284 | // ownerName: flight.flight_plan?.owner_name, |
| 285 | |
| 286 | // // Operator information |
| 287 | // operator: flight.operator?.name || flight.operator?.callsign, |
| 288 | // operatorIcao: flight.operator?.icao, |
| 289 | // operatorIata: flight.operator?.iata, |
| 290 | // operatorCountry: flight.operator?.country, |
| 291 | |
| 292 | // // Route information |
| 293 | // origin: { |
| 294 | // code: flight.origin?.code, |
| 295 | // codeIcao: flight.origin?.code_icao, |
| 296 | // codeIata: flight.origin?.code_iata, |
| 297 | // name: flight.origin?.name, |
| 298 | // city: flight.origin?.city, |
| 299 | // timezone: flight.origin?.timezone, |
| 300 | // }, |
| 301 | // destination: { |
| 302 | // code: flight.destination?.code, |
| 303 | // codeIcao: flight.destination?.code_icao, |
| 304 | // codeIata: flight.destination?.code_iata, |
| 305 | // name: flight.destination?.name, |
| 306 | // city: flight.destination?.city, |
| 307 | // timezone: flight.destination?.timezone, |
| 308 | // }, |
| 309 | |
| 310 | // // Flight status and timing |
| 311 | // status: flight.status, |
| 312 | // progressPercent: flight.progress_percent, |
| 313 | // routeDistance: flight.route_distance, |
| 314 | // filedAirspeedKts: flight.filed_airspeed_kts, |
| 315 | // filedAltitude: flight.filed_altitude, |
| 316 | |
| 317 | // // Schedule information |
| 318 | // scheduledOff: flight.scheduled_off, |
| 319 | // scheduledOn: flight.scheduled_on, |
| 320 | // estimatedOff: flight.estimated_off, |
| 321 | // estimatedOn: flight.estimated_on, |
| 322 | // actualOff: flight.actual_off, |
| 323 | // actualOn: flight.actual_on, |
| 324 | |
| 325 | // // Delays |
| 326 | // departureDelay: flight.departure_delay, |
| 327 | // arrivalDelay: flight.arrival_delay, |
| 328 | |
| 329 | // // Airport details |
| 330 | // gateOrigin: flight.gate_origin, |
| 331 | // gateDestination: flight.gate_destination, |
| 332 | // terminalOrigin: flight.terminal_origin, |
| 333 | // terminalDestination: flight.terminal_destination, |
| 334 | |
| 335 | // // Additional metadata |
| 336 | // route: flight.route, |
| 337 | // type: flight.type, |
| 338 | // })); |
| 339 | |
| 340 | // return { |
| 341 | // success: true, |
| 342 | // timestamp: new Date().toISOString(), |
| 343 | // bounds: { |
| 344 | // minLat, |
| 345 | // maxLat, |
| 346 | // minLng, |
| 347 | // maxLng, |
| 348 | // }, |
| 349 | // totalAircraft: flightAwareData.flights.length, |
| 350 | // airborneAircraft: flights.length, |
| 351 | // flights, |
| 352 | // }; |
| 353 | // } catch (error) { |
| 354 | // console.error('Error fetching flights in bounds:', error); |
| 355 | // if (error instanceof HttpException) { |
| 356 | // throw error; |
| 357 | // } |
| 358 | // throw new HttpException( |
| 359 | // 'Failed to fetch flight data for the specified region', |
| 360 | // HttpStatus.INTERNAL_SERVER_ERROR, |
| 361 | // ); |
| 362 | // } |
| 363 | } |
| 364 | |
| 365 | async getTrackedFlights(userId |
| 366 | try { |
| 367 | // Fetch all flights from the database, ordered by most recently created. |
| 368 | // Only include flights that have at least one identifier (iata or icao) |
| 369 | // defined for BOTH the departure and arrival airports. |
| 370 | const flights = |
| 371 | where: { |
| 372 | userId, |
| 373 | AND: [ |
| 374 | { |
| 375 | OR: [ |
| 376 | { departure: { path: |
| 377 | { departure: { path: |
| 378 | ], |
| 379 | }, |
| 380 | { |
| 381 | OR: [ |
| 382 | { arrival: { path: |
| 383 | { arrival: { path: |
| 384 | ], |
| 385 | }, |
| 386 | ], |
| 387 | }, |
| 388 | orderBy: { |
| 389 | createdAt: 'desc', |
| 390 | }, |
| 391 | include: { |
| 392 | greatCircleDistance: true, |
| 393 | flightAwareData: { |
| 394 | omit: { |
| 395 | faFlightId: true, |
| 396 | }, |
| 397 | }, |
| 398 | }, |
| 399 | }); |
| 400 | |
| 401 | // Collect all unique airport codes to query |
| 402 | const airportCodes = |
| 403 | // Collect all unique airline codes to query |
| 404 | const airlineIataCodes = |
| 405 | const airlineIcaoCodes = |
| 406 | flights.forEach((flight |
| 407 | const departure = |
| 408 | const arrival = |
| 409 | const airline = |
| 410 | |
| 411 | if (departure?.airport |
| 412 | if (departure?.airport |
| 413 | if (arrival?.airport |
| 414 | if (arrival?.airport |
| 415 | |
| 416 | if (airline?.iata |
| 417 | if (airline?.icao |
| 418 | }); |
| 419 | |
| 420 | // Parallelize airport and airline queries using Promise.allSettled |
| 421 | // This allows both queries to run simultaneously and handles failures gracefully |
| 422 | const airportCodesArray = |
| 423 | const airlineIataCodesArray = |
| 424 | const airlineIcaoCodesArray = |
| 425 | |
| 426 | const [airportsResult, |
| 427 | // Query airport table for all relevant airports |
| 428 | airportCodesArray.length > 0 |
| 429 | ? prisma.airport. |
| 430 | where: { |
| 431 | OR: [ |
| 432 | { iataCode: { in: |
| 433 | { ident: { in: |
| 434 | ], |
| 435 | }, |
| 436 | }) |
| 437 | : Promise.resolve([]) |
| 438 | // Query airline table for all relevant airlines |
| 439 | airlineIataCodesArray.length > 0 |
| 440 | ? prisma.airline. |
| 441 | where: { |
| 442 | OR: [ |
| 443 | { iata: { in: |
| 444 | { icao: { in: |
| 445 | ], |
| 446 | }, |
| 447 | select: { |
| 448 | iata: true, |
| 449 | icao: true, |
| 450 | image: true, |
| 451 | }, |
| 452 | }) |
| 453 | : Promise.resolve([]) |
| 454 | ]); |
| 455 | |
| 456 | // Extract results, defaulting to empty arrays if queries failed |
| 457 | const airports = |
| 458 | airportsResult.status === |
| 459 | const airlines = |
| 460 | airlinesResult.status === |
| 461 | |
| 462 | // Log errors if any occurred (but continue processing) |
| 463 | if (airportsResult.status |
| 464 | console.error('Error fetching airports: |
| 465 | } |
| 466 | if (airlinesResult.status |
| 467 | console.error('Error fetching airlines: |
| 468 | } |
| 469 | |
| 470 | // Create a map for quick airport lookup by code |
| 471 | const airportMap = |
| 472 | airports.forEach((airport |
| 473 | if (airport.iataCode |
| 474 | if (airport.ident |
| 475 | }); |
| 476 | |
| 477 | // Create maps for quick airline lookup by code |
| 478 | const airlineByIata = |
| 479 | const airlineByIcao = |
| 480 | airlines.forEach((airline |
| 481 | if (airline.iata |
| 482 | if (airline.icao |
| 483 | }); |
| 484 | |
| 485 | // Transform the flights to match the expected response format |
| 486 | const transformedFlights = |
| 487 | const flightData = |
| 488 | |
| 489 | // Handle aircraft data |
| 490 | const stored = |
| 491 | const aircraft = |
| 492 | ? { |
| 493 | modeS: stored.modeS |
| 494 | age: (stored.ageYears |
| 495 | image: stored.image |
| 496 | attribution: |
| 497 | stored.attribution ?? |
| 498 | isFreighter: stored.isFreighter |
| 499 | model: stored.typeName |
| 500 | registration: |
| 501 | stored.reg ?? |
| 502 | aircraft_id: stored.aircraft_id |
| 503 | payload: stored.payload |
| 504 | deliveryDate: stored.deliveryDate |
| 505 | ? new Date( |
| 506 | : undefined, |
| 507 | firstFlightDate: stored.firstFlightDate |
| 508 | ? new Date( |
| 509 | : undefined, |
| 510 | } |
| 511 | : undefined; |
| 512 | |
| 513 | // Fill in missing airport location data |
| 514 | const departure = |
| 515 | const arrival = |
| 516 | const airlineData = |
| 517 | |
| 518 | if (departure?.airport |
| 519 | const depAirport = |
| 520 | airportMap.get(departure |
| 521 | airportMap.get(departure |
| 522 | |
| 523 | if (depAirport) { |
| 524 | departure.airport.location |
| 525 | if ( |
| 526 | !departure.airport.location |
| 527 | departure.airport.location |
| 528 | ) { |
| 529 | departure.airport.location |
| 530 | } |
| 531 | if ( |
| 532 | !departure.airport.location |
| 533 | departure.airport.location |
| 534 | ) { |
| 535 | departure.airport.location |
| 536 | } |
| 537 | if ( |
| 538 | !departure.airport.name |
| 539 | departure.airport.name |
| 540 | ) { |
| 541 | departure.airport.name |
| 542 | } |
| 543 | if ( |
| 544 | !departure.airport.municipalityName |
| 545 | departure.airport.municipalityName |
| 546 | ) { |
| 547 | departure.airport.municipalityName |
| 548 | depAirport.municipality || |
| 549 | } |
| 550 | } |
| 551 | } |
| 552 | |
| 553 | if (arrival?.airport |
| 554 | const arrAirport = |
| 555 | airportMap.get(arrival |
| 556 | airportMap.get(arrival |
| 557 | |
| 558 | if (arrAirport) { |
| 559 | arrival.airport.location |
| 560 | if ( |
| 561 | !arrival.airport.location |
| 562 | arrival.airport.location |
| 563 | ) { |
| 564 | arrival.airport.location |
| 565 | } |
| 566 | if ( |
| 567 | !arrival.airport.location |
| 568 | arrival.airport.location |
| 569 | ) { |
| 570 | arrival.airport.location |
| 571 | } |
| 572 | if (!arrival.airport |
| 573 | arrival.airport.name |
| 574 | } |
| 575 | if ( |
| 576 | !arrival.airport.municipalityName |
| 577 | arrival.airport.municipalityName |
| 578 | ) { |
| 579 | arrival.airport.municipalityName |
| 580 | arrAirport.municipality || |
| 581 | } |
| 582 | } |
| 583 | } |
| 584 | |
| 585 | // Enrich airline with image from airline table when available |
| 586 | if (airlineData) { |
| 587 | const matchedAirline = |
| 588 | (airlineData.iata && |
| 589 | (airlineData.icao && |
| 590 | if (matchedAirline?.image |
| 591 | airlineData.image = |
| 592 | } |
| 593 | } |
| 594 | |
| 595 | return { |
| 596 | ...flight, |
| 597 | aircraft, |
| 598 | departure, |
| 599 | arrival, |
| 600 | airline: airlineData, |
| 601 | }; |
| 602 | }); |
| 603 | |
| 604 | return { |
| 605 | success: true, |
| 606 | total: transformedFlights.length, |
| 607 | flights: transformedFlights, |
| 608 | }; |
| 609 | } catch (error) |
| 610 | console.error('Error fetching tracked flights: |
| 611 | throw new HttpException( |
| 612 | 'Failed to fetch tracked flights', |
| 613 | HttpStatus.INTERNAL_SERVER_ERROR, |
| 614 | ); |
| 615 | } |
| 616 | } |
| 617 | } |