app.py 7.9 KB

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