예제 #1
0
 def Get(self, user):
     """Our handler for HTTP GET requests - the options are:
    1) game_ajax/list/<useremail> - fetches a list of games for the passed 
          user in least-recently-modified order (permissions check is done)
    2) game_ajax//move/<id>/<index> - fetches a list of entries for the game 
          matching the passed ID. Also takes an optional index URL parameter,
          in which case we send only entries with an index > t (useful for
          checking for updates)
    3) game_ajax/chat/<id>/<index> - fetches a list of chat entries 
          associated with this game. Takes an optional index param
 """
     # make sure the user is logged in
     self.response.headers["Content-Type"] = "text/javascript"
     # Parse the path into distinct entities
     path_list = self.request.path.strip("/").split("/")
     if len(path_list) < 2 or len(path_list) > 4:
         # Invalid query
         self.error(http.HTTP_ERROR)
         self.response.out.write("Invalid request")
     elif len(path_list) == 2:
         # user email passed - make sure they have permission to view the list
         email = urllib.unquote(path_list[1])
         if users.IsCurrentUserAdmin() or user.email() == email:
             game_list = self._get_game_list(user.email())
             # Emit list as array of json entities
             self.response.out.write("[")
             for game in game_list:
                 self.emit_game_as_json(game)
             self.response.out.write("]")
         else:
             self.error(http.HTTP_UNAUTHORIZED)
             self.response.out.write("Permissions error for " + email)
     else:
         # ID passed, look it up
         game = gamemodel.Game.get(path_list[2])
         if game is None:
             self.error(http.HTTP_GONE)
         elif not game.user_can_view(user):
             self.error(http.HTTP_UNAUTHORIZED)
         else:
             if path_list[1] == "chat":
                 # Get the last 200 chats on this channel
                 chatObj = chat.get_chat(str(game.key()), GAME_CHAT_LIMIT)
                 # Get the chat data - either starting at the start index, or
                 # using what the user passed in
                 index = 0
                 if len(path_list) > 3:
                     index = int(path_list[3])
                 if index == 0:
                     index = chatObj.index
                 self.response.out.write(simplejson.dumps(chatObj.to_dict(index)))
             else:
                 # Get the game data
                 index = 0
                 if len(path_list) > 3:
                     index = int(path_list[3])
                 result = game.to_dict(user)
                 result["num_moves"] = len(game.game_data)
                 result["game_data"] = game.game_data[index:]
                 self.response.out.write(simplejson.dumps(result))
예제 #2
0
  def Get(self, user):
    """ Sends down a list of players and games for the lobby in json format.

        The URL format is:
           GET /lobby/useremail/<opt_msgid>
           
        Fetches a list of games for the passed user.

        If the opt_msgid is present, we return a list of chats that were sent
        after that msgid, otherwise the chat list will be empty

        Response is a Javascript object with 4 attributes:
        {
          'player_list': ["player 1", "player 2"...],  // string array

          'game_list': [
            {
             // See Game.to_dict() for information about the format of
             // each game
            },
            ...more games...
          ],

          'chat_list': {
            'msg_id': 12345,             // The msg_id to pass up on the next
                                         // update
            data: [
              { 'author': "player 1",    // Omitted if this is a system msg
                'data': "blah blah blah"
              },
              ...more chats...
            ]
          }
        }
        
    """
    self.response.headers['Content-Type'] = 'text/javascript'
    # Parse the path into distinct entities
    path_list = self._get_path_list(user)
    if path_list:
      # Get the msgid if any
      msgid = 0
      if len(path_list) == 3:
        try:
          msgid = int(path_list[2])
        except ValueError:
          # Just ignore this and leave msgid as 0
          msgid = 0
            
      # Let the lobby know the user is here
      lobby.in_lobby(user)

      # Build our response and write it out
      response = {}
      response['player_list'] = self.get_player_list()
      response['game_list'] = self.get_game_list(user)
      response['chat_list'] = chat.get_chat("lobby", 50).to_dict(msgid)
      self.response.out.write(simplejson.dumps(response))
