def team_create(): mock = config_setting("TESTING") customNames = config_setting("CUSTOM_PLAYER_NAMES") if not g.user: return redirect('/login') form = TeamForm() # We wish to query this every time, since we can now upload photos. if not mock: form.logo.choices = logos.get_logo_choices() if request.method == 'POST': num_teams = g.user.teams.count() max_teams = config_setting('USER_MAX_TEAMS') if max_teams >= 0 and num_teams >= max_teams and not (util.is_admin( g.user) or util.is_super_admin(g.user)): flash('You already have the maximum number of teams ({}) stored'. format(num_teams)) elif form.validate(): data = form.data auths = form.get_auth_list() pref_names = form.get_pref_list() name = data['name'].strip() tag = data['tag'].strip() flag = data['country_flag'] logo = data['logo'] # Update the logo. Passing validation we have the filename in the # list now. if not mock and (util.is_admin(g.user) or util.is_super_admin( g.user)) and form.upload_logo.data: filename = secure_filename(form.upload_logo.data.filename) index_of_dot = filename.index('.') newLogoDetail = filename[:index_of_dot] # Reinit our logos. logos.add_new_logo(newLogoDetail) app.logger.info("Added new logo id {}".format(newLogoDetail)) data['logo'] = newLogoDetail team = Team.create( g.user, name, tag, flag, logo, auths, data['public_team'] and (util.is_admin(g.user) or util.is_super_admin(g.user)), pref_names) db.session.commit() app.logger.info('User {} created team {}'.format( g.user.id, team.id)) return redirect('/teams/{}'.format(team.user_id)) else: flash_errors(form) return render_template('team_create.html', user=g.user, form=form, edit=False, is_admin=(util.is_admin(g.user) or util.is_super_admin(g.user)), MAXPLAYER=Team.MAXPLAYERS, customNames=customNames)
def check_private_or_public(match, team1, team2): if match.is_private_match(): if not g.user: raise BadRequestError("Please login before viewing this match.") # Get team lists, and check if logged in user is part of match. if (g.user.id == match.user_id) or ( config_setting('ADMINS_ACCESS_ALL_MATCHES') and g.user.admin) or g.user.super_admin: isPlayer = False playerstats_steam = [ r.steam_id for r in PlayerStats.query.filter( PlayerStats.match_id == match.id) ] playerList = list( set(team1.auths + team2.auths + playerstats_steam)) app.logger.info("Our list: {}".format(playerList)) if (config_setting('ADMINS_ACCESS_ALL_MATCHES') and g.user.admin) or g.user.super_admin: isPlayer = True else: for player in playerList: if g.user.steam_id == player: isPlayer = True break if not isPlayer: raise BadRequestError( "You cannot view this match as you were not a part of it!")
def server_create(): if not g.user: return redirect('/login') form = ServerForm(request.form) if request.method == 'POST': num_servers = g.user.servers.count() max_servers = config_setting('USER_MAX_SERVERS', 0) if max_servers >= 0 and num_servers >= max_servers and not g.user.admin: flash('You already have the maximum number of servers ({}) stored'.format(num_servers)) elif form.validate(): mock = config_setting('TESTING', False) data = form.data server = GameServer.create( g.user, data['ip_string'], data['port'], data['rcon_password']) if mock or util.check_server_connection(server): db.session.commit() app.logger.info( 'User {} created server {}'.format(g.user.id, server.id)) return redirect('/myservers') else: db.session.remove() flash('Failed to connect to server') else: flash_errors(form) return render_template('server_create.html', user=g.user, form=form, edit=False)
class MatchForm(Form): server = QuerySelectField('Server', validators=[validators.required()], query_factory=server_query_factory) match_title = StringField( 'Match title text', default='Map {MAPNUMBER} of {MAXMAPS}', validators=[validators.Length(min=-1, max=Match.title.type.length)]) series_type = RadioField('Series type', validators=[validators.required()], default='bo1', choices=[ ('bo1-preset', 'Bo1 with preset map'), ('bo1', 'Bo1 with map vetoes'), ('bo2', 'Bo2 with map vetoes'), ('bo3', 'Bo3 with map vetoes'), ('bo5', 'Bo5 with map vetoes'), ('bo7', 'Bo7 with map vetoes'), ]) team1 = QuerySelectField('Team 1', get_label='name', validators=[validators.required()], query_factory=team_query_factory) team1_string = StringField('Team 1 title text', default='', validators=[ validators.Length( min=-1, max=Match.team1_string.type.length) ]) team2 = QuerySelectField( 'Team 2', get_label='name', query_factory=team_query_factory, validators=[validators.required(), different_teams_validator]) team2_string = StringField('Team 2 title text', default='', validators=[ validators.Length( min=-1, max=Match.team2_string.type.length) ]) mapchoices = config_setting('MAPLIST') default_mapchoices = config_setting('DEFAULT_MAPLIST') veto_mappool = MultiCheckboxField( 'Map pool', choices=[(name, util.format_mapname(name)) for name in mapchoices], default=default_mapchoices, validators=[mappool_validator], )
def tournament_create(): if not g.user: return redirect('/login') form = TournamentForm(request.form) if request.method == 'POST': num_tournaments = g.user.tournaments.count() max_tournaments = config_setting('USER_MAX_TOURNAMENTS') if max_tournaments >= 0 and num_tournaments >= max_tournaments and not g.user.admin: flash( 'You already have the maximum number of tournaments ({}) created' .format(num_tournaments)) if form.validate(): mock = config_setting('TESTING') reply = {} if mock: reply['id'] = 1234 reply['name'] = "Testy McTestTournament" reply['full_challonge_url'] = "http://www.test.mctest/test" message = 'Success' else: try: reply = chall.create_tournament( name=form.data['tournament_name'], url=form.data['tournament_url']) reply = reply['tournament'] except challonge.ChallongeException as e: flash(str(e)) if reply['id']: t = Tournament.create(g.user, reply['name'], reply['full_challonge_url'], challonge_id=reply['id'], challonge_data=reply, veto_mappool=form.data['veto_mappool'], serverpool=form.serverpool.data) db.session.commit() app.logger.info( 'User {} created tournament {} - {} url {}'.format( g.user.id, t.id, t.name, t.url)) return redirect( url_for('tournament.tournament', tournamentid=t.id)) else: get5.flash_errors(form) return render_template('tournament_create.html', form=form, user=g.user)
def team_create(): if not g.user: return redirect('/login') form = TeamForm(request.form) if request.method == 'POST': num_teams = g.user.teams.count() max_teams = config_setting('USER_MAX_TEAMS') if max_teams >= 0 and num_teams >= max_teams and not g.user.admin: flash( 'You already have the maximum number of teams ({}) stored'.format(num_teams)) elif form.validate(): data = form.data auths = form.get_auth_list() name = data['name'].strip() tag = data['tag'].strip() flag = data['country_flag'] logo = data['logo'] team = Team.create(g.user, name, tag, flag, logo, auths, data['public_team'] and g.user.admin) db.session.commit() app.logger.info( 'User {} created team {}'.format(g.user.id, team.id)) return redirect('/teams/{}'.format(team.user_id)) else: flash_errors(form) return render_template('team_create.html', user=g.user, form=form, edit=False, is_admin=g.user.admin)
def team_create(): if not g.user: return redirect('/login') form = TeamForm(request.form) if request.method == 'POST': num_teams = g.user.teams.count() max_teams = config_setting('USER_MAX_TEAMS', 0) if max_teams >= 0 and num_teams >= max_teams and not g.user.admin: flash('You already have the maximum number of teams ({}) stored'.format(num_teams)) elif form.validate(): data = form.data public_team = data['public_team'] auths = form.get_auth_list() team = Team.create(g.user, data['name'], data['country_flag'], data['logo'], auths, public_team) db.session.commit() app.logger.info( 'User {} created team {}'.format(g.user.id, team.id)) return redirect('/teams/{}'.format(team.user_id)) else: get5.flash_errors(form) return render_template('team_create.html', user=g.user, form=form, edit=False, is_admin=g.user.admin)
def get_flag_img_path(country_code): if not country_code: country_code = config_setting('DEFAULT_COUNTRY_CODE') if valid_country(country_code): return '/static/img/valve_flags/{}.png'.format(country_code.lower()) else: return '/static/img/_unknown.png'
def tournament(tournamentid): tournament = Tournament.query.get_or_404(tournamentid) participants = tournament.participants.all() matches = tournament.matches.all() pending_matches = [match for match in matches if match.pending()] live_matches = [match for match in matches if match.live()] finished_matches = [match for match in matches if match.finished()] serverpool = tournament.serverpool.all() is_owner = False has_admin_access = False if g.user: is_owner = (g.user.id == tournament.user_id) has_admin_access = is_owner or ( config_setting('ADMINS_ACCESS_ALL_TOURNAMENTS') and g.user.admin) return render_template('tournament.html', user=g.user, admin_access=has_admin_access, tournament=tournament, participants=participants, live_matches=live_matches, finished_matches=finished_matches, pending_matches=pending_matches, serverpool=serverpool)
def match_masscreate(): if not g.user: return redirect('/login') if not g.user.admin: return redirect('/match/create') form = MatchMultiForm(request.form) if request.method == 'POST': if form.validate(): match_list = form.data['matches'].split('\n') for item in match_list: split_parts = item.split(',') if not len(split_parts) == 3: continue server = get_next_empty_server() t1_name, t2_name, bo_whatever = split_parts max_maps = int(form.series_type.data[2]) team1 = Team.query.filter_by(name=t1_name).first() team2 = Team.query.filter_by(name=t2_name).first() default_mapchoices = config_setting('DEFAULT_MAPLIST') match = Match.create(g.user, team1.id, team2.id, team1.name, team2.name, max_maps, False, '', default_mapchoices, server.id) server.in_use = True match.plugin_version = 'unknown' db.session.commit() redirect('/matches') return render_template( 'match_mass_create.html', form=form, user=g.user, teams=g.user.teams, )
def country_name(country_code): if not country_code: country_code = config_setting('DEFAULT_COUNTRY_CODE') if not valid_country(country_code): return None return data[country_code.lower()]
def server_masscreate(): if not g.user: return redirect('/login') if not g.user.admin: return redirect('/server/create') form = MultiServerForm(request.form) if request.method == 'POST': if form.validate(): mock = config_setting('TESTING') servers = form.data.get('servers', '') serv_list = servers.split('\n') for serv in serv_list: serv_info = serv.split(',') if not len(serv_info) == 3: continue server = GameServer.create(g.user, '', serv_info[0], serv_info[1], serv_info[2], False) if mock or util.check_server_connection(server): db.session.commit() app.logger.info('User {} created server {}'.format( g.user.id, server.id)) else: db.session.remove() return redirect('/myservers') return render_template('server_create_multi.html', user=g.user, form=form, edit=False, is_admin=g.user.admin)
def season_create(): if not g.user: return redirect('/login') form = SeasonForm(request.form) if request.method == 'POST': num_seasons = g.user.seasons.count() max_seasons = config_setting('USER_MAX_SEASONS') if max_seasons >= 0 and num_seasons >= max_seasons and not (util.is_admin(g.user) or util.is_super_admin(g.user)): flash('You already have the maximum number of seasons ({}) created'.format( num_seasons)) elif form.validate(): season = Season.create( g.user, form.data['season_title'], form.data['start_date'], form.data['end_date']) db.session.commit() app.logger.info('User {} created season {}' .format(g.user.id, season.id)) return redirect('/myseasons') else: get5.flash_errors(form) return render_template( 'season_create.html', form=form, user=g.user)
def match(matchid): match = Match.query.get_or_404(matchid) # Begin Private/Public Match Implementation vetoes = Veto.query.filter_by(match_id=matchid) if match.server_id: server = GameServer.query.get_or_404(match.server_id) else: server = None team1 = Team.query.get_or_404(match.team1_id) team2 = Team.query.get_or_404(match.team2_id) check_private_or_public(match, team1, team2) map_stat_list = match.map_stats.all() completed = match.winner try: if server is not None and (completed is None and match.cancelled == 0): password = server.receive_rcon_value('sv_password') connect_string = str("steam://connect/") + str(server.ip_string) + str(":") + \ str(server.port) + str("/") + str(password) gotv_port = server.receive_rcon_value('tv_port') gotv_string = str("steam://connect/") + str(server.ip_string) + str(":") + \ str(gotv_port) else: connect_string = None gotv_string = None except util.RconError as e: connect_string = None gotv_string = None app.logger.info( 'Attempted to connect to server {}, but it is offline'.format( server.ip_string)) is_match_owner = False is_server_op = False has_admin_access = False has_super_admin_access = False if g.user: is_match_owner = (g.user.id == match.user_id) has_admin_access = (config_setting('ADMINS_ACCESS_ALL_MATCHES') and g.user.admin) has_super_admin_access = g.user.super_admin is_server_op = util.is_server_owner(g.user, server) return render_template('match.html', user=g.user, admin_access=has_admin_access, match=match, team1=team1, team2=team2, map_stat_list=map_stat_list, completed=completed, connect_string=connect_string, gotv_string=gotv_string, super_admin_access=has_super_admin_access, vetoes=vetoes, server_owner=is_server_op, match_owner=is_match_owner)
def server_create(): if not g.user: return redirect('/login') form = ServerForm(request.form) if request.method == 'POST': num_servers = g.user.servers.count() max_servers = config_setting('USER_MAX_SERVERS') if max_servers >= 0 and num_servers >= max_servers and not ( util.is_admin(g.user) or util.is_super_admin(g.user)): flash('You already have the maximum number of servers ({}) stored'. format(num_servers)) elif form.validate(): mock = config_setting('TESTING') data = form.data if not mock: encRcon = util.encrypt(dbKey, str(data['rcon_password'])) else: encRcon = data['rcon_password'] server = GameServer.create( g.user, data['display_name'], data['ip_string'], data['port'], encRcon, data['public_server'] and util.is_admin(g.user)) if mock or util.check_server_connection(server, dbKey): db.session.commit() app.logger.info('User {} created server {}'.format( g.user.id, server.id)) return redirect('/myservers') else: db.session.remove() flash('Failed to connect to server') else: flash_errors(form) return render_template('server_create.html', user=g.user, form=form, edit=False, is_admin=util.is_admin(g.user))
def admintools_check(user, tournament): if user is None: raise BadRequestError('You do not have access to this page') grant_admin_access = user.admin and get5.config_setting( 'ADMINS_ACCESS_ALL_TOURNAMENTS') if user.id != tournament.user_id and not grant_admin_access: raise BadRequestError('You do not have access to this page') if tournament.cancelled: raise BadRequestError('tournament is cancelled')
def admintools_check(user, match): if user is None: raise BadRequestError('You do not have access to this page') grant_admin_access = user.admin and get5.config_setting( 'ADMINS_ACCESS_ALL_MATCHES') if user.id != match.user_id and not grant_admin_access: raise BadRequestError('You do not have access to this page') if match.finished(): raise BadRequestError('Match already finished') if match.cancelled: raise BadRequestError('Match is cancelled')
def admintools_check(user, match): if user is None: raise BadRequestError('You do not have access to this page') grant_admin_access = user.admin and get5.config_setting( 'ADMINS_ACCESS_ALL_MATCHES') if user.id != match.user_id and not grant_admin_access: raise BadRequestError('You do not have access to this page') if match.finished(): raise BadRequestError('Match already finished') if match.cancelled: raise BadRequestError('Match is cancelled')
class TournamentForm(Form): tournament_name = StringField( 'Tournament name', default=config_setting('BRAND') + ' tournament', validators=[ validators.Length(min=-1, max=Tournament.name.type.length) ]) tournament_url = StringField( 'Tournament url', default=md5(str(time.time()).encode('ascii')).hexdigest(), validators=[validators.Length(min=-1, max=Tournament.url.type.length)]) tournament_type = RadioField('Tournament type', validators=[validators.required()], default='bo1', choices=[ ('single elimination', 'single elimination'.title()), ('double elimination', 'double elimination'.title()), ('round robin', 'round robin'.title()), ]) serverpool = QuerySelectMultipleField( 'Server pool', query_factory=server_query_factory, option_widget=widgets.CheckboxInput()) mapchoices = config_setting('MAPLIST') default_mapchoices = config_setting('DEFAULT_MAPLIST') veto_mappool = MultiCheckboxField('Map pool', choices=[(name, util.format_mapname(name)) for name in mapchoices], default=default_mapchoices, validators=[validators.required()])
def fetch(self, method, uri, params_prefix=None, **params): """Fetch the given uri and return the contents of the response.""" url = "{}{}.json".format(BASE_URL, uri) params = self._prepare_params(params, params_prefix) if method.lower() == 'get': params['api_key'] = config_setting('CHALLONGE_API_KEY') r_data = {"params": params} else: r_data = { "data": params, "params": { 'api_key': config_setting('CHALLONGE_API_KEY') } } try: response = request(method, url, **r_data) response.raise_for_status() except HTTPError: # wrap up application-level errors doc = response.json() if doc.get("errors"): raise ChallongeException(*doc['errors']) return response.json()
def match(matchid): match = Match.query.get_or_404(matchid) team1 = Team.query.get_or_404(match.team1_id) team2 = Team.query.get_or_404(match.team2_id) map_stat_list = match.map_stats.all() is_owner = False has_admin_access = False if g.user: is_owner = (g.user.id == match.user_id) has_admin_access = is_owner or (config_setting( 'ADMINS_ACCESS_ALL_MATCHES') and g.user.admin) return render_template('match.html', user=g.user, admin_access=has_admin_access, match=match, team1=team1, team2=team2, map_stat_list=map_stat_list)
def match(matchid): match = Match.query.get_or_404(matchid) team1 = Team.query.get_or_404(match.team1_id) team2 = Team.query.get_or_404(match.team2_id) map_stat_list = match.map_stats.all() is_owner = False has_admin_access = False if g.user: is_owner = (g.user.id == match.user_id) has_admin_access = is_owner or (config_setting( 'ADMINS_ACCESS_ALL_MATCHES') and g.user.admin) return render_template( 'match.html', user=g.user, admin_access=has_admin_access, match=match, team1=team1, team2=team2, map_stat_list=map_stat_list)
class TeamForm(FlaskForm): mock = config_setting("TESTING") name = StringField('Team Name', validators=[ validators.required(), validators.Length(min=-1, max=Team.name.type.length) ]) tag = StringField('Team Tag', validators=[ validators.optional(), validators.Length(min=-1, max=Team.tag.type.length) ]) flag_choices = [('', 'None')] + countries.country_choices country_flag = SelectField('Country Flag', choices=flag_choices, default='') if mock: logo_choices = logos.get_logo_choices() logo = SelectField('Logo Name', choices=logo_choices, default='') else: logo = SelectField('Logo Name', default='') upload_logo = FileField(validators=[valid_file]) public_team = BooleanField('Public Team') def get_auth_list(self): auths = [] for i in range(1, Team.MAXPLAYERS + 1): key = 'auth{}'.format(i) auths.append(self.data[key]) return auths def get_pref_list(self): prefs = [] for i in range(1, Team.MAXPLAYERS + 1): key = 'pref_name{}'.format(i) prefs.append(self.data[key]) return prefs
def add_maps(self, user): if self.mappick_team1.choices is None: self.mappick_team1.choices = [] mapchoices = config_setting('MAPLIST') if self.mappick_team2.choices is None: self.mappick_team2.choices = [] self.mappick_team1.choices = map(lambda name: ( name, util.format_mapname( name)), mapchoices) self.mappick_team2.choices = map(lambda name: ( name, util.format_mapname( name)), mapchoices) self.mappick_bo3.choices = map(lambda name: ( name, util.format_mapname( name)), mapchoices)
def match_create(): if not g.user: return redirect('/login') form = MatchForm(request.form) form.add_teams(g.user) form.add_servers(g.user) if request.method == 'POST': num_matches = g.user.matches.count() max_matches = config_setting('USER_MAX_MATCHES') if max_matches >= 0 and num_matches >= max_matches and not g.user.admin: flash('You already have the maximum number of matches ({}) created'.format( num_matches)) if form.validate(): mock = config_setting('TESTING') server = GameServer.query.get_or_404(form.data['server_id']) match_on_server = g.user.matches.filter_by( server_id=server.id, end_time=None, cancelled=False).first() server_avaliable = False json_reply = None if g.user.id != server.user_id: server_avaliable = False message = 'This is not your server!' elif match_on_server is not None: server_avaliable = False message = 'Match {} is already using this server'.format( match_on_server.id) elif mock: server_avaliable = True message = 'Success' else: json_reply, message = util.check_server_avaliability( server) server_avaliable = (json_reply is not None) if server_avaliable: skip_veto = 'preset' in form.data['series_type'] try: max_maps = int(form.data['series_type'][2]) except ValueError: max_maps = 1 match = Match.create( g.user, form.data['team1_id'], form.data['team2_id'], form.data['team1_string'], form.data['team2_string'], max_maps, skip_veto, form.data['match_title'], form.data['veto_mappool'], form.data['server_id']) # Save plugin version data if we have it if json_reply and 'plugin_version' in json_reply: match.plugin_version = json_reply['plugin_version'] else: match.plugin_version = 'unknown' server.in_use = True db.session.commit() app.logger.info('User {} created match {}, assigned to server {}' .format(g.user.id, match.id, server.id)) if mock or match.send_to_server(): return redirect('/mymatches') else: flash('Failed to load match configs on server') else: flash(message) else: get5.flash_errors(form) return render_template('match_create.html', form=form, user=g.user, teams=g.user.teams, match_text_option=config_setting('CREATE_MATCH_TITLE_TEXT'))
class MatchForm(Form): server_id = SelectField('Server', coerce=int, validators=[validators.required()]) match_title = StringField('Match title text', default='Map {MAPNUMBER} of {MAXMAPS}', validators=[validators.Length(min=-1, max=Match.title.type.length)]) series_type = RadioField('Series type', validators=[validators.required()], default='bo1', choices=[ ('bo1-preset', 'Bo1 with preset map'), ('bo1', 'Bo1 with map vetoes'), ('bo2', 'Bo2 with map vetoes'), ('bo3', 'Bo3 with map vetoes'), ('bo5', 'Bo5 with map vetoes'), ('bo7', 'Bo7 with map vetoes'), ]) side_type = RadioField('Side type', validators=[validators.required()], default='standard', choices=[ ('standard', 'Standard: Team that doesn\'t pick map gets side choice'), ('never_knife', 'Never Knife: Team 1 is CT and Team 2 is T.'), ('always_knife', 'Always Knife: Always have knife round.'), ]) team1_id = SelectField('Team 1', coerce=int, validators=[validators.required()]) team1_string = StringField('Team 1 title text', default='', validators=[validators.Length(min=-1, max=Match.team1_string.type.length)]) team2_id = SelectField('Team 2', coerce=int, validators=[validators.required(), different_teams_validator]) team2_string = StringField('Team 2 title text', default='', validators=[validators.Length(min=-1, max=Match.team2_string.type.length)]) mapchoices = config_setting('MAPLIST') default_mapchoices = config_setting('DEFAULT_MAPLIST') veto_mappool = MultiCheckboxField('Map pool', choices=map(lambda name: ( name, util.format_mapname( name)), mapchoices), default=default_mapchoices, validators=[mappool_validator], ) veto_first = RadioField('Veto', default='CT', choices=[ ('CT', 'CT gets first veto'), ('T', 'T get first veto'), ]) season_selection = SelectField('Season', coerce=int, validators=[validators.optional()]) enforce_teams = BooleanField('Enforce Teams', default=True) def add_teams(self, user): if self.team1_id.choices is None: self.team1_id.choices = [] if self.team2_id.choices is None: self.team2_id.choices = [] team_ids = [team.id for team in user.teams] for team in Team.query.filter_by(public_team=True): if team.id not in team_ids: team_ids.append(team.id) team_tuples = [] for teamid in team_ids: team_tuples.append((teamid, Team.query.get(teamid).name)) self.team1_id.choices += team_tuples self.team2_id.choices += team_tuples def add_servers(self, user): if self.server_id.choices is None: self.server_id.choices = [] server_ids = [] for s in user.servers: if not s.in_use: server_ids.append(s.id) for s in GameServer.query.filter_by(public_server=True): if not s.in_use and s.id not in server_ids: server_ids.append(s.id) server_tuples = [] for server_id in server_ids: server_tuples.append( (server_id, GameServer.query.get(server_id).get_display())) self.server_id.choices += server_tuples def add_seasons(self): if self.season_selection.choices is None: self.season_selection.choices = [] season_tuples = [] season_tuples.append((0, 'No Season')) for seasons in Season.query.filter(Season.end_date >= datetime.now()).order_by(-Season.id): season_tuples.append((seasons.id, seasons.name)) self.season_selection.choices += season_tuples
def match_create(): if not g.user: return redirect('/login') form = MatchForm(request.form) form.add_teams(g.user) form.add_servers(g.user) form.add_seasons() if request.method == 'POST': num_matches = g.user.matches.count() max_matches = config_setting('USER_MAX_MATCHES') season_id = None if max_matches >= 0 and num_matches >= max_matches and not g.user.admin: flash('You already have the maximum number of matches ({}) created'.format( num_matches)) elif form.validate(): mock = config_setting('TESTING') server = GameServer.query.get_or_404(form.data['server_id']) match_on_server = g.user.matches.filter_by( server_id=server.id, end_time=None, cancelled=False).first() server_available = False json_reply = None if g.user.id != server.user_id and not server.public_server: server_available = False message = 'This is not your server!' elif match_on_server is not None: server_available = False message = 'Match {} is already using this server'.format( match_on_server.id) elif mock: server_available = True message = 'Success' else: json_reply, message = util.check_server_avaliability( server,dbKey) server_available = (json_reply is not None) if server_available: skip_veto = 'preset' in form.data['series_type'] try: max_maps = int(form.data['series_type'][2]) except ValueError: max_maps = 1 if form.data['season_selection'] != 0: season_id = form.data['season_selection'] match = Match.create( g.user, form.data['team1_id'], form.data['team2_id'], form.data['team1_string'], form.data['team2_string'], max_maps, skip_veto, form.data['match_title'], form.data['veto_mappool'], season_id, form.data['side_type'], form.data['veto_first'], form.data['server_id']) # Save plugin version data if we have it if json_reply and 'plugin_version' in json_reply: match.plugin_version = json_reply['plugin_version'] else: match.plugin_version = 'unknown' # ADD FORM DATA FOR EXTRA GOODIES HERE LIKE CLAN TAG ETC. # Essentially stuff that doesn't need to be stored in DB. # Force Get5 to auth on official matches. Don't raise errors # if we cannot do this. if server_available and not mock: server.send_rcon_command('get5_check_auths ' + str(int(form.data['enforce_teams'])), num_retries=2, timeout=0.75) server.in_use = True db.session.commit() app.logger.info('User {} created match {}, assigned to server {}' .format(g.user.id, match.id, server.id)) if mock or match.send_to_server(): return redirect('/mymatches') else: flash('Failed to load match configs on server') else: flash(message) else: get5.flash_errors(form) return render_template( 'match_create.html', form=form, user=g.user, teams=g.user.teams, match_text_option=config_setting('CREATE_MATCH_TITLE_TEXT'))
def valid_file(form, field): if not field.data: return mock = config_setting("TESTING") if mock: return elif not g.user.admin: return filename = secure_filename(field.data.filename) # Safe method. if filename == '': return index_of_dot = filename.index('.') file_name_without_extension = filename[:index_of_dot] extension = filename.rsplit('.', 1)[1].lower() exists = os.path.isfile(app.config['LOGO_FOLDER'] + "/" + secure_filename(filename)) existsSVG = os.path.isfile(app.config['PANO_LOGO_FOLDER'] + "/" + secure_filename(filename)) if '.' not in filename: raise ValidationError('Image MUST be PNG or SVG.') elif extension not in {'svg', 'png'}: raise ValidationError('Image MUST be PNG or SVG.') elif len(filename.rsplit('.', 1)[0]) > 3: raise ValidationError('Image name can only be 3 characters long.') elif exists: raise ValidationError('Image already exists in PNG.') elif existsSVG: raise ValidationError('Image name already exists for SVG.') if extension == 'png': file = request.files['upload_logo'] img = Image.open(file) width, height = img.size out = io.BytesIO() if width != 64 or height != 64: app.logger.info("Resizing image as it is not 64x64.") img = img.resize((64, 64), Image.ANTIALIAS) img.save(out, format=extension) # check once more for size. if out.tell() > 16384: app.logger.info("Size: {}".format(out.tell())) raise ValidationError( 'Image is too large, must be 10kB or less.') img.save(os.path.join(app.config['LOGO_FOLDER'], filename), optimize=True) elif out.tell() > 16384: raise ValidationError('Image is too large, must be 10kB or less.') else: img.save(os.path.join(app.config['LOGO_FOLDER'], filename), optimize=True) else: file = request.files['upload_logo'] # Limited - attempt to find width and height. If nothing then deny # upload. tree = ET.parse(file) root = tree.getroot() try: width = root.attrib['width'] height = root.attrib['height'] except: raise ValidationError('SVG is not properly formatted.') if (width in {'64', '64px'}) and (height in {'64', '64px'}): tree.write(app.config['PANO_LOGO_FOLDER'] + "/" + secure_filename(filename)) else: raise ValidationError("Error in saving SVG to folder.")
def team_edit(teamid): mock = config_setting("TESTING") customNames = config_setting("CUSTOM_PLAYER_NAMES") team = Team.query.get_or_404(teamid) if not team.can_edit(g.user): raise BadRequestError("Not your team.") form = TeamForm() # We wish to query this every time, since we can now upload photos. if not mock: form.logo.choices = logos.get_logo_choices() if request.method == 'GET': # Set values here, as per new FlaskForms. form.name.data = team.name form.tag.data = team.tag form.country_flag.data = team.flag form.logo.data = team.logo for field in form: if "auth" in field.name: try: field.data = team.auths[ int(re.search(r'\d+', field.name).group()) - 1] except: field.data = None if "pref_name" in field.name: try: field.data = team.preferred_names[ int(re.search(r'\d+', field.name).group()) - 1] except: field.data = None form.public_team.data = team.public_team return render_template('team_create.html', user=g.user, form=form, edit=True, is_admin=(g.user.admin or g.user.super_admin), MAXPLAYER=Team.MAXPLAYERS, customNames=customNames) elif request.method == 'POST': if form.validate(): data = form.data public_team = team.public_team if (g.user.admin or g.user.super_admin): public_team = data['public_team'] # Update the logo. Passing validation we have the filename in the # list now. if not mock and (g.user.admin or g.user.super_admin) and form.upload_logo.data: filename = secure_filename(form.upload_logo.data.filename) index_of_dot = filename.index('.') newLogoDetail = filename[:index_of_dot] # Reinit our logos. logos.add_new_logo(newLogoDetail) data['logo'] = newLogoDetail allAuths = form.get_auth_list() allNames = form.get_pref_list() team.set_data(data['name'], data['tag'], data['country_flag'], data['logo'], allAuths, public_team, allNames) for auth, name in itertools.izip_longest(allAuths, allNames): if auth: teamNames = TeamAuthNames.set_or_create(teamid, auth, name) db.session.commit() return redirect('/teams/{}'.format(team.user_id)) else: flash_errors(form) return render_template('team_create.html', user=g.user, form=form, edit=True, is_admin=g.user.admin, MAXPLAYER=Team.MAXPLAYERS)
class MatchForm(Form): server_id = SelectField('Server', coerce=int, validators=[validators.required()]) match_title = StringField('Match title text', default='Map {MAPNUMBER} of {MAXMAPS}', validators=[validators.Length(min=-1, max=Match.title.type.length)]) series_type = RadioField('Series type', validators=[validators.required()], default='bo2', choices=[ ('bo1-preset', 'Bo1 with preset map - (Knife preset, ignore sidepick of teams)'), ('bo2', 'Bo2 with preset maps - (Sidepick A & B)'), ('bo3', 'Bo3 with preset maps - (Sidepick A & B + Knife)'), ]) sidepick_team1 = RadioField('Sidepick Team A for Map 2 (BO2/BO3)', validators=[validators.required()], default='team1_ct', choices =[ ('team1_ct', 'CT'), ('team1_t', 'T'), ]) sidepick_team2 = RadioField('Sidepick Team B for Map 1 (BO2/BO3)', validators=[validators.required()], default='team2_ct', choices =[ ('team2_ct', 'CT'), ('team2_t', 'T'), ]) team1_id = SelectField('Team A', coerce=int, validators=[validators.required()]) team1_string = StringField('Team A title text', default='', validators=[validators.Length(min=-1, max=Match.team1_string.type.length)]) mappick_team1 = SelectField('Mappick Team A') team2_id = SelectField('Team B', coerce=int, validators=[validators.required(), different_teams_validator]) team2_string = StringField('Team B title text', default='', validators=[validators.Length(min=-1, max=Match.team2_string.type.length)]) mappick_team2 = SelectField('Mappick Team B', default='') mappick_bo3 = SelectField('Mappick Last Map BO3', default='') mapchoices = config_setting('MAPLIST') default_mapchoices = config_setting('DEFAULT_MAPLIST') veto_mappool = MultiCheckboxField('Map pool', choices=map(lambda name: ( name, util.format_mapname( name)), mapchoices), default=default_mapchoices, ) def add_teams(self, user): if self.team1_id.choices is None: self.team1_id.choices = [] if self.team2_id.choices is None: self.team2_id.choices = [] team_ids = [team.id for team in user.teams] for team in Team.query.filter_by(public_team=True): if team.id not in team_ids: team_ids.append(team.id) team_tuples = [] for teamid in team_ids: team_tuples.append((teamid, Team.query.get(teamid).name)) team_tuples.sort(key=lambda tup: tup[1]) self.team1_id.choices += team_tuples self.team2_id.choices += team_tuples def add_servers(self, user): if self.server_id.choices is None: self.server_id.choices = [] server_ids = [] for s in user.servers: if not s.in_use: server_ids.append(s.id) for s in GameServer.query.filter_by(public_server=True): if not s.in_use and s.id not in server_ids: server_ids.append(s.id) server_tuples = [] for server_id in server_ids: server_tuples.append( (server_id, GameServer.query.get(server_id).get_display())) self.server_id.choices += server_tuples def add_maps(self, user): if self.mappick_team1.choices is None: self.mappick_team1.choices = [] mapchoices = config_setting('MAPLIST') if self.mappick_team2.choices is None: self.mappick_team2.choices = [] self.mappick_team1.choices = map(lambda name: ( name, util.format_mapname( name)), mapchoices) self.mappick_team2.choices = map(lambda name: ( name, util.format_mapname( name)), mapchoices) self.mappick_bo3.choices = map(lambda name: ( name, util.format_mapname( name)), mapchoices)
def match_create(): if not g.user: return redirect('/login') form = MatchForm(request.form) form.add_teams(g.user) form.add_servers(g.user) form.add_seasons() if request.method == 'POST': num_matches = g.user.matches.count() max_matches = config_setting('USER_MAX_MATCHES') season_id = None if max_matches >= 0 and num_matches >= max_matches and not ( g.user.admin or g.user.super_admin): flash( 'You already have the maximum number of matches ({}) created'. format(num_matches)) elif form.validate(): mock = config_setting('TESTING') server = GameServer.query.get_or_404(form.data['server_id']) match_on_server = g.user.matches.filter_by( server_id=server.id, end_time=None, cancelled=False).first() server_available = False json_reply = None if g.user.id != server.user_id and not server.public_server: server_available = False message = 'This is not your server!' elif match_on_server is not None: server_available = False message = 'Match {} is already using this server'.format( match_on_server.id) elif mock: server_available = True message = 'Success' else: json_reply, message = util.check_server_avaliability( server, dbKey) server_available = (json_reply is not None) if server_available: skip_veto = 'preset' in form.data['series_type'] try: max_maps = int(form.data['series_type'][2]) except ValueError: max_maps = 1 if form.data['season_selection'] != 0: season_id = form.data['season_selection'] # Series Score Feature. team1_series_score = form.data[ 'team1_series_score'] if not None else 0 team2_series_score = form.data[ 'team2_series_score'] if not None else 0 # End Series Score Feature. # Spectator Feature specList = [] if form.data['spectator_string']: for auth in form.data['spectator_string'].split(): suc, new_auth = steamid.auth_to_steam64(auth) if suc: specList.append(new_auth) if not specList: specList = None # End Spectator Feature match = Match.create( g.user, form.data['team1_id'], form.data['team2_id'], form.data['team1_string'], form.data['team2_string'], max_maps, skip_veto, form.data['match_title'], form.data['veto_mappool'], season_id, form.data['side_type'], form.data['veto_first'], form.data['server_id'], team1_series_score, team2_series_score, specList, form.data['private_match'], form.data['enforce_teams'], form.data['min_player_ready']) # Save plugin version data if we have it if json_reply and 'plugin_version' in json_reply: match.plugin_version = json_reply['plugin_version'] else: match.plugin_version = 'unknown' server.in_use = True db.session.commit() # Implement normalized spectator list. if specList: for singleAuth in specList: MatchSpectator.set_or_create(match.id, auth) app.logger.info( 'User {} created match {}, assigned to server {}'.format( g.user.id, match.id, server.id)) if mock or match.send_to_server(): return redirect('/mymatches') else: flash('Failed to load match configs on server') else: flash(message) else: get5.flash_errors(form) return render_template( 'match_create.html', form=form, user=g.user, teams=g.user.teams, match_text_option=config_setting('CREATE_MATCH_TITLE_TEXT'))
class MatchForm(Form): server_id = SelectField('Server', coerce=int, validators=[validators.required()]) match_title = StringField('Match title text', default='Map {MAPNUMBER} of {MAXMAPS}', validators=[validators.Length(min=-1, max=Match.title.type.length)]) series_type = RadioField('Series type', validators=[validators.required()], default='bo1', choices=[ ('bo1-preset', 'Bo1 with preset map'), ('bo1', 'Bo1 with map vetoes'), ('bo2', 'Bo2 with map vetoes'), ('bo3', 'Bo3 with map vetoes'), ('bo5', 'Bo5 with map vetoes'), ('bo7', 'Bo7 with map vetoes'), ]) team1_id = SelectField('Team 1', coerce=int, validators=[validators.required()]) team1_string = StringField('Team 1 title text', default='', validators=[validators.Length(min=-1, max=Match.team1_string.type.length)]) team2_id = SelectField('Team 2', coerce=int, validators=[validators.required(), different_teams_validator]) team2_string = StringField('Team 2 title text', default='', validators=[validators.Length(min=-1, max=Match.team2_string.type.length)]) mapchoices = config_setting('MAPLIST') default_mapchoices = config_setting('DEFAULT_MAPLIST') veto_mappool = MultiCheckboxField('Map pool', choices=map(lambda name: ( name, util.format_mapname(name)), mapchoices), default=default_mapchoices, validators=[mappool_validator], ) def add_teams(self, user): if self.team1_id.choices is None: self.team1_id.choices = [] if self.team2_id.choices is None: self.team2_id.choices = [] team_ids = [team.id for team in user.teams] for team in Team.query.filter_by(public_team=True): if team.id not in team_ids: team_ids.append(team.id) team_tuples = [] for teamid in team_ids: team_tuples.append((teamid, Team.query.get(teamid).name)) self.team1_id.choices += team_tuples self.team2_id.choices += team_tuples def add_servers(self, user): if self.server_id.choices is None: self.server_id.choices = [] server_ids = [] for s in user.servers: if not s.in_use: server_ids.append(s.id) for s in GameServer.query.filter_by(public_server=True): if not s.in_use and s.id not in server_ids: server_ids.append(s.id) server_tuples = [] for server_id in server_ids: server_tuples.append((server_id, GameServer.query.get(server_id).get_display())) self.server_id.choices += server_tuples
def match_create(): if not g.user: return redirect('/login') form = MatchForm(request.form) form.add_teams(g.user) form.add_servers(g.user) if request.method == 'POST': num_matches = g.user.matches.count() max_matches = config_setting('USER_MAX_MATCHES') if max_matches >= 0 and num_matches >= max_matches and not g.user.admin: flash('You already have the maximum number of matches ({}) created'.format( num_matches)) if form.validate(): mock = config_setting('TESTING') server = GameServer.query.get_or_404(form.data['server_id']) match_on_server = g.user.matches.filter_by( server_id=server.id, end_time=None, cancelled=False).first() server_avaliable = False json_reply = None if g.user.id != server.user_id and not server.public_server: server_avaliable = False message = 'This is not your server!' elif match_on_server is not None: server_avaliable = False message = 'Match {} is already using this server'.format( match_on_server.id) elif mock: server_avaliable = True message = 'Success' else: json_reply, message = util.check_server_avaliability( server) server_avaliable = (json_reply is not None) if server_avaliable: skip_veto = 'preset' in form.data['series_type'] try: max_maps = int(form.data['series_type'][2]) except ValueError: max_maps = 1 match = Match.create( g.user, form.data['team1_id'], form.data['team2_id'], form.data['team1_string'], form.data['team2_string'], max_maps, skip_veto, form.data['match_title'], form.data['veto_mappool'], form.data['server_id']) # Save plugin version data if we have it if json_reply and 'plugin_version' in json_reply: match.plugin_version = json_reply['plugin_version'] else: match.plugin_version = 'unknown' server.in_use = True db.session.commit() app.logger.info('User {} created match {}, assigned to server {}' .format(g.user.id, match.id, server.id)) if mock or match.send_to_server(): return redirect('/mymatches') else: flash('Failed to load match configs on server') else: flash(message) else: get5.flash_errors(form) return render_template( 'match_create.html', form=form, user=g.user, teams=g.user.teams, match_text_option=config_setting('CREATE_MATCH_TITLE_TEXT'))