Beispiel #1
0
def add_forum_bot(team_id=0):
    if not team_id or not g.user.is_team_leader(team_id):
        flash(u'You must be a team leader to add a forum helper.', 'error')
        return redirect(url_for('teams.my_teams'))

    form = ForumBotForm()
    form.game_id.choices = [ (-1, "Any match is added") ]
    form.game_id.choices += [ (game.id, "A %s match is added" % game.name) for \
            game in Game.query.all() ]
    if form.validate_on_submit():
        if form.game_id.data <= 0:
            game_id = None
        else:
            game_id = form.game_id.data

        forum_bot = ForumBot(team_id=team_id,
                             game_id=game_id,
                             type=form.type.data,
                             url=form.url.data,
                             forum_id=form.forum_id.data,
                             user_name=form.user_name.data,
                             password=form.password.data)
        db.session.add(forum_bot)
        db.session.commit()
        flash(u'The forum helper was successfully added.', 'success')
        return redirect(url_for('forum_bots',team_id=team_id))

    return rt('team_admin/forum_bot_form.html',
            team={'id' : team_id, 'name':g.user.teams[team_id].name},
            page={'top':'my_teams', 'sub':'forum_bots'},
            adding=True, form=form)
Beispiel #2
0
def add():
    if g.user.is_on_team():
        flash(u'You are already on a team.  Leave your current team first '
               'before creating a new one.', 'error')
        return redirect(url_for('my_teams'))

    team_names = [ t.name.lower() for t in Team.query.all() ]

    form = TeamForm()
    form.name.validators[0].values = team_names

    if form.validate_on_submit():
        team = Team(name=form.name.data,
                    tag=form.tag.data,
                    url=form.url.data,
                    date_created=datetime.datetime.utcnow(),
                    join_password=form.join_password.data)
        db.session.add(team)
        db.session.commit()

        # hmm, need to commit the team to get the team id
        team_player = TeamPlayer(team_id=team.id, user_id=g.user.id,
                                 status=TeamPlayer.StatusFounder)
        db.session.add(team_player)
        db.session.commit()

        flash(u'The team was successfully created.', 'success')
        return redirect(url_for('my_teams'))

    return rt('teams/create.html',
            page={'top': 'teams', 'sub': 'add_team'},
            adding=True,
            form=form)
Beispiel #3
0
def force_login(username):
    if app.debug:
        user = User.query.filter_by(name=username).first()
        if user is not None:
            flash(u'You are now logged in as %s.' % username, 'success')
            session['force_login'] = username
            g.user = user
        return redirect(url_for('create_profile'))
    return redirect(url_for('.index'))
Beispiel #4
0
def add_opponent(team_id=0):
    if not g.user.is_team_leader(team_id):
        flash(u'You must be a team leader to add an opponent.', 'error')
        return redirect(url_for('teams.my_teams'))

    opponents = Opponent.query.\
            filter_by(team_id=team_id).\
            order_by(Opponent.name.asc()).\
            all()

    api = request.values.get('api') == '1'

    form = OpponentForm()
    form.name.validators[0].values = [o.name for o in opponents]
    if form.validate_on_submit():
        opponent = Opponent(team_id=team_id,
                            name=form.name.data,
                            tag=form.tag.data)
        db.session.add(opponent)
        db.session.commit()
        flash(u'The opponent was successfully added.', 'success')

        if api:
            return jsonify(success=True,
                           opponent_id=opponent.id,
                           csrf=form.csrf_token.data,
                           opponent_name=opponent.name)

        if form.f.data == 'add_match':
            return redirect(url_for('matches.add',
                                    new_opponent_id=opponent.id))
        elif form.f.data:
            return redirect(
                url_for('matches.show',
                        action='edit',
                        match_id=int(form.f.data),
                        new_opponent_id=opponent.id))

        return redirect(url_for('opponents', team_id=team_id))

    form.f.data = request.values.get('f') or ''

    return rt('team_admin/opponent_form.html',
              team={
                  'id': team_id,
                  'name': g.user.teams[team_id].name
              },
              page={
                  'top': 'my_teams',
                  'sub': 'opponents'
              },
              adding=True,
              form=form)
Beispiel #5
0
def add_server(team_id=0):
    if not g.user.is_team_leader(team_id):
        flash(u'You must be a team leader to add a server.', 'error')
        return redirect(url_for('teams.my_teams'))

    servers = Server.query.\
            filter_by(team_id=team_id).\
            order_by(Server.name.asc()).\
            all()

    api = request.values.get('api') == '1'

    form = ServerForm()
    form.name.validators[0].values = [s.name for s in servers]
    if form.validate_on_submit():
        server = Server(team_id=team_id,
                        name=form.name.data,
                        address=form.address.data)
        db.session.add(server)
        db.session.commit()
        flash(u'The server was successfully added.', 'success')

        if api:
            return jsonify(success=True,
                           server_id=server.id,
                           csrf=form.csrf_token.data,
                           server_name=server.name)

        if form.f.data == 'add_match':
            return redirect(url_for('matches.add', new_server_id=server.id))
        elif form.f.data:
            return redirect(
                url_for('matches.show',
                        action='edit',
                        match_id=int(form.f.data),
                        new_server_id=server.id))

        return redirect(url_for('servers', team_id=team_id))

    form.f.data = request.values.get('f') or ''

    return rt('team_admin/server_form.html',
              page={
                  'top': 'my_teams',
                  'sub': 'servers'
              },
              team={
                  'id': team_id,
                  'name': g.user.teams[team_id].name
              },
              adding=True,
              form=form)
Beispiel #6
0
def create_or_login(resp):
    session['openid'] = resp.identity_url
    session.permanent = True

    user = User.query.filter_by(openid=resp.identity_url).first()
    if user is not None:
        flash(u'You were successfully signed in.', 'success')
        g.user = user
        return redirect(oid.get_next_url())

    return redirect(url_for('create_profile',
                            next=oid.get_next_url(),
                            name=resp.nickname,
                            email=resp.email))
Beispiel #7
0
def show(cmatch_id):
    cmatch = CompletedMatch.query.filter_by(id=cmatch_id).first()
    if not cmatch:
        flash(u'Match not found', 'error')
        return redirect('show_all')

    if g.user.is_on_team(cmatch.team_id):
        page={'top':'my_matches','sub':'previous'}
    else:
        page={'top':'matches','sub':'previous'}

    players = dict()
    kills = collections.defaultdict(int)
    deaths = collections.defaultdict(int)
    off_objs = collections.defaultdict(int)
    def_objs = collections.defaultdict(int)
    score = collections.defaultdict(int)
    for r in cmatch.rounds:
        for p in r.players:
            kills[p.user_id] += p.kills
            deaths[p.user_id] += p.deaths
            players[p.user_id] = p.user.name
            off_objs[p.user_id] += p.off_objs
            def_objs[p.user_id] += p.def_objs
            score[p.user_id] += p.score

    return rt('results/single.html',
            page=page,
            players=players,
            kills=kills,
            deaths=deaths,
            off_objs=off_objs,
            def_objs=def_objs,
            score=score,
            cmatch=cmatch)
Beispiel #8
0
def opponent(team_id, opponent_id, action):
    if not g.user.is_team_leader(team_id):
        flash(u'You must be a team leader to add an opponent.', 'error')
        return redirect(url_for('teams.my_teams'))

    opponent = Opponent.query.filter_by(id=opponent_id).first()

    if not opponent or not g.user.is_team_leader(opponent.team_id) \
            or team_id != opponent.team_id:
        flash(u'Opponent not found.', 'error')
        return redirect(url_for('teams.my_teams'))

    if action == 'edit':
        opponents = Opponent.query.\
                filter_by(team_id=team_id).\
                order_by(Opponent.name.asc()).\
                all()

        form = OpponentForm(request.form, obj=opponent)
        form.name.validators[0].values = [ o.name for o in opponents if o.id\
                != opponent_id ]
        if form.validate_on_submit():
            form.populate_obj(opponent)
            db.session.commit()
            flash(u'The opponent was successfully updated.', 'success')
        else:
            return rt('team_admin/opponent_form.html',
                      page={
                          'top': 'my_teams',
                          'sub': 'opponents'
                      },
                      team={
                          'id': team_id,
                          'name': g.user.teams[team_id].name
                      },
                      opponent_id=opponent_id,
                      adding=False,
                      form=form)
    elif action == 'delete':
        if request.method == 'POST':
            db.session.delete(opponent)
            db.session.commit()
            flash(u'The opponent was successfully deleted.', 'success')

    return redirect(url_for('opponents', team_id=team_id))
Beispiel #9
0
def add_opponent(team_id=0):
    if not g.user.is_team_leader(team_id):
        flash(u'You must be a team leader to add an opponent.', 'error')
        return redirect(url_for('teams.my_teams'))

    opponents = Opponent.query.\
            filter_by(team_id=team_id).\
            order_by(Opponent.name.asc()).\
            all()

    api = request.values.get('api') == '1'

    form = OpponentForm()
    form.name.validators[0].values = [ o.name for o in opponents ]
    if form.validate_on_submit():
        opponent = Opponent(team_id=team_id,
                            name=form.name.data,
                            tag=form.tag.data)
        db.session.add(opponent)
        db.session.commit()
        flash(u'The opponent was successfully added.', 'success')

        if api:
            return jsonify(success=True, opponent_id=opponent.id,
                    csrf=form.csrf_token.data,
                    opponent_name=opponent.name)

        if form.f.data == 'add_match':
            return redirect(url_for('matches.add', new_opponent_id=opponent.id))
        elif form.f.data:
            return redirect(url_for('matches.show', action='edit',
                match_id=int(form.f.data), new_opponent_id=opponent.id))

        return redirect(url_for('opponents',team_id=team_id))

    form.f.data = request.values.get('f') or ''

    return rt('team_admin/opponent_form.html',
            team={'id' : team_id, 'name':g.user.teams[team_id].name},
            page={'top':'my_teams', 'sub':'opponents'},
            adding=True, form=form)
Beispiel #10
0
def add_server(team_id=0):
    if not g.user.is_team_leader(team_id):
        flash(u'You must be a team leader to add a server.', 'error')
        return redirect(url_for('teams.my_teams'))

    servers = Server.query.\
            filter_by(team_id=team_id).\
            order_by(Server.name.asc()).\
            all()

    api = request.values.get('api') == '1'

    form = ServerForm()
    form.name.validators[0].values = [ s.name for s in servers ]
    if form.validate_on_submit():
        server = Server(team_id=team_id,
                        name=form.name.data,
                        address=form.address.data)
        db.session.add(server)
        db.session.commit()
        flash(u'The server was successfully added.', 'success')

        if api:
            return jsonify(success=True, server_id=server.id,
                    csrf=form.csrf_token.data,
                    server_name=server.name)

        if form.f.data == 'add_match':
            return redirect(url_for('matches.add', new_server_id=server.id))
        elif form.f.data:
            return redirect(url_for('matches.show', action='edit',
                match_id=int(form.f.data), new_server_id=server.id))

        return redirect(url_for('servers',team_id=team_id))

    form.f.data = request.values.get('f') or ''

    return rt('team_admin/server_form.html',
            page={'top':'my_teams', 'sub':'servers'},
            team={'id':team_id,'name':g.user.teams[team_id].name},
            adding=True, form=form)
