Esempio n. 1
0
    def get(self):

        isPlayer = login.isPlayer()
        isAdmin = login.isAdmin()

        if not isAdmin and not isPlayer:
            self.response.set_status(500, message='You must log in')
            self.response.out.write('You must log in')
            return

        logging.info(self.request)

        if self.request.get('currentUser'):
            user = users.get_current_user()
            player = Player.all()
            player = player.filter('email =', user.email()).get()
            if player:
                self.response.out.write(playerToJSON(player, isAdmin))
            else:
                self.response.set_status(500, message='You\'re not a player')
                self.response.out.write('You\'re not a player')
                return

        else:
            players = Player.all()
            self.response.out.write(playersToJSON(players, isAdmin))
Esempio n. 2
0
def reset(response):
    for player in Player.all().filter('isStarred', False):
        player.delete()
    for player in Player.all().filter('isStarred', True):
        response.out.write('full')
        player.status = 'waiting'
        player.put()
Esempio n. 3
0
    def post(self):

        if login.isAdmin():

            for player in Player.all().filter('isStarred', False):
                player.delete()
            for player in Player.all().filter('isStarred', True):
                player.status = 'waiting'
                player.put()

            #send message to clients
            result = playersToJSON(Player.all(), True)
            self.response.out.write(result)
            sendMessage(result)
Esempio n. 4
0
    def do_body(self, args):
        """Render the HTMl for the goal scorer tally"""
        year = self.get_year(args)
        mem_key = ScorersPage.get_mem_key(year)
        scorer_page = memcache.get(mem_key)
        if scorer_page is None:
            if year == ALL_YEARS:
                players = Player.all()
            else:
                players = [
                    t.player for t in TeamList.gql('WHERE year = :1', year)
                ]

            scorers = []
            for p in players:
                tally = 0
                for g in p.goal_set:
                    round = g.result.round
                    if (year == ALL_YEARS
                            or year == round.date.year) and round.num > 0:
                        # Only count real goals - negative rounds are trials
                        tally += g.count
                if tally > 0:
                    scorers.append((p.get_short_name(), tally))
            scorers.sort(self.sort_scores)
            data = {
                'scorers': scorers,
            }

            tpath = os.path.join(DeeWhyPage.TEMPLATE_DIR, 'scorers.html')
            scorer_page = template.render(tpath, data)
            memcache.set(mem_key, scorer_page)
        self.response.out.write(scorer_page)
Esempio n. 5
0
 def __init__(self):
   players = Player.all()
   self.player_opponents = {}
   logging.info("Initializing RPI Calculator.")
   logging.info("Finding opponents for all players.")
   for player in players:
     self.player_opponents[hash(player)] = self._get_opponents_for_player(player)
 def get(self):
     
     solids = Player.all()
     solids.filter('solid =', True)
     solids.filter('growth >', 0.0)
     for solid in solids:
         solid.payoutgrowth()
Esempio n. 7
0
    def post(self):
        game_name = self.request.get('game_name')
        game_key = db.Key.from_path('Game', game_name)
        game = db.get(game_key)
        user = users.get_current_user()
        logging.info('Player {0} playing move for game: {1}'.format(
            game, user.nickname()))

        move_type = self.request.get('move_type')
        selected_cards = self.request.get('selected_cards')

        players = Player.all().ancestor(game).run()
        for player in players:
            if player.user == user:
                this_player = player

        if not this_player:
            raise Exception("Player not found: {0}".format(user.nickname()))

        gamestate = {
            "players": players,
            "current_hand": this_player.cards,
            "player_turn": game.player_turn
        }

        for player in players:
            channel.send_message(
                "{0}:{1}".format(game_name, player.user.user_id()),
                json.dumps(gamestate))