예제 #3
0
    def Get(self, user):
        """ Sends down a list of players and games for the lobby in json format.

        The URL format is:
           GET /lobby/useremail/<opt_msgid>
           
        Fetches a list of games for the passed user.

        If the opt_msgid is present, we return a list of chats that were sent
        after that msgid, otherwise the chat list will be empty

        Response is a Javascript object with 4 attributes:
        {
          'player_list': ["player 1", "player 2"...],  // string array

          'game_list': [
            {
             // See Game.to_dict() for information about the format of
             // each game
            },
            ...more games...
          ],

          'chat_list': {
            'msg_id': 12345,             // The msg_id to pass up on the next
                                         // update
            data: [
              { 'author': "player 1",    // Omitted if this is a system msg
                'data': "blah blah blah"
              },
              ...more chats...
            ]
          }
        }
        
    """
        self.response.headers['Content-Type'] = 'text/javascript'
        # Parse the path into distinct entities
        path_list = self._get_path_list(user)
        if path_list:
            # Get the msgid if any
            msgid = 0
            if len(path_list) == 3:
                try:
                    msgid = int(path_list[2])
                except ValueError:
                    # Just ignore this and leave msgid as 0
                    msgid = 0

            # Let the lobby know the user is here
            lobby.in_lobby(user)

            # Build our response and write it out
            response = {}
            response['player_list'] = self.get_player_list()
            response['game_list'] = self.get_game_list(user)
            response['chat_list'] = chat.get_chat("lobby", 50).to_dict(msgid)
            self.response.out.write(simplejson.dumps(response))
예제 #4
0
def get_reply():
    '''
    参数格式:{"content":"text"}
    :return: {"content":"text"}
    '''
    content = request.args["content"]
    reply = chat.get_chat(content)
    print(reply)
    return json.dumps({"content": reply})
예제 #5
0
def chat_view(request, match_id):
    logs = chat.get_chat(match_id)
    if logs is not None:
        t = loader.get_template('chat.html')
        c = Context({'logs': logs})
        return HttpResponse(t.render(c))
    else:
        t = loader.get_template('error.html')
        c = Context({'id': match_id})
        return HttpResponse(t.render(c))
예제 #6
0
def chat_view(request, match_id):
    logs = chat.get_chat(match_id)
    if logs is not None:
        t = loader.get_template('chat.html')
        c = Context({'logs': logs})
        return HttpResponse(t.render(c))
    else:
        t = loader.get_template('error.html')
        c = Context({'id': match_id})
        return HttpResponse(t.render(c))
예제 #7
0
 def Get(self, user):
     """Our handler for HTTP GET requests - the options are:
    1) game_ajax/list/<useremail> - fetches a list of games for the passed 
          user in least-recently-modified order (permissions check is done)
    2) game_ajax//move/<id>/<index> - fetches a list of entries for the game 
          matching the passed ID. Also takes an optional index URL parameter,
          in which case we send only entries with an index > t (useful for
          checking for updates)
    3) game_ajax/chat/<id>/<index> - fetches a list of chat entries 
          associated with this game. Takes an optional index param
 """
     # make sure the user is logged in
     self.response.headers['Content-Type'] = 'text/javascript'
     # Parse the path into distinct entities
     path_list = self.request.path.strip('/').split('/')
     if len(path_list) < 2 or len(path_list) > 4:
         # Invalid query
         self.error(http.HTTP_ERROR)
         self.response.out.write('Invalid request')
     elif len(path_list) == 2:
         # user email passed - make sure they have permission to view the list
         email = urllib.unquote(path_list[1])
         if (users.IsCurrentUserAdmin() or user.email() == email):
             game_list = self._get_game_list(user.email())
             # Emit list as array of json entities
             self.response.out.write('[')
             for game in game_list:
                 self.emit_game_as_json(game)
             self.response.out.write(']')
         else:
             self.error(http.HTTP_UNAUTHORIZED)
             self.response.out.write('Permissions error for ' + email)
     else:
         # ID passed, look it up
         game = gamemodel.Game.get(path_list[2])
         if game is None:
             self.error(http.HTTP_GONE)
         elif not game.user_can_view(user):
             self.error(http.HTTP_UNAUTHORIZED)
         else:
             if (path_list[1] == "chat"):
                 # Get the last 200 chats on this channel
                 chatObj = chat.get_chat(str(game.key()), GAME_CHAT_LIMIT)
                 # Get the chat data - either starting at the start index, or
                 # using what the user passed in
                 index = 0
                 if len(path_list) > 3:
                     index = int(path_list[3])
                 if index == 0:
                     index = chatObj.index
                 self.response.out.write(
                     simplejson.dumps(chatObj.to_dict(index)))
             else:
                 # Get the game data
                 index = 0
                 if len(path_list) > 3:
                     index = int(path_list[3])
                 result = game.to_dict(user)
                 result["num_moves"] = len(game.game_data)
                 result["game_data"] = game.game_data[index:]
                 self.response.out.write(simplejson.dumps(result))