Beispiel #11
0
def forum_bot(team_id,forum_bot_id, action):
    if not g.user.is_team_leader(team_id):
        flash(u'You must be a team leader to add a forum helper.', 'error')
        return redirect(url_for('teams.my_teams'))

    forum_bot = ForumBot.query.filter_by(id=forum_bot_id).first()

    if not forum_bot or team_id != forum_bot.team_id:
        flash(u'Forum helper not found.', 'error')
        return redirect(url_for('teams.my_teams'))

    if action == 'edit':
        form = ForumBotForm(request.form, obj=forum_bot)
        # can't change the team to which the forum_bot belongs when editing
        form.game_id.choices = [ (-1, "Any match is added") ]
        form.game_id.choices += [ (game.id, "A %s match is added" % game.name) for \
                game in Game.query.all() ]
        if form.validate_on_submit():
            if form.game_id.data <= 0:
                form.game_id.data = None
            else:
                form.game_id.data = form.game_id.data
            form.populate_obj(forum_bot)
            db.session.commit()
            flash(u'The forum helper was successfully updated.', 'success')
        else:
            return rt('team_admin/forum_bot_form.html',
                    page={'top':'my_teams', 'sub':'forum_bots'},
                    team={'id' : team_id, 'name':g.user.teams[team_id].name},
                    forum_bot_id=forum_bot_id,
                    adding=False, form=form)
    elif action == 'delete':
        if request.method == 'POST':
            db.session.delete(forum_bot)
            db.session.commit()
            flash(u'The forum helper was successfully deleted.', 'success')

    return redirect(url_for('forum_bots', team_id=team_id))
Beispiel #12
0
def server(team_id, server_id, action):
    if not g.user.is_team_leader(team_id):
        flash(u'You must be a team leader to add a server.', 'error')
        return redirect(url_for('teams.my_teams'))

    server = Server.query.filter_by(id=server_id).first()

    if not server or not g.user.is_team_leader(server.team_id):
        flash(u'Server not found.', 'error')
        return redirect(url_for('teams.my_teams'))

    if action == 'edit':
        servers = Server.query.\
                filter_by(team_id=team_id).\
                order_by(Server.name.asc()).\
                all()

        form = ServerForm(request.form, obj=server)
        form.name.validators[0].values = [ s.name for s in servers if s.id != \
                server_id ]

        if form.validate_on_submit():
            form.populate_obj(server)
            db.session.commit()
            flash(u'The server was successfully updated.', 'success')
        else:
            return rt('team_admin/server_form.html',
                    team={'id':team_id, 'name':g.user.teams[team_id].name},
                    page={'top':'my_teams', 'sub':'servers'},
                    server_id=server_id,
                    adding=False, form=form)
    elif action == 'delete':
        if request.method == 'POST':
            db.session.delete(server)
            db.session.commit()
            flash(u'The server was successfully deleted.', 'success')

    return redirect(url_for('servers',team_id=team_id))
Beispiel #13
0
def opponent(team_id, opponent_id, action):
    if not g.user.is_team_leader(team_id):
        flash(u'You must be a team leader to add an opponent.', 'error')
        return redirect(url_for('teams.my_teams'))

    opponent = Opponent.query.filter_by(id=opponent_id).first()

    if not opponent or not g.user.is_team_leader(opponent.team_id) \
            or team_id != opponent.team_id:
        flash(u'Opponent not found.', 'error')
        return redirect(url_for('teams.my_teams'))

    if action == 'edit':
        opponents = Opponent.query.\
                filter_by(team_id=team_id).\
                order_by(Opponent.name.asc()).\
                all()

        form = OpponentForm(request.form, obj=opponent)
        form.name.validators[0].values = [ o.name for o in opponents if o.id\
                != opponent_id ]
        if form.validate_on_submit():
            form.populate_obj(opponent)
            db.session.commit()
            flash(u'The opponent was successfully updated.', 'success')
        else:
            return rt('team_admin/opponent_form.html',
                    page={'top':'my_teams', 'sub':'opponents'},
                    team={'id' : team_id, 'name':g.user.teams[team_id].name},
                    opponent_id=opponent_id,
                    adding=False, form=form)
    elif action == 'delete':
        if request.method == 'POST':
            db.session.delete(opponent)
            db.session.commit()
            flash(u'The opponent was successfully deleted.', 'success')

    return redirect(url_for('opponents', team_id=team_id))
Beispiel #14
0
def opponents(team_id):
    if not team_id or not g.user.is_team_leader(team_id):
        flash(u'You must be a team leader to administrate the team.', 'error')
        return redirect(url_for('teams.my_teams'))

    opponents = Opponent.query.\
            filter_by(team_id=team_id).\
            order_by(Opponent.name.asc()).\
            all()

    return rt('team_admin/opponents.html',
            page={'top':'my_teams','sub':'opponents'},
            team={'id' : team_id, 'name':g.user.teams[team_id].name},
            opponents=opponents)
Beispiel #15
0
def servers(team_id):
    if not team_id or not g.user.is_team_leader(team_id):
        flash(u'You must be a team leader to administrate the team.', 'error')
        return redirect(url_for('teams.my_teams'))

    servers = Server.query.\
            filter_by(team_id=team_id).\
            order_by(Server.name.asc()).\
            all()

    return rt('team_admin/servers.html',
            page={'top':'my_teams','sub':'servers'},
            team={'id' : team_id, 'name':g.user.teams[team_id].name},
            servers=servers)
Beispiel #16
0
def forum_bots(team_id=0):
    if not team_id or not g.user.is_team_leader(team_id):
        flash(u'You must be a team leader to administrate the team.', 'error')
        return redirect(url_for('teams.my_teams'))

    forum_bots = ForumBot.query.\
            filter_by(team_id=team_id).\
            order_by(ForumBot.id.desc()).\
            all()

    return rt('team_admin/forum_bots.html',
            page={'top':'my_teams','sub':'forum_bots'},
            team={'id' : team_id, 'name':g.user.teams[team_id].name},
            forum_bots=forum_bots)
Beispiel #17
0
def create_profile():
    if app.debug and 'openid' not in session:
        session['openid'] = 'test'

    if not g.user.is_guest or 'openid' not in session:
        return redirect(url_for('.index'))

    names = set()
    emails = set()
    for u in User.query.all():
        if u.name is not None:
            names.add(u.name.lower())
        if u.email is not None:
            emails.add(u.email.lower())

    form = UserForm()
    form.name.validators[0].values = names
    form.email.validators[0].values = emails

    if form.validate_on_submit():
        user = User(name=form.name.data,
                    email=form.email.data,
                    openid=session['openid'])

        db.session.add(user)
        db.session.commit()
        flash(u'Your profile was successfully created.', 'success')
        return redirect(oid.get_next_url())

    if not len(form.errors):
        form.name.data = request.values.get('name')
        form.email.data = request.values.get('email')

    form.next.data = oid.get_next_url()

    return rt('account/create.html', form=form)
Beispiel #18
0
def my_previous_matches():
    if g.user.is_guest:
        return redirect(url_for('all'))

    cutoff = datetime.datetime.utcnow()
    matches = Match.query.\
            filter(Match.team_id.in_(g.user.teams.keys())).\
            filter(Match.date <= cutoff).\
            options(eagerload('competition'), \
                    eagerload('server')).\
            order_by(Match.date.asc()).\
            order_by(Match.id.asc()).\
            all()

    return rt('matches/table.html',
        page={'top':'my_matches', 'sub':'previous'},
        previous_only=True,
        previous=matches)
Beispiel #19
0
def all(team_id=0):  # show all matches
    team = None
    if team_id:
        if not g.user.is_on_team(team_id):
            team = Team.query.filter_by(id=team_id).first()

            if not team:
                return redirect(url_for('all'))

            page = {'top': 'team', 'sub': 'matches'}
        else:
            team = {'id': team_id, 'name': g.user.teams[team_id].name}
            page = {'top': 'my_teams', 'sub': 'matches'}

        matches=Match.query.\
                options(eagerload('competition')).\
                filter_by(team_id=team_id).\
                order_by(Match.date.asc()).\
                order_by(Match.id.asc()).\
                all()
    else:
        matches=Match.query.\
                options(eagerload('competition')).\
                order_by(Match.date.asc()).\
                order_by(Match.id.asc()).\
                all()
        page = {'top': 'matches', 'sub': 'all_matches'}

    now = datetime.datetime.utcnow()
    upcoming = []
    previous = []
    for m in matches:
        if m.date > now:
            upcoming.append(m)
        else:
            previous.append(m)

    return rt('matches/table.html',
              page=page,
              team=team,
              upcoming=upcoming,
              previous=previous)
Beispiel #20
0
def forum_bots(team_id=0):
    if not team_id or not g.user.is_team_leader(team_id):
        flash(u'You must be a team leader to administrate the team.', 'error')
        return redirect(url_for('teams.my_teams'))

    forum_bots = ForumBot.query.\
            filter_by(team_id=team_id).\
            order_by(ForumBot.id.desc()).\
            all()

    return rt('team_admin/forum_bots.html',
              page={
                  'top': 'my_teams',
                  'sub': 'forum_bots'
              },
              team={
                  'id': team_id,
                  'name': g.user.teams[team_id].name
              },
              forum_bots=forum_bots)
Beispiel #21
0
def opponents(team_id):
    if not team_id or not g.user.is_team_leader(team_id):
        flash(u'You must be a team leader to administrate the team.', 'error')
        return redirect(url_for('teams.my_teams'))

    opponents = Opponent.query.\
            filter_by(team_id=team_id).\
            order_by(Opponent.name.asc()).\
            all()

    return rt('team_admin/opponents.html',
              page={
                  'top': 'my_teams',
                  'sub': 'opponents'
              },
              team={
                  'id': team_id,
                  'name': g.user.teams[team_id].name
              },
              opponents=opponents)
Beispiel #22
0
def servers(team_id):
    if not team_id or not g.user.is_team_leader(team_id):
        flash(u'You must be a team leader to administrate the team.', 'error')
        return redirect(url_for('teams.my_teams'))

    servers = Server.query.\
            filter_by(team_id=team_id).\
            order_by(Server.name.asc()).\
            all()

    return rt('team_admin/servers.html',
              page={
                  'top': 'my_teams',
                  'sub': 'servers'
              },
              team={
                  'id': team_id,
                  'name': g.user.teams[team_id].name
              },
              servers=servers)
Beispiel #23
0
def my_matches():
    if g.user.is_guest:
        return redirect(url_for('all'))

    cutoff = datetime.datetime.utcnow() - datetime.timedelta(hours=1)
    matches = Match.query.\
            outerjoin(CompletedMatch).\
            filter(CompletedMatch.id == None).\
            filter(Match.team_id.in_(g.user.teams.keys())).\
            filter(Match.date > cutoff).\
            options(eagerload('competition'), \
                    eagerload('server')).\
            order_by(Match.date.asc()).\
            order_by(Match.id.asc()).\
            all()

    return rt('matches/availability.html',
        page={'top':'my_matches', 'sub':'upcoming'},
        aform = MatchPlayerStatusForm(),
        matches=matches)
