app.py 7.3 KB

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