app.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  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. # get all IAFs of the airport
  108. iafs = []
  109. for runway in airport.Configuration.GngData.ArrivalRoutes:
  110. for route in airport.Configuration.GngData.ArrivalRoutes[runway]:
  111. found = False
  112. for iaf in iafs:
  113. if iaf['name'] == route.Iaf.Name:
  114. found = True
  115. break
  116. if False == found:
  117. iafs.append({ 'name' : route.Iaf.Name, 'lat' : route.Iaf.Coordinate[0], 'lon' : route.Iaf.Coordinate[1] })
  118. dictionary = {
  119. 'airport' : airport.Icao,
  120. 'useShallShouldMay' : config.UseShallShouldMay,
  121. 'availableRunways' : availableRunways,
  122. 'activeRunways' : config.ActiveArrivalRunways,
  123. 'dependentRunways' : dependencies,
  124. 'iafColorization' : airport.Configuration.IafColorization,
  125. 'iafs' : iafs
  126. }
  127. data = json.dumps(dictionary, ensure_ascii=True, cls=RunwaySequencingEncoder)
  128. return Response(data, status=200, mimetype='application/json')
  129. @app.route('/aman/sequence/<icao>')
  130. @cross_origin()
  131. def sequence(icao):
  132. airport = aman.findAirport(icao.upper())
  133. if None == airport:
  134. return Response('{}', status=404, mimetype='application/json')
  135. # convert the timestamp
  136. stamp = str(airport.SequencingConfiguration.LastUpdateTimestamp)
  137. delimiter = stamp.find('.')
  138. if -1 == delimiter:
  139. delimiter = stamp.find('+')
  140. dictionary = {
  141. 'airport': airport.Icao,
  142. 'lastConfigurationUpdate': stamp[0:delimiter],
  143. 'sequence': airport.inboundSequence()
  144. }
  145. data = json.dumps(dictionary, ensure_ascii=True, cls=InboundEncoder)
  146. return Response(data, status=200, mimetype='application/json')
  147. @app.route('/aman/configure', methods=['POST'])
  148. @cross_origin()
  149. def configure():
  150. data = request.get_json()
  151. # validate that the airport exists
  152. if 'airport' not in data:
  153. return Response('{}', status=404, mimetype='application/json')
  154. airport = aman.findAirport(data['airport'].upper())
  155. if None == airport:
  156. return Response('{}', status=404, mimetype='application/json')
  157. # check that all top-level information are available
  158. if 'useShallShouldMay' not in data or 'activeRunways' not in data or 'dependentRunways' not in data:
  159. return Response('{}', status=404, mimetype='application/json')
  160. if False == isinstance(data['useShallShouldMay'], bool) or 0 == len(data['activeRunways']):
  161. return Response('{}', status=404, mimetype='application/json')
  162. # create the toplevel information
  163. config = AirportSequencing(airport.Icao)
  164. config.Airport = data['airport'].upper()
  165. config.UseShallShouldMay = data['useShallShouldMay']
  166. # parse the active runways
  167. for activeRunway in data['activeRunways']:
  168. if 'runway' not in activeRunway or 'spacing' not in activeRunway:
  169. return Response('{}', status=404, mimetype='application/json')
  170. if False == isinstance(activeRunway['runway'], str) or False == isinstance(activeRunway['spacing'], int):
  171. return Response('{}', status=404, mimetype='application/json')
  172. gngRunway = None
  173. for runway in airport.Configuration.GngData.Runways[airport.Icao]:
  174. if runway.Name == activeRunway['runway']:
  175. gngRunway = runway
  176. break
  177. # could not find the runway
  178. if None == gngRunway:
  179. return None
  180. runway = RunwaySequencing(gngRunway)
  181. runway.Spacing = activeRunway['spacing']
  182. config.activateRunway(runway)
  183. # parse the dependent runways
  184. for dependency in data['dependentRunways']:
  185. if 2 != len(dependency) or False == isinstance(dependency[0], str) or False == isinstance(dependency[1], str):
  186. return Response('{}', status=404, mimetype='application/json')
  187. if False == config.addDependency(dependency[0], dependency[1]):
  188. return Response('{}', status=404, mimetype='application/json')
  189. airport.Configuration.assignmentUpdate(config)
  190. airport.configure(config)
  191. return Response('{}', status=200, mimetype='application/json')