Beispiel #24
0
def my_previous_matches():
    if g.user.is_guest:
        return redirect(url_for('all'))

    cutoff = datetime.datetime.utcnow()
    matches = Match.query.\
            filter(Match.team_id.in_(g.user.teams.keys())).\
            filter(Match.date <= cutoff).\
            options(eagerload('competition'), \
                    eagerload('server')).\
            order_by(Match.date.asc()).\
            order_by(Match.id.asc()).\
            all()

    return rt('matches/table.html',
              page={
                  'top': 'my_matches',
                  'sub': 'previous'
              },
              previous_only=True,
              previous=matches)
Beispiel #25
0
def signin(t):
    if not g.user.is_guest:
        return redirect(oid.get_next_url())

    if request.method == 'POST':
        if app.debug:
            openid = request.form.get('openid')
        else:
            openid = "http://steamcommunity.com/openid"
        if openid:
            return oid.try_login(openid, ask_for=['nickname','email'])

    n = request.url or oid.get_next_url()
    if n.endswith('signin') or n.endswith('signin/'):
        n = n.replace('signin', '')

    error = oid.fetch_error()
    if error:
        flash(error, "error")

    return rt('account/login.html', n=n, next=oid.get_next_url(), create=app.debug)
Beispiel #26
0
def all(team_id=0): # show all matches
    team = None
    if team_id:
        if not g.user.is_on_team(team_id):
            team = Team.query.filter_by(id=team_id).first()

            if not team:
                return redirect(url_for('all'))

            page = {'top':'team', 'sub':'matches'}
        else:
            team = {'id' : team_id, 'name' : g.user.teams[team_id].name}
            page = {'top':'my_teams', 'sub':'matches'}

        matches=Match.query.\
                options(eagerload('competition')).\
                filter_by(team_id=team_id).\
                order_by(Match.date.asc()).\
                order_by(Match.id.asc()).\
                all()
    else:
        matches=Match.query.\
                options(eagerload('competition')).\
                order_by(Match.date.asc()).\
                order_by(Match.id.asc()).\
                all()
        page={'top':'matches', 'sub':'all_matches'}

    now = datetime.datetime.utcnow()
    upcoming = []
    previous = []
    for m in matches:
        if m.date > now:
            upcoming.append(m)
        else:
            previous.append(m)

    return rt('matches/table.html',
        page=page, team=team,
        upcoming=upcoming, previous=previous)
Beispiel #27
0
def settings():
    emails = set()
    for u in User.query.all():
        if u.email is not None:
            emails.add(u.email.lower())

    if g.user.email is not None:
        email_lower = g.user.email.lower()
        if email_lower in emails:
            emails.remove(email_lower)

    form = UserSettingsForm(request.form, obj=g.user)
    form.email.validators[0].values = emails

    if form.validate_on_submit():
        form.populate_obj(g.user)
        db.session.commit()
        babel_refresh()
        flash(u'Your settings were successfully updated.', 'success')
        return redirect(url_for('settings'))

    return rt('account/create.html', settings=True, form=form)
Beispiel #28
0
def my_matches():
    if g.user.is_guest:
        return redirect(url_for('all'))

    cutoff = datetime.datetime.utcnow() - datetime.timedelta(hours=1)
    matches = Match.query.\
            outerjoin(CompletedMatch).\
            filter(CompletedMatch.id == None).\
            filter(Match.team_id.in_(g.user.teams.keys())).\
            filter(Match.date > cutoff).\
            options(eagerload('competition'), \
                    eagerload('server')).\
            order_by(Match.date.asc()).\
            order_by(Match.id.asc()).\
            all()

    return rt('matches/availability.html',
              page={
                  'top': 'my_matches',
                  'sub': 'upcoming'
              },
              aform=MatchPlayerStatusForm(),
              matches=matches)
Beispiel #29
0
def add():
    if not g.user.is_team_leader():
        flash(u'You must be a team leader to add a match.', 'error')
        return redirect(url_for('my_matches'))

    opponents = Opponent.query.\
            filter(Opponent.team_id.in_(g.user.team_leader_teams)).\
            order_by(Opponent.name.asc()).all()

    servers = Server.query.\
            filter(Server.team_id.in_(g.user.team_leader_teams)).\
            order_by('server_name')
    competitions = Competition.query.order_by('competition_name')

    form = AddMatchForm()
    form.team_id.choices = [(t, g.user.teams[t].name)
                            for t in g.user.team_leader_teams]
    form.competition_id.choices = [(c.id, c.name) for c in competitions]
    form.server_id.choices = [(s.id, s.name) for s in servers]
    form.opponent_id.choices = [(o.id, o.name) for o in opponents]

    if request.method == 'GET':
        if request.values.get('new_opponent_id'):
            form.opponent_id.data = int(request.values.get('new_opponent_id'))
        elif request.values.get('new_server_id'):
            form.server_id.data = int(request.values.get('new_server_id'))

        # default to tomorrow at 9pm
        form.date.data = datetime.datetime.combine((\
                    to_user_timezone(datetime.datetime.utcnow()) \
                        + datetime.timedelta(days=1))\
                        .date(),\
                    datetime.time(21))
        form.date.label.text += ' (in %s)' \
                % format_datetime(form.date.data, 'zzzz')

    if form.validate_on_submit():
        if not g.user.is_team_leader(form.team_id.data):
            flash(u'You must be a team leader to add a match.', 'error')
        else:
            date = to_utc(form.date.data)
            match = Match(team_id=form.team_id.data,
                          date=date,
                          comments=form.comments.data,
                          password=form.password.data,
                          opponent_id=form.opponent_id.data,
                          competition_id=form.competition_id.data,
                          creator_user_id=g.user.id,
                          server_id=form.server_id.data)
            db.session.add(match)
            db.session.commit()

            team_date = matches_datetime_format_full_for_team(date, \
                    g.user.teams[form.team_id.data].time_zone)

            date_short = matches_datetime_format(date)
            team_date_short = matches_datetime_format_for_team(date, \
                    g.user.teams[form.team_id.data].time_zone)

            email_vars = {
                'date': matches_datetime_format_full(date),
                'team_date': team_date,
                'date_short': date_short,
                'team_date_short': team_date_short,
                'team': g.user.teams[form.team_id.data].name,
                'opponent': match.opponent.name,
                'opponent_tag': match.opponent.tag,
                'competition': match.competition.name,
                'server': match.server.name,
                'address': match.server.address,
                'password': match.password,
                'comments': match.comments,
                'match_url': abs_url_for('show', match_id=match.id),
                'settings_url': abs_url_for('account.settings')
            }

            subject = "[tardyrush] New Match "\
                    "on %(date_short)s vs. %(opponent_tag)s" %\
                    email_vars
            team_subject = "[tardyrush] New Match "\
                    "on %(team_date_short)s vs. %(opponent_tag)s" %\
                    email_vars

            lines = ["A new match has been added."]
            lines.append("")

            lines.append("%(team)s vs. %(opponent)s" % email_vars)
            lines.append("%%(date)s" % email_vars)
            lines.append("")

            lines.append("Competition: %(competition)s" % email_vars)
            lines.append("Server: %(server)s" % email_vars)
            lines.append("Address: %(address)s" % email_vars)
            if len(email_vars['password']):
                lines.append("Password: %(password)s" % email_vars)
            lines.append("")

            if len(email_vars['comments']):
                lines.append("Comments:")
                lines.append("%(comments)s" % email_vars)
                lines.append("")

            lines.append("Set your status: %(match_url)s" % email_vars)
            lines.append("")

            lines.append("Change your settings: %(settings_url)s" % email_vars)
            lines.append("")

            raw_message = "\n".join(lines)

            message = raw_message % email_vars
            team_message = raw_message % {'date': email_vars['team_date']}

            # now notify players of new match via email
            players = db.session.query(User).\
                    select_from(join(User, TeamPlayer)).\
                    filter(TeamPlayer.team_id==form.team_id.data).\
                    filter(User.email_settings==User.EmailMatchAdded)

            if form.send_notification.data:
                try:
                    with mail.connect() as conn:
                        for p in players:
                            try:
                                msg = Message(recipients=[p.email],
                                              body=message,
                                              subject=subject,
                                              sender=Sender)
                                conn.send(msg)
                                app.logger.info("Sent mail to: %s" % p.email)
                            except Exception, e:
                                app.logger.error("Error sending mail: %s, %s" % \
                                        (p.email, e))
                except Exception, e:
                    app.logger.error("Error sending mail: %s" % e)

            # now notify players of new match via forum post
            if form.post_on_forums.data:
                forum_post = ForumBotQueuedPost(
                    team_id=match.team_id,
                    game_id=match.competition.game_id,
                    match_id=match.id,
                    subject=team_subject,
                    message=team_message)
                db.session.add(forum_post)
                db.session.commit()

            flash(u'The match was successfully added.', 'success')
            return redirect(url_for('my_matches'))
