示例#1
0
  def get(self, lotID):
    if 'authenticatedtoken' not in self.session:
      return self.redirect('http://' + wlnet + "/CLOT/Auth?p=856960317&state=join/" + str(long(lotID)))

    container = lot.getLot(lotID)
    inviteToken = self.session['authenticatedtoken']

    #Call the warlight API to get the name, color, and verify that the invite token is correct
    apiret = hitapi('/API/ValidateInviteToken', { 'Token':  inviteToken })

    if not "tokenIsValid" in apiret:
      return self.response.write('The supplied invite token is invalid.  Please contact the CLOT author for assistance.')

    #Check if this invite token is new to us
    player = Player.query(Player.inviteToken == inviteToken).get()
    if player is None:
      data = json.loads(apiret)
      player = Player(inviteToken=inviteToken, name=data['name'], color=data['color'])
      player.put()
      logging.info("Created player " + unicode(player))

    #Set them as participating in the current lot
    addIfNotPresent(container.lot.playersParticipating, player.key.id())
    container.players[player.key.id()] = player
    container.lot.put()
    container.changed()
    logging.info("Player " + unicode(player) + " joined " + unicode(container.lot))

    self.response.write(get_template('join.html').render({ 'container': container }))
示例#2
0
文件: cron.py 项目: FizzerWL/CLOT
def checkInProgressGames(container):
  """This is called periodically to look for games that are finished.  If we find a finished game, we record the winner"""

  #Find all games that we think aren't finished
  activeGames = [g for g in container.games if g.winner is None]

  for g in activeGames:
    #call WarLight's GameFeed API so that it can tell us if it's finished or not
    apiret = hitapi('/API/GameFeed?GameID=' + str(g.wlnetGameID), {})
    data = json.loads(apiret)
    state = data.get('state', 'err')
    if state == 'err': raise Exception("GameFeed API failed.  Message = " + data.get('error', apiret))

    if state == 'Finished':
      #It's finished. Record the winner and save it back.
      winner = findWinner(container, data)
      logging.info('Identified the winner of game ' + str(g.wlnetGameID) + ' is ' + unicode(winner))
      g.winner = winner.key.id()
      g.dateEnded = datetime.datetime.now()
      g.put()
    elif state == 'WaitingForPlayers':
      #It's in the lobby still. Check if it's been too long.
      elapsed = datetime.datetime.now() - g.dateCreated
      if not clot.gameFailedToStart(elapsed):
        logging.info("Game " + str(g.wlnetGameID) + " is in the lobby for " + str(elapsed.days) + " days.")
      else:
        logging.info('Game ' + str(g.wlnetGameID) + " is stuck in the lobby. Marking it as a loss for anyone who didn't join and deleting it.")

        #Delete it over at warlight.net so that players know we no longer consider it a real game
        config = getClotConfig()
        deleteRet = postToApi('/API/DeleteLobbyGame', json.dumps( { 
                                     'Email': config.adminEmail, 
                                     'APIToken': config.adminApiToken,
                                     'gameID': g.wlnetGameID }))

        #If the API doesn't return success, just ignore this game on this run. This can happen if the game just started between when we checked its status and when we told it to delete.
        if 'success' not in deleteRet:
          logging.info("DeleteLobbyGame did not return success. Ignoring this game for this run.  Return=" + deleteRet)
        else:
          #We deleted the game.  Mark it as deleted and finished
          g.deleted = True
          g.winner = findWinnerOfDeletedGame(container, data).key.id()
          g.put()

          #Also remove anyone that declines or fails to join from the ladder.  This is important for real-time ladders since we don't want idle people staying in forever, but you may not want this for your situation
          for playerID in [getPlayerByInviteToken(container, p['id']).key.id() for p in data['players'] if p['state'] != 'Playing']:
            if playerID in container.lot.playersParticipating:
              container.lot.playersParticipating.remove(playerID)
              logging.info("Removed " + str(playerID) + " from ladder since they did not join game " + str(g.wlnetGameID))


    else:
      #It's still going.
      logging.info('Game ' + str(g.wlnetGameID) + ' is not finished, state=' + state + ', numTurns=' + data['numberOfTurns'])
 def get(self, lotID):
     if 'authenticatedtoken' not in self.session:
         ############################################### SET TO main before going live ##################################
         # main - 5015900432
         # test - 314032996
         return self.redirect('http://' + wlnet + "/CLOT/Auth?p=3022124041&state=join/" + str(long(lotID)))
     
     container = lot.getLot(lotID)
     inviteToken = self.session['authenticatedtoken']
     
     templates = [655094]
     templateIDs = ','.join(str(template) for template in templates)
     
     logging.info("current templates in use : " + templateIDs)
     
     #Call the warlight API to get the name, color, and verify that the invite token is correct
     tempapiret = hitapi('/API/ValidateInviteToken', { 'Token':  inviteToken, 'TemplateIDs': templateIDs})
     
     logging.info('tempapi return value' + str(tempapiret))
     logging.info("invite token = " + inviteToken)
     
     if (not "tokenIsValid" in tempapiret) or ("CannotUseTemplate" in tempapiret):
         return self.response.write('The supplied invite token is invalid.  Please contact the CLOT author for assistance.')
     
     #Check if this invite token is new to us
     player = Player.query(Player.inviteToken == inviteToken).get()
     
     
     data = json.loads(tempapiret)
     currentColor = data['color']
     currentName = data['name']
     if player is None:
         player = Player(inviteToken=inviteToken, name=currentName, color=currentColor, customProperties = {}, numberOfGamesAtOnce=5)
         player.put()
         logging.info("Created player " + unicode(player))
     else:
         # Update player details
         if currentColor != player.color:
             player.color = currentColor
         if currentName != player.name:
             player.name = currentName
         player.put()
         logging.info("Update player metadata for " + unicode(player))
         
     
     #Set them as participating in the current lot
     addIfNotPresent(container.lot.playersParticipating, player.key.id())
     container.players[player.key.id()] = player
     container.lot.put()
     container.changed()
     logging.info("Player " + unicode(player) + " joined " + unicode(container.lot))
     
     self.response.write(get_template('join.html').render({ 'container': container }))
