def assign_character(request, caller_context, container_user):
    ''' data only call, json response
    '''
    
    characterController = CharacterController()
    logging.info('request is: %s' % request)
    if container_user.character:
        json = '{ "success" : true, "message" : "character already assign to this user" }'
        return HttpResponse(json)
    if not 'character_name' in request.REQUEST:
        json = '{ "success" : false, "message" : "Missing required field \'character_name\'" }'
        return HttpResponse(json)
    character_name = request.REQUEST['character_name'].strip()
    character_name = characterController.unquote_u(character_name)
    character_name = re.sub(r'[\'\"<>`]', ' ', character_name)

    character = Character.get_by_key_name(character_name)
    if character:
        container_users = characterController.get_character_users(character)
        if len(container_users):
            # no other container_user has this character, was probably an error in assignment for this user, so assign it now
            container_user.character = character 
            json = '{ "success" : true, "message" : "Found existing character and assigned it to user" }'
            return HttpResponse(json)
        json = '{ "success" : false, "message" : "Character name is already in use" }'
        return HttpResponse(json)
    character = characterController.create_character(caller_context.config, character_name, container_user.profile_image_url, is_fake=False)
    container_user.character = character
    container_user.put()
    response = { "success" : True, 
                 "message" : "Successfully associated character to container user" }
    return json_response(caller_context, container_user, response, False)
def json_response(caller_context, container_user, return_object, include_experience_data):
    ''' adds experience data for status bar to a json response
    '''
    if include_experience_data:
        characterController = CharacterController()
        status_bar_dict = characterController.get_status_bar_dict(caller_context.config, container_user.character) #refresh experience, gold etc
        return_object['experienceData'] = status_bar_dict
        
    encoder = simplejson.JSONEncoder()
    json = encoder.encode(return_object)
    return HttpResponse(json, 'application/json')
def record_invites(request, caller_context, container_user, brick_description=None):
    ''' data only call, json response
    '''
    
    if request.method != 'POST':
        return HttpResponse('only POST method is supported', 'text/plain')
    invitees = request.POST
    if not brick_description or brick_description == 'null':
        raise RuntimeError('no brick_description supplied for record_invites')
    logging.info('invitees: %s' % invitees)
    characterController = CharacterController()
    characterController.record_sent_invites(container_user, invitees, brick_description)
    response = {"success" : True }
    return json_response(caller_context, container_user, response, False)
def main(request, caller_context, container_user, page=1):
    
    pyramidController = PyramidController()
    chamberController = ChamberController()
    characterController = CharacterController()
    
    current_time = datetime.utcnow() - timedelta(hours = 7) #show Pac time to see if this page gets cached

    if not container_user:
        #user isn't logged in, show some open pyramids
        pyramid_ids = pyramidController.find_open_pyramid_ids(None, 1000)
        if len(pyramid_ids) < 10: # if there are fewer than 10 open pyramids, create one 
            pyramid = pyramidController.create_new_pyramid(4, 3, 100) # 4 total levels, fill 3 levels, $100 price
            pyramid_ids.append(pyramid.key().id())
            logging.debug('created new pyramid: ' + pyramid.to_xml())
        if pyramid_ids:
            pyramid_display, paginator, pyramid_page = get_paged_pyramids(caller_context.config, pyramid_ids, container_user)
        group = 'open'
        return render_to_response('_main.html', locals())

    if caller_context.platform == 'myspace_iframe':
        logging.debug('getting friends from container')
        friends_controller = Friends_controller()
        viewer_friends = friends_controller.refresh_container_friends(container_user)
        encoder = simplejson.JSONEncoder()
        viewer_friends_json = encoder.encode(viewer_friends)

    pyramid_ids = None
    if container_user.character:
        status_bar_dict = characterController.get_status_bar_dict(caller_context.config, container_user.character)
        pyramid_ids = pyramidController.get_character_pyramid_ids(container_user.character, True)
        if pyramid_ids:
            pyramid_display, paginator, pyramid_page = get_paged_pyramids(caller_context.config, pyramid_ids, container_user)
            group = 'joined'
            return render_to_response('_main.html', locals())

    # do this here?  refresh friends?
    #saved, failed = friends_controller.save_container_friends(container_user, viewer_friends)
    #friend_pyramid_ids = pyramidController.get_friend_pyramid_ids(container_user.character, True)

    pyramid_ids = pyramidController.find_open_pyramid_ids(None, 200)
    if pyramid_ids:
        pyramid_display, paginator, pyramid_page = get_paged_pyramids(caller_context.config, pyramid_ids, container_user)
    group = 'open'
    return render_to_response('_main.html', locals())