Beispiel #30
0
def add():
    if not g.user.is_team_leader():
        flash(u'You must be a team leader to add a match.', 'error')
        return redirect(url_for('my_matches'))

    opponents = Opponent.query.\
            filter(Opponent.team_id.in_(g.user.team_leader_teams)).\
            order_by(Opponent.name.asc()).all()

    servers = Server.query.\
            filter(Server.team_id.in_(g.user.team_leader_teams)).\
            order_by('server_name')
    competitions = Competition.query.order_by('competition_name')

    form = AddMatchForm()
    form.team_id.choices = [ (t, g.user.teams[t].name) for t in g.user.team_leader_teams ]
    form.competition_id.choices = [(c.id, c.name) for c in competitions ]
    form.server_id.choices = [ (s.id, s.name) for s in servers ]
    form.opponent_id.choices = [ (o.id, o.name) for o in opponents ]

    if request.method == 'GET':
        if request.values.get('new_opponent_id'):
            form.opponent_id.data = int(request.values.get('new_opponent_id'))
        elif request.values.get('new_server_id'):
            form.server_id.data = int(request.values.get('new_server_id'))

        # default to tomorrow at 9pm
        form.date.data = datetime.datetime.combine((\
                    to_user_timezone(datetime.datetime.utcnow()) \
                        + datetime.timedelta(days=1))\
                        .date(),\
                    datetime.time(21))
        form.date.label.text += ' (in %s)' \
                % format_datetime(form.date.data, 'zzzz')

    if form.validate_on_submit():
        if not g.user.is_team_leader(form.team_id.data):
            flash(u'You must be a team leader to add a match.', 'error')
        else:
            date = to_utc(form.date.data)
            match = Match(team_id=form.team_id.data,
                          date=date,
                          comments=form.comments.data,
                          password=form.password.data,
                          opponent_id=form.opponent_id.data,
                          competition_id=form.competition_id.data,
                          creator_user_id=g.user.id,
                          server_id=form.server_id.data)
            db.session.add(match)
            db.session.commit()

            team_date = matches_datetime_format_full_for_team(date, \
                    g.user.teams[form.team_id.data].time_zone)

            date_short = matches_datetime_format(date)
            team_date_short = matches_datetime_format_for_team(date, \
                    g.user.teams[form.team_id.data].time_zone)

            email_vars = { 'date' : matches_datetime_format_full(date),
                           'team_date' : team_date,
                           'date_short' : date_short,
                           'team_date_short' : team_date_short,
                           'team' : g.user.teams[form.team_id.data].name,
                           'opponent' : match.opponent.name,
                           'opponent_tag' : match.opponent.tag,
                           'competition' : match.competition.name,
                           'server' : match.server.name,
                           'address' : match.server.address,
                           'password' : match.password,
                           'comments' : match.comments,
                           'match_url' : abs_url_for('show',
                               match_id=match.id),
                           'settings_url' : abs_url_for('account.settings') }

            subject = "[tardyrush] New Match "\
                    "on %(date_short)s vs. %(opponent_tag)s" %\
                    email_vars
            team_subject = "[tardyrush] New Match "\
                    "on %(team_date_short)s vs. %(opponent_tag)s" %\
                    email_vars

            lines = [ "A new match has been added." ]
            lines.append("")

            lines.append( "%(team)s vs. %(opponent)s" % email_vars )
            lines.append( "%%(date)s" % email_vars )
            lines.append("")

            lines.append( "Competition: %(competition)s" % email_vars )
            lines.append( "Server: %(server)s" % email_vars )
            lines.append( "Address: %(address)s" % email_vars )
            if len(email_vars['password']):
                lines.append( "Password: %(password)s" % email_vars )
            lines.append("")

            if len(email_vars['comments']):
                lines.append( "Comments:" )
                lines.append( "%(comments)s" % email_vars )
                lines.append("")

            lines.append( "Set your status: %(match_url)s" % email_vars )
            lines.append("")

            lines.append( "Change your settings: %(settings_url)s" % email_vars )
            lines.append("")

            raw_message = "\n".join(lines)

            message = raw_message % email_vars
            team_message = raw_message % { 'date' : email_vars['team_date'] }

            # now notify players of new match via email
            players = db.session.query(User).\
                    select_from(join(User, TeamPlayer)).\
                    filter(TeamPlayer.team_id==form.team_id.data).\
                    filter(User.email_settings==User.EmailMatchAdded)

            if form.send_notification.data:
                try:
                    with mail.connect() as conn:
                        for p in players:
                            try:
                                msg = Message(recipients=[p.email],
                                              body=message,
                                              subject=subject,
                                              sender=Sender)
                                conn.send(msg)
                                app.logger.info("Sent mail to: %s" % p.email)
                            except Exception, e:
                                app.logger.error("Error sending mail: %s, %s" % \
                                        (p.email, e))
                except Exception, e:
                    app.logger.error("Error sending mail: %s" % e)

            # now notify players of new match via forum post
            if form.post_on_forums.data:
                forum_post = ForumBotQueuedPost(team_id=match.team_id,
                                                game_id=match.competition.game_id,
                                                match_id=match.id,
                                                subject=team_subject,
                                                message=team_message)
                db.session.add(forum_post)
                db.session.commit()

            flash(u'The match was successfully added.', 'success')
            return redirect(url_for('my_matches'))
Beispiel #31
0
def show(match_id, action):
    match = Match.query.filter_by(id=match_id).first()
    if not match:
        flash(u"That match doesn't exist.", "error")
        return redirect(url_for('my_matches'))

    if not g.user.is_on_team(match.team_id):
        flash(u'You must be on the team to view its match availability.', "error")
        return redirect(url_for('all'))

    if match.date < datetime.datetime.utcnow():
        up_prev = 'previous'
    else:
        up_prev = 'upcoming'

    if action == 'edit':
        if not g.user.is_team_leader(match.team_id):
            flash(u'You must be a team leader to edit this match.', 'error')
            return redirect(url_for('my_matches'))

        servers = Server.query.\
                filter_by(team_id=match.team_id).\
                order_by('server_name')

        form = MatchForm(request.form, obj=match)
        form.competition_id.choices = [(c.id, c.name) for c in
                Competition.query.order_by('competition_name')]
        form.server_id.choices = [ (s.id, s.name) for s in servers ]
        form.team_id.choices = [ (t, g.user.teams[t].name) for t in g.user.team_leader_teams ]
        form.opponent_id.choices = [ (o.id, o.name) for o in \
                Opponent.query.filter_by(team_id=match.team_id).\
                order_by(Opponent.name.asc()).all() ]

        players = {}
        for p in match.players:
            players[p.user_id] = p.user.name

        if request.method == 'GET':
            if request.values.get('new_opponent_id'):
                form.opponent_id.data = int(request.values.get('new_opponent_id'))
            elif request.values.get('new_server_id'):
                form.server_id.data = int(request.values.get('new_server_id'))

            form.date.data = to_user_timezone(form.date.data)
            form.date.label.text += ' (in %s)' \
                    % format_datetime(form.date.data, 'zzzz')

        if form.validate_on_submit():
            form.date.data = to_utc(form.date.data)

            to_delete = []
            for f in form.players:
                if f.delete.data:
                    to_delete.append(f.user_id.data)

            form.populate_obj(match)

            if len(to_delete):
                MatchPlayer.query.\
                        filter_by(match_id=match_id).\
                        filter(MatchPlayer.user_id.in_(to_delete)).delete(False)

            db.session.commit()
            flash(u'The match was successfully updated.', 'success')

            if request.values.get('from') == 'single':
                return redirect(url_for('show', match_id=match_id))

            return redirect(url_for('my_matches'))

        oform = OpponentForm()
        sform = ServerForm()
        tzform = UserTimeZoneForm(obj=g.user)

        return rt('matches/form.html', form=form, players=players,
                page={'top':'my_matches', 'sub':up_prev},
                when=up_prev,
                adding=False,
                user_now=to_user_timezone(datetime.datetime.utcnow()),
                tzform=tzform,
                oform=oform,
                sform=sform,
                team_id=g.user.team_leader_teams[0],
                match_id=match.id)
    elif action == 'delete':
        if not g.user.is_team_leader(match.team_id):
            flash(u'You must be a team leader to edit this match.', 'error')
            return redirect(url_for('my_matches'))

        if request.method == 'POST':
            db.session.delete(match)
            db.session.commit()
            flash(u'The match was successfully deleted.', 'success')

        return redirect(url_for('my_matches'))
    elif action == 'status':
        if not g.user.is_on_team(match.team_id):
            flash(u'You must be on this team to change your status.', 'error')
            return redirect(url_for('my_matches'))

        if up_prev == 'previous':
            flash(u'You cannot change your status on a past match.', 'error')
            return redirect(url_for('my_previous_matches'))

        form = MatchPlayerStatusForm(request.form)

        if form.validate_on_submit():
            if request.values.get('s') == 'available':
                player_status = MatchPlayer.StatusAvailable
            elif request.values.get('s') == 'maybe':
                player_status = MatchPlayer.StatusMaybe
            elif request.values.get('s') == 'unavailable':
                player_status = MatchPlayer.StatusUnavailable
            else:
                player_status = None

            if player_status is None:
                flash(u'That status is not valid!', 'error')
            else:
                try:
                    mu = MatchPlayer.query.filter_by(match_id=match.id,
                                                     user_id=g.user.id).one()
                    mu.status = player_status
                except NoResultFound:
                    mu = MatchPlayer(match_id=match.id, user_id=g.user.id,
                                     status=player_status)
                except Exception, e:
                    app.logger.error('Error finding MatchPlayer: %s, %s' % \
                            (g.user.id, e))
                    flash(u'Something bad happened. Please try again.', 'error')
                    return redirect(url_for('my_matches'))

                mu.date_updated = datetime.datetime.utcnow()
                db.session.add(mu)
                db.session.commit()

                if request.values.get('api') == '1':
                    psp = mu.pretty_status
                    return jsonify(success=True,
                            csrf=form.csrf_token.data,
                            match_id=match.id,
                            user_id=g.user.id,
                            user_name=g.user.name,
                            player_status=player_status,
                            player_status_pretty=psp)

                if request.values.get('from') == 'single':
                    return redirect(url_for('show', match_id=match_id))
