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