app.py 7.4 KB

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