Beispiel #32
0
def show(team_id=-1, action=''):
    page = { 'top' : 'team', 'sub' : 'main' }

    if team_id and type(team_id) == int:
        if team_id == -1:
            team_id = g.user.one_team.id
            page = {'top':'my_teams', 'sub':'all_my'}
        elif g.user.is_on_team(team_id):
            page = {'top':'my_teams', 'sub':'all_my'}

        if team_id == -1:
            if not g.user.is_guest:
                team_players = TeamPlayer.query.options(eagerload('team')).\
                        filter_by(user_id=g.user.id).\
                        order_by(TeamPlayer.status.asc()).\
                        all()
                teams = [ t.team for t in team_players ]
                return rt('teams/table.html',
                        page={'top':'my_teams', 'sub':'all_my'},
                        teams=teams)
            return redirect(url_for('all'))

        if team_id > 0:
            team = Team.query.filter_by(id=team_id).first()
        else:
            team = None

        if not team:
            flash(u'Team not found', 'error')
            return redirect(url_for('all'))

        if action == 'join':
            if g.user.is_guest:
                flash(u'You must be signed in to join a team.', 'error')
            elif g.user.is_on_team(team_id):
                flash(u'You are already on this team.', 'info')
            elif g.user.is_on_team():
                flash(u'You are already on a team.  Leave your current team '
                       'first before joining this team.', 'error')
            else:
                join_form = JoinTeamForm(request.form)

                def validate_password(form, field):
                    if field.data != team.join_password:
                        raise ValidationError(\
                                u"The password you entered is incorrect.")

                JoinTeamForm.validate_password = validate_password

                if join_form.validate_on_submit():
                    tp = TeamPlayer(user_id=g.user.id,
                                    team_id=team.id,
                                    date_joined=datetime.datetime.utcnow(),
                                    status=TeamPlayer.StatusNormal)
                    db.session.add(tp)
                    db.session.commit()
                    flash(u'You have successfully joined this team.', 'success')

                return redirect(url_for('show', team_id=team.id))

        elif action == 'leave':
            if g.user.is_guest:
                flash(u'You must be signed in to join a team.', 'error')
            elif not g.user.is_on_team(team_id):
                flash(u'You are not on this team.', 'error')
            else:
                leave_form = LeaveTeamForm(request.form)

                if leave_form.validate_on_submit():
                    # make sure there is still a founder on the team

                    skip = False
                    if team.id in g.user.founder_teams:
                        other_founders = False
                        for p in team.players:
                            if p.status == TeamPlayer.StatusFounder and \
                                    p.user_id != g.user.id:
                                other_founders = True
                                break

                        if not other_founders:
                            flash(u'You cannot leave this team because you '\
                                   'are the only founder.  Add another '\
                                   'founder first.', 'error')
                            skip = True

                    if not skip:
                        TeamPlayer.query.\
                                filter_by(team_id=team.id).\
                                filter_by(user_id=g.user.id).delete(False)

                        MatchPlayer.query.\
                                filter(MatchPlayer.match_id.in_(\
                                    db.session.query(Match.id).\
                                    filter_by(team_id=team.id))).\
                                filter_by(user_id=g.user.id).delete(False)
                        db.session.commit()
                        flash(u'You have successfully left this team.',
                              'success')
                        return redirect(url_for('show',team_id=team.id))

        # only edit or delete for own team if a team leader
        elif g.user.is_team_leader(team_id):
            if action == 'edit' and \
                    request.values.get('edit_players') == '1':
                action = 'edit_players'

            team_names = [ t.name.lower() for t in Team.query.all() ]
            if team.name.lower() in team_names:
                team_names.remove(team.name.lower())

            if action == 'edit':
                form = TeamForm(request.form, obj=team)
                players_form = TeamPlayersForm(ImmutableMultiDict(), obj=team)
            else:
                form = TeamForm(ImmutableMultiDict(), obj=team)
                players_form = TeamPlayersForm(request.form, obj=team)

            form.name.validators[0].values = team_names

            if action == 'edit':
                players = {}
                for p in team.players:
                    players[p.user_id] = p.user.name

                if not g.user.is_founder(team_id):
                    choices_no_founder = [ (s, n) for s, n in \
                            TeamPlayer.StatusChoices if s !=
                            TeamPlayer.StatusFounder ]

                    for f in players_form.players:
                        if f.status.data == TeamPlayer.StatusFounder:
                            f.delete.disabled = True
                            f.status.disabled = True
                            f.status.choices = [ (TeamPlayer.StatusFounder,
                                                  "Founder") ]
                        else:
                            f.status.choices = choices_no_founder

                if form.validate_on_submit():
                    form.populate_obj(team)
                    db.session.commit()
                    flash(u'The team was successfully updated.', 'success')
                    return redirect(url_for('show',
                        team_id=team.id, action='edit'))

                return rt('teams/create.html', team_id=team.id,
                        page={'top':'my_teams', 'sub':'edit'},
                        team=team,
                        players=players, form=form, players_form=players_form)
            elif action == 'edit_players':
                players = {}
                for p in team.players:
                    players[p.user_id] = p.user.name

                if not g.user.is_founder(team_id):
                    choices_no_founder = [ (s, n) for s, n in \
                            TeamPlayer.StatusChoices if s !=
                            TeamPlayer.StatusFounder ]

                    for f in players_form.players:
                        if f.status.data == TeamPlayer.StatusFounder:
                            f.delete.disabled = True
                            f.status.disabled = True
                            f.status.choices = [ (TeamPlayer.StatusFounder,
                                                  "Founder") ]
                        else:
                            f.status.choices = choices_no_founder

                if players_form.validate_on_submit():
                    founders = set([ p.user_id for p in team.players if
                        p.status==TeamPlayer.StatusFounder ])

                    new_statuses = {}
                    new_founders = set([f for f in founders])
                    editing_founders = False
                    deleting_founders = False
                    to_delete = []
                    for f in players_form.players:
                        if f.delete.data:
                            to_delete.append(f.user_id.data)
                            if f.user_id.data in founders:
                                new_founders.remove(f.user_id.data)
                                deleting_founders = True
                        elif f.status.data == TeamPlayer.StatusFounder:
                            new_founders.add(f.user_id.data)
                        else:
                            try:
                                new_founders.remove(f.user_id.data)
                            except:
                                pass

                        new_statuses[f.user_id.data] = f.status.data

                    if founders != new_founders:
                        editing_founders = True

                    save = True
                    if len(new_founders) < 1:
                        flash(u'There must be at least one founder on the '
                               'team.', 'error')
                        save = False

                    if team_id not in g.user.founder_teams and \
                            (editing_founders or deleting_founders):
                        flash(u'You must be a founder to edit or delete a '
                               'founder.', 'error')
                        save = False

                    if save:
                        for p in team.players:
                            if p.user_id in new_statuses:
                                p.status = new_statuses[p.user_id]

                        if len(to_delete):
                            TeamPlayer.query.filter_by(team_id=team_id).\
                                    filter(TeamPlayer.user_id.in_(to_delete)).\
                                    delete(False)
                            MatchPlayer.query.\
                                    filter_by(team_id=team_id).\
                                    filter(MatchPlayer.user_id.in_(to_delete)).\
                                    delete(False)

                        db.session.commit()
                        flash(u'The team was successfully updated.', 'success')
                        return redirect(url_for('show',
                            team_id=team.id, action='edit'))

                return rt('teams/create.html',
                        page={'top':'my_teams', 'sub':'edit'},
                        team_id=team.id, team=team,
                        players=players, form=form, players_form=players_form)

            elif action == 'delete':
                if request.method == 'POST':
                    db.session.delete(team)
                    db.session.commit()
                    flash(u'The team was successfuly deleted.', 'success')
                    return redirect(url_for('all'))

                flash(u"That team doesn't exist.", 'error')
                return redirect(url_for('show', team_id=team.id))

        elif action in ('delete', 'edit'):
            flash(u'You must be a team leader to edit the team.', 'error')

        join_form = None
        leave_form = None
        if not g.user.is_guest:
            if not g.user.is_on_team(team_id):
                join_form = JoinTeamForm()
            else:
                leave_form = LeaveTeamForm()

        cmatches = CompletedMatch.query.filter_by(team_id=team_id).all()

        wins = 0
        losses = 0
        draws = 0
        for c in cmatches:
            if c.wins > c.losses:
                wins += 1
            elif c.wins < c.losses:
                losses += 1
            else:
                draws += 1

        players = team.players.join(User).\
                order_by(TeamPlayer.status.asc()).\
                order_by(User.name.asc())

        return rt('teams/single.html',
                page=page,
                wins=wins, losses=losses, draws=draws,
                team=team,
                players=players,
                leave_form=leave_form,
                join_form=join_form)

    return redirect(url_for('all'))
Beispiel #33
0
def add(cmatch_id, action):
    if not g.user.is_team_leader():
        flash(u'You must be a team leader to add results.', 'error')
        return redirect(url_for('matches.my_matches'))

    if cmatch_id > 0:
        corr_match_id = cmatch_id
        adding = False

        corr_match = CompletedMatch.query.filter_by(id=cmatch_id).first()
        if not corr_match:
            flash(u"That result doesn't exist.", "error")
            return redirect(url_for('matches.my_matches'))
    else:
        cmatch_id = 0
        adding = True
        corr_match_id = request.values.get('match_id')
        corr_match = Match.query.filter_by(id=corr_match_id).\
                filter(Match.team_id.in_(g.user.team_leader_teams)).first()

        if not corr_match:
            flash(u'Corresponding availability match not found.', 'error')
            return redirect(url_for('matches.my_matches'))

        if corr_match.date > datetime.datetime.utcnow():
            flash(u'Cannot add results to match in the future.', 'error')
            return redirect(url_for('matches.my_matches'))

        if len(corr_match.results):
            flash(u'Results have already been added.', 'error')
            return redirect(url_for('add',
                cmatch_id=corr_match.results[0].id,
                action='edit'))

    opponents = Opponent.query.\
            filter(Opponent.team_id.in_(g.user.team_leader_teams)).\
            order_by(Opponent.name.asc()).all()

    servers = Server.query.\
            filter(Server.team_id.in_(g.user.team_leader_teams)).\
            order_by('server_name')

    if not adding:
        form = CompletedMatchForm(request.form, obj=corr_match)
        if request.method == 'GET':
            tz = to_user_timezone(corr_match.date_played)
            form.date_played.data = tz
            form.date_played.label.text += \
                    ' (in %s)' % format_datetime(tz, 'zzzz')
    else:
        form = CompletedMatchForm()
        if request.method == 'GET':
            tz = to_user_timezone(corr_match.date)
            form.date_played.data = tz
            form.date_played.label.text += \
                    ' (in %s)' % format_datetime(tz, 'zzzz')

    form.match_id.data = int(corr_match_id)
    form.team_id.choices = [ (corr_match.team_id,
                              g.user.teams[corr_match.team_id].name) ]
    form.competition_id.choices = [ (corr_match.competition.id,
        corr_match.competition.name) ]
    form.server_id.choices = [ (corr_match.server.id,
        corr_match.server.name) ]
    form.opponent_id.choices = [ (corr_match.opponent.id,
        corr_match.opponent.name) ]

    form.team_id.data = corr_match.team_id
    form.competition_id.data = corr_match.competition_id
    form.server_id.data = corr_match.server_id
    form.opponent_id.data = corr_match.opponent_id

    #cutoff = datetime.datetime.utcnow() + datetime.timedelta(hours=2)
    #recent_matches = Match.query.\
    #        filter(Match.team_id.in_(g.user.team_leader_teams)).\
    #        filter(Match.date < cutoff).\
    #        order_by(Match.date.desc()).all()

    #form.match_id.choices = [ (m.id, "%s vs %s" % (m.date,
    #    m.opponent.tag)) for m in recent_matches ]

    maps = Map.query.filter_by(game_id=corr_match.competition.game_id).\
                     order_by(Map.name.asc()).all()
    map_choices = [ (m.id, m.name) for m in maps ]

    sides = Side.query.filter_by(game_id=corr_match.competition.game_id).\
                       order_by(Side.name.asc()).all()
    side_choices = [ (s.id, s.name) for s in sides ]

    gametypes = GameType.query.\
            filter_by(game_id=corr_match.competition.game_id).\
            order_by(GameType.name.asc()).\
            all()
    gametype_choices = [ (gt.id, gt.name) for gt in gametypes ]

    players = Team.query.filter_by(id=corr_match.team_id).first().\
            players.all()
    player_choices = \
            sorted([ (p.user_id, p.user.name) for p in players ],
                   key=lambda x: x[1].lower())

    if adding and request.method == 'GET':
        form.rounds.append_entry()

    for e in form.rounds.entries:
        e.map_id.choices = map_choices
        e.side_id.choices = side_choices
        e.gametype_id.choices = gametype_choices

        if adding and request.method == 'GET':
            e.players.append_entry()

        for ep in e.players.entries:
            ep.user_id.choices = player_choices

    forfeit_result = request.values.get('forfeit_result')

    if form.validate_on_submit():
        if not g.user.is_team_leader(form.team_id.data):
            flash(u'Invalid team', 'error')
        elif not len(form.rounds) and not forfeit_result:
            flash(u'Invalid rounds', 'error')
        else:
            error = False

            date = to_utc(form.date_played.data)
            if adding:
                cmatch = CompletedMatch(team_id=form.team_id.data,
                                        date_created=datetime.datetime.utcnow(),
                                        opponent_id=form.opponent_id.data,
                                        competition_id=form.competition_id.data,
                                        creator_user_id=g.user.id,
                                        server_id=form.server_id.data,
                                        match_id=corr_match.id)
            else:
                cmatch = corr_match
                for r in cmatch.rounds.all():
                    cmatch.rounds.remove(r)

            cmatch.date_played = date
            cmatch.comments = form.comments.data

            if forfeit_result in ('1', '0'):
                cmatch.final_result_method = CompletedMatch.FinalResultByForfeit
                cmatch.draws = 0

                if forfeit_result == '1':
                    cmatch.wins = 1
                    cmatch.losses = 0
                else:
                    cmatch.wins = 0
                    cmatch.losses = 1

                if adding:
                    db.session.add(cmatch)

                db.session.commit()

                flash(u'The results were successfully saved.', 'success')
                return redirect(url_for('matches.my_previous_matches'))

            else:
                cmatch.final_result_method = form.final_result_method.data
                cmatch.wins = 0
                cmatch.losses = 0
                cmatch.draws = 0

            if adding:
                db.session.add(cmatch)
                db.session.flush()

            total_wins = 0
            total_losses = 0
            total_draws = 0
            round_wins = 0
            round_losses = 0
            round_draws = 0

            round_num = 1
            for r in form.rounds:
                rnd = CompletedMatchRound(cmatch_id=cmatch.id,
                                          round_id=round_num,
                                          map_id=r.map_id.data,
                                          side_id=r.side_id.data,
                                          gametype_id=r.gametype_id.data,
                                          wins=r.wins.data,
                                          losses=r.losses.data,
                                          draws=r.draws.data)
                cmatch.rounds.append(rnd)
                db.session.flush()

                if not len(r.players):
                    flash(u'No players found', 'error')
                    error = True
                    break

                total_wins += rnd.wins
                total_losses += rnd.losses
                total_draws += rnd.draws

                if rnd.wins > rnd.losses:
                    round_wins += 1
                elif rnd.wins < rnd.losses:
                    round_losses += 1
                else:
                    round_draws += 1

                player_set = set()
                for p in r.players:
                    if p.user_id.data in player_set:
                        errmsg = u'You have duplicate players in round %d. ' %\
                                round_num
                        errmsg += 'A player may appear in a round only once.'
                        flash(errmsg, 'error')
                        error = True
                        break

                    player_set.add(p.user_id.data)
                    player = CompletedMatchPlayer(cmatch_id=cmatch.id,
                                                  round_id=round_num,
                                                  user_id=p.user_id.data,
                                                  kills=p.kills.data,
                                                  deaths=p.deaths.data,
                                                  off_objs=p.off_objs.data,
                                                  def_objs=p.def_objs.data,
                                                  score=p.score.data)
                    rnd.players.append(player)

                if error:
                    break

                round_num += 1

            if cmatch.final_result_method == CompletedMatch.FinalResultByScore:
                cmatch.wins = total_wins
                cmatch.losses = total_losses
                cmatch.draws = total_draws
            else:
                cmatch.wins = round_wins
                cmatch.losses = round_losses
                cmatch.draws = round_draws

            if error:
                db.session.rollback()
            else:
                db.session.commit()

                flash(u'The results were successfully saved.', 'success')
                return redirect(url_for('matches.my_previous_matches'))

    return rt('results/form.html',
            page={'top':'my_matches', 'sub':'previous'},
            adding=adding,
            player_choices=player_choices,
            map_choices=map_choices,
            side_choices=side_choices,
            gametype_choices=gametype_choices,
            corr_match=corr_match,
            form=form)
