app.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  1. #!/usr/bin/env python
  2. import json
  3. import os
  4. from subprocess import Popen, PIPE
  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/admin/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. child = Popen(cmd, stdout=PIPE, stderr=PIPE)
  53. stdout, _ = child.communicate()
  54. if 0 != child.returncode:
  55. return Response('{}', status=404, mimetype='application/json')
  56. keys = stdout.splitlines()
  57. server = keys[0].decode('ascii')
  58. public = keys[1].decode('ascii')
  59. private = keys[2].decode('ascii')
  60. dictionary = {
  61. 'server' : server,
  62. 'public' : public,
  63. 'private' : private,
  64. }
  65. data = json.dumps(dictionary, ensure_ascii=True)
  66. return Response(data, status=200, mimetype='application/json')
  67. @app.route('/aman/configuration/<icao>')
  68. @cross_origin()
  69. def configuration(icao):
  70. airport = aman.findAirport(icao.upper())
  71. if None == airport:
  72. return Response('{}', status=404, mimetype='application/json')
  73. config = airport.SequencingConfiguration
  74. dependencies = []
  75. for dependency in config.RunwayDependencies:
  76. rwy0 = config.runway(dependency[0])
  77. rwy1 = config.runway(dependency[1])
  78. cand1 = [ rwy0.Name, rwy1.Name ]
  79. cand2 = [ rwy1.Name, rwy0.Name ]
  80. found = False
  81. for dep in dependencies:
  82. if cand1 == dep or cand2 == dep:
  83. found = True
  84. break
  85. if False == found:
  86. dependencies.append(cand1)
  87. runways = airport.Configuration.GngData.Runways[airport.Icao];
  88. availableRunways = [];
  89. for runway in runways:
  90. availableRunways.append(runway.Name);
  91. dictionary = {
  92. 'airport' : airport.Icao,
  93. 'useShallShouldMay' : config.UseShallShouldMay,
  94. 'availableRunways' : availableRunways,
  95. 'activeRunways' : config.ActiveArrivalRunways,
  96. 'dependentRunways' : dependencies
  97. }
  98. data = json.dumps(dictionary, ensure_ascii=True, cls=RunwaySequencingEncoder)
  99. return Response(data, status=200, mimetype='application/json')
  100. @app.route('/aman/sequence/<icao>')
  101. @cross_origin()
  102. def sequence(icao):
  103. airport = aman.findAirport(icao.upper())
  104. if None == airport:
  105. return Response('{}', status=404, mimetype='application/json')
  106. # convert the timestamp
  107. stamp = str(airport.SequencingConfiguration.LastUpdateTimestamp)
  108. delimiter = stamp.find('.')
  109. if -1 == delimiter:
  110. delimiter = stamp.find('+')
  111. dictionary = {
  112. 'airport': airport.Icao,
  113. 'lastConfigurationUpdate': stamp[0:delimiter],
  114. 'sequence': airport.inboundSequence()
  115. }
  116. data = json.dumps(dictionary, ensure_ascii=True, cls=InboundEncoder)
  117. return Response(data, status=200, mimetype='application/json')
  118. @app.route('/aman/configure', methods=['POST'])
  119. @cross_origin()
  120. def configure():
  121. data = request.get_json()
  122. # validate that the airport exists
  123. if 'airport' not in data:
  124. return Response('{}', status=404, mimetype='application/json')
  125. airport = aman.findAirport(data['airport'].upper())
  126. if None == airport:
  127. return Response('{}', status=404, mimetype='application/json')
  128. # check that all top-level information are available
  129. if 'useShallShouldMay' not in data or 'activeRunways' not in data or 'dependentRunways' not in data:
  130. return Response('{}', status=404, mimetype='application/json')
  131. if False == isinstance(data['useShallShouldMay'], bool) or 0 == len(data['activeRunways']):
  132. return Response('{}', status=404, mimetype='application/json')
  133. # create the toplevel information
  134. config = AirportSequencing(airport.Icao)
  135. config.Airport = data['airport'].upper()
  136. config.UseShallShouldMay = data['useShallShouldMay']
  137. # parse the active runways
  138. for activeRunway in data['activeRunways']:
  139. if 'runway' not in activeRunway or 'spacing' not in activeRunway:
  140. return Response('{}', status=404, mimetype='application/json')
  141. if False == isinstance(activeRunway['runway'], str) or False == isinstance(activeRunway['spacing'], int):
  142. return Response('{}', status=404, mimetype='application/json')
  143. gngRunway = None
  144. for runway in airport.Configuration.GngData.Runways[airport.Icao]:
  145. if runway.Name == activeRunway['runway']:
  146. gngRunway = runway
  147. break
  148. # could not find the runway
  149. if None == gngRunway:
  150. return None
  151. runway = RunwaySequencing(gngRunway)
  152. runway.Spacing = activeRunway['spacing']
  153. config.activateRunway(runway)
  154. # parse the dependent runways
  155. for dependency in data['dependentRunways']:
  156. if 2 != len(dependency) or False == isinstance(dependency[0], str) or False == isinstance(dependency[1], str):
  157. return Response('{}', status=404, mimetype='application/json')
  158. if False == config.addDependency(dependency[0], dependency[1]):
  159. return Response('{}', status=404, mimetype='application/json')
  160. airport.Configuration.assignmentUpdate(config)
  161. airport.configure(config)
  162. return Response('{}', status=200, mimetype='application/json')