app.py 7.7 KB

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