示例#4
0
文件: login.py 项目: FizzerWL/CLOT
  def get(self):
    #Cast token to long to ensure the only contain numerical digits (this is easy in python since longs can go to any size.   In other languages we might have to do more work here to avoid overflows since tokens can exceed 2^32)
    token = str(long(self.request.GET['token']))
    clotpass = self.request.GET['clotpass']

    apiret = json.loads(hitapi('/API/ValidateInviteToken', { 'Token':  token }))

    if clotpass != apiret['clotpass']:
      return self.redirect('/loginfailed')

    self.session_store = sessions.get_store(request=self.request)

    self.session['authenticatedtoken'] = token

    self.redirect('/' + self.request.GET['state'])
示例#5
0
    def get(self, lotID):
        if 'authenticatedtoken' not in self.session:
            return self.redirect('http://' + wlnet +
                                 "/CLOT/Auth?p=62456969&state=join/" +
                                 str(long(lotID)))

        container = lot.getLot(lotID)
        inviteToken = self.session['authenticatedtoken']

        #Call the warlight API to get the name, color, and verify that the invite token is correct
        apiret = hitapi('/API/ValidateInviteToken', {'Token': inviteToken})

        if not "tokenIsValid" in apiret:
            return self.response.write(
                'The supplied invite token is invalid.  Please contact the CLOT author for assistance.'
            )

        #Check if this invite token is new to us
        player = Player.query(Player.inviteToken == inviteToken).get()
        if player is None:
            data = json.loads(apiret)
            player = Player(inviteToken=inviteToken,
                            name=data['name'],
                            color=data['color'])
            player.put()
            logging.info("Created player " + unicode(player))

        #Set them as participating in the current lot
        addIfNotPresent(container.lot.playersParticipating, player.key.id())
        container.players[player.key.id()] = player
        container.lot.put()
        container.changed()
        logging.info("Player " + unicode(player) + " joined " +
                     unicode(container.lot))

        self.response.write(
            get_template('join.html').render({'container': container}))