Esempio n. 8
0
 def get(self):
     games = memcache.get('gamedates')
     if not games:
         games = GameDate.all()
         games.order('date')
     game = games[0]
     players = memcache.get('players')
     if not players:
         players = Player.all()
         players.order('lname')
         players.order('fname')
         memcache.set('players', players)
     to_list = []
     for player in players:
         if not player.sub:
             to_list.append(player.email)
     email_sender = "Esri Hockey <*****@*****.**>"
     email_subject = "Esri Hockey - %d/%d/%d" % (
         game.date.month, game.date.day, game.date.year)
     email_body = """Head on over to http://esrihockey.appspot.com to let us know if you are in or out."""
     if not game.isThisWeek():
         logging.info("NOT GAME THIS WEEK")
         email_subject = "Esri Hockey - No Game This Week"
         email_body = """Reminder we are off this week. Our next game will be %d/%d/%d.""" % (
             game.date.month, game.date.day, game.date.year)
     mail.send_mail(sender=email_sender,
                    to=to_list,
                    subject=email_subject,
                    body=email_body)
Esempio n. 9
0
 def get(self):
     user = users.get_current_user()
     players = Player.all().filter('user ='******'id'] = s.key().id()
         line['hostedby'] = s.player_1.user.nickname()
         line['started'] = s.started
         line['lastmove'] = s.modified
         if s.state in ('hosted', 'ready'):
             line['turn'] = s.dealer.user.nickname()
         else:
             line['turn'] = s.turn.user.nickname()
         line['state'] = s.state
         result.append(line)
     domain = self.request.headers.get('host', 'no host')
     self.response.out.write(render('sessions.html', options({'sessions': result, 'domain': domain})))
Esempio n. 10
0
	def post(self):
		regulars = self.request.get('regulars')
		subs = self.request.get('subs')
		players = memcache.get('players')		
		if not players:
			players = Player.all()
			players.order("lname")
			players.order("fname")
			memcache.set("players", players)
			
		email_sender = "Esri Hockey <*****@*****.**>"
		allRegulars = self.request.get('allRegulars')
		allSubs = self.request.get('allSubs')	
		email_to = GetEmailList(regulars=allRegulars, subs=allSubs)
		logging.info(email_to)
		email_subject = self.request.get("subject")
		email_body = self.request.get("body")
		if len(email_to) < 1:
			values = { "message" : "Specify regulars or subs.", "email_body":email_body, "email_subject":email_subject}
			path = os.path.join(os.path.dirname(__file__), 'templates/email.html')
			self.response.out.write(template.render(path, values))
			return
		#for player in players:
		#	if player.inThisWeek:
		#		if regulars and not player.sub:
		#			mail.send_mail(sender=email_sender, to=player.email, subject=email_subject, body=email_body)
		mail.send_mail(sender=email_sender, to=email_to, subject=email_subject, body=email_body)
Esempio n. 11
0
	def post(self):
		players = memcache.get('players')
		if not players:
			players = Player.all()
		if players:
			for player in players:
				if player.inThisWeek:
					team = self.request.get("""blueOrWhite%d""" % player.key().id())
					logging.info("team: %s", team)
					if team == "blue" or team == "white":
						player.team = team
						player.put()
		memcache.set('players', players)
		results = db.GqlQuery('SELECT * FROM GameDate ORDER BY date ASC')
		game = results.fetch(1)[0]
		subject = """Esri Hockey Rosters for %d/%d/%d""" % (game.date.month, game.date.day, game.date.year)
		finalize = self.request.get("finalize")		
		if finalize:
			email_body = self.request.get('email_body')
			if email_body == "":
				email_body = """Rosters for Esri Hockey are available at: http://esrihockey.appspot.com/rosters"""
			else:
				appendText = """Rosters for Esri Hockey are available at: http://esrihockey.appspot.com/rosters"""
				email_body = email_body + "\n\n%s" % appendText
			email_to_list = GetEmailListAllIn()
			mail.send_mail(sender="Esri Hockey <*****@*****.**>",
			to=email_to_list,
			subject=subject,
			body=email_body)
		values = { "message" : "Changes have been saved successfully."}
		path = os.path.join(os.path.dirname(__file__), 'templates/admin_success.html')
		self.response.out.write(template.render(path, values))		
  def post(self):
    game_name = self.request.get('game_name')
    game_key = db.Key.from_path('Game', game_name)
    game = db.get(game_key)
    user = users.get_current_user()
    logging.info('Player {0} playing move for game: {1}'.format(game, user.nickname()))

    move_type = self.request.get('move_type')
    selected_cards = self.request.get('selected_cards')

    players = Player.all().ancestor(game).run()
    for player in players:
      if player.user == user:
        this_player = player

    if not this_player:
      raise Exception("Player not found: {0}".format(user.nickname()))

    gamestate = {
      "players": players,
      "current_hand": this_player.cards,
      "player_turn": game.player_turn
    }

    for player in players:
      channel.send_message("{0}:{1}".format(game_name, player.user.user_id()),
        json.dumps(gamestate))
