-
Notifications
You must be signed in to change notification settings - Fork 1
/
iflive.js
711 lines (543 loc) · 19.1 KB
/
iflive.js
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
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
/*
iflive: JavaScript client for Infinite Flight Live API
Version: 0.9.0
Author: @likeablegeek (https://likeablegeek.com/)
Distributed by: FlightSim Ninja (http://flightim.ninja)
Copyright 2022.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*****
* Import required modules
*/
const request = require("request"); // For making HTTP JSON requests
const events = require('events'); // For emitting events back to calling scripts
const csv = require("csv-parse/sync"); // For importing the aircraft and liveries CSVs
const fs = require("fs"); // For reading files
const path = require("path"); // For system-independent file path creation
/*****
* Import aircraft CSV
*/
const aircraftCSV = fs.readFileSync(path.join(__dirname,"aircraft.csv"));
const aircraft = csv.parse(aircraftCSV,{
input: true,
skip_empty_lines: true,
columns: true,
objname: 'id'
});
/*****
* Import aircraft CSV
*/
const liveriesCSV = fs.readFileSync(path.join(__dirname,"liveries.csv"));
const liveries = csv.parse(liveriesCSV,{
input: true,
skip_empty_lines: true,
columns: true,
objname: 'id'
});
/****
* Define iflive object
*/
let IFL = {
/*****
* Module name
*/
name: "iflive",
/*****
* Constants for referencing error levels in logging
*/
INFO: 3,
WARN: 2,
ERROR: 1,
MANDATORY: 0,
/*****
* Global variables
*/
apikey: "", // IF LIve API key needed for iflive to work
hostname: "api.infiniteflight.com", // Hostname for Live API endpoint
basepath: "/public/v2/", // Path for current version of Live API
isCallback: false, // By default we trigger events instead of callbacks
sessions: {}, // On initialisation we will fetch and store the current active sessions for immediate use
/*****
* Event emitter for return events to client
*/
eventEmitter: new events.EventEmitter(),
/*****
* Default logging state
*/
enableLog: false, // Control logging -- default is false
logLevel: this.MANDATORY, // Logging message level -- default is MANDATORY
/*****
* Command manifest
*/
manifest: {
// Infinite Flight Live API reference: https://infiniteflight.com/guide/developer-reference/live-api/sessions
sessions: {
type: "GET",
path: "sessions"
},
// Infinite Flight Live API reference: https://infiniteflight.com/guide/developer-reference/live-api/flights
flights: {
type: "GET",
path: "sessions/[sessionId]/flights"
},
// Infinite Flight Live API reference: https://infiniteflight.com/guide/developer-reference/live-api/flight-route
flightRoute: {
type: "GET",
path: "sessions/[sessionId]/flights/[flightId]/route"
},
// Infinite Flight Live API reference: https://infiniteflight.com/guide/developer-reference/live-api/flight-plan
flightPlan: {
type: "GET",
path: "sessions/[sessionId]/flights/[flightId]/flightplan"
},
// Infinite Flight Live API reference: https://infiniteflight.com/guide/developer-reference/live-api/atc
atcFreqs: {
type: "GET",
path: "sessions/[sessionId]/atc"
},
// Infinite Flight Live API reference: https://infiniteflight.com/guide/developer-reference/live-api/user-stats
users: {
type: "POST",
path: "users"
},
// Infinite Flight Live API reference: https://infiniteflight.com/guide/developer-reference/live-api/user-grade
userDetails: {
type: "GET",
path: "users/[userId]"
},
// Infinite Flight Live API reference: https://infiniteflight.com/guide/developer-reference/live-api/atis
airportAtis: {
type: "GET",
path: "sessions/[sessionId]/airport/[icao]/atis"
},
// Infinite Flight Live API reference: https://infiniteflight.com/guide/developer-reference/live-api/airport-status
airportStatus: {
type: "GET",
path: "sessions/[sessionId]/airport/[icao]/status"
},
// Infinite Flight Live API reference: https://infiniteflight.com/guide/developer-reference/live-api/world-status
worldStatus: {
type: "GET",
path: "sessions/[sessionId]/world"
},
// Infinite Flight Live API reference: https://infiniteflight.com/guide/developer-reference/live-api/oceanic-tracks
tracks: {
type: "GET",
path: "tracks"
},
// Infinite Flight Live API reference: https://infiniteflight.com/guide/developer-reference/live-api/user-flights
userFlights: {
type: "GET",
path: "users/[userId]/flights"
},
// Infinite Flight Live API reference: https://infiniteflight.com/guide/developer-reference/live-api/user-flight
userFlight: {
type: "GET",
path: "users/[userId]/flights/[flightId]"
},
// Infinite Flight Live API reference: https://infiniteflight.com/guide/developer-reference/live-api/user-atc-sessions
userAtcSessions: {
type: "GET",
path: "users/[userId]/atc"
},
// Infinite Flight Live API reference: https://infiniteflight.com/guide/developer-reference/live-api/user-atc-session
userAtcSession: {
type: "GET",
path: "users/[userId]/atc/[atcSessionId]"
},
// Infinite Flight Live API reference: https://infiniteflight.com/guide/developer-reference/live-api/notams
notams: {
type: "GET",
path: "sessions/[sessionId]/notams"
},
// Infinite Flight Live API reference: https://infiniteflight.com/guide/developer-reference/live-api/aircraft
aircraft: {
type: "GET",
path: "aircraft"
},
// Infinite Flight Live API reference: https://infiniteflight.com/guide/developer-reference/live-api/aircraft-liveries
aircraftLiveries: {
type: "GET",
path: "aircraft/[aircraftId]/liveries"
},
// Infinite Flight Live API reference: https://infiniteflight.com/guide/developer-reference/live-api/liveries
liveries: {
type: "GET",
path: "aircraft/liveries"
},
// Infinite Flight Live API reference: https://infiniteflight.com/guide/developer-reference/live-api/3d-airports
airports: {
type: "GET",
path: "airports"
},
// Infinite Flight Live API reference: https://infiniteflight.com/guide/developer-reference/live-api/airport-information
airportInfo: {
type: "GET",
path: "airports/[airportIcao]"
}
},
/*****
* Cache object to hold cache data for all commands
*/
cache: {
session: {},
flights: {},
flightRoute: {},
flightPlan: {},
atcFreqs: {},
users: {},
userDetails: {},
airportAtis: {},
airportStatus: {},
worldStatus: {},
tracks: {},
userFlights: {},
userFlight: {},
userAtcSessions: {},
userAtcSession: {},
notams: {},
aircraft: {},
aircraftLiveries: {},
liveries: {},
airports: {},
airportInfo: {}
},
/*****
* Poll object to hold polling interval objects for all commands
*/
polls: {
session: {},
flights: {},
flightRoute: {},
flightPlan: {},
atcFreqs: {},
users: {},
userDetails: {},
airportAtis: {},
airportStatus: {},
worldStatus: {},
tracks: {},
userFlights: {},
userFlight: {},
userAtcSessions: {},
userAtcSession: {},
notams: {},
aircraft: {},
aircraftLiveries: {},
liveries: {},
airports: {},
airportInfo: {}
},
/*****
* Logging function
*/
log: (msg,level = IFL.logLevel) => { // generic logging function
if (IFL.enableLog) {
if (level <= IFL.logLevel) {
console.log(IFL.name, msg);
}
}
},
/*****
* Utility function to get aircraft name from aircraft ID
*/
aircraft: (id) => {
return aircraft[id].name;
},
/*****
*
* Utility function to get livery name from livery ID
*/
livery: (id) => {
return liveries[id].name;
},
/*****
* Function to allow client to define listener for events emitted by module
*/
on: (event, listener) => {
IFL.log("Setting listener for: " + event);
IFL.eventEmitter.on(event, listener);
},
/*****
* Utility function for issuing API calls
*
* Handles HTTP GET, POST, PUT, PATCH and DELETE; Live API currently
* only uses GET and POST but this allows extension to cover other
* request types.
*
* This function is based on a similar function in the `upcloud-api`
* npm module which uses the same basic architecture:
*
* https://github.com/likeablegeek/upcloud-api
*/
call: (cmd, params = {}, data = {}, callback = () => {}) => {
IFL.log("call: " + cmd, IFL.INFO);
IFL.log("params: " + JSON.stringify(params), IFL.WARN);
IFL.log("data: " + JSON.stringify(data), IFL.WARN);
// fn will rever to the appropriate method of the `request` package
let fn = request.get; // GET is default requesst type
// Determine the request type from the manifest and set `fn` accordingly
switch(IFL.manifest[cmd].type) {
case "GET":
fn = request.get;
break;
case "POST":
fn = request.post;
break;
case "PUT":
fn = request.put;
break;
case "PATCH":
fn = request.patch;
break;
case "DELETE":
fn = request.del;
break;
}
// Determine the URL path for the API call
let path = IFL.manifest[cmd].path;
// Replace query parameters in the URL path, if any
for (param in params) {
path = path.replace("[" + param + "]", params[param]);
}
IFL.log("Request path: " + path, IFL.INFO);
// Set up options for HTTP request
let options = {
url: "https://" + IFL.hostname + IFL.basepath + path,
headers: {
authorization: "Bearer " + IFL.apikey
}
};
// If POST, PUT or PATCH, pass `data` as JSON in the body
if (IFL.manifest[cmd].type == "POST" || IFL.manifest[cmd].type == "PUT" || IFL.manifest[cmd].type == "PATCH") {
options.json = true;
options.body = data;
}
try {
// Call the API
fn(options, (err, res, body) => {
// Callback for API response
IFL.log("call: received data from API", IFL.INFO);
IFL.log("Data received: " + JSON.stringify(body), IFL.WARN);
// Convert to string, parse as JSON
if (typeof(body) == "string" && body.length > 0) {
resData = JSON.parse(body).result;
} else if (body.result) {
resData = body.result;
} else {
resData = {};
}
IFL.log("Data to return: " + JSON.stringify(resData), IFL.WARN);
// Save cache data with key as one of:
//
// cmd
// cmd + params object
// cmd + data object
//
if (Object.entries(params).length > 0) {
IFL.cache[cmd][params] = {
data: resData,
ts: Date.now()
}
} else if (Object.entries(data).length > 0) {
IFL.cache[cmd][data] = {
data: resData,
ts: Date.now()
}
} else {
IFL.cache[cmd] = {
data: resData,
ts: Date.now()
};
}
// Callback or event to return result
if (IFL.isCallback) { // Use a callback if one is available
callback(resData);
} else { // Use an event
IFL.eventEmitter.emit('IFLdata',{"command": cmd, "params": params, "data": data, "result": resData}); // Return data to calling script through an event
}
});
} catch (err) {
IFL.log("call: " + err.message, IFL.ERROR);
}
},
/*****
* Fetch from cache if available otherwise fetch from cache and cache
*/
get: (cmd, params = {}, data = {}, callback = () => {}) => {
IFL.log("get: " + cmd, IFL.INFO);
IFL.log("params: " + JSON.stringify(params), IFL.WARN);
IFL.log("data: " + JSON.stringify(data), IFL.WARN);
// Tracking variable to see if we are done returning a value
let done = false;
// Return cache data if available using one of the following as cache key:
//
// cmd
// cmd + params object
// cmd + data object
//
if (Object.entries(params).length > 0) { // Any parameters?
// Do we have a cache entry? If so, do we have any cache data?
if (IFL.cache[cmd].hasOwnProperty(params) && Object.entries(IFL.cache[cmd][params]).length > 0) {
IFL.log("Cache hit: params", IFL.WARN);
// Callback or event to return result
if (IFL.isCallback) { // Use a callback if one is available
callback(IFL.cache[cmd][params]);
} else { // Use an event
IFL.eventEmitter.emit('IFLdata',{"command": cmd, "params": params, "data": data, "result": IFL.cache[cmd][params]}); // Return data to calling script through an event
}
done = true;
}
} else if (Object.entries(data).length > 0) { // Any post data?
IFL.log("Cache hit: data", IFL.WARN);
// Do we have a cache entry? If so, do we have any cache data?
if (IFL.cache[cmd].hasOwnProperty(data) && Object.entries(IFL.cache[cmd][data]).length > 0) {
// Callback or event to return result
if (IFL.isCallback) { // Use a callback if one is available
callback(IFL.cache[cmd][data]);
} else { // Use an event
IFL.eventEmitter.emit('IFLdata',{"command": cmd, "params": params, "data": data, "result": IFL.cache[cmd][data]}); // Return data to calling script through an event
}
done = true;
}
} else {
if (Object.entries(IFL.cache[cmd]).length > 0) { // Any cache hit for just the cmd?
IFL.log("Cache hit: plain", IFL.WARN);
// Callback or event to return result
if (IFL.isCallback) { // Use a callback if one is available
callback(IFL.cache[cmd]);
} else { // Use an event
IFL.eventEmitter.emit('IFLdata',{"command": cmd, "params": params, "data": data, "result": IFL.cache[cmd]}); // Return data to calling script through an event
}
done = true;
}
}
// We didn't return anything so let's fetch it
if (!done) {
IFL.log("No cache hit", IFL.WARN);
// Call the API to fetch data; callback provided if callbacks are being used; event will get returned directly from call functions
IFL.call(cmd, params, data, (res) => {
// Fire the callback using data from the cache for consistency with cases where there is a cache hit
if (Object.entries(params).length > 0) {
if (IFL.cache[cmd].hasOwnProperty(params) && Object.entries(IFL.cache[cmd][params]).length > 0) {
IFL.log("Cache hit: params", IFL.WARN);
callback(IFL.cache[cmd][params]);
}
} else if (Object.entries(data).length > 0) {
if (IFL.cache[cmd].hasOwnProperty(data) && Object.entries(IFL.cache[cmd][data]).length > 0) {
IFL.log("Cache hit: data", IFL.WARN);
callback(IFL.cache[cmd][data]);
}
} else if (Object.entries(IFL.cache[cmd]).length > 0) {
IFL.log("Cache hit: plain", IFL.WARN);
callback(IFL.cache[cmd]);
} else {
// Nothing in the cache -- return null
IFL.log("Still no cache hit", IFL.WARN);
callback(null);
}
});
}
},
/*****
* Set a polling frequency for a given command
*/
poll: (pollCmd, pollParams = {}, pollData = {}, pollThrottle = 30000, pollCallback = () => {}) => {
IFL.log("poll: " + pollCmd, IFL.INFO);
IFL.log("params: " + JSON.stringify(pollParams), IFL.WARN);
IFL.log("data: " + JSON.stringify(pollData), IFL.WARN);
// Clear poll
IFL.clear(pollCmd, pollParams, pollData, pollCallback);
// Establish poll storing the interval objects with a cache key:
//
// cmd
// cmd + params object
// cmd + data object
//
if (Object.entries(pollParams).length > 0) {
// Call the command initially before creating interval
IFL.call(pollCmd,pollParams,pollData,pollCallback);
// Create interval for polling
IFL.polls[pollCmd][pollParams] = {
interval: setInterval((cmd,params,data,callback) => {
IFL.call(cmd,params,data,callback);
}, pollThrottle, pollCmd, pollParams, pollData, pollCallback)
}
} else if (Object.entries(pollData).length > 0) {
// Call the command initially before creating interval
IFL.call(pollCmd,pollParams,pollData,pollCallback);
// Create interval for polling
IFL.polls[pollCmd][pollData] = {
interval: setInterval((cmd,params,data,callback) => {
IFL.call(cmd,params,data,callback);
}, pollThrottle, pollCmd, pollParams, pollData, pollCallback)
}
} else {
// Call the command initially before creating interval
IFL.call(pollCmd,pollParams,pollData,pollCallback);
// Create interval for polling
IFL.polls[pollCmd] = {
interval: setInterval((cmd,params,data,callback) => {
IFL.call(cmd,params,data,callback);
}, pollThrottle, pollCmd, pollParams, pollData, pollCallback)
};
}
},
/*****
* Clear polling interval
*/
clear: (pollCmd, pollParams = {}, pollData = {}) => {
IFL.log("clear: " + pollCmd, IFL.INFO);
IFL.log("params: " + JSON.stringify(pollParams), IFL.WARN);
IFL.log("data: " + JSON.stringify(pollData), IFL.WARN);
// Clear poll using appropriate cache key:
//
// cmd
// cmd + params object
// cmd + data object
//
if (Object.entries(pollParams).length > 0) {
if (IFL.polls[pollCmd][pollParams] && IFL.polls[pollCmd][pollParams].hasOwnProperty("interval")) {
clearInterval(IFL.polls[pollCmd][pollParams]["interval"]);
}
} else if (Object.entries(pollData).length > 0) {
if (IFL.polls[pollCmd][pollData] && IFL.polls[pollCmd][pollData].hasOwnProperty("interval")) {
clearInterval(IFL.polls[pollCmd][pollData]["interval"]);
}
} else {
if (IFL.polls[pollCmd].hasOwnProperty("interval")) {
clearInterval(IFL.polls[pollCmd]["interval"]);
}
}
},
/*****
* Initialise API
*/
init: (apikey, params = {}, callback = () => {}) => {
IFL.log("init", IFL.INFO);
IFL.log("params: " + JSON.stringify(params), IFL.WARN);
try {
IFL.apikey = apikey;
if (params.enableLog) IFL.enableLog = params.enableLog; // Set Logging on/off
if (params.logLevel) IFL.logLevel = params.logLevel; // Set logging message level
if (params.callback) IFL.isCallback = params.callback; // Set if we are using callbacks
// Callback or event to return result
if (IFL.isCallback) { // Use a callback if one is available
callback();
} else { // Use an event
IFL.eventEmitter.emit('IFLinit',"initialised"); // Return data to calling script through an event
}
} catch(e) {
IFL.eventEmitter.emit('IFLerror',e);
}
}
};
module.exports = IFL;