1 |
|
---|
2 | from . import const
|
---|
3 | from . import util
|
---|
4 | from .rpc import Registration, BookedFlight
|
---|
5 | from . import rpc
|
---|
6 | from . import rpccommon
|
---|
7 |
|
---|
8 | from .common import MAVA_BASE_URL
|
---|
9 | from .pirep import PIREP
|
---|
10 |
|
---|
11 | import threading
|
---|
12 | import sys
|
---|
13 | import urllib.request, urllib.parse, urllib.error
|
---|
14 | import urllib.request, urllib.error, urllib.parse
|
---|
15 | import hashlib
|
---|
16 | import time
|
---|
17 | import re
|
---|
18 | import datetime
|
---|
19 | import codecs
|
---|
20 | import traceback
|
---|
21 | import xml.sax
|
---|
22 | import xmlrpc.client
|
---|
23 | import html.parser
|
---|
24 | import certifi
|
---|
25 |
|
---|
26 | #---------------------------------------------------------------------------------------
|
---|
27 |
|
---|
28 | ## @package mlx.web
|
---|
29 | #
|
---|
30 | # Web interface.
|
---|
31 | #
|
---|
32 | # This module implements a thread that can perform (HTTP) requests
|
---|
33 | # asynchronously. When the request is performed, a callback is called. The main
|
---|
34 | # interface is the \ref Handler class. Each of its functions creates a \ref
|
---|
35 | # Request subclass instance and puts it to the request queue. The handler
|
---|
36 | # thread then takes the requests one by one, and executes them.
|
---|
37 | #
|
---|
38 | # This module also defines some data classes the contents of which are
|
---|
39 | # retrieved or sent via HTTP. \ref Fleet and \ref Plane represents the MAVA
|
---|
40 | # fleet and the gates at Ferihegy and \ref NOTAM is a NOTAM.
|
---|
41 |
|
---|
42 | #---------------------------------------------------------------------------------------
|
---|
43 |
|
---|
44 | def readline(f):
|
---|
45 | """Read a line from the given file.
|
---|
46 |
|
---|
47 | The line is stripped and empty lines are discarded."""
|
---|
48 | while True:
|
---|
49 | line = f.readline()
|
---|
50 | if not line: return ""
|
---|
51 | line = line.strip()
|
---|
52 | if line:
|
---|
53 | return line
|
---|
54 |
|
---|
55 | #------------------------------------------------------------------------------
|
---|
56 |
|
---|
57 | class Plane(rpccommon.Plane):
|
---|
58 | """Information about an airplane in the fleet."""
|
---|
59 | def __init__(self, s):
|
---|
60 | """Build a plane info based on the given string.
|
---|
61 |
|
---|
62 | The string consists of three, space-separated fields.
|
---|
63 | The first field is the tail number, the second field is the gate
|
---|
64 | number, the third field is the plane's status as a character."""
|
---|
65 | super(Plane, self).__init__()
|
---|
66 |
|
---|
67 | try:
|
---|
68 | words = s.split(" ")
|
---|
69 | tailNumber = words[0]
|
---|
70 | self.tailNumber = tailNumber
|
---|
71 |
|
---|
72 | status = words[2] if len(words)>2 else None
|
---|
73 | self._setStatus(status)
|
---|
74 |
|
---|
75 | gateNumber = words[1] if len(words)>1 else ""
|
---|
76 | self.gateNumber = gateNumber if gateNumber else None
|
---|
77 |
|
---|
78 | except:
|
---|
79 | print("Plane string is invalid: '" + s + "'", file=sys.stderr)
|
---|
80 | self.tailNumber = None
|
---|
81 |
|
---|
82 | #------------------------------------------------------------------------------
|
---|
83 |
|
---|
84 | class Fleet(rpccommon.Fleet):
|
---|
85 | """Information about the whole fleet."""
|
---|
86 | def __init__(self, f):
|
---|
87 | """Construct the fleet information by reading the given file object."""
|
---|
88 | super(Fleet, self).__init__()
|
---|
89 |
|
---|
90 | while True:
|
---|
91 | line = readline(f)
|
---|
92 | if not line or line == "#END": break
|
---|
93 |
|
---|
94 | plane = Plane(line)
|
---|
95 | self._addPlane(plane)
|
---|
96 |
|
---|
97 | #------------------------------------------------------------------------------
|
---|
98 |
|
---|
99 | class NOTAM(object):
|
---|
100 | """A NOTAM for an airport."""
|
---|
101 | def __init__(self, ident, basic,
|
---|
102 | begin, notice, end = None, permanent = False,
|
---|
103 | repeatCycle = None):
|
---|
104 | """Construct the NOTAM."""
|
---|
105 | self.ident = ident
|
---|
106 | self.basic = basic
|
---|
107 | self.begin = begin
|
---|
108 | self.notice = notice
|
---|
109 | self.end = end
|
---|
110 | self.permanent = permanent
|
---|
111 | self.repeatCycle = repeatCycle
|
---|
112 |
|
---|
113 | def __repr__(self):
|
---|
114 | """Get the representation of the NOTAM."""
|
---|
115 | s = "<NOTAM " + str(self.begin)
|
---|
116 | if self.end:
|
---|
117 | s += " - " + str(self.end)
|
---|
118 | elif self.permanent:
|
---|
119 | s += " - PERMANENT"
|
---|
120 | if self.repeatCycle:
|
---|
121 | s += " (" + self.repeatCycle + ")"
|
---|
122 | s += ": " + self.notice
|
---|
123 | s += ">"
|
---|
124 | return s
|
---|
125 |
|
---|
126 | def __str__(self):
|
---|
127 | """Get the string representation of the NOTAM."""
|
---|
128 | s = ""
|
---|
129 | s += str(self.ident) + " " + str(self.basic) + "\n"
|
---|
130 | s += str(self.begin)
|
---|
131 | if self.end is not None:
|
---|
132 | s += " - " + str(self.end)
|
---|
133 | elif self.permanent:
|
---|
134 | s += " - PERMANENT"
|
---|
135 | s += "\n"
|
---|
136 | if self.repeatCycle:
|
---|
137 | s += "Repeat cycle: " + self.repeatCycle + "\n"
|
---|
138 | s += self.notice + "\n"
|
---|
139 | return s
|
---|
140 |
|
---|
141 | #------------------------------------------------------------------------------
|
---|
142 |
|
---|
143 | class NOTAMHandler(xml.sax.handler.ContentHandler):
|
---|
144 | """A handler for the NOTAM database."""
|
---|
145 | def __init__(self, airportICAOs):
|
---|
146 | """Construct the handler for the airports with the given ICAO code."""
|
---|
147 | self._notams = {}
|
---|
148 | for icao in airportICAOs:
|
---|
149 | self._notams[icao] = []
|
---|
150 |
|
---|
151 | def startElement(self, name, attrs):
|
---|
152 | """Start an element."""
|
---|
153 | if name!="notam" or \
|
---|
154 | "ident" not in attrs or not attrs["ident"] or \
|
---|
155 | "Q" not in attrs or not attrs["Q"] or \
|
---|
156 | "A" not in attrs or not attrs["A"] or \
|
---|
157 | "B" not in attrs or not attrs["B"] or \
|
---|
158 | "E" not in attrs or not attrs["E"]:
|
---|
159 | return
|
---|
160 |
|
---|
161 | icao = attrs["A"]
|
---|
162 | if icao not in self._notams:
|
---|
163 | return
|
---|
164 |
|
---|
165 | begin = datetime.datetime.strptime(attrs["B"], "%Y-%m-%d %H:%M:%S")
|
---|
166 |
|
---|
167 | c = attrs["C"] if "C" in attrs else None
|
---|
168 | end = datetime.datetime.strptime(c, "%Y-%m-%d %H:%M:%S") if c else None
|
---|
169 |
|
---|
170 | permanent = attrs["C_flag"]=="PERM" if "C_flag" in attrs else False
|
---|
171 |
|
---|
172 | repeatCycle = attrs["D"] if "D" in attrs else None
|
---|
173 |
|
---|
174 | self._notams[icao].append(NOTAM(attrs["ident"], attrs["Q"],
|
---|
175 | begin, attrs["E"], end = end,
|
---|
176 | permanent = permanent,
|
---|
177 | repeatCycle = repeatCycle))
|
---|
178 |
|
---|
179 | def get(self, icao):
|
---|
180 | """Get the NOTAMs for the given ICAO code."""
|
---|
181 | return self._notams[icao] if icao in self._notams else []
|
---|
182 |
|
---|
183 | #------------------------------------------------------------------------------
|
---|
184 |
|
---|
185 | class PilotsWebNOTAMsParser(html.parser.HTMLParser):
|
---|
186 | """XML handler for the NOTAM query results on the PilotsWeb website."""
|
---|
187 | def __init__(self):
|
---|
188 | """Construct the handler."""
|
---|
189 | html.parser.HTMLParser.__init__(self)
|
---|
190 |
|
---|
191 | self._notams = []
|
---|
192 | self._currentNOTAM = ""
|
---|
193 | self._stage = 0
|
---|
194 |
|
---|
195 | def handle_starttag(self, name, attrs):
|
---|
196 | """Start an element."""
|
---|
197 | if (self._stage==0 and name=="div" and ("id", "notamRight") in attrs) or \
|
---|
198 | (self._stage==1 and name=="span") or \
|
---|
199 | (self._stage==2 and name=="pre"):
|
---|
200 | self._stage += 1
|
---|
201 | if self._stage==1:
|
---|
202 | self._currentNOTAM = ""
|
---|
203 |
|
---|
204 | def handle_data(self, content):
|
---|
205 | """Handle characters"""
|
---|
206 | if self._stage==3:
|
---|
207 | self._currentNOTAM += content
|
---|
208 |
|
---|
209 | def handle_endtag(self, name):
|
---|
210 | """End an element."""
|
---|
211 | if (self._stage==3 and name=="pre") or \
|
---|
212 | (self._stage==2 and name=="span") or \
|
---|
213 | (self._stage==1 and name=="div"):
|
---|
214 | self._stage -= 1
|
---|
215 | if self._stage==0:
|
---|
216 | self._processCurrentNOTAM()
|
---|
217 |
|
---|
218 | def getNOTAMs(self):
|
---|
219 | """Get the NOTAMs collected"""
|
---|
220 | return self._notams
|
---|
221 |
|
---|
222 | def _processCurrentNOTAM(self):
|
---|
223 | """Parse the current NOTAM and append its contents to the list of
|
---|
224 | NOTAMS."""
|
---|
225 | notam = None
|
---|
226 | try:
|
---|
227 | notam = self._parseCurrentNOTAM2()
|
---|
228 | except Exception as e:
|
---|
229 | print("Error parsing current NOTAM: " + str(e))
|
---|
230 |
|
---|
231 | if notam is None:
|
---|
232 | print("Could not parse NOTAM: " + self._currentNOTAM)
|
---|
233 | if self._currentNOTAM:
|
---|
234 | self._notams.append(self._currentNOTAM + "\n")
|
---|
235 | else:
|
---|
236 | self._notams.append(notam)
|
---|
237 |
|
---|
238 | def _parseCurrentNOTAM(self):
|
---|
239 | """Parse the current NOTAM, if possible, and return a NOTAM object."""
|
---|
240 | lines = self._currentNOTAM.splitlines()
|
---|
241 | lines = [line.strip() for line in lines]
|
---|
242 |
|
---|
243 | if len(lines)<4:
|
---|
244 | return None
|
---|
245 |
|
---|
246 | if not lines[1].startswith("Q)") or \
|
---|
247 | not lines[2].startswith("A)") or \
|
---|
248 | not (lines[3].startswith("E)") or
|
---|
249 | (lines[3].startswith("D)") and lines[4].startswith("E)"))):
|
---|
250 | return None
|
---|
251 |
|
---|
252 | ident = lines[0].split()[0]
|
---|
253 | basic = lines[1][2:].strip()
|
---|
254 |
|
---|
255 | words = lines[2].split()
|
---|
256 | if len(words)<4 or words[0]!="A)" or words[2]!="B)":
|
---|
257 | return None
|
---|
258 |
|
---|
259 | begin = datetime.datetime.strptime(words[3], "%y%m%d%H%M")
|
---|
260 | end = None
|
---|
261 | permanent = False
|
---|
262 | if words[4]=="C)" and len(words)>=6:
|
---|
263 | if words[5] in ["PERM", "UFN"]:
|
---|
264 | permanent = True
|
---|
265 | else:
|
---|
266 | end = datetime.datetime.strptime(words[5], "%y%m%d%H%M")
|
---|
267 | else:
|
---|
268 | permanent = True
|
---|
269 |
|
---|
270 | repeatCycle = None
|
---|
271 | noticeStartIndex = 3
|
---|
272 | if lines[3].startswith("D)"):
|
---|
273 | repeatCycle = lines[3][2:].strip()
|
---|
274 | noticeStartIndex = 4
|
---|
275 |
|
---|
276 | notice = ""
|
---|
277 | for index in range(noticeStartIndex, len(lines)):
|
---|
278 | line = lines[index][2:] if index==noticeStartIndex else lines[index]
|
---|
279 | line = line.strip()
|
---|
280 |
|
---|
281 | if line.lower().startswith("created:") or \
|
---|
282 | line.lower().startswith("source:"):
|
---|
283 | break
|
---|
284 |
|
---|
285 | if notice: notice += " "
|
---|
286 | notice += line
|
---|
287 |
|
---|
288 | return NOTAM(ident, basic, begin, notice, end = end,
|
---|
289 | permanent = permanent, repeatCycle = repeatCycle)
|
---|
290 |
|
---|
291 | def _parseCurrentNOTAM2(self):
|
---|
292 | """Parse the current NOTAM with a second, more flexible method."""
|
---|
293 | self._currentNOTAM = self._currentNOTAM.replace("\\n", "\n")
|
---|
294 | lines = self._currentNOTAM.splitlines()
|
---|
295 | if len(lines)==1:
|
---|
296 | lines = lines[0].splitlines()
|
---|
297 | lines = [line.strip() for line in lines]
|
---|
298 |
|
---|
299 | if not lines:
|
---|
300 | return None
|
---|
301 |
|
---|
302 | ident = lines[0].split()[0]
|
---|
303 |
|
---|
304 | lines = lines[1:]
|
---|
305 | for i in range(0, 2):
|
---|
306 | l = lines[-1].lower()
|
---|
307 | if l.startswith("created:") or l.startswith("source:"):
|
---|
308 | lines = lines[:-1]
|
---|
309 |
|
---|
310 | lines = [line.strip() for line in lines]
|
---|
311 | contents = " ".join(lines).split()
|
---|
312 |
|
---|
313 | items = {}
|
---|
314 | for i in ["Q)", "A)", "B)", "C)", "D)", "E)"]:
|
---|
315 | items[i] = ""
|
---|
316 |
|
---|
317 | currentItem = None
|
---|
318 | for word in contents:
|
---|
319 | if word in items:
|
---|
320 | currentItem = word
|
---|
321 | elif currentItem in items:
|
---|
322 | s = items[currentItem]
|
---|
323 | if s: s+= " "
|
---|
324 | s += word
|
---|
325 | items[currentItem] = s
|
---|
326 |
|
---|
327 | if not items["Q)"] or not items["A)"] or not items["B)"] or \
|
---|
328 | not items["E)"]:
|
---|
329 | return None
|
---|
330 |
|
---|
331 | def parseTime(item):
|
---|
332 | item = re.sub("([0-9]+).*", "\\1", item)
|
---|
333 | try:
|
---|
334 | return datetime.datetime.strptime(item, "%y%m%d%H%M")
|
---|
335 | except ValueError:
|
---|
336 | return datetime.datetime.strptime(item, "%Y%m%d%H%M")
|
---|
337 |
|
---|
338 | basic = items["Q)"]
|
---|
339 | begin = parseTime(items["B)"])
|
---|
340 |
|
---|
341 | end = None
|
---|
342 | permanent = False
|
---|
343 | if items["C)"]:
|
---|
344 | endItem = items["C)"]
|
---|
345 | if endItem in ["PERM", "UFN"]:
|
---|
346 | permanent = True
|
---|
347 | else:
|
---|
348 | end = parseTime(items["C)"])
|
---|
349 | else:
|
---|
350 | permanent = True
|
---|
351 |
|
---|
352 | repeatCycle = None
|
---|
353 | if items["D)"]:
|
---|
354 | repeatCycle = items["D)"]
|
---|
355 |
|
---|
356 | notice = items["E)"]
|
---|
357 |
|
---|
358 | return NOTAM(ident, basic, begin, notice, end = end,
|
---|
359 | permanent = permanent, repeatCycle = repeatCycle)
|
---|
360 |
|
---|
361 | #------------------------------------------------------------------------------
|
---|
362 |
|
---|
363 | class Result(object):
|
---|
364 | """A result object.
|
---|
365 |
|
---|
366 | An instance of this filled with the appropriate data is passed to the
|
---|
367 | callback function on each request."""
|
---|
368 |
|
---|
369 | def __repr__(self):
|
---|
370 | """Get a representation of the result."""
|
---|
371 | s = "<Result:"
|
---|
372 | for (key, value) in self.__dict__.items():
|
---|
373 | s += " " + key + "=" + str(value)
|
---|
374 | s += ">"
|
---|
375 | return s
|
---|
376 |
|
---|
377 | #------------------------------------------------------------------------------
|
---|
378 |
|
---|
379 | class Request(object):
|
---|
380 | """Base class for requests.
|
---|
381 |
|
---|
382 | It handles any exceptions and the calling of the callback.
|
---|
383 |
|
---|
384 | If an exception occurs during processing, the callback is called with
|
---|
385 | the two parameters: a boolean value of False, and the exception object.
|
---|
386 |
|
---|
387 | If no exception occurs, the callback is called with True and the return
|
---|
388 | value of the run() function.
|
---|
389 |
|
---|
390 | If the callback function throws an exception, that is caught and logged
|
---|
391 | to the debug log."""
|
---|
392 | def __init__(self, callback):
|
---|
393 | """Construct the request."""
|
---|
394 | self._callback = callback
|
---|
395 |
|
---|
396 | def perform(self):
|
---|
397 | """Perform the request.
|
---|
398 |
|
---|
399 | The object's run() function is called. If it throws an exception,
|
---|
400 | the callback is called with False, and the exception. Otherwise the
|
---|
401 | callback is called with True and the return value of the run()
|
---|
402 | function. Any exceptions thrown by the callback are caught and
|
---|
403 | reported."""
|
---|
404 | try:
|
---|
405 | result = self.run()
|
---|
406 | returned = True
|
---|
407 | except Exception as e:
|
---|
408 | traceback.print_exc()
|
---|
409 | result = e
|
---|
410 | returned = False
|
---|
411 |
|
---|
412 | try:
|
---|
413 | self._callback(returned, result)
|
---|
414 | except Exception as e:
|
---|
415 | print("web.Handler.Request.perform: callback throwed an exception: " + util.utf2unicode(str(e)), file=sys.stderr)
|
---|
416 | #traceback.print_exc()
|
---|
417 |
|
---|
418 | #------------------------------------------------------------------------------
|
---|
419 |
|
---|
420 | class RPCRequest(Request):
|
---|
421 | """Common base class for RPC requests.
|
---|
422 |
|
---|
423 | It stores the RPC client received from the handler."""
|
---|
424 | def __init__(self, client, callback):
|
---|
425 | """Construct the request."""
|
---|
426 | super(RPCRequest, self).__init__(callback)
|
---|
427 | self._client = client
|
---|
428 |
|
---|
429 | #------------------------------------------------------------------------------
|
---|
430 |
|
---|
431 | class Register(RPCRequest):
|
---|
432 | """A registration request."""
|
---|
433 | def __init__(self, client, callback, registrationData):
|
---|
434 | """Construct the request."""
|
---|
435 | super(Register, self).__init__(client, callback)
|
---|
436 | self._registrationData = registrationData
|
---|
437 |
|
---|
438 | def run(self):
|
---|
439 | """Perform the registration."""
|
---|
440 |
|
---|
441 | registrationData = self._registrationData
|
---|
442 |
|
---|
443 | (resultCode, pilotID) = self._client.register(registrationData)
|
---|
444 | result = Result()
|
---|
445 | result.registered = resultCode==rpc.Client.RESULT_OK
|
---|
446 | if result.registered:
|
---|
447 | result.pilotID = pilotID
|
---|
448 |
|
---|
449 | self._client.setCredentials(pilotID, registrationData.password)
|
---|
450 | LoginRPC.setupLoginResult(result, self._client, pilotID,
|
---|
451 | registrationData.password)
|
---|
452 |
|
---|
453 | result.invalidData = \
|
---|
454 | resultCode==rpc.Client.RESULT_INVALID_DATA
|
---|
455 | result.emailAlreadyRegistered = \
|
---|
456 | resultCode==rpc.Client.RESULT_EMAIL_ALREADY_REGISTERED
|
---|
457 |
|
---|
458 | return result
|
---|
459 |
|
---|
460 | #------------------------------------------------------------------------------
|
---|
461 |
|
---|
462 | class LoginRPC(RPCRequest):
|
---|
463 | """An RPC-based login request."""
|
---|
464 | @staticmethod
|
---|
465 | def setupLoginResult(result, client, pilotID, password):
|
---|
466 | """Setup the login result with the given client, pilot ID and
|
---|
467 | password."""
|
---|
468 | loginResult = client.login()
|
---|
469 | result.loggedIn = loginResult is not None
|
---|
470 | if result.loggedIn:
|
---|
471 | result.pilotID = pilotID
|
---|
472 | result.pilotName = loginResult[0]
|
---|
473 | result.rank = loginResult[1]
|
---|
474 | result.types = loginResult[2]
|
---|
475 | result.sessionID = loginResult[3]
|
---|
476 | result.password = password
|
---|
477 | result.fleet = client.getFleet()
|
---|
478 | result.gates = client.getGates()
|
---|
479 | flights = client.getFlights()
|
---|
480 | result.flights = flights[0]
|
---|
481 | result.reportedFlights = flights[1]
|
---|
482 | result.rejectedFlights = flights[2]
|
---|
483 | if result.rank=="STU":
|
---|
484 | reply = client.getEntryExamStatus()
|
---|
485 | result.entryExamPassed = reply[0]
|
---|
486 | result.entryExamLink = reply[1]
|
---|
487 | result.checkFlightStatus = reply[2]
|
---|
488 | if reply[3]:
|
---|
489 | result.rank = "FO"
|
---|
490 |
|
---|
491 |
|
---|
492 | def __init__(self, client, callback, pilotID, password):
|
---|
493 | """Construct the login request with the given pilot ID and
|
---|
494 | password."""
|
---|
495 | super(LoginRPC, self).__init__(client, callback)
|
---|
496 |
|
---|
497 | self._pilotID = pilotID
|
---|
498 | self._password = password
|
---|
499 |
|
---|
500 | def run(self):
|
---|
501 | """Perform the login request."""
|
---|
502 | result = Result()
|
---|
503 |
|
---|
504 | self._client.setCredentials(self._pilotID, self._password)
|
---|
505 | LoginRPC.setupLoginResult(result, self._client,
|
---|
506 | self._pilotID, self._password)
|
---|
507 |
|
---|
508 | return result
|
---|
509 |
|
---|
510 | #------------------------------------------------------------------------------
|
---|
511 |
|
---|
512 | class GetEntryExamStatus(RPCRequest):
|
---|
513 | """A request to get the entry exam status."""
|
---|
514 | def __init__(self, client, callback):
|
---|
515 | """Construct the request."""
|
---|
516 | super(GetEntryExamStatus, self).__init__(client, callback)
|
---|
517 |
|
---|
518 | def run(self):
|
---|
519 | """Perform the query."""
|
---|
520 | result = Result()
|
---|
521 |
|
---|
522 | reply = self._client.getEntryExamStatus()
|
---|
523 |
|
---|
524 | result.entryExamPassed = reply[0]
|
---|
525 | result.entryExamLink = reply[1]
|
---|
526 | result.checkFlightStatus = reply[2]
|
---|
527 | result.madeFO = reply[3]
|
---|
528 |
|
---|
529 | return result
|
---|
530 |
|
---|
531 | #------------------------------------------------------------------------------
|
---|
532 |
|
---|
533 | class GetFleetRPC(RPCRequest):
|
---|
534 | """Request to get the fleet from the website using RPC."""
|
---|
535 | def __init__(self, client, callback):
|
---|
536 | """Construct the request with the given client and callback function."""
|
---|
537 | super(GetFleetRPC, self).__init__(client, callback)
|
---|
538 |
|
---|
539 | def run(self):
|
---|
540 | """Perform the login request."""
|
---|
541 | result = Result()
|
---|
542 |
|
---|
543 | result.fleet = self._client.getFleet()
|
---|
544 |
|
---|
545 | return result
|
---|
546 |
|
---|
547 | #------------------------------------------------------------------------------
|
---|
548 |
|
---|
549 | class UpdatePlaneRPC(RPCRequest):
|
---|
550 | """RPC request to update the status and the position of a plane in the
|
---|
551 | fleet."""
|
---|
552 | def __init__(self, client, callback, tailNumber, status, gateNumber = None):
|
---|
553 | """Construct the request."""
|
---|
554 | super(UpdatePlaneRPC, self).__init__(client, callback)
|
---|
555 | self._tailNumber = tailNumber
|
---|
556 | self._status = status
|
---|
557 | self._gateNumber = gateNumber
|
---|
558 |
|
---|
559 | def run(self):
|
---|
560 | """Perform the plane update."""
|
---|
561 | self._client.updatePlane(self._tailNumber, self._status, self._gateNumber)
|
---|
562 |
|
---|
563 | # Otherwise an exception is thrown
|
---|
564 | result = Result()
|
---|
565 | result.success = True
|
---|
566 |
|
---|
567 | return result
|
---|
568 |
|
---|
569 | #------------------------------------------------------------------------------
|
---|
570 |
|
---|
571 | class GetNOTAMs(Request):
|
---|
572 | """Get the NOTAMs from EURoutePro and select the ones we are interested
|
---|
573 | in."""
|
---|
574 | def __init__(self, callback, departureICAO, arrivalICAO):
|
---|
575 | """Construct the request for the given airports."""
|
---|
576 | super(GetNOTAMs, self).__init__(callback)
|
---|
577 | self._departureICAO = departureICAO
|
---|
578 | self._arrivalICAO = arrivalICAO
|
---|
579 |
|
---|
580 | def run(self):
|
---|
581 | """Perform the retrieval of the NOTAMs."""
|
---|
582 | departureNOTAMs = self.getPilotsWebNOTAMs(self._departureICAO)
|
---|
583 | arrivalNOTAMs = self.getPilotsWebNOTAMs(self._arrivalICAO)
|
---|
584 |
|
---|
585 | icaos = []
|
---|
586 | if not departureNOTAMs: icaos.append(self._departureICAO)
|
---|
587 | if not arrivalNOTAMs: icaos.append(self._arrivalICAO)
|
---|
588 |
|
---|
589 | if icaos:
|
---|
590 | xmlParser = xml.sax.make_parser()
|
---|
591 | notamHandler = NOTAMHandler(icaos)
|
---|
592 | xmlParser.setContentHandler(notamHandler)
|
---|
593 |
|
---|
594 | url = "http://notams.euroutepro.com/notams.xml"
|
---|
595 |
|
---|
596 | f = urllib.request.urlopen(url, timeout = 10.0)
|
---|
597 | try:
|
---|
598 | xmlParser.parse(f)
|
---|
599 | finally:
|
---|
600 | f.close()
|
---|
601 |
|
---|
602 | for icao in icaos:
|
---|
603 | if icao==self._departureICAO:
|
---|
604 | departureNOTAMs = notamHandler.get(icao)
|
---|
605 | else:
|
---|
606 | arrivalNOTAMs = notamHandler.get(icao)
|
---|
607 |
|
---|
608 | result = Result()
|
---|
609 | result.departureNOTAMs = departureNOTAMs
|
---|
610 | result.arrivalNOTAMs = arrivalNOTAMs
|
---|
611 |
|
---|
612 | return result
|
---|
613 |
|
---|
614 | def getPilotsWebNOTAMs(self, icao):
|
---|
615 | """Try to get the NOTAMs from FAA's PilotsWeb site for the given ICAO
|
---|
616 | code.
|
---|
617 |
|
---|
618 | Returns a list of PilotsWEBNOTAM objects, or None in case of an error."""
|
---|
619 | try:
|
---|
620 | parser = PilotsWebNOTAMsParser()
|
---|
621 |
|
---|
622 | url = "https://pilotweb.nas.faa.gov/PilotWeb/notamRetrievalByICAOAction.do?method=displayByICAOs&formatType=ICAO&retrieveLocId=%s&reportType=RAW&actionType=notamRetrievalByICAOs" % \
|
---|
623 | (icao.upper(),)
|
---|
624 |
|
---|
625 | request = urllib.request.Request(url, headers = {
|
---|
626 | "cookie": "akamai_pilotweb_access=true;"
|
---|
627 | });
|
---|
628 | f = urllib.request.urlopen(request, timeout = 10.0, cafile=certifi.where())
|
---|
629 | try:
|
---|
630 | data = f.read(16384)
|
---|
631 | while data:
|
---|
632 | parser.feed(str(data))
|
---|
633 | data = f.read(16384)
|
---|
634 | finally:
|
---|
635 | f.close()
|
---|
636 |
|
---|
637 | return parser.getNOTAMs()
|
---|
638 |
|
---|
639 | except Exception as e:
|
---|
640 | traceback.print_exc()
|
---|
641 | print("mlx.web.GetNOTAMs.getPilotsWebNOTAMs: failed to get NOTAMs for '%s': %s" % \
|
---|
642 | (icao, str(e)))
|
---|
643 | return None
|
---|
644 |
|
---|
645 | #------------------------------------------------------------------------------
|
---|
646 |
|
---|
647 | class GetMETARs(Request):
|
---|
648 | """Get the METARs from the NOAA website for certain airport ICAOs."""
|
---|
649 |
|
---|
650 | def __init__(self, callback, airports):
|
---|
651 | """Construct the request for the given airports."""
|
---|
652 | super(GetMETARs, self).__init__(callback)
|
---|
653 | self._airports = airports
|
---|
654 |
|
---|
655 | def run(self):
|
---|
656 | """Perform the retrieval opf the METARs."""
|
---|
657 | url = "https://aviationweather.gov/cgi-bin/data/metar.php?"
|
---|
658 | data = urllib.parse.urlencode([ ("ids", ",".join(self._airports)),
|
---|
659 | ("hours", "0"),
|
---|
660 | ("format", "raw") ])
|
---|
661 | result = Result()
|
---|
662 | result.metars = {}
|
---|
663 | try:
|
---|
664 | url += data
|
---|
665 | f = urllib.request.urlopen(url, timeout = 10.0, cafile = certifi.where())
|
---|
666 | try:
|
---|
667 | for line in f.readlines():
|
---|
668 | line = str(line, "iso-8859-1")
|
---|
669 | if len(line)>5 and line[4]==' ':
|
---|
670 | icao = line[0:4]
|
---|
671 | if icao in self._airports:
|
---|
672 | result.metars[icao] = line.strip().split(",")[0]
|
---|
673 | finally:
|
---|
674 | f.close()
|
---|
675 | except Exception as e:
|
---|
676 | traceback.print_exc()
|
---|
677 | print("mlx.web.GetMETARs.run: failed to get METARs for %s: %s" % \
|
---|
678 | (self._airports, str(e)))
|
---|
679 |
|
---|
680 | return result
|
---|
681 |
|
---|
682 | #------------------------------------------------------------------------------
|
---|
683 |
|
---|
684 | class SendPIREPRPC(RPCRequest):
|
---|
685 | """A request to send a PIREP to the MAVA website via the RPC interface."""
|
---|
686 |
|
---|
687 | def __init__(self, client, callback, pirep, update):
|
---|
688 | """Construct the sending of the PIREP."""
|
---|
689 | super(SendPIREPRPC, self).__init__(client, callback)
|
---|
690 | self._pirep = pirep
|
---|
691 | self._update = update
|
---|
692 |
|
---|
693 | def run(self):
|
---|
694 | """Perform the sending of the PIREP."""
|
---|
695 | pirep = self._pirep
|
---|
696 | resultCode = self._client.addPIREP(pirep.bookedFlight.id, pirep,
|
---|
697 | self._update)
|
---|
698 |
|
---|
699 | result = Result()
|
---|
700 | result.success = resultCode==rpc.Client.RESULT_OK
|
---|
701 | result.alreadyFlown = resultCode==rpc.Client.RESULT_FLIGHT_ALREADY_REPORTED
|
---|
702 | result.notAvailable = resultCode==rpc.Client.RESULT_FLIGHT_NOT_EXISTS
|
---|
703 |
|
---|
704 | return result
|
---|
705 |
|
---|
706 | #------------------------------------------------------------------------------
|
---|
707 |
|
---|
708 | class SendACARSRPC(RPCRequest):
|
---|
709 | """A request to send an ACARS to the MAVA website via JSON-RPC."""
|
---|
710 | def __init__(self, client, callback, acars):
|
---|
711 | """Construct the request for the given PIREP."""
|
---|
712 | super(SendACARSRPC, self).__init__(client, callback)
|
---|
713 | self._acars = acars
|
---|
714 |
|
---|
715 | def run(self):
|
---|
716 | """Perform the sending of the ACARS."""
|
---|
717 | print("Sending the online ACARS via JSON-RPC")
|
---|
718 |
|
---|
719 | self._client.updateOnlineACARS(self._acars)
|
---|
720 | return Result()
|
---|
721 |
|
---|
722 | #------------------------------------------------------------------------------
|
---|
723 |
|
---|
724 | class SendBugReport(Request):
|
---|
725 | """A request to send a bug report to the project homepage."""
|
---|
726 | _latin2Encoder = codecs.getencoder("iso-8859-2")
|
---|
727 |
|
---|
728 | def __init__(self, callback, summary, description, email):
|
---|
729 | """Construct the request for the given bug report."""
|
---|
730 | super(SendBugReport, self).__init__(callback)
|
---|
731 | self._summary = summary
|
---|
732 | self._description = description
|
---|
733 | self._email = email
|
---|
734 |
|
---|
735 | def run(self):
|
---|
736 | """Perform the sending of the bug report."""
|
---|
737 | serverProxy = xmlrpc.client.ServerProxy("http://mlx.varadiistvan.hu/rpc")
|
---|
738 |
|
---|
739 | result = Result()
|
---|
740 | result.success = False
|
---|
741 |
|
---|
742 | attributes = {}
|
---|
743 | if self._email:
|
---|
744 | attributes["reporter"] = self._email
|
---|
745 |
|
---|
746 | result.ticketID = serverProxy.ticket.create(self._summary, self._description,
|
---|
747 | attributes, True)
|
---|
748 | print("Created ticket with ID:", result.ticketID)
|
---|
749 | result.success = True
|
---|
750 |
|
---|
751 | return result
|
---|
752 |
|
---|
753 | #------------------------------------------------------------------------------
|
---|
754 |
|
---|
755 | class SetCheckFlightPassed(RPCRequest):
|
---|
756 | """A request to mark the user as one having passed the check flight."""
|
---|
757 | def __init__(self, client, callback, aircraftType):
|
---|
758 | """Construct the request for the given type."""
|
---|
759 | super(SetCheckFlightPassed, self).__init__(client, callback)
|
---|
760 | self._aircraftType = aircraftType
|
---|
761 |
|
---|
762 | def run(self):
|
---|
763 | """Perform the update."""
|
---|
764 | aircraftType = BookedFlight.TYPE2TYPECODE[self._aircraftType]
|
---|
765 | self._client.setCheckFlightPassed(aircraftType)
|
---|
766 | return Result()
|
---|
767 |
|
---|
768 | #------------------------------------------------------------------------------
|
---|
769 |
|
---|
770 | class GetPIREP(RPCRequest):
|
---|
771 | """A request to retrieve the PIREP of a certain flight."""
|
---|
772 | def __init__(self, client, callback, flightID):
|
---|
773 | """Construct the request."""
|
---|
774 | super(GetPIREP, self).__init__(client, callback)
|
---|
775 | self._flightID = flightID
|
---|
776 |
|
---|
777 | def run(self):
|
---|
778 | """Perform the update."""
|
---|
779 | result = Result()
|
---|
780 |
|
---|
781 | pirepData = self._client.getPIREP(self._flightID)
|
---|
782 | print("pirepData:", pirepData)
|
---|
783 |
|
---|
784 | bookedFlight = BookedFlight(id = self._flightID)
|
---|
785 | bookedFlight.setupFromPIREPData(pirepData)
|
---|
786 |
|
---|
787 | result.pirep = PIREP(None)
|
---|
788 | result.pirep.setupFromPIREPData(pirepData, bookedFlight)
|
---|
789 |
|
---|
790 | return result
|
---|
791 |
|
---|
792 | #------------------------------------------------------------------------------
|
---|
793 |
|
---|
794 | class ReflyFlights(RPCRequest):
|
---|
795 | """A request to mark certain flights for reflying."""
|
---|
796 | def __init__(self, client, callback, flightIDs):
|
---|
797 | """Construct the request."""
|
---|
798 | super(ReflyFlights, self).__init__(client, callback)
|
---|
799 | self._flightIDs = flightIDs
|
---|
800 |
|
---|
801 | def run(self):
|
---|
802 | """Perform the update."""
|
---|
803 | self._client.reflyFlights(self._flightIDs)
|
---|
804 | return Result()
|
---|
805 |
|
---|
806 | #------------------------------------------------------------------------------
|
---|
807 |
|
---|
808 | class DeleteFlights(RPCRequest):
|
---|
809 | """A request to delete certain flights."""
|
---|
810 | def __init__(self, client, callback, flightIDs):
|
---|
811 | """Construct the request."""
|
---|
812 | super(DeleteFlights, self).__init__(client, callback)
|
---|
813 | self._flightIDs = flightIDs
|
---|
814 |
|
---|
815 | def run(self):
|
---|
816 | """Perform the update."""
|
---|
817 | self._client.deleteFlights(self._flightIDs)
|
---|
818 | return Result()
|
---|
819 |
|
---|
820 | #------------------------------------------------------------------------------
|
---|
821 |
|
---|
822 | class GetAcceptedFlights(RPCRequest):
|
---|
823 | """Request to get the accepted flights."""
|
---|
824 | def __init__(self, client, callback):
|
---|
825 | """Construct the request with the given client and callback function."""
|
---|
826 | super(GetAcceptedFlights, self).__init__(client, callback)
|
---|
827 |
|
---|
828 | def run(self):
|
---|
829 | """Perform the login request."""
|
---|
830 | result = Result()
|
---|
831 |
|
---|
832 | result.flights = self._client.getAcceptedFlights()
|
---|
833 |
|
---|
834 | return result
|
---|
835 |
|
---|
836 | #------------------------------------------------------------------------------
|
---|
837 |
|
---|
838 | class GetTimetable(RPCRequest):
|
---|
839 | """Request to get the timetable."""
|
---|
840 | def __init__(self, client, callback, date, types):
|
---|
841 | """Construct the request with the given client and callback function."""
|
---|
842 | super(GetTimetable, self).__init__(client, callback)
|
---|
843 | self._date = date
|
---|
844 | self._types = types
|
---|
845 |
|
---|
846 | def run(self):
|
---|
847 | """Perform the login request."""
|
---|
848 | result = Result()
|
---|
849 |
|
---|
850 | result.flightPairs = self._client.getTimetable(self._date, self._types)
|
---|
851 |
|
---|
852 | return result
|
---|
853 |
|
---|
854 | #------------------------------------------------------------------------------
|
---|
855 |
|
---|
856 | class BookFlights(RPCRequest):
|
---|
857 | """Request to book flights."""
|
---|
858 | def __init__(self, client, callback, flightIDs, date, tailNumber):
|
---|
859 | """Construct the request with the given client and callback function."""
|
---|
860 | super(BookFlights, self).__init__(client, callback)
|
---|
861 | self._flightIDs = flightIDs
|
---|
862 | self._date = date
|
---|
863 | self._tailNumber = tailNumber
|
---|
864 |
|
---|
865 | def run(self):
|
---|
866 | """Perform the login request."""
|
---|
867 | result = Result()
|
---|
868 |
|
---|
869 | result.bookedFlights = self._client.bookFlights(self._flightIDs,
|
---|
870 | self._date,
|
---|
871 | self._tailNumber)
|
---|
872 |
|
---|
873 | return result
|
---|
874 |
|
---|
875 | #------------------------------------------------------------------------------
|
---|
876 |
|
---|
877 | class GetSimBriefResult(RPCRequest):
|
---|
878 | """Request the SimBrief result."""
|
---|
879 | def __init__(self, client, callback, timestamp):
|
---|
880 | """Construct the request with the given client and callback function."""
|
---|
881 | super(GetSimBriefResult, self).__init__(client, callback)
|
---|
882 | self._timestamp = timestamp
|
---|
883 |
|
---|
884 | def run(self):
|
---|
885 | """Perform the request."""
|
---|
886 | result = Result()
|
---|
887 |
|
---|
888 | result.result = self._client.getSimBriefResult(self._timestamp)
|
---|
889 |
|
---|
890 | return result
|
---|
891 |
|
---|
892 | #------------------------------------------------------------------------------
|
---|
893 |
|
---|
894 | class Handler(threading.Thread):
|
---|
895 | """The handler for the web services.
|
---|
896 |
|
---|
897 | It can process one request at a time. The results are passed to a callback
|
---|
898 | function."""
|
---|
899 | def __init__(self, config, getCredentialsFn):
|
---|
900 | """Construct the handler."""
|
---|
901 | super(Handler, self).__init__()
|
---|
902 |
|
---|
903 | self._requests = []
|
---|
904 | self._requestCondition = threading.Condition()
|
---|
905 |
|
---|
906 | self.daemon = True
|
---|
907 | self._config = config
|
---|
908 | self._rpcClient = rpc.Client(getCredentialsFn)
|
---|
909 | if config.rememberPassword:
|
---|
910 | self._rpcClient.setCredentials(config.pilotID, config.password)
|
---|
911 |
|
---|
912 | def register(self, callback, registrationData):
|
---|
913 | """Enqueue a registration request."""
|
---|
914 | self._addRequest(Register(self._rpcClient, callback, registrationData))
|
---|
915 |
|
---|
916 | def login(self, callback, pilotID, password):
|
---|
917 | """Enqueue a login request."""
|
---|
918 | request = LoginRPC(self._rpcClient, callback, pilotID, password)
|
---|
919 |
|
---|
920 | self._addRequest(request)
|
---|
921 |
|
---|
922 | def getEntryExamStatus(self, callback):
|
---|
923 | """Get the entry exam status."""
|
---|
924 | self._addRequest(GetEntryExamStatus(self._rpcClient, callback))
|
---|
925 |
|
---|
926 | def getFleet(self, callback):
|
---|
927 | """Enqueue a fleet retrieval request."""
|
---|
928 | request = GetFleetRPC(self._rpcClient, callback,)
|
---|
929 | self._addRequest(request)
|
---|
930 |
|
---|
931 | def updatePlane(self, callback, tailNumber, status, gateNumber = None):
|
---|
932 | """Update the status of the given plane."""
|
---|
933 | request = UpdatePlaneRPC(self._rpcClient, callback,
|
---|
934 | tailNumber, status, gateNumber)
|
---|
935 | self._addRequest(request)
|
---|
936 |
|
---|
937 | def getNOTAMs(self, callback, departureICAO, arrivalICAO):
|
---|
938 | """Get the NOTAMs for the given two airports."""
|
---|
939 | self._addRequest(GetNOTAMs(callback, departureICAO, arrivalICAO))
|
---|
940 |
|
---|
941 | def getMETARs(self, callback, airports):
|
---|
942 | """Get the METARs for the given airports."""
|
---|
943 | self._addRequest(GetMETARs(callback, airports))
|
---|
944 |
|
---|
945 | def sendPIREP(self, callback, pirep, update = False):
|
---|
946 | """Send the given PIREP."""
|
---|
947 | request = SendPIREPRPC(self._rpcClient, callback, pirep, update)
|
---|
948 | self._addRequest(request)
|
---|
949 |
|
---|
950 | def sendACARS(self, callback, acars):
|
---|
951 | """Send the given ACARS"""
|
---|
952 | request = SendACARSRPC(self._rpcClient, callback, acars)
|
---|
953 | self._addRequest(request)
|
---|
954 |
|
---|
955 | def sendBugReport(self, callback, summary, description, email):
|
---|
956 | """Send a bug report with the given data."""
|
---|
957 | self._addRequest(SendBugReport(callback, summary, description, email))
|
---|
958 |
|
---|
959 | def setCheckFlightPassed(self, callback, aircraftType):
|
---|
960 | """Mark the check flight as passed."""
|
---|
961 | self._addRequest(SetCheckFlightPassed(self._rpcClient,
|
---|
962 | callback, aircraftType))
|
---|
963 |
|
---|
964 | def getPIREP(self, callback, flightID):
|
---|
965 | """Query the PIREP for the given flight."""
|
---|
966 | self._addRequest(GetPIREP(self._rpcClient, callback, flightID))
|
---|
967 |
|
---|
968 | def reflyFlights(self, callback, flightIDs):
|
---|
969 | """Mark the flights with the given IDs for reflying."""
|
---|
970 | self._addRequest(ReflyFlights(self._rpcClient, callback, flightIDs))
|
---|
971 |
|
---|
972 | def deleteFlights(self, callback, flightIDs):
|
---|
973 | """Delete the flights with the given IDs."""
|
---|
974 | self._addRequest(DeleteFlights(self._rpcClient, callback, flightIDs))
|
---|
975 |
|
---|
976 | def getAcceptedFlights(self, callback):
|
---|
977 | """Enqueue a request to get the accepted flights."""
|
---|
978 | self._addRequest(GetAcceptedFlights(self._rpcClient, callback))
|
---|
979 |
|
---|
980 | def getTimetable(self, callback, date, types):
|
---|
981 | """Enqueue a request to get the timetable."""
|
---|
982 | self._addRequest(GetTimetable(self._rpcClient, callback, date, types))
|
---|
983 |
|
---|
984 | def bookFlights(self, callback, flightIDs, date, tailNumber):
|
---|
985 | """Enqueue a request to book some flights."""
|
---|
986 | self._addRequest(BookFlights(self._rpcClient, callback,
|
---|
987 | flightIDs, date, tailNumber))
|
---|
988 |
|
---|
989 | def getSimBriefResult(self, callback, timestamp):
|
---|
990 | """Enqueue a request to get the SimBrief result."""
|
---|
991 | self._addRequest(GetSimBriefResult(self._rpcClient, callback,
|
---|
992 | timestamp))
|
---|
993 |
|
---|
994 | def run(self):
|
---|
995 | """Process the requests."""
|
---|
996 | while True:
|
---|
997 | with self._requestCondition:
|
---|
998 | while not self._requests:
|
---|
999 | self._requestCondition.wait()
|
---|
1000 | request = self._requests[0]
|
---|
1001 | del self._requests[0]
|
---|
1002 |
|
---|
1003 | request.perform()
|
---|
1004 |
|
---|
1005 | def _addRequest(self, request):
|
---|
1006 | """Add the given request to the queue."""
|
---|
1007 | with self._requestCondition:
|
---|
1008 | self._requests.append(request)
|
---|
1009 | self._requestCondition.notify()
|
---|
1010 |
|
---|
1011 | #------------------------------------------------------------------------------
|
---|
1012 |
|
---|
1013 | if __name__ == "__main__":
|
---|
1014 | import time
|
---|
1015 |
|
---|
1016 | def callback(returned, result):
|
---|
1017 | print(returned, str(result))
|
---|
1018 |
|
---|
1019 | handler = Handler()
|
---|
1020 | handler.start()
|
---|
1021 |
|
---|
1022 | #handler.login(callback, "P096", "V5fwj")
|
---|
1023 | #handler.getFleet(callback)
|
---|
1024 | # Plane: HA-LEG home (gate 67)
|
---|
1025 | #handler.updatePlane(callback, "HA-LQC", const.PLANE_AWAY, "72")
|
---|
1026 | #time.sleep(3)
|
---|
1027 | #handler.getFleet(callback)
|
---|
1028 | #time.sleep(3)
|
---|
1029 |
|
---|
1030 | #handler.getNOTAMs(callback, "LHBP", "EPWA")
|
---|
1031 | #handler.getMETARs(callback, ["LHBP", "EPWA"])
|
---|
1032 | #time.sleep(5)
|
---|
1033 |
|
---|
1034 | handler.updatePlane(callback, "HA-LON", const.PLANE_AWAY, "")
|
---|
1035 | time.sleep(3)
|
---|
1036 |
|
---|
1037 | #------------------------------------------------------------------------------
|
---|