def invite_player(gid, iid, invitee):
  """ Add invitee to the list of players invited to the specified instance.

  Args:
    gid: The game id of the Game object that this method targets.
    iid: The instance id of the Game Instance object that this
      method targets.
    invitee: The player id of the person to invite.

  Only modifies the instance if the player has not already been
  invited and has not joined the game.

  Returns:
    A tuple of the game instance and a single item dictionary:
      inv: The email address of the invited player if they are
        invited. If the player is not invited (because they have
        already been invited or have already joined the game), the
        value of 'inv' is the empty string.

  Raises:
    ValueError if the game id, iid or invitee email address are
    invalid.
  """
  utils.check_gameid(gid)
  utils.check_instanceid(iid)
  player = utils.check_playerid(invitee)
  instance = utils.get_instance_model(gid, iid)
  if player not in instance.invited and player not in instance.players:
    instance.invited.append(player)
    instance.put()
  else:
    player = ''
  return instance, {INVITEE_KEY : player}
def server_command(gid, iid, pid, command, arguments):
  """ Performs the desired server command.

  Args:
    gid: The game id of the Game model for this operation.
    iid: The instance id of the GameInstance model for
      this operation.
    pid: The player id of the requesting player.
    command: The key identifying the command to execute.
    arguments: JSON representation of arguments to the command.

  If the gid and iid specify a valid game instance model it will be
  passed to the server command. In the case that the iid is empty or
  refers to a game instance that doesn't exist, a game model will be
  used. Most commands will fail if passed a game model instead of a
  game instance, but some are indifferent to the model passed to
  them.

  Unless the dynamic property do_not_put has been set to False, this
  will put the database model after the command has been
  performed. This means that server commands do not need to make
  intermediate puts of the instance model passed to them.

  Returns:
    A tuple of the model used in the server command's execution and a
    two item dictionary:
      'type': The requested command key.
      'contents': A Python value of the response value of the
        command. This varies among server commands but must always be
        able to be encoded to JSON.

  Raises:
    ValueError if the game id or player id is invalid.
    ValueError if the arguments json cannot be parsed.
    ValueError if command is not a known server command.
  """
  utils.check_gameid(gid)
  player = utils.check_playerid(pid)
  model = None
  if iid:
    model = utils.get_instance_model(gid, iid)
  if model is None:
    model = utils.get_game_model(gid)
    if model is None:
      model = Game(key_name = gid, instance_count = 0)

  arguments = simplejson.loads(arguments)
  reply = ''

  if command in command_dict:
    reply = command_dict[command](model, player, arguments)
    if 'do_not_put' not in model.dynamic_properties() or not model.do_not_put:
      model.put()
  else:
    raise ValueError("Invalid server command: %s." % command)

  if not isinstance(reply, list):
    reply = [reply]
  return model, {TYPE_KEY : command, CONTENTS_KEY: reply}
def join_instance(gid, iid, pid):
  """ Attempt to add a player to an instance.

  Args:
    gid: The game id of the Game object that this method targets.
    iid: The instance id of the Game Instance to join.
    pid: A string containing the requesting player's email address.

  A player can join a game instance if it is not full and either the
  instance is public or the player has been invited. If this
  operation is invoked by a player that is not current in the
  specified instance and they are unable to join, it will fail.

  If the player is already in the game instance this will succeed
  without modifying the instance.

  If the specified game instance doesn't exist, it will be created as
  in new_instance with the specified instance id.

  If no players are in the game when this player tries to join they
  will automatically become the leader.

  Returns:
    A tuple of the game instance and the instance list dictionary
    for this player (see get_instance_lists_as_dictionary).

  Raises:
    ValueError if the game id, instance id or player id are invalid.
    ValueError if the player is not already in the game and is unable
      to join.
  """
  utils.check_gameid(gid)
  utils.check_instanceid(iid)
  player = utils.check_playerid(pid)
  instance = utils.get_instance_model(gid, iid)
  if instance is None:
    return new_instance(gid, iid, pid)
  game = instance.parent()
  instance_lists = get_instances_lists_as_dictionary(game, player)
  instance.add_player(player)
  instance.put()
  if iid in instance_lists['invited']:
    instance_lists['invited'].remove(instance.key().name())
  if iid not in instance_lists['joined']:
    instance_lists['joined'].append(instance.key().name())
  return instance, instance_lists
def new_instance(gid, iid_prefix, pid, make_public = False):
  """ Create a new instance of the specified game.

  Args:
    gid: The game id of the Game parent of the new instance.
    iid_prefix: The desired instance id. If no instance has been made
      with this name before, then this will be the instance id of the
      newly created instance. However, since instance ids must be
      unique, the actual instance id will likely be iid_prefix with a
      number suffix.
    pid: The id of the first player and leader of the game.
    make_public: A boolean indicating whether this instance should
      be able to be seen and joined by anyone.

  The instance id will start with iid_prefix, but could have any
  suffix. If the parent Game object does not exist, it will
  automatically be created.

  Returns:
    A tuple of the newly created instance and an instance lists
    dictionary (see get_instance_lists_as_dictionary).

  Raises:
    ValueError if the gameid or player id are invalid.
  """
  utils.check_gameid(gid)
  player = utils.check_playerid(pid)
  game = Game.get_by_key_name(gid)
  if game is None:
    game = Game(key_name = gid, instance_count = 0)

  if not iid_prefix:
    iid_prefix = player + 'instance'
  instance = game.get_new_instance(iid_prefix, player)

  instance_lists = get_instances_lists_as_dictionary(game, player)
  instance_lists['joined'].append(instance.key().name())
  if make_public:
    instance.public = True
    instance_lists['public'].append(instance.key().name())
  instance.put()
  game.put()

  return instance, instance_lists
def get_instance_lists(gid, iid, pid):
  """ Return the instances that a player has been invited to and joined.

  Args:
    gid: The game id of the Game object that this method targets.
    iid: The instance id of the Game Instance object that this
      method targets.
    pid: A string containing the requesting player's email address.

  The gid and pid must be valid, but the iid can be blank. This is
  because a player must be able to query for lists of instances
  without being in one.

  Returns:
    A tuple containing a database model and a dictionary of instance
    lists.  The database model will be a Game Instance if the gid and
    iid parameters specify a valid GameInstance, otherwise the model
    will be a Game.  Instance lists are returned in the same format
    as get_instance_lists_dictionary.

  Raises:
    ValueError if the game id or player id are invalid.
  """
  utils.check_gameid(gid)
  player = utils.check_playerid(pid)
  model = game = utils.get_game_model(gid)
  if game is None:
    game = Game(key_name = gid, instance_count = 0)
    game.put()
    model = game
  elif iid:
    instance = utils.get_instance_model(gid,iid)
    if instance:
      model = instance
  instance_lists = get_instances_lists_as_dictionary(game, player)
  return model, instance_lists