Beispiel #34
0
def index():
    if not g.user.is_guest:
        return redirect(url_for('matches.my_matches'))

    return rt('splash.html')
Beispiel #35
0
def signout():
    session.pop('openid', None)
    session.pop('force_login', None)
    session.clear()
    flash(u'You were signed out.  See ya.', 'info')
    return redirect('/')
Beispiel #36
0
def my_teams():
    if g.user.is_on_team():
        return show()

    return redirect(url_for('all'))
Beispiel #37
0
                            match_id=match.id,
                            user_id=g.user.id,
                            user_name=g.user.name,
                            player_status=player_status,
                            player_status_pretty=psp)

                if request.values.get('from') == 'single':
                    return redirect(url_for('show', match_id=match_id))
    else:
        return rt('matches/single.html',
                page={'top':'my_matches','sub':up_prev},
                when=up_prev,
                aform = MatchPlayerStatusForm(),
                match=match)

    return redirect(url_for('my_matches'))


###############
@matches.route('/match/')
@matches.route('/match/upcoming/')
def my_matches():
    if g.user.is_guest:
        return redirect(url_for('all'))

    cutoff = datetime.datetime.utcnow() - datetime.timedelta(hours=1)
    matches = Match.query.\
            outerjoin(CompletedMatch).\
            filter(CompletedMatch.id == None).\
            filter(Match.team_id.in_(g.user.teams.keys())).\
            filter(Match.date > cutoff).\
Beispiel #38
0
def stats(team_id=0):
    team = Team.query.filter_by(id=team_id).first()

    if not team:
        return redirect(url_for('all'))

    if g.user.is_on_team(team_id):
        page = { 'top' : 'my_teams', 'sub' : 'player_stats' }
    else:
        page = { 'top' : 'team', 'sub' : 'player_stats' }

    # only look at one game at a time.  but the tables only have competition
    # id, so get the competition ids from the game id.
    game_id = int(request.values.get('game', 1))

    games = db.session.query(Game).all()
    game = [ ga for ga in games if ga.id == game_id ]

    if not game:
        flash("That game doesn't exit.", "info")
        return redirect(url_for('stats', team_id=team_id))
    else:
        game = game[0]

    competitions = db.session.query(Competition.id,
                                    Competition.abbr,
                                    Competition.name).\
            filter_by(game_id=game_id).order_by(Competition.abbr).all()
    gametypes = db.session.query(GameType.id, GameType.name).\
            filter_by(game_id=game_id).\
            order_by(GameType.name).\
            all()
    maps = db.session.query(Map.id, Map.name).\
            filter_by(game_id=game_id).\
            order_by(Map.name).all()

    competition_ids = [ c.id for c in competitions ]

    combine_form = PlayerStatsCombineForm()
    combine_form.game.choices = [ (ga.id, ga.name) for ga in games ]
    combine_form.competition.choices = [ (0, "Competition"), (0, "Any") ]
    combine_form.gametype.choices = [ (0, "Game Type"), (0, "Any") ]
    combine_form.map.choices = [ (0, "Map"), (0, "Any") ]
    combine_form.competition.choices.extend([ (c.id, c.abbr) for c in\
        competitions ])
    combine_form.gametype.choices.extend([ (gt.id, gt.name) for gt in\
        gametypes ])
    combine_form.map.choices.extend([ (m.id, m.name) for m in\
        maps ])

    combine_form.game.data = game_id

    grouper_id = grouper_id_to_int(request.values.get('grouper'))

    if grouper_id == StatsGrouperGametype:
        grouper = CompletedMatchRound.gametype_id

        ghash = dict()
        for gt in gametypes:
            ghash[gt.id] = gt.name
    elif grouper_id == StatsGrouperMap:
        grouper = CompletedMatchRound.map_id

        ghash = dict()
        for m in maps:
            ghash[m.id] = m.name
    elif grouper_id == StatsGrouperCompetition:
        grouper = CompletedMatch.competition_id

        ghash = dict()
        for c in competitions:
            ghash[c.id] = c.name
    else:
        return redirect(url_for('stats', team_id=team_id))

    ##########################################################
    # fetch totals

    pcount_subquery = \
            db.session.query(CompletedMatchPlayer.user_id).\
            join((CompletedMatch,
                  CompletedMatchPlayer.cmatch_id == CompletedMatch.id)).\
            filter(CompletedMatch.team_id == team_id).\
            filter(CompletedMatch.competition_id.in_(competition_ids)).\
            group_by(CompletedMatchPlayer.cmatch_id).\
            group_by(CompletedMatchPlayer.user_id).\
            having(db.func.sum(CompletedMatchPlayer.kills) >=\
                   db.func.sum(CompletedMatchPlayer.deaths)).\
            with_entities(CompletedMatchPlayer.user_id).\
            subquery()

    positive_counts = db.engine.execute( \
            db.select(columns=['user_id', db.func.count()],\
                      from_obj=pcount_subquery).\
            group_by('user_id') )

    pcounts = dict()
    for p in positive_counts:
        pcounts[ p[0] ] = p[1]

    record_subquery = \
            db.session.query(CompletedMatchPlayer.user_id,
                             CompletedMatchPlayer.cmatch_id).\
            group_by(CompletedMatchPlayer.cmatch_id).\
            group_by(CompletedMatchPlayer.user_id).\
            with_entities(CompletedMatchPlayer.user_id,\
                          CompletedMatchPlayer.cmatch_id).\
            subquery()

    records = db.session.query(\
                               record_subquery.c.user_id,
                               db.func.sum(\
                                   db.cast(CompletedMatch.wins >\
                                           CompletedMatch.losses, db.INT)), \
                               db.func.sum(\
                                   db.cast(CompletedMatch.losses >\
                                           CompletedMatch.wins, db.INT))\
                              ).\
                         select_from(CompletedMatch).\
                         join((record_subquery,\
                               CompletedMatch.id ==\
                               record_subquery.c.cmatch_id\
                               )).\
                         filter(CompletedMatch.team_id == team_id).\
                         filter(CompletedMatch.competition_id.in_(competition_ids)).\
                         group_by(record_subquery.c.user_id)

    stats_pm = dict()
    for s in records:
        stats_pm[ s[0] ] = (s[1], s[2])

    stats_res = db.session.query(CompletedMatchPlayer.user_id,
                                 db.func.sum(CompletedMatchPlayer.kills),
                                 db.func.sum(CompletedMatchPlayer.deaths),
                                 db.func.sum(CompletedMatchPlayer.off_objs),
                                 db.func.sum(CompletedMatchPlayer.def_objs),
                                 db.func.sum(CompletedMatchPlayer.score),
                  db.func.count(db.func.distinct(CompletedMatch.id))).\
            join((CompletedMatch,
                  CompletedMatchPlayer.cmatch_id == CompletedMatch.id)).\
            filter(CompletedMatch.team_id == team_id).\
            filter(CompletedMatch.competition_id.in_(competition_ids)).\
            group_by(CompletedMatchPlayer.user_id).\
            all()

    total_stats = []
    for s in stats_res:
        w = 0
        l = 0
        pos_kdr = 0
        if s[0] in stats_pm:
            w, l = stats_pm[ s[0] ]
        if s[0] in pcounts:
            pos_kdr = pcounts[ s[0] ]
        if (w+l) == 0:
            ts = 0
        else:
            ts = float(s[3] + s[4]) / float(w+l)
        stats_item = { 'user_id' : s[0],
                       'kills' : s[1],
                       'deaths' : s[2],
                       'offobjs' : s[3],
                       'defobjs' : s[4],
                       'score' : s[5],
                       'team_score' : ts,
                       'wins' : w,
                       'losses' : l,
                       'pos_kdr' : pos_kdr
                     }
        total_stats.append(stats_item)

    ##########################################################


    pcount_subquery = \
            db.session.query(CompletedMatchPlayer.user_id,
                             grouper).\
            join((CompletedMatch,
                  CompletedMatchPlayer.cmatch_id == CompletedMatch.id)).\
            join((CompletedMatchRound,\
                  db.and_(\
                      CompletedMatchRound.cmatch_id == CompletedMatch.id,\
                      CompletedMatchRound.round_id ==\
                          CompletedMatchPlayer.round_id,\
                  ))).\
            filter(CompletedMatch.team_id == team_id).\
            filter(CompletedMatch.competition_id.in_(competition_ids)).\
            group_by(grouper).\
            group_by(CompletedMatchPlayer.cmatch_id).\
            group_by(CompletedMatchPlayer.user_id).\
            having(db.func.sum(CompletedMatchPlayer.kills) >=\
                   db.func.sum(CompletedMatchPlayer.deaths)).\
            with_entities(CompletedMatchPlayer.user_id,\
                          grouper).\
            subquery()

    positive_counts = db.engine.execute( \
            db.select(columns=['user_id', grouper.key, db.func.count()],\
                      from_obj=pcount_subquery).\
            group_by(grouper.key, 'user_id') )

    pcounts = dict()
    for p in positive_counts:
        pcounts[ (p[0], p[1]) ] = p[2]

    record_subquery = \
            db.session.query(CompletedMatchPlayer.user_id,
                             grouper,
                             CompletedMatchPlayer.cmatch_id).\
            join((CompletedMatchRound,\
                  db.and_(\
                      CompletedMatchRound.cmatch_id ==\
                          CompletedMatchPlayer.cmatch_id,\
                      CompletedMatchRound.round_id ==\
                          CompletedMatchPlayer.round_id,\
                  )))

    if grouper.key == 'competition_id':
        record_subquery = record_subquery.\
                filter(CompletedMatch.id == CompletedMatchPlayer.cmatch_id)

    record_subquery = record_subquery.\
            group_by(grouper).\
            group_by(CompletedMatchPlayer.cmatch_id).\
            group_by(CompletedMatchPlayer.user_id).\
            with_entities(CompletedMatchPlayer.user_id,
                          grouper,
                          CompletedMatchPlayer.cmatch_id).\
            subquery()

    records = db.session.query(\
                               record_subquery.c.user_id,
                               record_subquery.c.get(grouper.key),
                               db.func.sum(\
                                   db.cast(CompletedMatch.wins >\
                                           CompletedMatch.losses, db.INT)), \
                               db.func.sum(\
                                   db.cast(CompletedMatch.losses >\
                                           CompletedMatch.wins, db.INT))\
                              ).\
                         select_from(CompletedMatch).\
                         join((record_subquery,\
                               CompletedMatch.id ==\
                               record_subquery.c.cmatch_id\
                               )).\
                         filter(CompletedMatch.team_id == team_id).\
                         filter(CompletedMatch.competition_id.\
                                    in_(competition_ids)).\
                         group_by(record_subquery.c.get(grouper.key)).\
                         group_by(record_subquery.c.user_id)

    stats_pm = dict()
    for s in records:
        stats_pm[ (s[0], s[1]) ] = (s[2], s[3])

    stats_res = db.session.query(CompletedMatchPlayer.user_id,
                                 grouper,
                                 db.func.sum(CompletedMatchPlayer.kills),
                                 db.func.sum(CompletedMatchPlayer.deaths),
                                 db.func.sum(CompletedMatchPlayer.off_objs),
                                 db.func.sum(CompletedMatchPlayer.def_objs),
                                 db.func.sum(CompletedMatchPlayer.score),
                  db.func.count(db.func.distinct(CompletedMatch.id))).\
            join((CompletedMatch,
                  CompletedMatchPlayer.cmatch_id == CompletedMatch.id)).\
            join((CompletedMatchRound,\
                  db.and_(\
                      CompletedMatchRound.cmatch_id == CompletedMatch.id,\
                      CompletedMatchRound.round_id ==\
                          CompletedMatchPlayer.round_id,\
                  ))).\
            filter(CompletedMatch.team_id == team_id).\
            filter(CompletedMatch.competition_id.in_(competition_ids)).\
            group_by(grouper).\
            group_by(CompletedMatchPlayer.user_id).\
            all()

    stats = []
    for s in stats_res:
        w = 0
        l = 0
        pos_kdr = 0
        if (s[0], s[1]) in stats_pm:
            w, l = stats_pm[ (s[0], s[1]) ]
        if (s[0], s[1]) in pcounts:
            pos_kdr = pcounts[ (s[0], s[1]) ]
        if (w+l) == 0:
            ts = 0
        else:
            ts = float(s[4] + s[5]) / float(w+l)
        stats_item = { 'user_id' : s[0],
                       'grouper' : s[1],
                       'kills' : s[2],
                       'deaths' : s[3],
                       'offobjs' : s[4],
                       'defobjs' : s[5],
                       'score' : s[6],
                       'team_score' : ts,
                       'wins' : w,
                       'losses' : l,
                       'pos_kdr' : pos_kdr
                     }
        stats.append(stats_item)

    if grouper.key == 'competition_id':
        cmatches = db.session.query(grouper,
                CompletedMatch.id,
                CompletedMatch.wins,
                CompletedMatch.losses).\
                filter_by(team_id=team_id).\
                filter(CompletedMatch.competition_id.in_(competition_ids)).\
                filter(CompletedMatch.final_result_method !=\
                       CompletedMatch.FinalResultByForfeit).\
                all()
    else:
        cmatches = db.session.query(grouper,
                CompletedMatchRound.cmatch_id,
                CompletedMatch.wins,
                CompletedMatch.losses).\
                join(CompletedMatch).\
                filter_by(team_id=team_id).\
                filter(CompletedMatch.competition_id.in_(competition_ids)).\
                filter(CompletedMatch.final_result_method !=\
                       CompletedMatch.FinalResultByForfeit).\
                all()

    total_wins = 0
    total_losses = 0
    total_draws = 0
    seen_matches = set()
    seen_match_grouper = set()
    wins = collections.defaultdict(int)
    losses = collections.defaultdict(int)
    draws = collections.defaultdict(int)
    for c in cmatches:
        val = c[0]
        cmatch_id = c[1]
        if (cmatch_id, val) in seen_match_grouper:
            continue
        seen_match_grouper.add((cmatch_id, val))
        wins[val] += 0
        if c.wins > c.losses:
            wins[val] += 1
        elif c.wins < c.losses:
            losses[val] += 1
        else:
            draws[val] += 1

        if cmatch_id not in seen_matches:
            seen_matches.add(cmatch_id)
            if c.wins > c.losses:
                total_wins += 1
            elif c.wins < c.losses:
                total_losses += 1
            else:
                total_draws += 1

    phash = dict()
    for p in team.players:
        phash[p.user_id] = p.user.name

    return rt('teams/stats.html',
            page=page,
            game=game,
            combined=False,
            stats=stats,
            pcounts=pcounts,
            ghash=ghash,
            phash=phash,
            combine_form=combine_form,
            grouper=grouper.key[:-3],
            wins=wins, losses=losses, draws=draws,
            total_stats=total_stats,
            total_wins=total_wins, total_losses=total_losses,
            total_draws=total_draws,
            team=team)