示例#6
0
def checkInProgressGames(container):
    """This is called periodically to look for games that are finished.  If we find a finished game, we record the winner"""

    #Find all games that we think aren't finished
    activeGames = [g for g in container.games if g.winner is None]

    for g in activeGames:
        #call WarLight's GameFeed API so that it can tell us if it's finished or not
        apiret = hitapi('/API/GameFeed?GameID=' + str(g.wlnetGameID), {})
        data = json.loads(apiret)
        state = data.get('state', 'err')
        if state == 'err': raise Exception("GameFeed API failed.  Message = " + data.get('error', apiret))
        
        if state == 'Finished':        
            #It's finished. Record the winner and save it back.
            winner = findWinner(container, data)
            logging.info('Identified the winner of game ' + str(g.wlnetGameID) + ' is ' + unicode(winner))
            g.winner = winner.key.id()
            g.dateEnded = datetime.datetime.now()
            g.put()        
        elif state == 'WaitingForPlayers':
            #It's in the lobby still. Check if it's been too long.
            elapsed = datetime.datetime.now() - g.dateCreated
            players = data.get('players', 'err')
            if players == 'err' : raise Exception("GameFeed API failed.  Message = " + data.get('error', apiret))
            
            hasEitherPlayerDeclined = False
            for p in players:
                playerState = p.get('state', 'err')
                if playerState =='err' : raise Exception("GameFeed API failed.  Message = " + data.get('error', apiret)) 
                if playerState == 'Declined':
                    hasEitherPlayerDeclined = True
                    break
            
            if clot.gameFailedToStart(elapsed) or hasEitherPlayerDeclined == True:
                logging.info('Game ' + str(g.wlnetGameID) + " is stuck in the lobby. Marking it as a loss for anyone who didn't join and deleting it.")
            
                #Delete it over at warlight.net so that players know we no longer consider it a real game
                config = getClotConfig()
                deleteRet = postToApi('/API/DeleteLobbyGame', json.dumps( { 
                                             'Email': config.adminEmail, 
                                             'APIToken': config.adminApiToken,
                                             'gameID': g.wlnetGameID }))
                
                #If the API doesn't return success, just ignore this game on this run. This can happen if the game just started between when we checked its status and when we told it to delete.
                if 'success' not in deleteRet:
                    logging.info("DeleteLobbyGame did not return success. Ignoring this game for this run.  Return=" + deleteRet)
                else:
                    #We deleted the game.  Mark it as deleted and finished
                    g.deleted = True
                    g.winner = findWinnerOfDeletedGame(container, data).key.id()
                    g.put()
                    
                    #Also remove anyone that declines or fails to join from the ladder.  This is important for real-time ladders since we don't want idle people staying in forever, but you may not want this for your situation
                    for playerID in [getPlayerByInviteToken(container, p['id']).key.id() for p in data['players'] if p['state'] != 'Playing']:
                        if playerID in container.lot.playersParticipating:
                            container.lot.playersParticipating.remove(playerID)
                            logging.info("Removed " + str(playerID) + " from ladder since they did not join game " + str(g.wlnetGameID))    
            else :
                logging.info("Game " + str(g.wlnetGameID) + " is in the lobby for " + str(elapsed.days) + " days.")    
        else:
            #It's still going.
            logging.info('Game ' + str(g.wlnetGameID) + ' is not finished, state=' + state + ', numTurns=' + data['numberOfTurns'])
示例#7
0
文件: join.py 项目: mslasm/MDLadder
    def get(self, lotID):
        if 'authenticatedtoken' not in self.session:
            ############################################### SET TO main before going live ##################################
            # main - 5015900432
            # test - 314032996
            return self.redirect('http://' + wlnet +
                                 "/CLOT/Auth?p=314032996&state=join/" +
                                 str(long(lotID)))

        container = lot.getLot(lotID)
        inviteToken = self.session['authenticatedtoken']

        templates = [620619]
        templateIDs = ','.join(str(template) for template in templates)

        logging.info("current templates in use : " + templateIDs)

        #Call the warlight API to get the name, color, and verify that the invite token is correct
        tempapiret = hitapi('/API/ValidateInviteToken', {
            'Token': inviteToken,
            'TemplateIDs': templateIDs
        })

        logging.info('tempapi return value' + str(tempapiret))
        logging.info("invite token = " + inviteToken)

        if (not "tokenIsValid" in tempapiret) or ("CannotUseTemplate"
                                                  in tempapiret):
            return self.response.write(
                'The supplied invite token is invalid.  Please contact the CLOT author for assistance.'
            )

        #Check if this invite token is new to us
        player = Player.query(Player.inviteToken == inviteToken).get()

        data = json.loads(tempapiret)
        currentColor = data['color']
        currentName = data['name']
        if player is None:
            player = Player(inviteToken=inviteToken,
                            name=currentName,
                            color=currentColor,
                            customProperties={},
                            numberOfGamesAtOnce=5)
            player.put()
            logging.info("Created player " + unicode(player))
        else:
            # Update player details
            if currentColor != player.color:
                player.color = currentColor
            if currentName != player.name:
                player.name = currentName
            player.put()
            logging.info("Update player metadata for " + unicode(player))

        #Set them as participating in the current lot
        addIfNotPresent(container.lot.playersParticipating, player.key.id())
        container.players[player.key.id()] = player
        container.lot.put()
        container.changed()
        logging.info("Player " + unicode(player) + " joined " +
                     unicode(container.lot))

        self.response.write(
            get_template('join.html').render({'container': container}))