def uncover_square(request, caller_context, container_user, chamber_character_name, grid_pos_x, grid_pos_y):
    ''' data only call, json response
    '''
    chamberController = ChamberController()
    chamber_character = Character.get_by_key_name(chamber_character_name)
    if not chamber_character:
        raise Exception('chamber owner character not found')
    
    uncover_square_result, info, air_level = chamberController.uncover_dig_square(caller_context.config, container_user, chamber_character, int(grid_pos_x), int(grid_pos_y))
    
    if uncover_square_result:
        square = info # if success, info contains the item to return
        response_square = {
                             'gridPosX' : square.position_x,
                             'gridPosY' : square.position_y,
                          }
        if square.item:
            response_square['item'] = { 
                                 'itemName' : square.item.item_name,
                                 'description' : square.item.description,
                                 'smallImageUrl' : caller_context.static_root + square.item.get_small_image_path(),
                                 'largeImageUrl' : caller_context.static_root + square.item.get_large_image_path()
                                 }
        else:
            response_square['item'] = None
        response =  { 'success' : True,
                      'airLevel' : air_level,
                      'square' : response_square
                    }
    else:
        response = { 'success' : False,
                     'reason' : info
                   }

    include_experience_data = False
    if uncover_square_result and square.item:
        characterController = CharacterController()
        characterController.add_character_reward(container_user.character, "found grid treasure", 'experience', 75)
        include_experience_data = True
        
    return json_response(caller_context, container_user, response, include_experience_data)
def get_client_actions(request, caller_context, container_user):
    actions = {}
    
    #make sure we have a character
    if not container_user.character:
        actions['promptForCharacter'] = container_user.display_name
        return json_response(caller_context, container_user, actions, False)

    # check for daily gold bonus
    characterController = CharacterController()
    daily_gold = characterController.check_daily_reward(container_user)
    if daily_gold > 0:
        actions['dailyGold'] = daily_gold

    # get invites
    pyramidController = PyramidController()
    invited_pyramid_ids, invites = pyramidController.get_invited_pyramid_ids(container_user, True)
    if invites:
        actions['invites'] = {}
        for invite in invites:
            actions['invites'][invite.key().name()] = { "character_name" : invite.inviter_character.character_name, 
                                                        "inviterUrl" : invite.inviter_character.image_url }
            #startupJs += 'addToInviteQueue("%s", "%s", "%s");\n' % (invite.key().name(), invite.inviter_character.character_name, invite.inviter_character.image_url)
            
    # check for messages to player
    popup_messages = characterController.get_messages(container_user.character, 20, popup=True, unread=True)
    if popup_messages:
        actions['messages'] = {}
        for message in popup_messages:
            actions['messages'][message.key().name()] = { "title": message.title, 
                                                          "body" : message.body}
    characterController.mark_messages_read(popup_messages) # messages may not have actually been read, this would be better if confirmed via ajax callback
    
    if container_user.character.tutorial_on:
        actions["showTutorial"] = True

    include_experience_data = True
    return json_response(caller_context, container_user, actions, include_experience_data)
def join(request, caller_context, container_user, join_pyramid_id=None, join_brick_id=None, join_invite_key_name=None, action=None):
    ''' data only call, json response
    '''
    pyramidController = PyramidController()
    
    if join_invite_key_name:
        if action == 'accept':
            joinResult, joinInfo  = pyramidController.join_from_invite(caller_context.config, container_user, join_invite_key_name)
        elif action == 'decline':
            joinResult, joinInfo = pyramidController.decline_invite(container_user, join_invite_key_name)
    else:    
        joinResult, joinInfo  = pyramidController.join_pyramid(caller_context.config, int(join_pyramid_id), int(join_brick_id), container_user.character)
    
    joinResponse = { 'success' : joinResult, 
                      'result' : joinInfo}
    
    include_experience_data = False
    if joinResult:
        characterController = CharacterController()
        characterController.add_character_reward(container_user.character, "brick join", 'experience', 75)
        include_experience_data = True
    
    return json_response(caller_context, container_user, joinResponse, include_experience_data)
def messages(request, caller_context, container_user, page=1):
    characterController = CharacterController()
    messages = characterController.get_messages(container_user.character, 30)
    return render_to_response('messages.html', locals())