-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathindex.ts
More file actions
562 lines (469 loc) · 14.1 KB
/
index.ts
File metadata and controls
562 lines (469 loc) · 14.1 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
// Types
export declare class MetarResponse {
icao: string;
source: string;
metar: string;
}
export declare class TafResponse {
icao: string;
source: string;
taf: string;
}
export declare class AtisResponse {
icao: string;
source: string;
combined?: string;
arr?: string;
dep?: string;
}
export declare class AirportResponse {
icao: string;
iata: string;
type: string;
name: string;
lat: number;
lon: number;
elevation: number;
continent: string;
country: string;
transAlt: number;
}
export enum AtcType {
UNKNOWN,
DELIVERY,
GROUND,
TOWER,
DEPARTURE,
APPROACH,
RADAR,
ATIS
}
export declare class ATCInfo {
callsign:string;
frequency:string;
visualRange:number;
textAtis: string[];
type:AtcType;
latitude?: number;
longitude?: number;
}
export declare class PilotInfo {
callsign: string;
name: string;
latitude?: number;
longitude?: number;
altitude:number;
heading:number;
groundspeed:number;
departure: string;
arrival: string;
aircraft: string;
}
export declare class TelexConnection {
id: string;
isActive: boolean;
firstContact: Date;
lastContact: Date;
flight: string;
location: {
x: number;
y: number;
};
trueAltitude: number;
heading: number;
freetextEnabled: boolean;
aircraftType: string;
origin: string;
destination: string;
}
export declare class SearchResult<T> {
fullMatch?: T;
matches: T[];
}
export declare class TelexMessage {
id: string;
createdAt: Date;
received: boolean;
message: string;
isProfane: boolean;
from: TelexConnection;
to?: TelexConnection;
}
export declare class Token {
accessToken: string;
connection: string;
flight: string;
}
export declare class AircraftStatus {
location: {
long: number;
lat: number;
};
trueAltitude: number;
heading: number;
origin: string;
destination: string;
freetextEnabled: boolean;
flight: string;
aircraftType: string;
}
export declare class CommitInfo {
sha: string;
timestamp: Date;
}
export declare class ReleaseInfo {
name: string;
publishedAt: Date;
htmlUrl: string;
body: string;
}
export declare class PullLabel {
id: string;
name: string;
color: string;
}
export declare class PullInfo {
number: number;
title: string;
author: string;
labels: PullLabel[];
isDraft: boolean;
}
export declare class ArtifactInfo {
artifactUrl: string;
}
export declare class Chart {
url: string;
name: string;
}
export declare class ChartsResponse {
icao: string;
charts?: Chart[];
}
export declare class Paginated<T> {
results: T[];
count: number;
total: number;
}
export declare class Bounds {
north: number;
east: number;
south: number;
west: number;
}
export declare type StageCallback = (flights: TelexConnection[]) => void;
export class HttpError extends Error {
public readonly status;
constructor(status: number, message?: string) {
super(message);
this.status = status;
}
}
export class TelexNotConnectedError extends Error {
constructor() {
super("TELEX is not connected");
}
}
function _get<T>(url: URL, headers?: any): Promise<T> {
return fetch(url.href, { headers })
.then((response) => {
if (!response.ok) {
throw new HttpError(response.status);
}
return response.json();
});
}
function _delete(url: URL, headers?: any): Promise<void> {
return fetch(url.href, { method: "DELETE", headers })
.then((response) => {
if (!response.ok) {
throw new HttpError(response.status);
}
return;
});
}
function _post<T>(url: URL, body: any, headers?: any): Promise<T> {
const headersToSend = {
"Content-Type": "application/json",
...headers
};
return fetch(url.href, { method: "POST", body: JSON.stringify(body), headers: headersToSend })
.then((response) => {
if (!response.ok) {
throw new HttpError(response.status);
}
return response.json();
});
}
function _put<T>(url: URL, body: any, headers?: any): Promise<T> {
const headersToSend = {
"Content-Type": "application/json",
...headers
};
return fetch(url.href, { method: "PUT", body: JSON.stringify(body), headers: headersToSend })
.then((response) => {
if (!response.ok) {
throw new HttpError(response.status);
}
return response.json();
});
}
export class NXApi {
public static url = new URL("https://api.flybywiresim.com");
// public static url = new URL("http://localhost:3000");
}
export class Metar {
public static get(icao: string, source?: string): Promise<MetarResponse> {
if (!icao) {
throw new Error("No ICAO provided");
}
const url = new URL(`/metar/${icao}`, NXApi.url);
if (source) {
url.searchParams.set("source", source);
}
return _get<MetarResponse>(url);
}
}
export class Atis {
public static get(icao: string, source?: string): Promise<AtisResponse> {
if (!icao) {
throw new Error("No ICAO provided");
}
const url = new URL(`/atis/${icao}`, NXApi.url);
if (source) {
url.searchParams.set("source", source);
}
return _get<AtisResponse>(url);
}
}
export class Taf {
public static get(icao: string, source?: string): Promise<TafResponse> {
if (!icao) {
throw new Error("No ICAO provided");
}
const url = new URL(`/taf/${icao}`, NXApi.url);
if (source) {
url.searchParams.set("source", source);
}
return _get<TafResponse>(url);
}
}
export class Telex {
private static accessToken: string;
public static refreshRate = 15000;
public static connect(status: AircraftStatus): Promise<Token> {
return _post<Token>(new URL(`/txcxn`, NXApi.url), Telex.buildBody(status))
.then(res => {
Telex.accessToken = res.accessToken;
return res;
});
}
public static update(status: AircraftStatus): Promise<TelexConnection> {
Telex.connectionOrThrow();
return _put<TelexConnection>(new URL(`/txcxn`, NXApi.url), Telex.buildBody(status), {
Authorization: Telex.buildToken()
})
.then(Telex.mapConnection);
}
public static disconnect(): Promise<void> {
Telex.connectionOrThrow();
return _delete(new URL(`/txcxn`, NXApi.url), {
Authorization: Telex.buildToken()
})
.then(() => {
Telex.accessToken = "";
return;
});
}
public static sendMessage(recipientFlight: string, message: string): Promise<TelexMessage> {
Telex.connectionOrThrow();
return _post<TelexMessage>(new URL(`/txmsg`, NXApi.url), {
to: recipientFlight,
message: message
}, {
Authorization: Telex.buildToken()
})
.then(Telex.mapMessage);
}
public static fetchMessages(): Promise<TelexMessage[]> {
Telex.connectionOrThrow();
return _get<TelexMessage[]>(new URL(`/txmsg`, NXApi.url), {
Authorization: Telex.buildToken()
})
.then(res => res.map(Telex.mapMessage));
}
public static fetchConnections(skip?: number, take?: number, bounds?: Bounds): Promise<Paginated<TelexConnection>> {
const url = new URL(`/txcxn`, NXApi.url);
if (skip) {
url.searchParams.set("skip", skip.toString());
}
if (take) {
url.searchParams.append("take", take.toString());
}
if (bounds) {
url.searchParams.append("north", bounds.north.toString());
url.searchParams.append("east", bounds.east.toString());
url.searchParams.append("south", bounds.south.toString());
url.searchParams.append("west", bounds.west.toString());
}
return _get<Paginated<TelexConnection>>(url)
.then(res => {
return {
...res,
results: res.results.map(Telex.mapConnection)
};
});
}
public static async fetchAllConnections(bounds?: Bounds, stageCallback?: StageCallback): Promise<TelexConnection[]> {
let flights: TelexConnection[] = [];
let skip = 0;
let total = 0;
do {
const data = await Telex.fetchConnections(skip, 100, bounds);
total = data.total;
skip += data.count;
flights = flights.concat(data.results);
if (stageCallback) {
stageCallback(flights);
}
}
while (total > skip);
return flights;
}
public static fetchConnection(id: string): Promise<TelexConnection> {
return _get<TelexConnection>(new URL(`/txcxn/${id}`, NXApi.url))
.then(Telex.mapConnection);
}
public static findConnections(flightNumber: string): Promise<SearchResult<TelexConnection>> {
const url = new URL(`/txcxn/_find`, NXApi.url);
url.searchParams.set("flight", flightNumber);
return _get<SearchResult<TelexConnection>>(url)
.then(res => {
return {
matches: res.matches.map(Telex.mapConnection),
fullMatch: res.fullMatch ? Telex.mapConnection(res.fullMatch) : undefined,
}
});
}
public static countConnections(): Promise<number> {
return _get<number>(new URL(`/txcxn/_count`, NXApi.url));
}
private static buildBody(status: AircraftStatus) {
return {
location: {
x: status.location.long,
y: status.location.lat
},
trueAltitude: status.trueAltitude,
heading: status.heading,
origin: status.origin,
destination: status.destination,
freetextEnabled: status.freetextEnabled,
flight: status.flight,
aircraftType: status.aircraftType
};
}
private static buildToken(): string {
return `Bearer ${Telex.accessToken}`;
}
private static connectionOrThrow() {
if (!Telex.accessToken) {
throw new TelexNotConnectedError();
}
}
private static mapConnection(connection: TelexConnection): TelexConnection {
return {
...connection,
firstContact: new Date(connection.firstContact),
lastContact: new Date(connection.lastContact)
};
}
private static mapMessage(message: TelexMessage): TelexMessage {
const msg: TelexMessage = {
...message,
createdAt: new Date(message.createdAt)
};
if (message.from) {
msg.from = Telex.mapConnection(message.from);
}
if (message.to) {
msg.to = Telex.mapConnection(message.to);
}
return msg;
}
}
export class Airport {
public static get(icao: string): Promise<AirportResponse> {
if (!icao) {
throw new Error("No ICAO provided");
}
return _get<AirportResponse>(new URL(`/api/v1/airport/${icao}`, NXApi.url));
}
public static getBatch(icaos: string[]): Promise<AirportResponse[]> {
if (!icaos) {
throw new Error("No ICAOs provided");
}
return _post<AirportResponse[]>(new URL(`/api/v1/airport/_batch`, NXApi.url), { icaos });
}
}
export class ATC {
public static getAtc(source: string): Promise<ATCInfo[]> {
const url = new URL(`/api/v1/atc?source=${source}`, NXApi.url);
return _get<ATCInfo[]>(url);
}
}
export class Pilot {
public static getPilots(source: string) : Promise<PilotInfo[]>{
const url = new URL(`/api/v1/pilot?source=${source}`, NXApi.url);
return _get<PilotInfo[]>(url);
}
}
export class GitVersions {
public static getNewestCommit(user: string, repo: string, branch: string): Promise<CommitInfo> {
if (!user || !repo || !branch) {
throw new Error("Missing argument");
}
return _get<CommitInfo>(new URL(`/api/v1/git-versions/${user}/${repo}/branches/${branch}`, NXApi.url))
.then((res: CommitInfo) => {
return {
...res,
timestamp: new Date(res.timestamp)
};
});
}
public static getReleases(user: string, repo: string, includePreReleases?: boolean): Promise<ReleaseInfo[]> {
if (!user || !repo) {
throw new Error("Missing argument");
}
return _get<ReleaseInfo[]>(
new URL(`/api/v1/git-versions/${user}/${repo}/releases?${includePreReleases === true}`, NXApi.url)
)
.then(res => res.map(rel => {
return {
...rel,
publishedAt: new Date(rel.publishedAt)
};
}));
}
public static getPulls(user: string, repo: string): Promise<PullInfo[]> {
if (!user || !repo) {
throw new Error("Missing argument");
}
return _get<PullInfo[]>(new URL(`/api/v1/git-versions/${user}/${repo}/pulls`, NXApi.url));
}
public static getArtifact(user: string, repo: string, pull: string): Promise<ArtifactInfo> {
if (!user || !repo || !pull) {
throw new Error("Missing argument");
}
return _get<ArtifactInfo>(new URL(`/api/v1/git-versions/${user}/${repo}/pulls/${pull}/artifact`, NXApi.url));
}
}
export class Charts {
public static get(icao: string, source?: string): Promise<ChartsResponse> {
if (!icao) {
throw new Error("No ICAO provided");
}
const url = new URL(`/api/v1/charts/${icao}`, NXApi.url);
return _get<ChartsResponse>(url);
}
}