app.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  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. runways = airport.Configuration.GngData.Runways[airport.Icao];
  85. availableRunways = [];
  86. for runway in runways:
  87. availableRunways.append(runway.Name);
  88. dictionary = {
  89. 'airport' : airport.Icao,
  90. 'useShallShouldMay' : config.UseShallShouldMay,
  91. 'availableRunways' : availableRunways,
  92. 'activeRunways' : config.ActiveArrivalRunways,
  93. 'dependentRunways' : dependencies
  94. }
  95. data = json.dumps(dictionary, ensure_ascii=True, cls=RunwaySequencingEncoder)
  96. return Response(data, status=200, mimetype='application/json')
  97. @app.route('/aman/sequence/<icao>')
  98. @cross_origin()
  99. def sequence(icao):
  100. airport = aman.findAirport(icao.upper())
  101. if None == airport:
  102. return Response('{}', status=404, mimetype='application/json')
  103. # convert the timestamp
  104. stamp = str(airport.SequencingConfiguration.LastUpdateTimestamp)
  105. delimiter = stamp.find('.')
  106. if -1 == delimiter:
  107. delimiter = stamp.find('+')
  108. dictionary = {
  109. 'airport': airport.Icao,
  110. 'lastConfigurationUpdate': stamp[0:delimiter],
  111. 'sequence': airport.inboundSequence()
  112. }
  113. data = json.dumps(dictionary, ensure_ascii=True, cls=InboundEncoder)
  114. return Response(data, status=200, mimetype='application/json')
  115. @app.route('/aman/configure', methods=['POST'])
  116. @cross_origin()
  117. def configure():
  118. data = request.get_json()
  119. # validate that the airport exists
  120. if 'airport' not in data:
  121. return Response('{}', status=404, mimetype='application/json')
  122. airport = aman.findAirport(data['airport'].upper())
  123. if None == airport:
  124. return Response('{}', status=404, mimetype='application/json')
  125. # check that all top-level information are available
  126. if 'useShallShouldMay' not in data or 'activeRunways' not in data or 'dependentRunways' not in data:
  127. return Response('{}', status=404, mimetype='application/json')
  128. if False == isinstance(data['useShallShouldMay'], bool) or 0 == len(data['activeRunways']):
  129. return Response('{}', status=404, mimetype='application/json')
  130. # create the toplevel information
  131. config = AirportSequencing(airport.Icao)
  132. config.Airport = data['airport'].upper()
  133. config.UseShallShouldMay = data['useShallShouldMay']
  134. # parse the active runways
  135. for activeRunway in data['activeRunways']:
  136. if 'runway' not in activeRunway or 'spacing' not in activeRunway:
  137. return Response('{}', status=404, mimetype='application/json')
  138. if False == isinstance(activeRunway['runway'], str) or False == isinstance(activeRunway['spacing'], int):
  139. return Response('{}', status=404, mimetype='application/json')
  140. gngRunway = None
  141. for runway in airport.Configuration.GngData.Runways[airport.Icao]:
  142. if runway.Name == activeRunway['runway']:
  143. gngRunway = runway
  144. break
  145. # could not find the runway
  146. if None == gngRunway:
  147. return None
  148. runway = RunwaySequencing(gngRunway)
  149. runway.Spacing = activeRunway['spacing']
  150. config.activateRunway(runway)
  151. # parse the dependent runways
  152. for dependency in data['dependentRunways']:
  153. if 2 != len(dependency) or False == isinstance(dependency[0], str) or False == isinstance(dependency[1], str):
  154. return Response('{}', status=404, mimetype='application/json')
  155. if False == config.addDependency(dependency[0], dependency[1]):
  156. return Response('{}', status=404, mimetype='application/json')
  157. airport.Configuration.assignmentUpdate(config)
  158. airport.configure(config)
  159. return Response('{}', status=200, mimetype='application/json')