Beispiel #39
0
def show(match_id, action):
    match = Match.query.filter_by(id=match_id).first()
    if not match:
        flash(u"That match doesn't exist.", "error")
        return redirect(url_for('my_matches'))

    if not g.user.is_on_team(match.team_id):
        flash(u'You must be on the team to view its match availability.',
              "error")
        return redirect(url_for('all'))

    if match.date < datetime.datetime.utcnow():
        up_prev = 'previous'
    else:
        up_prev = 'upcoming'

    if action == 'edit':
        if not g.user.is_team_leader(match.team_id):
            flash(u'You must be a team leader to edit this match.', 'error')
            return redirect(url_for('my_matches'))

        servers = Server.query.\
                filter_by(team_id=match.team_id).\
                order_by('server_name')

        form = MatchForm(request.form, obj=match)
        form.competition_id.choices = [
            (c.id, c.name)
            for c in Competition.query.order_by('competition_name')
        ]
        form.server_id.choices = [(s.id, s.name) for s in servers]
        form.team_id.choices = [(t, g.user.teams[t].name)
                                for t in g.user.team_leader_teams]
        form.opponent_id.choices = [ (o.id, o.name) for o in \
                Opponent.query.filter_by(team_id=match.team_id).\
                order_by(Opponent.name.asc()).all() ]

        players = {}
        for p in match.players:
            players[p.user_id] = p.user.name

        if request.method == 'GET':
            if request.values.get('new_opponent_id'):
                form.opponent_id.data = int(
                    request.values.get('new_opponent_id'))
            elif request.values.get('new_server_id'):
                form.server_id.data = int(request.values.get('new_server_id'))

            form.date.data = to_user_timezone(form.date.data)
            form.date.label.text += ' (in %s)' \
                    % format_datetime(form.date.data, 'zzzz')

        if form.validate_on_submit():
            form.date.data = to_utc(form.date.data)

            to_delete = []
            for f in form.players:
                if f.delete.data:
                    to_delete.append(f.user_id.data)

            form.populate_obj(match)

            if len(to_delete):
                MatchPlayer.query.\
                        filter_by(match_id=match_id).\
                        filter(MatchPlayer.user_id.in_(to_delete)).delete(False)

            db.session.commit()
            flash(u'The match was successfully updated.', 'success')

            if request.values.get('from') == 'single':
                return redirect(url_for('show', match_id=match_id))

            return redirect(url_for('my_matches'))

        oform = OpponentForm()
        sform = ServerForm()
        tzform = UserTimeZoneForm(obj=g.user)

        return rt('matches/form.html',
                  form=form,
                  players=players,
                  page={
                      'top': 'my_matches',
                      'sub': up_prev
                  },
                  when=up_prev,
                  adding=False,
                  user_now=to_user_timezone(datetime.datetime.utcnow()),
                  tzform=tzform,
                  oform=oform,
                  sform=sform,
                  team_id=g.user.team_leader_teams[0],
                  match_id=match.id)
    elif action == 'delete':
        if not g.user.is_team_leader(match.team_id):
            flash(u'You must be a team leader to edit this match.', 'error')
            return redirect(url_for('my_matches'))

        if request.method == 'POST':
            db.session.delete(match)
            db.session.commit()
            flash(u'The match was successfully deleted.', 'success')

        return redirect(url_for('my_matches'))
    elif action == 'status':
        if not g.user.is_on_team(match.team_id):
            flash(u'You must be on this team to change your status.', 'error')
            return redirect(url_for('my_matches'))

        if up_prev == 'previous':
            flash(u'You cannot change your status on a past match.', 'error')
            return redirect(url_for('my_previous_matches'))

        form = MatchPlayerStatusForm(request.form)

        if form.validate_on_submit():
            if request.values.get('s') == 'available':
                player_status = MatchPlayer.StatusAvailable
            elif request.values.get('s') == 'maybe':
                player_status = MatchPlayer.StatusMaybe
            elif request.values.get('s') == 'unavailable':
                player_status = MatchPlayer.StatusUnavailable
            else:
                player_status = None

            if player_status is None:
                flash(u'That status is not valid!', 'error')
            else:
                try:
                    mu = MatchPlayer.query.filter_by(match_id=match.id,
                                                     user_id=g.user.id).one()
                    mu.status = player_status
                except NoResultFound:
                    mu = MatchPlayer(match_id=match.id,
                                     user_id=g.user.id,
                                     status=player_status)
                except Exception, e:
                    app.logger.error('Error finding MatchPlayer: %s, %s' % \
                            (g.user.id, e))
                    flash(u'Something bad happened. Please try again.',
                          'error')
                    return redirect(url_for('my_matches'))

                mu.date_updated = datetime.datetime.utcnow()
                db.session.add(mu)
                db.session.commit()

                if request.values.get('api') == '1':
                    psp = mu.pretty_status
                    return jsonify(success=True,
                                   csrf=form.csrf_token.data,
                                   match_id=match.id,
                                   user_id=g.user.id,
                                   user_name=g.user.name,
                                   player_status=player_status,
                                   player_status_pretty=psp)

                if request.values.get('from') == 'single':
                    return redirect(url_for('show', match_id=match_id))
