-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.py
1755 lines (1226 loc) · 62.6 KB
/
api.py
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
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
from datetime import datetime, timedelta
import http.server
import socketserver
from urllib import parse
import json
import sys
import os
import logging
import logging.handlers as handlers
import signal
import mysql.connector #pip3 install mysql-connector-python
from enum import Enum
import hashlib
def handle_interrupt(signal, frame):
raise sigKill("SIGKILL Requested")
def setLogLevel(logLevel):
logLevel = logLevel.lower()
if logLevel == "debug":
logger.setLevel(logging.DEBUG)
logger.debug("Logging set to DEBUG.")
return
if logLevel == "error":
logger.setLevel(logging.ERROR)
logger.error("Logging set to ERROR.")
return
if logLevel == "warning":
logger.setLevel(logging.WARNING)
logger.warning("Logging set to WARNING.")
return
if logLevel == "critical":
logger.setLevel(logging.CRITICAL)
logger.critical("Logging set to CRITICAL.")
return
def responseHandler(requestHandler, status, headers=[], body=None, contentType="application/json"):
#Send the HTTP status code requested
requestHandler.send_response(status)
if status == 404:
contentType = None
if contentType != None and body != None:
tmpHeader = {}
tmpHeader['key'] = "Content-Type"
tmpHeader['value'] = contentType
headers.append(tmpHeader)
tmpHeader = {}
tmpHeader['key'] = 'Access-Control-Allow-Origin'
tmpHeader['value'] = "*"
headers.append(tmpHeader)
#Send each header to the caller
for header in headers:
requestHandler.send_header(header['key'], header['value'])
#Send a blank line to the caller
requestHandler.end_headers()
#Empty the headers
headers.clear()
#Write the response body to the caller
if body is not None:
if contentType == "application/json":
requestHandler.wfile.write(json.dumps(body).encode("utf8"))
else:
requestHandler.wfile.write(body)
def authenticate(requestHandler):
#Ensure the header exists
if "x-api-key" not in requestHandler.headers:
raise HTTPUnauthorizedResponse(status=401)
#Ensure the header matches
if requestHandler.headers['x-api-key'] != settings['api']['x-api-key']:
raise HTTPUnauthorizedResponse(status=401)
def parseURL(path):
#Get the operation requested by the user
returnValue = parse.urlsplit(path).path.split("/")
#Remove the first element in the array, it's going to be empty
returnValue.pop(0)
#Clean up each element in the array
position = 0
for element in returnValue:
returnValue[position] = parse.unquote(element).strip()
position = position + 1
return returnValue
def parseBody(requestHandler):
#Ensure the data is JSON
if requestHandler.headers.get('Content-Type') != "application/json":
raise HTTPErrorResponse(status=415, message="Unexpected Content-Type; Send application/json")
content_len = int(requestHandler.headers.get('Content-Length'))
return json.loads(requestHandler.rfile.read(content_len))
def registration_get(requestHandler, urlPath):
if len(urlPath) < 3:
raise HTTPErrorResponse(status=400, message="Parameter type (icao_hex|registration) and value is required")
if urlPath[1] not in ['icao_hex', 'registration']:
raise HTTPErrorResponse(status=400, message="Parameter type (icao_hex or registration) is required")
if len(urlPath[2]) == 0:
raise HTTPErrorResponse(status=400, message="Search criteria is required")
#See if the user specified the type, default to "simple"
if len(urlPath) == 4:
if urlPath[3] in ['simple', 'detailed']:
data_type = urlPath[3]
else:
raise HTTPErrorResponse(status=400, message="Parameter " + urlPath[3] + " is invalid")
else:
data_type = None
if urlPath[1] == "registration":
tmpRegistration = registration(registration=urlPath[2], data_type=data_type)
if urlPath[1] == "icao_hex":
tmpRegistration = registration(icao_hex=urlPath[2], data_type=data_type)
getResult = tmpRegistration.get()
#Ensure we have a result
if getResult['status'] == ENUM_RESULT.SUCCESS:
responseHandler(requestHandler, 200, body=getResult['data'])
return
if getResult['status'] == ENUM_RESULT.INVALID_REQUEST:
raise HTTPErrorResponse(status=400, message=getResult['message'])
if getResult['status'] == ENUM_RESULT.NOT_FOUND:
#Auto redirect to the opposite if possible
if requestHandler.headers.get('referer') is None and data_type == None:
tmpHeaders = []
tmpHeader = {}
tmpHeader['key'] = "referer"
tmpHeader['value'] = "http://" + requestHandler.headers['Host'] + requestHandler.path
tmpHeaders.append(tmpHeader)
tmpHeader = {}
tmpHeader['key'] = "location"
tmpHeader['value'] = "http://" + requestHandler.headers['Host'] + "/registration/" + str(urlPath[1]) + "/" + str(urlPath[2])
if data_type == "detailed":
tmpHeader['value'] = tmpHeader['value'] + "/simple"
tmpHeaders.append(tmpHeader)
responseHandler(requestHandler, 303, headers=tmpHeaders)
return
else:
tmpHeader['value'] = tmpHeader['value'] + "/detailed"
tmpHeaders.append(tmpHeader)
responseHandler(requestHandler, 303, headers=tmpHeaders)
return
responseHandler(requestHandler, 404)
return
if getResult['status'] == ENUM_RESULT.UNEXPECTED_RESULT:
raise HTTPErrorResponse(status=409, message=getResult['message'])
#Default to a 500
raise HTTPErrorResponse()
def operator_get(requestHandler, urlPath):
if len(urlPath) < 2 or len(urlPath[1]) == 0:
logger.debug("Parameter 'airline_designator' is required" + str(urlPath))
raise HTTPErrorResponse(status=400, message="Parameter 'airline_designator' is required")
tmpOperator = operator()
tmpOperator.airline_designator = parse.unquote(urlPath[1]).strip()
getResult = tmpOperator.get()
#Ensure we have a result
if getResult == ENUM_RESULT.SUCCESS:
responseHandler(requestHandler, 200, body=tmpOperator.toDict())
return
if getResult == ENUM_RESULT.NOT_FOUND:
responseHandler(requestHandler, 404)
return
if getResult == ENUM_RESULT.UNEXPECTED_RESULT:
responseHandler(requestHandler, 409)
return
#Default
logger.debug("Unhandled response in operator_get for data" + str(urlPath))
raise HTTPErrorResponse()
def operator_post(requestHandler):
#Get the body from the post
body = parseBody(requestHandler)
#Verify the object passed has the correct parameters
if "airline_designator" not in body:
raise HTTPErrorResponse(status=400, message="Parameter 'airline_designator' is required")
if "name" not in body:
raise HTTPErrorResponse(status=400, message="Parameter 'name' is required")
if "callsign" not in body:
raise HTTPErrorResponse(status=400, message="Parameter 'callsign' is required")
if "country" not in body:
raise HTTPErrorResponse(status=400, message="Parameter 'country' is required")
if "source" not in body:
raise HTTPErrorResponse(status=400, message="Parameter 'source' is required")
tmpOperator = operator()
tmpOperator.airline_designator = body['airline_designator']
tmpOperator.name = body['name']
tmpOperator.callsign = body['callsign']
tmpOperator.country = body['country']
tmpOperator.source = body['source']
operator_postResponse = tmpOperator.post()
if operator_postResponse['status'] == ENUM_RESULT.SUCCESS:
responseHandler(requestHandler, 204)
return
if operator_postResponse['status'] == ENUM_RESULT.SUCCESS_NOT_MODIFIED:
raise HTTPErrorResponse(status=409, message=operator_postResponse['message'])
if operator_postResponse['status'] == ENUM_RESULT.UNEXPECTED_RESULT:
raise HTTPErrorResponse(status=400, message=operator_postResponse['message'])
if operator_postResponse['status'] == ENUM_RESULT.UNKNOWN_FAILURE:
raise HTTPErrorResponse(status=500, message=operator_postResponse['message'])
#Default
logger.debug("Unhandled response in operator_post")
raise HTTPErrorResponse()
def operator_patch(requestHandler, urlPath):
if len(urlPath) < 2 or len(urlPath[1]) == 0:
logger.debug("Parameter 'airline_designator' is required" + str(urlPath))
raise HTTPErrorResponse(status=400, message="Parameter 'airline_designator' is required")
#Get the body from the post
body = parseBody(requestHandler)
#Verify the object passed has the correct parameters
if "airline_designator" in body:
raise HTTPErrorResponse(status=400, message="Parameter 'airline_designator' is not allowed in request body for this operation")
if "name" not in body:
raise HTTPErrorResponse(status=400, message="Parameter 'name' is required")
if "callsign" not in body:
raise HTTPErrorResponse(status=400, message="Parameter 'callsign' is required")
if "country" not in body:
raise HTTPErrorResponse(status=400, message="Parameter 'country' is required")
if "source" not in body:
raise HTTPErrorResponse(status=400, message="Parameter 'source' is required")
tmpOperator = operator(urlPath[1], body['name'], body['callsign'], body['country'], body['source'])
operator_patchResponse = tmpOperator.patch()
if operator_patchResponse['status'] == ENUM_RESULT.SUCCESS:
responseHandler(requestHandler, 204)
return
if operator_patchResponse['status'] == ENUM_RESULT.UNEXPECTED_RESULT or operator_patchResponse['status'] == ENUM_RESULT.INVALID_REQUEST:
raise HTTPErrorResponse(status=400, message=operator_patchResponse['message'])
if operator_patchResponse['status'] == ENUM_RESULT.NOT_FOUND:
responseHandler(requestHandler, 404)
return
if operator_patchResponse['status'] == ENUM_RESULT.SUCCESS_NOT_MODIFIED:
raise HTTPErrorResponse(status=409, message=operator_patchResponse['message'])
if operator_patchResponse['status'] == ENUM_RESULT.UNKNOWN_FAILURE:
raise HTTPErrorResponse(status=500, message=operator_patchResponse['message'])
#Default
logger.debug("Unhandled response in operator_patch")
raise HTTPErrorResponse()
def operator_delete(requestHandler, urlPath):
if len(urlPath) < 2 or len(urlPath[1]) == 0:
logger.debug("Parameter 'airline_designator' is required" + str(urlPath))
raise HTTPErrorResponse(status=400, message="Parameter 'airline_designator' is required")
tmpOperator = operator(urlPath[1])
operator_deleteResponse = tmpOperator.delete()
if operator_deleteResponse['status'] == ENUM_RESULT.SUCCESS:
responseHandler(requestHandler, 204)
return
if operator_deleteResponse['status'] == ENUM_RESULT.UNEXPECTED_RESULT:
raise HTTPErrorResponse(status=400, message=operator_deleteResponse['message'])
if operator_deleteResponse['status'] == ENUM_RESULT.NOT_FOUND:
responseHandler(requestHandler, 404)
return
if operator_deleteResponse['status'] == ENUM_RESULT.SUCCESS_NOT_MODIFIED:
raise HTTPErrorResponse(status=409, message=operator_deleteResponse['message'])
if operator_deleteResponse['status'] == ENUM_RESULT.UNKNOWN_FAILURE:
raise HTTPErrorResponse(status=500, message=operator_deleteResponse['message'])
#Default
logger.debug("Unhandled response in operator_delete")
raise HTTPErrorResponse()
def operator_unknown_get(requestHandler, urlPath):
tmpUnknown = operator_unknown()
getResult = tmpUnknown.get()
#Ensure we have a result
if getResult == ENUM_RESULT.SUCCESS:
responseHandler(requestHandler, 200, body=tmpUnknown.operators())
return
if getResult == ENUM_RESULT.NOT_FOUND:
responseHandler(requestHandler, 404)
return
if getResult == ENUM_RESULT.UNEXPECTED_RESULT:
responseHandler(requestHandler, 409)
return
#Default
logger.debug("Unhandled response in operator_unknown_get for data" + str(urlPath))
raise HTTPErrorResponse()
def operator_unknown_delete(requestHandler, urlPath):
if len(urlPath) < 2 or len(urlPath[1]) == 0:
logger.debug("Parameter 'airline_designator' is required" + str(urlPath))
raise HTTPErrorResponse(status=400, message="Parameter 'airline_designator' is required")
tmpUnknown = operator_unknown()
tmpUnknown.airline_designator = urlPath[1]
operator_deleteResponse = tmpUnknown.delete()
if operator_deleteResponse['status'] == ENUM_RESULT.SUCCESS:
responseHandler(requestHandler, 204)
return
if operator_deleteResponse['status'] == ENUM_RESULT.UNEXPECTED_RESULT:
raise HTTPErrorResponse(status=400, message=operator_deleteResponse['message'])
if operator_deleteResponse['status'] == ENUM_RESULT.NOT_FOUND:
responseHandler(requestHandler, 404)
return
if operator_deleteResponse['status'] == ENUM_RESULT.SUCCESS_NOT_MODIFIED:
raise HTTPErrorResponse(status=409, message=operator_deleteResponse['message'])
if operator_deleteResponse['status'] == ENUM_RESULT.UNKNOWN_FAILURE:
raise HTTPErrorResponse(status=500, message=operator_deleteResponse['message'])
def flight_info_get(requestHandler, urlPath):
if len(urlPath) < 2 or len(urlPath[1]) == 0:
logger.debug("Parameter 'ident' is required" + str(urlPath))
raise HTTPErrorResponse(status=400, message="Parameter 'ident' is required")
#Parse the query string
queryString = parse.parse_qs(parse.urlsplit(requestHandler.path).query)
airport_icao = None
#Ensure we only have 1 instance of each hint
if "airport_icao" in queryString:
if len(queryString['airport_icao']) != 1:
raise HTTPErrorResponse(status=400, message="Exactly 1 airport_icao hint must be supplied")
airport_icao = queryString['airport_icao'][0]
tmpFlightInfo = flight_info(urlPath[1], focus_airport_icao_code=airport_icao)
getResult = tmpFlightInfo.get()
#Ensure we have a result
if getResult == ENUM_RESULT.SUCCESS:
responseHandler(requestHandler, 200, body=tmpFlightInfo.toDict())
return
if getResult == ENUM_RESULT.NOT_FOUND:
responseHandler(requestHandler, 404)
return
if getResult == ENUM_RESULT.UNEXPECTED_RESULT:
responseHandler(requestHandler, 409)
return
#Default
logger.debug("Unhandled response in flight_info_get for data" + str(urlPath))
raise HTTPErrorResponse()
def flight_info_post(requestHandler):
#Get the body from the post
body = parseBody(requestHandler)
#Verify the object passed has the correct parameters
if "ident" not in body:
raise HTTPErrorResponse(status=400, message="Parameter 'ident' is required")
if "airline_designator" not in body:
raise HTTPErrorResponse(status=400, message="Parameter 'airline_designator' is required")
if "flight_number" not in body:
raise HTTPErrorResponse(status=400, message="Parameter 'flight_number' is required")
if "origin" not in body:
raise HTTPErrorResponse(status=400, message="Parameter 'origin' is required")
if "destination" not in body:
raise HTTPErrorResponse(status=400, message="Parameter 'destination' is required")
if "source" not in body:
raise HTTPErrorResponse(status=400, message="Parameter 'source' is required")
tmpFlight = flight_info(ident=body['ident'])
tmpFlight.airline_designator = body['airline_designator']
tmpFlight.flight_number = body['flight_number']
tmpFlight.origin['icao_code'] = str(body['origin'])
tmpFlight.destination['icao_code'] = str(body['destination'])
tmpFlight.source = body['source']
if 'expires' in body:
tmpFlight.expires = datetime.fromisoformat(body['expires'])
flight_postResponse = tmpFlight.post()
if flight_postResponse['status'] == ENUM_RESULT.SUCCESS:
responseHandler(requestHandler, 204)
return
if flight_postResponse['status'] == ENUM_RESULT.SUCCESS_NOT_MODIFIED:
raise HTTPErrorResponse(status=409, message=flight_postResponse['message'])
if flight_postResponse['status'] == ENUM_RESULT.UNEXPECTED_RESULT:
raise HTTPErrorResponse(status=400, message=flight_postResponse['message'])
if flight_postResponse['status'] == ENUM_RESULT.UNKNOWN_FAILURE:
raise HTTPErrorResponse(status=500, message=flight_postResponse['message'])
#Default
logger.debug("Unhandled response in flight_post")
raise HTTPErrorResponse()
def flight_info_delete(requestHandler, urlPath):
#/flights/{ident}/{origin_airport_icao_code}/{destination_airport_icao_code}
if len(urlPath) < 4:
raise HTTPErrorResponse(status=400, message="Insufficient number of parameters provided")
if len(urlPath[1]) == 0:
logger.debug("Parameter 'ident' is required" + str(urlPath))
raise HTTPErrorResponse(status=400, message="Parameter 'ident' is required")
if len(urlPath[2]) == 0:
logger.debug("Parameter 'origin_airport_icao_code' is required" + str(urlPath))
raise HTTPErrorResponse(status=400, message="Parameter 'origin_airport_icao_code' is required")
if len(urlPath[3]) == 0:
logger.debug("Parameter 'destination_airport_icao_code' is required" + str(urlPath))
raise HTTPErrorResponse(status=400, message="Parameter 'destination_airport_icao_code' is required")
tmpFlight = flight_info(urlPath[1])
tmpFlight.origin['icao_code'] = urlPath[2]
tmpFlight.destination['icao_code'] = urlPath[3]
flight_deleteResponse = tmpFlight.delete()
if flight_deleteResponse['status'] == ENUM_RESULT.SUCCESS:
responseHandler(requestHandler, 204)
return
if flight_deleteResponse['status'] == ENUM_RESULT.UNEXPECTED_RESULT:
raise HTTPErrorResponse(status=400, message=flight_deleteResponse['message'])
if flight_deleteResponse['status'] == ENUM_RESULT.NOT_FOUND:
responseHandler(requestHandler, 404)
return
if flight_deleteResponse['status'] == ENUM_RESULT.SUCCESS_NOT_MODIFIED:
raise HTTPErrorResponse(status=409, message=flight_deleteResponse['message'])
if flight_deleteResponse['status'] == ENUM_RESULT.UNKNOWN_FAILURE:
raise HTTPErrorResponse(status=500, message=flight_deleteResponse['message'])
#Default
logger.debug("Unhandled response in flight_info_delete")
raise HTTPErrorResponse()
def flight_info_conflicts_get(requestHandler):
tmpFlightInfo = flight_info(None)
getResult = tmpFlightInfo.get_conflicts()
#Ensure we have a result
if getResult == ENUM_RESULT.SUCCESS:
responseHandler(requestHandler, 200, body=tmpFlightInfo.conflicts())
return
if getResult == ENUM_RESULT.NOT_FOUND:
responseHandler(requestHandler, 404)
return
if getResult == ENUM_RESULT.UNEXPECTED_RESULT:
responseHandler(requestHandler, 409)
return
#Default
logger.debug("Unhandled response in flight_info_conflicts_get")
raise HTTPErrorResponse()
class sigKill(Exception):
pass
class RequestHandler(http.server.SimpleHTTPRequestHandler):
#Create a conversation tracker for this request
def __init__(self, request, client_address, server):
http.server.SimpleHTTPRequestHandler.__init__(self, request, client_address, server)
def log_message(self, format, *args):
#Quiet the logs
return
def do_PATCH(self):
try:
#Ensure the correct key was sent
authenticate(self)
#Get the operation requested by the user
urlPath = parseURL(self.path)
if urlPath[0] == "operator":
operator_patch(self, urlPath)
return
#All other requests get 405
responseHandler(self, 405)
except HTTPErrorResponse as ex:
responseHandler(self, ex.status, body={"error": ex.message})
except HTTPUnauthorizedResponse as ex:
responseHandler(self, ex.status)
except Exception as ex:
logger.error({"exception": ex})
responseHandler(self, 500, body={"error": "Unknown Error"})
def do_DELETE(self):
try:
#Ensure the correct key was sent
authenticate(self)
#Get the operation requested by the user
urlPath = parseURL(self.path)
if urlPath[0] == "operator":
operator_delete(self, urlPath)
return
if urlPath[0] == "flight":
flight_info_delete(self, urlPath)
return
if urlPath[0] == "operators_unknown":
operator_unknown_delete(self, urlPath)
return
#All other requests get 405
responseHandler(self, 405)
except HTTPErrorResponse as ex:
responseHandler(self, ex.status, body={"error": ex.message})
except HTTPUnauthorizedResponse as ex:
responseHandler(self, ex.status)
except Exception as ex:
logger.error({"exception": ex})
responseHandler(self, 500, body={"error": "Unknown Error"})
def do_POST(self):
try:
#Ensure the correct key was sent
authenticate(self)
#Get the operation requested by the user
urlPath = parseURL(self.path)
if urlPath[0] == "operator":
if len(urlPath) > 1:
raise HTTPErrorResponse(status=400, message="Airline designator should not be provided in path when performing POST")
operator_post(self)
return
if urlPath[0] == "flight":
if len(urlPath) > 1:
raise HTTPErrorResponse(status=400, message="Flight ident should not be provided in path when performing POST")
flight_info_post(self)
return
#All other requests get 405
responseHandler(self, 405)
except HTTPErrorResponse as ex:
responseHandler(self, ex.status, body={"error": ex.message})
except HTTPUnauthorizedResponse as ex:
responseHandler(self, ex.status)
except Exception as ex:
logger.error({"exception": ex})
responseHandler(self, 500, body={"error": "Unknown Error"})
def do_OPTIONS(self):
tmpHeaders = []
tmpHeader = {}
tmpHeader['key'] = 'Access-Control-Allow-Methods'
tmpHeader['value'] = "*"
tmpHeaders.append(tmpHeader)
tmpHeader = {}
tmpHeader['key'] = 'Access-Control-Allow-Headers'
tmpHeader['value'] = "*"
tmpHeaders.append(tmpHeader)
responseHandler(self, 200, headers=tmpHeaders)
def do_GET(self):
try:
#Get the operation requested by the user
urlPath = parseURL(self.path)
if urlPath[0] == "manage":
self.handleStaticFile(urlPath)
return
if urlPath[0] == "favicon.ico":
self.sendStaticFile("manage/favicon.ico")
return
#Ensure the correct key was sent
authenticate(self)
if urlPath[0] == "registration":
registration_get(self, urlPath)
return
if urlPath[0] == "operator":
operator_get(self, urlPath)
return
if urlPath[0] == "operators_unknown":
operator_unknown_get(self, urlPath)
return
if urlPath[0] == "flight" and urlPath[1] != "conflicts":
flight_info_get(self, urlPath)
return
if urlPath[0] == "flight" and urlPath[1] == "conflicts":
flight_info_conflicts_get(self)
return
#All other requests get 404
responseHandler(self, 404)
except HTTPErrorResponse as ex:
responseHandler(self, ex.status, body={"error": ex.message})
except HTTPUnauthorizedResponse as ex:
responseHandler(self, ex.status)
except Exception as ex:
logger.error({"exception": ex})
responseHandler(self, 500, body={"error": "Unknown Error"})
def sendStaticFile(self, fileName):
rootDirectory = os.path.dirname(os.path.realpath(__file__))
fileName = os.path.join(rootDirectory,fileName)
if os.path.exists(fileName) == False:
responseHandler(self, 404)
return
if os.path.isfile(fileName) == False:
if os.path.exists(os.path.join(fileName, "index.html")):
fileName = os.path.join(fileName, "index.html")
else:
responseHandler(self, 404)
return
data = None
contentType = None
with open(fileName, "rb") as f:
contentType = self.getContentType(fileName)
data = f.read()
f.close()
responseHandler(self, 200, body=data, contentType=contentType)
def handleStaticFile(self, fileName:list):
if "common.js" in fileName:
self.sendStaticFile("manage/common.js")
return
if "common.html" in fileName:
self.sendStaticFile("manage/common.html")
return
strFileName = ""
for entry in fileName:
strFileName = os.path.join(strFileName, entry)
self.sendStaticFile(strFileName)
def getContentType(self, fileName:str):
if fileName.endswith(".html"):
return "text/html"
if fileName.endswith(".ico"):
return "image/x-icon"
if fileName.endswith(".js"):
return "text/javascript"
return None
class HTTPErrorResponse(Exception):
#Custom error message wrapper
def __init__(self, status=500, message="Unknown Error"):
self.status = status
self.message = message
super().__init__(self.status, self.message)
class HTTPUnauthorizedResponse(Exception):
#Custom unauthorized message wrapper
def __init__(self, status=401):
self.status = status
super().__init__(self.status)
class flight_info():
def __init__(self, ident, focus_airport_icao_code = None):
self.ident = ""
self.airline_designator = ""
self.flight_number = ""
self.origin = {}
self.destination = {}
self.expires = None
self.source = ""
self.hash = ""
self.focus_airport_icao_code = focus_airport_icao_code
self.ident = ident
self._conflicts = []
class conflict():
def __init__(self):
self.ident = ""
self.airline_designator = ""
self.flight_number = ""
self.source = ""
self.expires = ""
self.origin = {}
self.destination = {}
def get(self):
operatorsDb = mysql.connector.connect(
host=settings['mySQL']['uri'],
user=settings['mySQL']['username'],
password=settings['mySQL']['password'],
database=settings['mySQL']['database'])
mysqlCur = operatorsDb.cursor(dictionary=True)
sqlQuery = "SELECT "\
"flight_numbers.airline_designator, "\
"flight_numbers.flight_number, "\
"flight_numbers.expires, "\
"origin_airport.icao_code AS origin_airport_icao_code, "\
"origin_airport.name AS origin_airport_name, "\
"origin_airport.city AS origin_airport_city, "\
"origin_airport.region AS origin_airport_region, "\
"origin_airport.country AS origin_airport_country, "\
"origin_airport.phonic AS origin_airport_phonic, "\
"destination_airport.icao_code AS destination_airport_icao_code, "\
"destination_airport.name AS destination_airport_name, "\
"destination_airport.city AS destination_airport_city, "\
"destination_airport.region AS destination_airport_region, "\
"destination_airport.country AS destination_airport_country, "\
"destination_airport.phonic AS destination_airport_phonic, "\
"flight_numbers.hash, "\
"sources.agency AS source "\
"FROM flight_numbers "\
"LEFT OUTER JOIN airports AS origin_airport ON origin_airport.icao_code = flight_numbers.origin "\
"LEFT OUTER JOIN airports AS destination_airport ON destination_airport.icao_code = flight_numbers.destination "\
"LEFT OUTER JOIN sources ON sources.unique_id = flight_numbers.source "\
"WHERE "\
"flight_numbers.expires >= now() AND "\
"flight_numbers.ident='" + self.ident + "'"
if self.focus_airport_icao_code is not None:
sqlQuery = sqlQuery + " AND (origin_airport.icao_code = '" + self.focus_airport_icao_code + "' OR destination_airport.icao_code = '" + self.focus_airport_icao_code + "')"
mysqlCur.execute(sqlQuery)
result = mysqlCur.fetchall()
mysqlCur.close()
operatorsDb.close()
#Ensure we have have exactly 1 row
if len(result) == 1:
self.airline_designator = result[0]['airline_designator']
self.flight_number = result[0]['flight_number']
self.expires = result[0]['expires']
self.origin['icao_code'] = result[0]['origin_airport_icao_code']
self.origin['name'] = result[0]['origin_airport_name']
self.origin['city'] = result[0]['origin_airport_city']
self.origin['region'] = result[0]['origin_airport_region']
self.origin['country'] = result[0]['origin_airport_country']
self.origin['phonic'] = result[0]['origin_airport_phonic']
self.destination['icao_code'] = result[0]['destination_airport_icao_code']
self.destination['name'] = result[0]['destination_airport_name']
self.destination['city'] = result[0]['destination_airport_city']
self.destination['region'] = result[0]['destination_airport_region']
self.destination['country'] = result[0]['destination_airport_country']
self.destination['phonic'] = result[0]['destination_airport_phonic']
self.source = result[0]['source']
self.hash = result[0]['hash']
return ENUM_RESULT.SUCCESS
if len(result) == 0:
return ENUM_RESULT.NOT_FOUND
if len(result) > 1:
logger.warning("Retrieved " + str(len(result)) + " records from MySQL when querying " + json.dumps(self.__dict__, default=str) + ". Expected 0 or 1.")
return ENUM_RESULT.UNEXPECTED_RESULT
#Return unknown failure
return {"status" : ENUM_RESULT.UNKNOWN_FAILURE}
def post(self):
try:
returnValue = {
"status" : ENUM_RESULT.UNKNOWN_FAILURE,
"message" : ""
}
if self.ident.strip() == "":
return {"status" : ENUM_RESULT.INVALID_REQUEST, "message" : "ident is empty"}
if self.airline_designator.strip() == "":
return {"status" : ENUM_RESULT.INVALID_REQUEST, "message" : "airline_designator is empty"}
if self.flight_number.strip() == "":
return {"status" : ENUM_RESULT.INVALID_REQUEST, "message" : "flight_number is empty"}
if "icao_code" not in self.origin:
return {"status" : ENUM_RESULT.INVALID_REQUEST, "message" : "origin icao_code is missing"}
if self.origin['icao_code'].strip() == "":
return {"status" : ENUM_RESULT.INVALID_REQUEST, "message" : "origin icao_code is empty"}
if "icao_code" not in self.destination:
return {"status" : ENUM_RESULT.INVALID_REQUEST, "message" : "destination icao_code is missing"}
if self.destination['icao_code'].strip() == "":
return {"status" : ENUM_RESULT.INVALID_REQUEST, "message" : "destination icao_code is empty"}
if self.source.strip() == "":
return {"status" : ENUM_RESULT.INVALID_REQUEST, "message" : "source is empty"}
#If no expiration is provided, default to 30 days
if self.expires == None:
self.expires = datetime.now() + timedelta(days=30)
self.ident = self.ident.strip().upper()
self.airline_designator = self.airline_designator.strip().upper()
self.flight_number = self.flight_number.strip().upper()
self.origin['icao_code'] = self.origin['icao_code'].strip().upper()
self.destination['icao_code'] = self.destination['icao_code'].strip().upper()
self.source = self.source.strip()
self.compute_hash()
operatorsDb = mysql.connector.connect(
host=settings['mySQL']['uri'],
user=settings['mySQL']['username'],
password=settings['mySQL']['password'],
database=settings['mySQL']['database'])
mysqlCur = operatorsDb.cursor()
#Ensure the source exists
mysqlCur.execute("INSERT INTO sources (agency) \
SELECT * FROM (SELECT '" + self.source + "') AS tmp \
WHERE NOT EXISTS ( \
SELECT agency FROM sources WHERE agency = '" + self.source + "' \