mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-22 21:11:14 +00:00
feat(flight-live): follow booked flights live from keyless ADS-B feeds
A new flight-live domain polls the open feeds adsb.lol and adsb.fi (no key, no cost; adsb.fi only on self-hosted installs, its terms are non-commercial) for every booked flight leg in its watch window, derives phase, take-off, landing, delay and an arrival estimate, and pushes changes as flight:live. GET /api/trips/:tripId/flights/live, the MCP tool get_trip_flight_status, notifications for take-off, landing and delays, and the admin switch flight_live_enabled (FLIGHT_LIVE_ENABLED wins) come with it.
This commit is contained in:
@@ -0,0 +1,65 @@
|
||||
import { EntityRepositoryType, type Opt, PrimaryKeyProp, defineEntity, p } from '@mikro-orm/core';
|
||||
import { FlightLiveStatesRepository } from '../repositories/FlightLiveStates.repository';
|
||||
import { DbTimestampType } from '../types';
|
||||
|
||||
export class FlightLiveStates {
|
||||
[EntityRepositoryType]?: FlightLiveStatesRepository;
|
||||
[PrimaryKeyProp]?: ['callsign', 'service_date', 'origin', 'destination'];
|
||||
callsign!: string;
|
||||
service_date!: string;
|
||||
origin!: string;
|
||||
destination!: string;
|
||||
phase: string & Opt = 'scheduled';
|
||||
departed_at?: string | null;
|
||||
landed_at?: string | null;
|
||||
lat?: number | null;
|
||||
lng?: number | null;
|
||||
altitude_ft?: number | null;
|
||||
ground_speed_kt?: number | null;
|
||||
track_deg?: number | null;
|
||||
vertical_rate_fpm?: number | null;
|
||||
on_ground?: number | null;
|
||||
registration?: string | null;
|
||||
aircraft_type?: string | null;
|
||||
source?: string | null;
|
||||
first_seen_at?: string | null;
|
||||
last_seen_at?: string | null;
|
||||
fetched_at?: string | null;
|
||||
next_poll_at?: string | null;
|
||||
fail_count: number & Opt = 0;
|
||||
departed_notified: number & Opt = 0;
|
||||
landed_notified: number & Opt = 0;
|
||||
delay_notified: number & Opt = 0;
|
||||
}
|
||||
|
||||
export const FlightLiveStatesSchema = defineEntity({
|
||||
class: FlightLiveStates,
|
||||
repository: () => FlightLiveStatesRepository,
|
||||
properties: {
|
||||
callsign: p.text().primary(),
|
||||
service_date: p.text().primary(),
|
||||
origin: p.text().primary(),
|
||||
destination: p.text().primary(),
|
||||
phase: p.text().default('scheduled'),
|
||||
departed_at: p.type(DbTimestampType).nullable(),
|
||||
landed_at: p.type(DbTimestampType).nullable(),
|
||||
lat: p.double().nullable(),
|
||||
lng: p.double().nullable(),
|
||||
altitude_ft: p.double().nullable(),
|
||||
ground_speed_kt: p.double().nullable(),
|
||||
track_deg: p.double().nullable(),
|
||||
vertical_rate_fpm: p.double().nullable(),
|
||||
on_ground: p.integer().nullable(),
|
||||
registration: p.text().nullable(),
|
||||
aircraft_type: p.text().nullable(),
|
||||
source: p.text().nullable(),
|
||||
first_seen_at: p.type(DbTimestampType).nullable(),
|
||||
last_seen_at: p.type(DbTimestampType).nullable(),
|
||||
fetched_at: p.type(DbTimestampType).nullable(),
|
||||
next_poll_at: p.type(DbTimestampType).nullable(),
|
||||
fail_count: p.integer().default(0),
|
||||
departed_notified: p.integer().default(0),
|
||||
landed_notified: p.integer().default(0),
|
||||
delay_notified: p.integer().default(0),
|
||||
},
|
||||
});
|
||||
@@ -40,6 +40,7 @@ import { DocumentProvidersSchema } from './DocumentProviders.entity';
|
||||
import { DocumentSyncItemsSchema } from './DocumentSyncItems.entity';
|
||||
import { FerrataTilesSchema } from './FerrataTiles.entity';
|
||||
import { FileLinksSchema } from './FileLinks.entity';
|
||||
import { FlightLiveStatesSchema } from './FlightLiveStates.entity';
|
||||
import { GoogleApiUsageSchema } from './GoogleApiUsage.entity';
|
||||
import { GooglePlacePhotoMetaSchema } from './GooglePlacePhotoMeta.entity';
|
||||
import { HiddenCountriesSchema } from './HiddenCountries.entity';
|
||||
@@ -209,6 +210,7 @@ export const ALL_ENTITIES: readonly EntitySchema[] = [
|
||||
DocumentSyncItemsSchema,
|
||||
FerrataTilesSchema,
|
||||
FileLinksSchema,
|
||||
FlightLiveStatesSchema,
|
||||
GoogleApiUsageSchema,
|
||||
GooglePlacePhotoMetaSchema,
|
||||
HiddenCountriesSchema,
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
// Generated by scripts/generate-db-types.ts from the migrated schema. Do not edit by hand:
|
||||
// change the migration, then run `npm run gen:db-types`.
|
||||
import type { InsertOptional } from './columns';
|
||||
|
||||
export interface FlightLiveStatesTable {
|
||||
callsign: string;
|
||||
service_date: string;
|
||||
origin: string;
|
||||
destination: string;
|
||||
phase: InsertOptional<string>;
|
||||
departed_at: InsertOptional<string | null>;
|
||||
landed_at: InsertOptional<string | null>;
|
||||
lat: InsertOptional<number | null>;
|
||||
lng: InsertOptional<number | null>;
|
||||
altitude_ft: InsertOptional<number | null>;
|
||||
ground_speed_kt: InsertOptional<number | null>;
|
||||
track_deg: InsertOptional<number | null>;
|
||||
vertical_rate_fpm: InsertOptional<number | null>;
|
||||
on_ground: InsertOptional<number | null>;
|
||||
registration: InsertOptional<string | null>;
|
||||
aircraft_type: InsertOptional<string | null>;
|
||||
source: InsertOptional<string | null>;
|
||||
first_seen_at: InsertOptional<string | null>;
|
||||
last_seen_at: InsertOptional<string | null>;
|
||||
fetched_at: InsertOptional<string | null>;
|
||||
next_poll_at: InsertOptional<string | null>;
|
||||
fail_count: InsertOptional<number>;
|
||||
departed_notified: InsertOptional<number>;
|
||||
landed_notified: InsertOptional<number>;
|
||||
delay_notified: InsertOptional<number>;
|
||||
}
|
||||
@@ -43,6 +43,7 @@ import type { DocumentProvidersTable } from './DocumentProviders.table';
|
||||
import type { DocumentSyncItemsTable } from './DocumentSyncItems.table';
|
||||
import type { FerrataTilesTable } from './FerrataTiles.table';
|
||||
import type { FileLinksTable } from './FileLinks.table';
|
||||
import type { FlightLiveStatesTable } from './FlightLiveStates.table';
|
||||
import type { GoogleApiUsageTable } from './GoogleApiUsage.table';
|
||||
import type { GooglePlacePhotoMetaTable } from './GooglePlacePhotoMeta.table';
|
||||
import type { HiddenCountriesTable } from './HiddenCountries.table';
|
||||
@@ -218,6 +219,7 @@ export interface DB {
|
||||
document_sync_items: DocumentSyncItemsTable;
|
||||
ferrata_tiles: FerrataTilesTable;
|
||||
file_links: FileLinksTable;
|
||||
flight_live_states: FlightLiveStatesTable;
|
||||
google_api_usage: GoogleApiUsageTable;
|
||||
google_place_photo_meta: GooglePlacePhotoMetaTable;
|
||||
hidden_countries: HiddenCountriesTable;
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import { Migration } from '@mikro-orm/migrations';
|
||||
|
||||
/**
|
||||
* Live flight status: what the open ADS-B feeds last said about one flight on
|
||||
* one day, keyed by the callsign it transmits, its local departure date and
|
||||
* its two airports. A through flight keeps one flight number over two sectors
|
||||
* (FRA to BOM to SIN as LH 754 on one day), and each sector has a state of its own.
|
||||
* One row serves every trip that booked the same flight, so the feeds are asked
|
||||
* once per flight, not once per traveller. Next to the derived state sit the
|
||||
* poll's bookkeeping (when to ask next, how often it failed) and whether each
|
||||
* notification already went out, so a departure is announced once.
|
||||
*
|
||||
* No foreign key: the row describes a flight in the air, not a booking, and is
|
||||
* found again from the bookings by its key.
|
||||
*/
|
||||
export class Migration20200101046400_a_booked_flight_shows_where_it_is extends Migration {
|
||||
override name = 'Migration20200101046400_a_booked_flight_shows_where_it_is';
|
||||
|
||||
override up(): void {
|
||||
this.addSql(`
|
||||
CREATE TABLE IF NOT EXISTS flight_live_states (
|
||||
callsign TEXT NOT NULL,
|
||||
service_date TEXT NOT NULL,
|
||||
origin TEXT NOT NULL,
|
||||
destination TEXT NOT NULL,
|
||||
phase TEXT NOT NULL DEFAULT 'scheduled',
|
||||
departed_at DATETIME,
|
||||
landed_at DATETIME,
|
||||
lat REAL,
|
||||
lng REAL,
|
||||
altitude_ft REAL,
|
||||
ground_speed_kt REAL,
|
||||
track_deg REAL,
|
||||
vertical_rate_fpm REAL,
|
||||
on_ground INTEGER,
|
||||
registration TEXT,
|
||||
aircraft_type TEXT,
|
||||
source TEXT,
|
||||
first_seen_at DATETIME,
|
||||
last_seen_at DATETIME,
|
||||
fetched_at DATETIME,
|
||||
next_poll_at DATETIME,
|
||||
fail_count INTEGER NOT NULL DEFAULT 0,
|
||||
departed_notified INTEGER NOT NULL DEFAULT 0,
|
||||
landed_notified INTEGER NOT NULL DEFAULT 0,
|
||||
delay_notified INTEGER NOT NULL DEFAULT 0,
|
||||
PRIMARY KEY (callsign, service_date, origin, destination)
|
||||
)
|
||||
`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
import type { FlightLiveStates } from '../entities/FlightLiveStates.entity';
|
||||
import type { DB } from '../kysely/db';
|
||||
import type { DbTimestamp } from '../types';
|
||||
import { TrekRepository } from './_shared/trek-repository';
|
||||
|
||||
/** A flight booking as the live flight status reads it; the metadata is the stored text. */
|
||||
export interface FlightBookingDbRow {
|
||||
id: number;
|
||||
trip_id: number;
|
||||
trip_title: string;
|
||||
metadata: string | null;
|
||||
day_id: number | null;
|
||||
end_day_id: number | null;
|
||||
reservation_time: string | null;
|
||||
reservation_end_time: string | null;
|
||||
}
|
||||
|
||||
interface FlightEndpointDbRow {
|
||||
reservation_id: number;
|
||||
role: string;
|
||||
sequence: number;
|
||||
name: string;
|
||||
code: string | null;
|
||||
lat: number;
|
||||
lng: number;
|
||||
timezone: string | null;
|
||||
local_date: string | null;
|
||||
local_time: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* One flight state, every column; timestamps in the canonical UTC text. `T`
|
||||
* is `string` for a row read back and `DbTimestamp` for one being written.
|
||||
*/
|
||||
interface FlightLiveStateFields<T extends string> {
|
||||
callsign: string;
|
||||
service_date: string;
|
||||
origin: string;
|
||||
destination: string;
|
||||
phase: string;
|
||||
departed_at: T | null;
|
||||
landed_at: T | null;
|
||||
lat: number | null;
|
||||
lng: number | null;
|
||||
altitude_ft: number | null;
|
||||
ground_speed_kt: number | null;
|
||||
track_deg: number | null;
|
||||
vertical_rate_fpm: number | null;
|
||||
on_ground: number | null;
|
||||
registration: string | null;
|
||||
aircraft_type: string | null;
|
||||
source: string | null;
|
||||
first_seen_at: T | null;
|
||||
last_seen_at: T | null;
|
||||
fetched_at: T | null;
|
||||
next_poll_at: T | null;
|
||||
fail_count: number;
|
||||
departed_notified: number;
|
||||
landed_notified: number;
|
||||
delay_notified: number;
|
||||
}
|
||||
|
||||
export type FlightLiveStateRow = FlightLiveStateFields<string>;
|
||||
export type FlightLiveStateWrite = FlightLiveStateFields<DbTimestamp>;
|
||||
|
||||
const BOOKING_COLUMNS = [
|
||||
'reservations.id',
|
||||
'reservations.trip_id',
|
||||
'reservations.metadata',
|
||||
'reservations.day_id',
|
||||
'reservations.end_day_id',
|
||||
'reservations.reservation_time',
|
||||
'reservations.reservation_end_time',
|
||||
] as const;
|
||||
|
||||
const ENDPOINT_COLUMNS = [
|
||||
'reservation_id',
|
||||
'role',
|
||||
'sequence',
|
||||
'name',
|
||||
'code',
|
||||
'lat',
|
||||
'lng',
|
||||
'timezone',
|
||||
'local_date',
|
||||
'local_time',
|
||||
] as const;
|
||||
|
||||
/**
|
||||
* `flight_live_states`: what the open ADS-B feeds last said about a flight on
|
||||
* a day, one row per (callsign, service date, origin, destination) whichever
|
||||
* trips booked it.
|
||||
*
|
||||
* The flight bookings, their endpoints, the days they name and their
|
||||
* travellers are read here too, through Kysely: the live status only reads
|
||||
* them, and the reservations domain has no read of flights across all trips.
|
||||
*/
|
||||
export class FlightLiveStatesRepository extends TrekRepository<FlightLiveStates> {
|
||||
/** The flight bookings of one trip. */
|
||||
async listFlightBookingsForTrip(trip_id: number): Promise<FlightBookingDbRow[]> {
|
||||
return await this.kysely<Pick<DB, 'reservations' | 'trips'>>()
|
||||
.selectFrom('reservations')
|
||||
.innerJoin('trips', 'trips.id', 'reservations.trip_id')
|
||||
.select([...BOOKING_COLUMNS, 'trips.title as trip_title'])
|
||||
.where('reservations.trip_id', '=', trip_id)
|
||||
.where('reservations.type', '=', 'flight')
|
||||
.orderBy('reservations.id')
|
||||
.execute();
|
||||
}
|
||||
|
||||
/**
|
||||
* The flight bookings of every trip that is not archived and whose dates
|
||||
* (where it has any) reach into `from_date`..`to_date`: the candidates for a
|
||||
* poll. Which leg is really in its window the caller works out from the
|
||||
* schedule.
|
||||
*/
|
||||
async listFlightBookingsBetween(from_date: string, to_date: string): Promise<FlightBookingDbRow[]> {
|
||||
return await this.kysely<Pick<DB, 'reservations' | 'trips'>>()
|
||||
.selectFrom('reservations')
|
||||
.innerJoin('trips', 'trips.id', 'reservations.trip_id')
|
||||
.select([...BOOKING_COLUMNS, 'trips.title as trip_title'])
|
||||
.where('reservations.type', '=', 'flight')
|
||||
.where((eb) => eb.or([eb('trips.is_archived', 'is', null), eb('trips.is_archived', '=', 0)]))
|
||||
.where((eb) => eb.or([eb('trips.end_date', 'is', null), eb('trips.end_date', '>=', from_date)]))
|
||||
.where((eb) => eb.or([eb('trips.start_date', 'is', null), eb('trips.start_date', '<=', to_date)]))
|
||||
.orderBy('reservations.id')
|
||||
.execute();
|
||||
}
|
||||
|
||||
/** The endpoints of the given bookings, in their order. */
|
||||
async listEndpoints(reservation_ids: readonly number[]): Promise<FlightEndpointDbRow[]> {
|
||||
if (reservation_ids.length === 0) return [];
|
||||
return await this.kysely<Pick<DB, 'reservation_endpoints'>>()
|
||||
.selectFrom('reservation_endpoints')
|
||||
.select([...ENDPOINT_COLUMNS])
|
||||
.where('reservation_id', 'in', [...reservation_ids])
|
||||
.orderBy('reservation_id')
|
||||
.orderBy('sequence')
|
||||
.execute();
|
||||
}
|
||||
|
||||
/** The date of each given trip day that has one. */
|
||||
async listDayDates(day_ids: readonly number[]): Promise<Array<{ id: number; date: string }>> {
|
||||
if (day_ids.length === 0) return [];
|
||||
const rows = await this.kysely<Pick<DB, 'days'>>()
|
||||
.selectFrom('days')
|
||||
.select(['id', 'date'])
|
||||
.where('id', 'in', [...day_ids])
|
||||
.execute();
|
||||
return rows.flatMap((row) => (row.date ? [{ id: row.id, date: row.date }] : []));
|
||||
}
|
||||
|
||||
/**
|
||||
* The users put on a booking as its travellers who still belong to its trip:
|
||||
* the owner or a member. Someone removed from the trip stays on the
|
||||
* traveller list until it is edited, and must hear nothing more of it.
|
||||
*/
|
||||
async listTravelerIds(reservation_id: number): Promise<number[]> {
|
||||
const rows = await this.kysely<Pick<DB, 'reservation_travelers' | 'reservations' | 'trips' | 'trip_members'>>()
|
||||
.selectFrom('reservation_travelers as rt')
|
||||
.innerJoin('reservations as r', 'r.id', 'rt.reservation_id')
|
||||
.innerJoin('trips as t', 't.id', 'r.trip_id')
|
||||
.select('rt.user_id')
|
||||
.where('rt.reservation_id', '=', reservation_id)
|
||||
.where((eb) =>
|
||||
eb.or([
|
||||
eb('t.user_id', '=', eb.ref('rt.user_id')),
|
||||
eb.exists(
|
||||
eb
|
||||
.selectFrom('trip_members as tm')
|
||||
.select('tm.id')
|
||||
.whereRef('tm.trip_id', '=', 'r.trip_id')
|
||||
.whereRef('tm.user_id', '=', 'rt.user_id'),
|
||||
),
|
||||
]),
|
||||
)
|
||||
.orderBy('rt.user_id')
|
||||
.execute();
|
||||
return rows.map((row) => row.user_id);
|
||||
}
|
||||
|
||||
/** Every stored state of the given callsigns, whatever their day. */
|
||||
async findForCallsigns(callsigns: readonly string[]): Promise<FlightLiveStateRow[]> {
|
||||
if (callsigns.length === 0) return [];
|
||||
return await this.kysely<Pick<DB, 'flight_live_states'>>()
|
||||
.selectFrom('flight_live_states')
|
||||
.selectAll()
|
||||
.where('callsign', 'in', [...callsigns])
|
||||
.execute();
|
||||
}
|
||||
|
||||
/** Writes a flight's whole state, replacing the one stored under its key. */
|
||||
async saveState(row: FlightLiveStateWrite): Promise<void> {
|
||||
const { callsign, service_date, origin, destination, ...changes } = row;
|
||||
await this.kysely<Pick<DB, 'flight_live_states'>>()
|
||||
.insertInto('flight_live_states')
|
||||
.values({ callsign, service_date, origin, destination, ...changes })
|
||||
.onConflict((oc) => oc.columns(['callsign', 'service_date', 'origin', 'destination']).doUpdateSet(changes))
|
||||
.execute();
|
||||
}
|
||||
|
||||
/** Drops the states of flights that departed before `service_date`; answers how many went. */
|
||||
async deleteBefore(service_date: string): Promise<number> {
|
||||
const result = await this.kysely<Pick<DB, 'flight_live_states'>>()
|
||||
.deleteFrom('flight_live_states')
|
||||
.where('service_date', '<', service_date)
|
||||
.executeTakeFirst();
|
||||
return Number(result.numDeletedRows);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user