Beispiel #40
0
def combined_stats(team_id=0):
    team = Team.query.filter_by(id=team_id).first()

    if not team:
        return redirect(url_for('all'))

    if g.user.is_on_team(team_id):
        page = { 'top' : 'my_teams', 'sub' : 'player_stats' }
    else:
        page = { 'top' : 'team', 'sub' : 'player_stats' }

    game_id = int(request.values.get('game', 1))

    games = db.session.query(Game).all()
    game = [ ga for ga in games if ga.id == game_id ]

    if not game:
        flash("That game doesn't exit.", "info")
        return redirect(url_for('stats', team_id=team_id))
    else:
        game = game[0]

    competitions = db.session.query(Competition.id, Competition.name).\
            filter_by(game_id=game_id).all()

    competition_ids = [ c.id for c in competitions ]

    gametype_id = int(request.values.get('gametype', 0))
    map_id = int(request.values.get('map', 0))
    competition_id = int(request.values.get('competition', 0))

    competitions = db.session.query(Competition.id,
                                    Competition.abbr,
                                    Competition.name).\
            filter_by(game_id=game_id).order_by(Competition.abbr).all()
    gametypes = db.session.query(GameType.id, GameType.name).\
            order_by(GameType.name).\
            all()
    maps = db.session.query(Map.id, Map.name).order_by(Map.name).all()

    competition = next((v for v in competitions if v.id == competition_id), None)
    gametype = next((v for v in gametypes if v.id == gametype_id), None)
    mapp = next((v for v in maps if v.id == map_id), None)

    if not gametype and not mapp and not competition:
        return redirect(url_for('stats', team_id=team_id, game=game_id))

    combine_form = PlayerStatsCombineForm()
    combine_form.game.choices = [ (ga.id, ga.name) for ga in games ]
    combine_form.competition.choices = [ (0, "Competition"), (0, "Any") ]
    combine_form.gametype.choices = [ (0, "Game Type"), (0, "Any") ]
    combine_form.map.choices = [ (0, "Map"), (0, "Any") ]
    combine_form.competition.choices.extend([ (c.id, c.abbr) for c in\
        competitions ])
    combine_form.gametype.choices.extend([ (gt.id, gt.name) for gt in\
        gametypes ])
    combine_form.map.choices.extend([ (m.id, m.name) for m in\
        maps ])

    combine_form.game.data = game_id
    combine_form.competition.data = competition_id
    combine_form.gametype.data = gametype_id
    combine_form.map.data = map_id

    pcount_subquery = \
            db.session.query(CompletedMatchPlayer.user_id,
                             CompletedMatchRound.gametype_id,
                             CompletedMatchRound.map_id,
                             CompletedMatch.competition_id).\
            join((CompletedMatch,
                  CompletedMatchPlayer.cmatch_id == CompletedMatch.id)).\
            join((CompletedMatchRound,\
                  db.and_(\
                      CompletedMatchRound.cmatch_id == CompletedMatch.id,\
                      CompletedMatchRound.round_id ==\
                          CompletedMatchPlayer.round_id,\
                  ))).\
            filter(CompletedMatch.team_id == team_id)

    if gametype_id:
        pcount_subquery = pcount_subquery.filter_by(gametype_id=gametype_id)
    if map_id:
        pcount_subquery = pcount_subquery.filter_by(map_id=map_id)
    if competition_id:
        pcount_subquery = pcount_subquery.\
                filter(CompletedMatch.competition_id == competition_id)
    else:
        pcount_subquery = pcount_subquery.\
                filter(CompletedMatch.competition_id.in_(competition_ids))

    pcount_subquery = pcount_subquery.\
            group_by(CompletedMatchPlayer.cmatch_id).\
            group_by(CompletedMatchPlayer.user_id).\
            having(db.func.sum(CompletedMatchPlayer.kills) >=\
                   db.func.sum(CompletedMatchPlayer.deaths)).\
            with_entities(CompletedMatchPlayer.user_id).\
            subquery()

    positive_counts = db.engine.execute( \
            db.select(columns=['user_id', db.func.count()],\
                      from_obj=pcount_subquery).\
            group_by('user_id') )

    pcounts = dict()
    for p in positive_counts:
        pcounts[ p[0] ] = p[1]

    record_subquery = \
            db.session.query(CompletedMatchPlayer.user_id,
                             CompletedMatch.competition_id,
                             CompletedMatchPlayer.cmatch_id).\
            join((CompletedMatchRound,\
                  db.and_(\
                      CompletedMatchRound.cmatch_id ==\
                          CompletedMatchPlayer.cmatch_id,\
                      CompletedMatchRound.round_id ==\
                          CompletedMatchPlayer.round_id,\
                  )))

    if gametype_id:
        record_subquery = record_subquery.filter_by(gametype_id=gametype_id)
    if map_id:
        record_subquery = record_subquery.filter_by(map_id=map_id)
    if competition_id:
        record_subquery = record_subquery.\
                filter(CompletedMatch.competition_id == competition_id)

    record_subquery = record_subquery.\
            filter(CompletedMatch.id == CompletedMatchPlayer.cmatch_id).\
            group_by(CompletedMatchPlayer.cmatch_id).\
            group_by(CompletedMatchPlayer.user_id).\
            with_entities(CompletedMatchPlayer.user_id,
                          CompletedMatchPlayer.cmatch_id).\
            subquery()

    records = db.session.query(\
                               record_subquery.c.user_id,
                               db.func.sum(\
                                   db.cast(CompletedMatch.wins >\
                                           CompletedMatch.losses, db.INT)), \
                               db.func.sum(\
                                   db.cast(CompletedMatch.losses >\
                                           CompletedMatch.wins, db.INT))\
                              ).\
                         select_from(CompletedMatch).\
                         join((record_subquery,\
                               CompletedMatch.id ==\
                               record_subquery.c.cmatch_id\
                               )).\
                         filter(CompletedMatch.team_id == team_id).\
                         filter(CompletedMatch.competition_id.\
                                    in_(competition_ids)).\
                         group_by(record_subquery.c.user_id)

    stats_pm = dict()
    for s in records:
        stats_pm[ s[0] ] = (s[1], s[2])

    stats_res = db.session.query(CompletedMatchPlayer.user_id,
                                 db.func.sum(CompletedMatchPlayer.kills),
                                 db.func.sum(CompletedMatchPlayer.deaths),
                                 db.func.sum(CompletedMatchPlayer.off_objs),
                                 db.func.sum(CompletedMatchPlayer.def_objs),
                                 db.func.sum(CompletedMatchPlayer.score),
                  db.func.count(db.func.distinct(CompletedMatch.id))).\
            join((CompletedMatch,
                  CompletedMatchPlayer.cmatch_id == CompletedMatch.id)).\
            join((CompletedMatchRound,\
                  db.and_(\
                      CompletedMatchRound.cmatch_id == CompletedMatch.id,\
                      CompletedMatchRound.round_id ==\
                          CompletedMatchPlayer.round_id,\
                  ))).\
            filter(CompletedMatch.team_id == team_id)

    if gametype_id:
        stats_res = stats_res.filter_by(gametype_id=gametype_id)
    if map_id:
        stats_res = stats_res.filter_by(map_id=map_id)
    if competition_id:
        stats_res = stats_res.\
                filter(CompletedMatch.competition_id == competition_id)
    else:
        stats_res = stats_res.\
                filter(CompletedMatch.competition_id.in_(competition_ids))

    stats_res = stats_res.\
            group_by(CompletedMatchPlayer.user_id).\
            all()

    stats = []
    for s in stats_res:
        w = 0
        l = 0
        pos_kdr = 0
        if s[0] in stats_pm:
            w, l = stats_pm[ s[0] ]
        if s[0] in pcounts:
            pos_kdr = pcounts[ s[0] ]
        if (w+l) == 0:
            ts = 0
        else:
            ts = float(s[3] + s[4]) / float(w+l)
        stats_item = { 'user_id' : s[0],
                       'kills' : s[1],
                       'deaths' : s[2],
                       'offobjs' : s[3],
                       'defobjs' : s[4],
                       'score' : s[5],
                       'team_score' : ts,
                       'wins' : w,
                       'losses' : l,
                       'pos_kdr' : pos_kdr
                     }
        stats.append(stats_item)

    # team record

    cmatches = db.session.query(\
            CompletedMatchRound.cmatch_id,
            CompletedMatch.wins,
            CompletedMatch.losses,\
            CompletedMatch.final_result_method).\
            join(CompletedMatch).\
            filter_by(team_id=team_id).\
            filter(CompletedMatch.final_result_method !=\
                   CompletedMatch.FinalResultByForfeit)

    if gametype_id:
        cmatches = cmatches.\
                filter(CompletedMatchRound.gametype_id == gametype_id)
    if map_id:
        cmatches = cmatches.\
                filter(CompletedMatchRound.map_id == map_id)
    if competition_id:
        cmatches = cmatches.\
                filter(CompletedMatch.competition_id == competition_id)
    else:
        cmatches = cmatches.\
                filter(CompletedMatch.competition_id.in_(competition_ids))

    cmatches = cmatches.all()

    total_wins = 0
    total_losses = 0
    total_draws = 0
    seen_matches = set()
    for c in cmatches:
        cmatch_id = c[0]
        if cmatch_id in seen_matches:
            continue
        seen_matches.add(cmatch_id)

        if c.wins > c.losses:
            total_wins += 1
        elif c.wins < c.losses:
            total_losses += 1
        else:
            total_draws += 1

    phash = dict()
    for p in team.players:
        phash[p.user_id] = p.user.name

    return rt('teams/stats.html',
            page=page,
            game=game,
            combined=True,
            total_stats=stats,
            stats=[],
            phash=phash,
            gametype=gametype,
            map=mapp,
            combine_form=combine_form,
            competition=competition,
            total_wins=total_wins,
            total_losses=total_losses,
            total_draws=total_draws,
            team=team)
Beispiel #41
0
                                   player_status=player_status,
                                   player_status_pretty=psp)

                if request.values.get('from') == 'single':
                    return redirect(url_for('show', match_id=match_id))
    else:
        return rt('matches/single.html',
                  page={
                      'top': 'my_matches',
                      'sub': up_prev
                  },
                  when=up_prev,
                  aform=MatchPlayerStatusForm(),
                  match=match)

    return redirect(url_for('my_matches'))


###############
@matches.route('/match/')
@matches.route('/match/upcoming/')
def my_matches():
    if g.user.is_guest:
        return redirect(url_for('all'))

    cutoff = datetime.datetime.utcnow() - datetime.timedelta(hours=1)
    matches = Match.query.\
            outerjoin(CompletedMatch).\
            filter(CompletedMatch.id == None).\
            filter(Match.team_id.in_(g.user.teams.keys())).\
            filter(Match.date > cutoff).\