app.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. #!/usr/bin/env python
  2. import json
  3. import os
  4. import subprocess
  5. from flask import Flask, Response, request
  6. from flask_cors import CORS, cross_origin
  7. from json import JSONEncoder
  8. from aman.AMAN import AMAN
  9. from aman.config.AirportSequencing import AirportSequencing
  10. from aman.config.RunwaySequencing import RunwaySequencing
  11. class InboundEncoder(JSONEncoder):
  12. def default(self, o):
  13. pta = str(o.PlannedArrivalTime)
  14. delimiter = pta.find('.')
  15. if -1 == delimiter:
  16. delimiter = pta.find('+')
  17. return { 'callsign' : o.Callsign, 'fixed' : o.FixedSequence, 'runway' : o.PlannedRunway.Name, 'pta' : pta[0:delimiter] }
  18. class RunwaySequencingEncoder(JSONEncoder):
  19. def default(self, o):
  20. return { 'runway' : o.Runway.Name, 'spacing' : o.Spacing }
  21. # initialize the environment variables
  22. if 'AMAN_PATH' not in os.environ:
  23. os.environ['AMAN_PATH'] = 'C:\\Repositories\VATSIM\\AMAN\\aman-sys\\aman'
  24. if 'AMAN_CONFIG_PATH' not in os.environ:
  25. os.environ['AMAN_CONFIG_PATH'] = 'C:\\Repositories\\VATSIM\\AMAN\\config'
  26. # initialize the AMAN and the interface version
  27. aman = AMAN()
  28. version = '0.0.0'
  29. with open(os.path.join(os.environ['AMAN_PATH'], 'VERSION')) as file:
  30. version = file.readline()
  31. # initialize the web services
  32. app = Flask('AMAN')
  33. cors = CORS(app)
  34. app.config['CORS_HEADERS'] = 'Content-Type'
  35. if __name__ == '__main__':
  36. app.run()
  37. @app.route('/aman/airports')
  38. @cross_origin()
  39. def airports():
  40. # get the airports
  41. retval = []
  42. for airport in aman.Workers:
  43. retval.append(airport.Icao)
  44. data = json.dumps({ 'version' : version, 'airports' : retval }, ensure_ascii=True)
  45. return Response(data, status=200, mimetype='application/json')
  46. @app.route('/aman/newuser')
  47. def newUser():
  48. toolpath = os.path.join(os.path.join(os.environ['AMAN_PATH'], 'tools'), 'KeyPairCreator.py')
  49. serverKeypath = os.path.join(os.path.join(os.path.join(AMAN.findConfigPath(), 'keys'), 'server'), 'server.key')
  50. clientKeypath = os.path.join(os.path.join(AMAN.findConfigPath(), 'keys'), 'clients')
  51. cmd = ['python', toolpath, '--directory=' + clientKeypath, '--publickey=' + serverKeypath]
  52. stdout = subprocess.check_output(cmd)
  53. keys = stdout.splitlines()
  54. server = keys[0].decode('ascii')
  55. public = keys[1].decode('ascii')
  56. private = keys[2].decode('ascii')
  57. dictionary = {
  58. 'server' : server,
  59. 'public' : public,
  60. 'private' : private,
  61. }
  62. data = json.dumps(dictionary, ensure_ascii=True)
  63. return Response(data, status=200, mimetype='application/json')
  64. @app.route('/aman/configuration/<icao>')
  65. @cross_origin()
  66. def configuration(icao):
  67. airport = aman.findAirport(icao.upper())
  68. if None == airport:
  69. return Response('{}', status=404, mimetype='application/json')
  70. config = airport.SequencingConfiguration
  71. dependencies = []
  72. for dependency in config.RunwayDependencies:
  73. rwy0 = config.runway(dependency[0])
  74. rwy1 = config.runway(dependency[1])
  75. cand1 = [ rwy0.Name, rwy1.Name ]
  76. cand2 = [ rwy1.Name, rwy0.Name ]
  77. found = False
  78. for dep in dependencies:
  79. if cand1 == dep or cand2 == dep:
  80. found = True
  81. break
  82. if False == found:
  83. dependencies.append(cand1)
  84. dictionary = {
  85. 'airport' : airport.Icao,
  86. 'useShallShouldMay' : config.UseShallShouldMay,
  87. 'activeRunways' : config.ActiveArrivalRunways,
  88. 'dependentRunways' : dependencies
  89. }
  90. data = json.dumps(dictionary, ensure_ascii=True, cls=RunwaySequencingEncoder)
  91. return Response(data, status=200, mimetype='application/json')
  92. @app.route('/aman/sequence/<icao>')
  93. @cross_origin()
  94. def sequence(icao):
  95. airport = aman.findAirport(icao.upper())
  96. if None == airport:
  97. return Response('{}', status=404, mimetype='application/json')
  98. # convert the timestamp
  99. stamp = str(airport.SequencingConfiguration.LastUpdateTimestamp)
  100. delimiter = stamp.find('.')
  101. if -1 == delimiter:
  102. delimiter = stamp.find('+')
  103. dictionary = {
  104. 'airport': airport.Icao,
  105. 'lastConfigurationUpdate': stamp[0:delimiter],
  106. 'sequence': airport.inboundSequence()
  107. }
  108. data = json.dumps(dictionary, ensure_ascii=True, cls=InboundEncoder)
  109. return Response(data, status=200, mimetype='application/json')
  110. @app.route('/aman/configure', methods=['POST'])
  111. @cross_origin()
  112. def configure():
  113. data = request.get_json()
  114. # validate that the airport exists
  115. if 'airport' not in data:
  116. return Response('{}', status=404, mimetype='application/json')
  117. airport = aman.findAirport(data['airport'].upper())
  118. if None == airport:
  119. return Response('{}', status=404, mimetype='application/json')
  120. # check that all top-level information are available
  121. if 'useShallShouldMay' not in data or 'activeRunways' not in data or 'dependentRunways' not in data:
  122. return Response('{}', status=404, mimetype='application/json')
  123. if False == isinstance(data['useShallShouldMay'], bool) or 0 == len(data['activeRunways']):
  124. return Response('{}', status=404, mimetype='application/json')
  125. # create the toplevel information
  126. config = AirportSequencing(airport.Icao)
  127. config.Airport = data['airport'].upper()
  128. config.UseShallShouldMay = data['useShallShouldMay']
  129. # parse the active runways
  130. for activeRunway in data['activeRunways']:
  131. if 'runway' not in activeRunway or 'spacing' not in activeRunway:
  132. return Response('{}', status=404, mimetype='application/json')
  133. if False == isinstance(activeRunway['runway'], str) or False == isinstance(activeRunway['spacing'], int):
  134. return Response('{}', status=404, mimetype='application/json')
  135. gngRunway = None
  136. for runway in airport.Configuration.GngData.Runways[airport.Icao]:
  137. if runway.Name == activeRunway['runway']:
  138. gngRunway = runway
  139. break
  140. # could not find the runway
  141. if None == gngRunway:
  142. return None
  143. runway = RunwaySequencing(gngRunway)
  144. runway.Spacing = activeRunway['spacing']
  145. config.activateRunway(runway)
  146. # parse the dependent runways
  147. for dependency in data['dependentRunways']:
  148. if 2 != len(dependency) or False == isinstance(dependency[0], str) or False == isinstance(dependency[1], str):
  149. return Response('{}', status=404, mimetype='application/json')
  150. if False == config.addDependency(dependency[0], dependency[1]):
  151. return Response('{}', status=404, mimetype='application/json')
  152. airport.Configuration.assignmentUpdate(config)
  153. airport.configure(config)
  154. return Response('{}', status=200, mimetype='application/json')