Esempio n. 13
0
def isPlayer():
    user = users.get_current_user()
    if not user:
        return False
    else:
        player = Player.all().filter('email =', user.email()).get()
        return player != None
 def get(self):
     
     solids = Player.all()
     solids.filter('solid =', True)
     solids.filter('taxes >', 0.0)
     for solid in solids:
         solid.payoutdividendamount() #this in turn calls task: dividendpayer
Esempio n. 15
0
def users():
    us = Player.all()
    users = {}
    for u in us:
        users[u.username] = {'username': u.username, 'email': u.email, 'creation_date': u.creation_date,
                             'player_id': u.key().id()}
    return jsonify(**users)
Esempio n. 16
0
def kill():
    try:
        msg = request.json["msg"].upper()
        killer = Player.all().filter('username ='******'game =', game)\
            .filter('killer =', killer)\
            .filter('is_complete =', False).get()
        if msg == old_game_history_success.confirm_msg:
            will_be_last_kill = None
            if GameHistory.all().filter("game =", game).filter("is_complete =", False).count() == 2:
                will_be_last_kill = True
            old_target = old_game_history_success.target
            old_game_history_success.is_complete = True
            old_game_history_success.put()
            old_game_history_failure = GameHistory.all()\
                .filter('game =', game)\
                .filter('killer =', old_target)\
                .filter('is_complete =', False).get()
            old_game_history_failure.is_complete = True
            old_game_history_failure.put()
            if will_be_last_kill:
                game_player = GamePlayer.all().filter('game =', game).filter('player =', killer).get()
                game_player.is_winner = True
                game_player.put()
                return jsonify({"success": True, "info": "Your enemy has been slain! "})
            new_target = old_game_history_failure.target
            GameHistory(killer=killer, target=new_target, game=game, is_complete=False, confirm_msg=msg_generator()).put()
            return jsonify({"success": True, "info": "Your enemy has been slain! "})
        else:
            return jsonify({"success": False, "info": "The message is incorrect. Are you trying to game the system?!"})
    except:  # TODO: please handle exceptions in a more proper way
        return jsonify({"success": False, "info": "Something is fundamentally wrong. ", "Data received by server": str(request.data)})
Esempio n. 17
0
def updateCurrentGames():
    games = memcache.get("gamedates")
    if not games:
        games = GameDate.all()
        games.order("date")
    current_games = []
    deletedGame = False
    now = localTime()
    datetimenow = datetime.datetime(month=now.month, year=now.year, day=now.day)
    for game in games:
        # if game.date.month <= now.month and game.date.day < now.day and game.date.year <= now.year:
        if game.date < datetimenow:
            game.delete()
            deletedGame = True
        else:
            current_games.append(game)
            # when we delete a game, we should also
            # reset all players to be OUT and NOT goalie
    if deletedGame:
        players = Player.all()
        for player in players:
            player.inThisWeek = False
            if not player.sub:
                player.goalie = False
            player.team = ""
            player.put()
        memcache.set("players", players)
        comments = Comment.all()
        for comment in comments:
            comment.delete()
    return current_games
Esempio n. 18
0
def updateCurrentGames():
    games = memcache.get('gamedates')
    if not games:
        games = GameDate.all()
        games.order('date')
    current_games = []
    deletedGame = False
    now = localTime()
    datetimenow = datetime.datetime(month=now.month,
                                    year=now.year,
                                    day=now.day)
    for game in games:
        #if game.date.month <= now.month and game.date.day < now.day and game.date.year <= now.year:
        if game.date < datetimenow:
            game.delete()
            deletedGame = True
        else:
            current_games.append(game)
    # when we delete a game, we should also
    # reset all players to be OUT and NOT goalie
    if deletedGame:
        players = Player.all()
        for player in players:
            player.inThisWeek = False
            if not player.sub:
                player.goalie = False
            player.team = ""
            player.put()
        memcache.set('players', players)
        comments = Comment.all()
        for comment in comments:
            comment.delete()
    return current_games
