Ignore:
Timestamp:
05/16/12 18:04:55 (12 years ago)
Author:
István Váradi <ivaradi@…>
Branch:
default
hg-Phase:
(<MercurialRepository 1 'hg:/home/ivaradi/mlx/hg' '/'>, 'public')
Message:

Added support for the entrance exam

File:
1 edited

Legend:

Unmodified
Added
Removed
  • src/mlx/web.py

    r151 r184  
    6565                      const.AIRCRAFT_T154 : "TU5",
    6666                      const.AIRCRAFT_YK40 : "YK4" }
    67    
    68     def __init__(self, id, f):
    69         """Construct a booked flight with the given ID.
    70 
    71         The rest of the data is read from the given file."""
    72 
     67
     68    @staticmethod
     69    def getDateTime(date, time):
     70        """Get a datetime object from the given textual date and time."""
     71        return datetime.datetime.strptime(date + " " + time,
     72                                          "%Y-%m-%d %H:%M:%S")
     73
     74    def __init__(self, id = None):
     75        """Construct a booked flight with the given ID."""
    7376        self.id = id
     77
     78    def readFromWeb(self, f):
     79        """Read the data of the flight from the web via the given file
     80        object."""
    7481        self.callsign = readline(f)
    7582
     
    8996
    9097        departureTime = readline(f)
    91         self.departureTime = datetime.datetime.strptime(date + " " + departureTime,
    92                                                         "%Y-%m-%d %H:%M:%S")
     98        self.departureTime = BookedFlight.getDateTime(date, departureTime)
    9399                                               
    94100        arrivalTime = readline(f)
    95         self.arrivalTime = datetime.datetime.strptime(date + " " + arrivalTime,
    96                                                       "%Y-%m-%d %H:%M:%S")
     101        self.arrivalTime = BookedFlight.getDateTime(date, arrivalTime)
    97102
    98103        if not readline(f)==".NEXT.":
    99104            raise Exception("Invalid line in flight data")
    100105
     106    def readFromFile(self, f):
     107        """Read the data of the flight from a file via the given file
     108        object."""
     109        date = None
     110        departureTime = None
     111        arrivalTime = None
     112       
     113        line = f.readline()
     114        lineNumber = 0   
     115        while line:
     116            lineNumber += 1
     117            line = line.strip()
     118           
     119            hashIndex = line.find("#")
     120            if hashIndex>=0: line = line[:hashIndex]
     121            if line:
     122                equalIndex = line.find("=")
     123                lineOK = equalIndex>0
     124               
     125                if lineOK:
     126                    key = line[:equalIndex].strip()                   
     127                    value = line[equalIndex+1:].strip().replace("\:", ":")
     128                   
     129                    lineOK = key and value
     130
     131                if lineOK:
     132                    if key=="callsign": self.callsign = value
     133                    elif key=="date": date = value
     134                    elif key=="dep_airport": self.departureICAO = value
     135                    elif key=="dest_airport": self.arrivalICAO = value
     136                    elif key=="planecode": self.aircraftType = \
     137                         self._decodeAircraftType(value)
     138                    elif key=="tail_nr": self.tailNumber = value
     139                    elif key=="passenger": self.numPassengers = int(value)
     140                    elif key=="crew": self.numCrew = int(value)
     141                    elif key=="bag": self.bagWeight = int(value)
     142                    elif key=="cargo": self.cargoWeight = int(value)
     143                    elif key=="mail": self.mailWeight = int(value)
     144                    elif key=="flight_route": self.route = value
     145                    elif key=="departure_time": departureTime = value
     146                    elif key=="arrival_time": arrivalTime = value
     147                    elif key=="foglalas_id": pass
     148                    elif key=="planetype": pass
     149                    else: lineOK = False
     150
     151                if not lineOK:
     152                    print "web.BookedFlight.readFromFile: line %d is invalid" % \
     153                          (lineNumber,)
     154
     155            line = f.readline()
     156
     157        if date is not None:
     158            if departureTime is not None:
     159                self.departureTime = BookedFlight.getDateTime(date,
     160                                                              departureTime)
     161            if arrivalTime is not None:
     162                self.arrivalTime = BookedFlight.getDateTime(date,
     163                                                            arrivalTime)
     164
     165        d = dir(self)
     166        for attribute in ["callsign", "departureICAO", "arrivalICAO",
     167                          "aircraftType", "tailNumber",
     168                          "numPassengers", "numCrew",
     169                          "bagWeight", "cargoWeight", "mailWeight",
     170                          "route", "departureTime", "arrivalTime"]:
     171            if attribute not in d:
     172                raise Exception("Attribute %s could not be read" % (attribute,))
     173           
    101174    def _readAircraftType(self, f):
    102175        """Read the aircraft type from the given file."""
    103176        line = readline(f)
    104177        typeCode = line[:3]
     178        self.aircraftType = self._decodeAircraftType(typeCode)
     179
     180    def _decodeAircraftType(self, typeCode):
     181        """Decode the aircraft type from the given typeCode."""
    105182        if typeCode in self.TYPECODE2TYPE:
    106             self.aircraftType = self.TYPECODE2TYPE[typeCode]
     183            return self.TYPECODE2TYPE[typeCode]
    107184        else:
    108185            raise Exception("Invalid aircraft type code: '" + typeCode + "'")
     
    346423    iso88592decoder = codecs.getdecoder("iso-8859-2")
    347424   
    348     def __init__(self, callback, pilotID, password):
     425    def __init__(self, callback, pilotID, password, entranceExam):
    349426        """Construct the login request with the given pilot ID and
    350427        password."""
     
    353430        self._pilotID = pilotID
    354431        self._password = password
     432        self._entranceExam = entranceExam
    355433
    356434    def run(self):
     
    364442        password = md5.hexdigest()
    365443
    366         url = "http://www.virtualairlines.hu/leker2.php?pid=%s&psw=%s" % \
    367               (pilotID, password)
     444        if self._entranceExam:
     445            url = "http://www.virtualairlines.hu/ellenorzo/getflightplan.php?pid=%s" % \
     446                  (pilotID,)
     447        else:
     448            url = "http://www.virtualairlines.hu/leker2.php?pid=%s&psw=%s" % \
     449                  (pilotID, password)
    368450
    369451        result = Result()
     452        result.entranceExam = self._entranceExam
    370453
    371454        f = urllib2.urlopen(url, timeout = 10.0)
    372455
    373456        status = readline(f)
    374         result.loggedIn = status == ".OK."
     457        if self._entranceExam:
     458            result.loggedIn = status != "#NOEXAM"
     459        else:
     460            result.loggedIn = status == ".OK."
    375461
    376462        if result.loggedIn:
    377463            result.pilotID = self._pilotID
    378             result.pilotName = self.iso88592decoder(readline(f))[0]
    379             result.exams = readline(f)
    380464            result.flights = []
    381 
    382             while True:
    383                 line = readline(f)
    384                 if not line or line == "#ENDPIREP": break
    385 
    386                 flight = BookedFlight(line, f)
    387                 result.flights.append(flight)
     465            # FIXME: this may not be the correct behaviour
     466            # for an entrance exam, but the website returns
     467            # an error
     468            if self._entranceExam:
     469                result.pilotName = result.pilotID
     470                result.exams = ""
     471            else:
     472                result.pilotName = self.iso88592decoder(readline(f))[0]
     473                result.exams = readline(f)
     474               
     475                while True:
     476                    line = readline(f)
     477                    if not line or line == "#ENDPIREP": break
     478
     479                    flight = BookedFlight(line)
     480                    flight.readFromWeb(f)
     481                    result.flights.append(flight)
    388482
    389483            result.flights.sort(cmp = lambda flight1, flight2:
     
    740834        self.daemon = True
    741835
    742     def login(self, callback, pilotID, password):
     836    def login(self, callback, pilotID, password, entranceExam = False):
    743837        """Enqueue a login request."""
    744         self._addRequest(Login(callback, pilotID, password))
     838        self._addRequest(Login(callback, pilotID, password, entranceExam))
    745839
    746840    def getFleet(self, callback):
Note: See TracChangeset for help on using the changeset viewer.