app.py 7.8 KB

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