예제 #8
0
def get_chat(update):
    chatId = int(update["message"]["chat"]["id"])
    if chat.has_chat(chatId):
        return chat.get_chat(chatId)
    return chat.new_chat(chatId, update["message"]["chat"]["first_name"],
                         update["message"]["chat"]["username"])
예제 #9
0
def do_chat():
    content = bottle.request.body.read().decode()
    content = json.loads(content)
    chat.add_message(content['message'])

    return json.dumps(chat.get_chat())
예제 #10
0
def get_chat():
    return json.dumps(chat.get_chat())
예제 #11
0
파일: dex.py 프로젝트: ramsay/projectloot
 def Get(self, user):
     ''' Our handler for HTTP GET requests, copying from GAE demo
     "blitz"
     1) game_ajax/list/<useremail> - fetches a list of games for the passed 
          user in least-recently-modified order (permissions check is done)
     2) game_ajax//move/<id>/<index> - fetches a list of entries for the game 
          matching the passed ID. Also takes an optional index URL parameter,
          in which case we send only entries with an index > t (useful for
          checking for updates)
     3) game_ajax/chat/<id>/<index> - fetches a list of chat entries 
          associated with this game. Takes an optional index param
     '''
     # make sure the user is logged in
     self.response.headers['Content-Type'] = 'text/javascript'
     # Parse the path into distinct entities
     path_list = self.request.path.strip('/').split('/')
     if len(path_list) < 2 or len(path_list) > 4:
         # Invalid query
         self.error(http.HTTP_ERROR)
         self.response.out.write('Invalid request')
     elif len(path_list) == 2:
         # user email passed - make sure they have permission to view the list
         email = urllib.unquote(path_list[1])
         if (users.IsCurrentUserAdmin() or user.email() == email):
             game_list = self._get_game_list(user.email())
             # Emit list as array of json entities
             self.response.out.write('[')
             for game in game_list:
                 self.emit_game_as_json(game)
             self.response.out.write(']')
         else:
             self.error(http.HTTP_UNAUTHORIZED)
             self.response.out.write('Permissions error for ' + email)
     else:
         # ID passed, look it up
         battle = Battle.get(path_list[2])
         if battle is None:
             self.error(http.HTTP_GONE)
         elif not battle.user_can_view(user):
             self.error(http.HTTP_UNAUTHORIZED)
         else:
             if (path_list[1] == "chat"):
                 # Get the last 200 chats on this channel
                 chatObj = chat.get_chat(str(battle.key()), GAME_CHAT_LIMIT)
                 # Get the chat data - either starting at the start index, or
                 # using what the user passed in
                 index = 0
                 if len(path_list) > 3:
                     index = int(path_list[3])
                 if index == 0:
                     index = chatObj.index
                 self.response.out.write(simplejson.dumps(chatObj.to_dict(index)))
             else:
                 # Get the game data
                 index = 0
                 if len(path_list) > 3:
                     index = int(path_list[3])
                 result = battle.to_dict(user)
                 result["num_moves"] = len(battle.game_data)
                 result["game_data"] = []
                 if result["num_moves"] > 0:
                     result["game_data"] = battle.game_data[index:]
                 result["teams"] ={'black': {
     'health': 10,
     'magic': 4,
     'defense': 0,
     'roster': [
         {
             'name': 'Fighter',
             'img_class': '.warrior',
             'strength': 2,
             'agility': 3,
             'defense': 1,
             'ability' : { 'name': 'Roar',
                         'cost': 0,
                         'description': 'Strike fear in the hears of foes'},
         },
         {   'name': 'Mage',
             'img_class': '.white_mage',
             'strength': 1,
             'agility': 5,
             'defense': 1,
             'ability' : { 'name': 'Heal',
                         'cost': 2,
                         'description': 'use primitive medical skills'}
         }
     ]
 },'white': {
     'health': 10,
     'magic': 4,
     'defense': 0,
     'roster': [
         {
             'name': 'Fighter',
             'img_class': '.warrior',
             'strength': 2,
             'agility': 3,
             'defense': 1,
             'ability' : { 'name': 'Roar',
                         'cost': 0,
                         'description': 'Strike fear in the hears of foes'},
         },
         {   'name': 'Mage',
             'img_class': '.white_mage',
             'strength': 1,
             'agility': 5,
             'defense': 1,
             'ability' : { 'name': 'Heal',
                         'cost': 2,
                         'description': 'use primitive medical skills'}
         }
     ]
 }
                                   }
                 self.response.out.write(simplejson.dumps(result))