Esempio n. 19
0
def GetAllPlayers():
    players = memcache.get("players")
    if not players:
        players = Player.all()
        players.order("lname")
        players.order("fname")
        memcache.set("players", players)
    return players
Esempio n. 20
0
def GetAllPlayers():
    players = memcache.get('players')
    if not players:
        players = Player.all()
        players.order("lname")
        players.order("fname")
        memcache.set('players', players)
    return players
Esempio n. 21
0
	def get(self):
		players = Player.all()
		for player in players:
			player.team = None
			player.put()
		values = { "message" : "Rosters have been reset."}
		path = os.path.join(os.path.dirname(__file__), 'templates/admin_success.html')
		self.response.out.write(template.render(path, values))
Esempio n. 22
0
 def getPlayerList(self, status):
     return map(lambda player: 
             {
                 'name': player.name,
                 'current': self.email() == player.email,
                 'id': player.key().id()
             }, 
             Player.all().filter('status', status))
Esempio n. 23
0
def get_user():
    user = None
    if 'username' in request.args:
        user = Player.all().filter('username ='******'username']).get()
    if user is None:
        return jsonify({'success': False, 'info': None})
    info = to_dict(user)
    info.pop("password_hash", None) #We don't want to show the hash
    info['success'] = True
    return jsonify({'success': True, 'info': info})  # does not render a page, just returns a Json
Esempio n. 24
0
    def put(self, id):
        isActive = Configuration.all().filter('name', 'checkin').get()
        isAdmin = login.isAdmin()
        isPlayer = login.isPlayer() and not isAdmin
        user = users.get_current_user()
        if not isAdmin and not isPlayer:
            self.response.out.write('not_logged_in')
        else:
            request = json.loads(self.request.body)
            status = request['status']
            n_presents = Player.all().filter('status =', 'present').count()

            if status != 'present' or n_presents < 10:
                player = None
                if isAdmin:
                    id = long(id)
                    player = Player.get_by_id(id)
                    logging.info('Admin set status to \'' + status + '\' for ' +
                                 str(player.email))
                elif isPlayer and (isActive is None or isActive.value):
                    player = Player.all()
                    player = player.filter('email =', user.email()).get()
                    logging.info(str(player.email) + ' set status to \'' +
                                 status + '\'')

                if player:
                    player.status = status
                    player.put()
                    #self.response.out.write('ok')
                else:
                    logging.info(user.nickname() + ' (' + user.email() +
                                 ') tried to set status to \'' +
                                 status + '\' but it was inactive')
                    self.response.set_status(401, 'La lista &egrave; bloccata o \
                            non sei pi&ugrave; loggato')

            else:
                logging.info(user.nickname() + ' (' + user.email() +
                             ') tried to set status to \'' + status +
                             '\' but it was full')
                self.response.set_status(500, 'La lista &egrave; piena')
Esempio n. 25
0
    def post(self):
        #email = users.get_current_user().email()
        isActive = Configuration.all().filter('name', 'checkin').get()
        isAdmin = login.isAdmin()
        isPlayer = login.isPlayer() and not isAdmin
        user = users.get_current_user()
        if not isAdmin and not isPlayer:
            self.response.out.write('not_logged_in')
        else:
            n_presents = Player.all().filter('status =', 'present').count()
            status = self.request.get('status')
            if status != 'present' or n_presents < 10:
                player = None
                id = self.request.get('id')
                if isAdmin and id:
                    id = long(id)
                    player = Player.get_by_id(id)
                    logging.info('Admin set status to \'' + 
                            status + '\' for ' + str(player.email))
                elif isActive == None or isActive.value:
                    player = Player.all()
                    player = player.filter('email =', user.email()).get()
                    logging.info(str(player.email) + ' set status to \'' + 
                            status + '\'')

                if player:
                    player.status = status
                    player.put()
                    self.response.out.write('ok')
                else:
                    logging.info(user.nickname() + ' (' + user.email() + 
                            ') tried to set status to \'' + status + 
                            '\' but it was inactive')
                    self.response.out.write('inactive')

            else:
                logging.info(user.nickname() + ' (' + user.email() + 
                        ') tried to set status to \'' + status + 
                        '\' but it was full')
                self.response.out.write('full')
Esempio n. 26
0
    def do_body(self, args):
        year = self.get_year(args)
        if year == ALL_YEARS:
            players = Player.all()
        else:
            players = [t.player for t in TeamList.gql('WHERE year = :1', year)]
        players.sort(self.sort_players)
        data = {
            'players': players,
        }

        tpath = os.path.join(DeeWhyPage.TEMPLATE_DIR, 'manage_protected.html')
        protected_page = template.render(tpath, data)
        self.response.out.write(protected_page)
Esempio n. 27
0
def rest_login():
    error = None
    # The first item is username, and the second is password
    user_data = [str(request.json['username']), str(request.json['password'])]  # get this from the url
    player = Player.all().filter('username ='******'Username does not exist'
        return jsonify({'status': error, "user_id": None})
    elif not verify_password(user_data[1], player.password_hash):
        error = "Invalid password"
        return jsonify({'status': error, "user_id": None})
    else:
        session['logged_in'] = True
        flash('You were logged in')
        return jsonify({'status': True, "user_id": player.key().id()})  # this tells the client side that the user is successfully logged in
Esempio n. 28
0
def create_new_game():
    if Game.all().filter('title =', request.json['title']).count() == 0:
        name_of_player_to_join = list(set(request.json['players']))  # Makes sure each player is registered only once
        shuffle(name_of_player_to_join)
        players_to_join = [Player.all().filter('username ='******'title'], num_player=len(players_to_join))
        new_game.put()
        for i in range(-1, len(players_to_join)-1):
            killer = players_to_join[i]
            GamePlayer(game=new_game, player=killer).put()
            target = players_to_join[i+1]
            GameHistory(killer=killer, target=target, game=new_game, is_complete=False, confirm_msg=msg_generator()).put()
        return jsonify({"success": True})
    else:
        return jsonify({"success": False})
Esempio n. 29
0
    def present(self): 
        result = []
        players = Player.all().filter('status', 'present')
        for (counter, player) in enumerate(players):
            result.append({
                    'name': player.name,
                    'current': self.email == player.email,
                    'id': player.key().id(),
                    'team': 'team1' if counter < 5 else 'team2',
                    'index': counter + 1,
                    'playing': True
                })

        #for i in range(len(result), 10):
            #result.append({'index': i + 1})
        return result
Esempio n. 30
0
def games_for_player():
    username = request.args['username']
    # get all users, find where username matches game player
    users = Player.all().filter('username ='******'success': False})
    else:
        user = users.get()
        game_players = user.games
        games = {}
        for gp in game_players:
            game = gp.game
            game_id = game.key().id_or_name()
            games[game_id] = parse_game(game)
        info = {"success": True, "games": games, "username": username}
        return jsonify(**info)
Esempio n. 31
0
	def get(self):
		players = memcache.get('players')
		if not players:
			logging.info("no players in cache")
			players = Player.all()
			players.order("lname")
			players.order("fname")
			memcache.set('players', players)
		skaters = []
		goalies = []
		for player in players:
			if player.inThisWeek:
				if player.goalie:
					goalies.append(player)
				else:
					skaters.append(player)
		values = {"goalies":goalies, "skaters":skaters}
		path = os.path.join(os.path.dirname(__file__), 'templates/edit_rosters.html')
		self.response.out.write(template.render(path, values))
Esempio n. 32
0
  def calculate_rankings(self):
    """
    Calculates rankings based on the RPI method. The implementation
    is naive, and would not work for a large number of players.
    """
    logging.info("Calculating RPI rankings.")
    for player in Player.all():
      wp = stats(player)['percent_win']

      opponents = self.player_opponents[hash(player)]
      owp = self._average_percent_win(opponents)

      opponents_opponents = self._get_opponents_for_players(opponents)
      oowp = self._average_percent_win(opponents_opponents)

      rpi_rank = (wp * 0.25) + (owp * 0.5) + (oowp * 0.25)
      logging.info('For player %s. RPI = %s (%s * 0.25 + %s * 0.5 + %s * 0.25)'
                   % (player.pseudonym,rpi_rank, wp, owp, oowp))

      player.rpi_rank = rpi_rank
      player.put()
Esempio n. 33
0
	def get(self):
		games = memcache.get('gamedates')
		if not games:
			games = GameDate.all()
			games.order('date')
		game = games[0]
		players = memcache.get('players')
		if not players:
			players = Player.all()
			players.order('lname')
			players.order('fname')
			memcache.set('players', players)
		to_list = []
		for player in players:
			if not player.sub:
				to_list.append(player.email)
		email_sender = "Esri Hockey <*****@*****.**>"
		email_subject = "Esri Hockey - %d/%d/%d" % (game.date.month, game.date.day, game.date.year)
		email_body = """Head on over to http://esrihockey.appspot.com to let us know if you are in or out."""		
		if not game.isThisWeek():
			logging.info("NOT GAME THIS WEEK")
			email_subject = "Esri Hockey - No Game This Week"
			email_body = """Reminder we are off this week. Our next game will be %d/%d/%d.""" % (game.date.month, game.date.day, game.date.year)
		mail.send_mail(sender=email_sender, to=to_list, subject=email_subject, body=email_body)
Esempio n. 34
0
def playersToJsonApp(request):

    isPlayer = login.isPlayer()
    isAdmin = login.isAdmin()
    user = users.get_current_user()
    email = str(user.email()) if user else ''

    #uri = 'www.google.com/accounts/o8/id'
    url = request.referer or '/'
    logging.info(url)
    loginUrl = users.create_login_url(url)
    logoutUrl = users.create_logout_url(url)

    result = []
    result.append('{"isAdmin": "' + str(isAdmin) + '", ')
    result.append('"user": "******", ')
    result.append('"isPlayer": "' + str(isPlayer) + '", ')
    result.append('"loginUrl": "' + loginUrl + '", ')
    result.append('"logoutUrl": "' + logoutUrl + '"')

    if isAdmin or isPlayer:
        players = Player.all()
        result.append(', "players": ' + playersToJSON(players, isAdmin) + '')
        currentId = None
        current_user = users.get_current_user()
        for player in players:
            id = str(player.key().id())
            if current_user and current_user.email() == player.email:
                currentId = id

        if currentId:
            result.append(', "id": "' + currentId + '"')

    result.append('}')

    return ''.join(result)
Esempio n. 35
0
def get_game_status():
    info = {"target": None, "in_game": False, "game_exists": False, "msg": None, "player_exists": False, "game_completed": False, "time_left": None}
    try:
        game = Game.get_by_id(int(request.args["game_id"]))
        if game is None:
            info["msg"] = "Game does not exists. "
            return jsonify(info)
        info["game_exists"] = True
        killer = Player.all().filter('username ='******'game =', game).filter('player =', killer).get()
        if player_in is None:
            info["msg"] = "Player trying to kill is not in this game. "
            return jsonify(info)
        info["in_game"] = True
        if GameHistory.all().filter("game =", game).filter("is_complete =", False).count() == 0:
            info["game_completed"] = True
            game_player = GamePlayer.all().filter('game =', game).filter('is_winner =', True).get()
            info["winner_name"] = str(game_player.player.username)
            return jsonify(info)
        to_kill_game_history = GameHistory.all().filter('killer =', killer).filter('game =', game).filter('is_complete', False).get()
        be_killed_game_history = GameHistory.all().filter('target =', killer).filter('game =', game).filter('is_complete', False).get()
        if to_kill_game_history is None:
            return jsonify(info)
        else:
            info["time_left"] = to_kill_game_history.assign_date + timedelta(hours=1)
            info["target"] = to_kill_game_history.target.username
            info["msg"] = be_killed_game_history.confirm_msg
            return jsonify(info)
    except:
        # info["time_left"] = str(datetime.datetime.now())
        info["msg"] = "Something is fundamentally wrong. "
        return jsonify(info)
Esempio n. 36
0
 def getnewsoftinvestments(self):
     players = Player.all()
     players.filter("solid =", False)
     players.order("-creation")
     return players.fetch(10)