split views.py in events + new field in events model for automatching

This commit is contained in:
Danhia 2022-01-16 22:18:39 +01:00
parent cd5dcd9093
commit 8fbbd2d953
8 changed files with 204 additions and 169 deletions

View File

@ -0,0 +1,18 @@
# Generated by Django 3.1.5 on 2022-01-16 21:09
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('events', '0006_auto_20220114_2319'),
]
operations = [
migrations.AddField(
model_name='event',
name='auto_match',
field=models.BooleanField(default=False),
),
]

View File

@ -15,6 +15,7 @@ class Event(models.Model):
password = models.CharField(max_length=200, blank=True) password = models.CharField(max_length=200, blank=True)
slug = models.SlugField(max_length=55) slug = models.SlugField(max_length=55)
team_size = models.PositiveIntegerField(default=1) team_size = models.PositiveIntegerField(default=1)
auto_match = models.BooleanField(default=False)
def __str__(self): def __str__(self):
return self.name return self.name

View File

@ -46,6 +46,7 @@
<a href="{% url 'events:create_team' event_slug=event.slug %}" class="list-group-item">{% trans "Create Team" %}</a> <a href="{% url 'events:create_team' event_slug=event.slug %}" class="list-group-item">{% trans "Create Team" %}</a>
<a href="{% url 'events:join_team' event_slug=event.slug %}" class="list-group-item">{% trans "Join Team" %}</a> <a href="{% url 'events:join_team' event_slug=event.slug %}" class="list-group-item">{% trans "Join Team" %}</a>
</ul> </ul>
{% if event.auto_match %}
<ul class="list-group"> <ul class="list-group">
<form method='GET' action="{% url 'events:find_team' event_slug=event.slug %}"> <form method='GET' action="{% url 'events:find_team' event_slug=event.slug %}">
{%csrf_token%} {%csrf_token%}
@ -54,6 +55,7 @@
</li> </li>
</form> </form>
</ul> </ul>
{% endif %}
</div> </div>
</div> </div>
{% endblock %} {% endblock %}

View File

@ -51,6 +51,7 @@
<a href="{% url 'events:join_team' event_slug=event.slug %}" class="list-group-item">{% trans "Join Team" %}</a> <a href="{% url 'events:join_team' event_slug=event.slug %}" class="list-group-item">{% trans "Join Team" %}</a>
<a href="{% url 'events:create_team' event_slug=event.slug %}" class="list-group-item">{% trans "Create Team" %}</a> <a href="{% url 'events:create_team' event_slug=event.slug %}" class="list-group-item">{% trans "Create Team" %}</a>
</ul> </ul>
{% if event.auto_match %}
<ul class="list-group"> <ul class="list-group">
<form method='GET' action="{% url 'events:find_team' event_slug=event.slug %}"> <form method='GET' action="{% url 'events:find_team' event_slug=event.slug %}">
{%csrf_token%} {%csrf_token%}
@ -59,6 +60,7 @@
</li> </li>
</form> </form>
</ul> </ul>
{% endif %}
</div> </div>
</div> </div>
{% endblock %} {% endblock %}

View File

@ -3,7 +3,7 @@ from random import choice, randint
colors = ['blue', 'red', 'yellow', 'green', 'black', 'white', 'purple', 'orange', 'brown', 'fuchsia', 'gold', 'pink', 'cyan', colors = ['blue', 'red', 'yellow', 'green', 'black', 'white', 'purple', 'orange', 'brown', 'fuchsia', 'gold', 'pink', 'cyan',
'magenta', 'pearl'] 'magenta', 'pearl']
animals = ['tiger', 'bee', 'dog', 'cat', 'otter', 'lizard', 'horse', 'mouse', 'butterfly', 'dolphin', 'elephant', 'falcon', 'goat' animals = ['tiger', 'bee', 'dog', 'cat', 'otter', 'lizard', 'horse', 'mouse', 'butterfly', 'dolphin', 'elephant', 'falcon', 'goat',
'cow', 'lion', 'ostrich'] 'cow', 'lion', 'ostrich']
def get_random_name(): def get_random_name():

View File

@ -0,0 +1,2 @@
from .events import *
from .teams import *

View File

@ -1,16 +1,12 @@
from django.shortcuts import render, get_object_or_404, redirect from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.decorators import login_required from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import timezone from django.contrib.auth.models import timezone
from .forms import submit_flag, TeamUpdateForm from ..forms import submit_flag
from .models import Event, EventPlayer, Team from ..models import Event, EventPlayer, Team
from ctfs.models import CTF, CTF_flags, Category from ctfs.models import CTF, CTF_flags, Category
from django.utils.translation import get_language from django.utils.translation import get_language
from django.contrib.auth.models import User from django.contrib.auth.models import User
from accounts.models import UserProfileInfo
from django.db.models import Q
from django.utils.translation import gettext_lazy as _ from django.utils.translation import gettext_lazy as _
from .utils import get_random_name
from random import randint
def get_description_by_lang(ctf): def get_description_by_lang(ctf):
lang = get_language() lang = get_language()
@ -222,47 +218,6 @@ def subscribe_to_event(request, event_slug):
return render(request, 'events/create_team.html', {'event' : ev, 'logged': True, 'wrongpwd': False, 'registered' : True, 'notexist' : False}) return render(request, 'events/create_team.html', {'event' : ev, 'logged': True, 'wrongpwd': False, 'registered' : True, 'notexist' : False})
return redirect('events:event_info', event_slug=event_slug) return redirect('events:event_info', event_slug=event_slug)
@login_required
def create_team(request, event_slug):
response = redirect('events:create_team', event_slug=event_slug)
ev = get_object_or_404(Event, slug=event_slug)
if request.method == 'POST':
if request.user.is_authenticated and ev.team_size > 1:
if Team.objects.filter(name=request.POST.get('teamname'), event=ev).exists():
return render(request, 'events/create_team.html', {'event' : ev, 'logged': True, 'wrongpwd': False, 'registered' : True, 'exist' : True})
new = Team(name=request.POST.get('teamname'), password=request.POST.get('password'), event=ev)
new.save()
player = EventPlayer.objects.get(user=request.user, event=ev)
player.team = new
player.save()
return redirect('events:event_info', event_slug=event_slug)
@login_required
def join_team(request, event_slug):
response = redirect('events:join_team', event_slug=event_slug)
ev = get_object_or_404(Event, slug=event_slug)
if request.method == 'POST':
if request.user.is_authenticated and ev.team_size > 1:
try:
team = Team.objects.get(name=request.POST.get('teamname'), event=ev)
except:
team = None
if team is None:
return render(request, 'events/join_team.html', {'event' : ev, 'logged': True, 'wrongpwd': True, 'registered' : True, 'notexist' : True})
else:
members = EventPlayer.objects.filter(team=team)
if request.POST.get('password') != team.password:
return render(request, 'events/join_team.html', {'event' : ev, 'logged': True, 'wrongpwd': True, 'registered' : True, 'notexist' : False})
if members.count() >= ev.team_size:
return render(request, 'events/join_team.html', {'event' : ev, 'logged': True, 'wrongpwd': False, 'registered' : True, 'notexist' : False, 'max' : True})
else:
player = EventPlayer.objects.get(user=request.user, event=ev)
player.team = team
player.save()
else:
return render(request, 'events/join_team.html', {'event' : ev, 'logged': True, 'wrongpwd': False, 'registered' : True, 'notexist' : False})
return redirect('events:event_info', event_slug=event_slug)
@login_required @login_required
def profile(request, user_name, event_slug): def profile(request, user_name, event_slug):
catsDatas = [] catsDatas = []
@ -302,125 +257,4 @@ def profile(request, user_name, event_slug):
return render(request,'accounts/profile.html', {'user':user_obj, 'solves':solves,'solved':solved,'catsDatas': catsDatas, 'pointDatas': pointDatas, return render(request,'accounts/profile.html', {'user':user_obj, 'solves':solves,'solved':solved,'catsDatas': catsDatas, 'pointDatas': pointDatas,
'rank': rank, 'score' : somme, 'cats':cats}) 'rank': rank, 'score' : somme, 'cats':cats})
@login_required
def team_info(request, name, event_slug):
event_info = get_object_or_404(Event, slug=event_slug)
team = Team.objects.get(name=name, event=event_info)
catsDatas = []
players = EventPlayer.objects.filter(team=team, event=event_info)
users = [p.user for p in players]
all_teams = list(Team.objects.filter(event=event_info).order_by('-score', 'last_submission_date', 'name'))
rank = all_teams.index(get_object_or_404(Team, id=team.id, event=event_info)) + 1
all_cats = Category.objects.all()
cats = [cat for cat in all_cats if CTF.objects.filter(category__name=cat.name, event=event_info)]
pointDatas = {}
for cat in cats:
# prepare categories
solved_count = 0
solved = []
max_count = CTF.objects.filter(category__name=cat.name, event=event_info).count()
somme = 0
pointDatas[cat.name] = [[event_info.start_date.timestamp()*1000, 0]]
for user_obj in users:
# get datas
solved_count += CTF_flags.objects.filter(user=user_obj, ctf__event=event_info , ctf__category__name=cat.name).count()
solved += CTF_flags.objects.filter(user=user_obj, ctf__category__name=cat.name, ctf__event=event_info).order_by('flag_date')
percent = (solved_count / max_count) * 100
catsDatas.append([cat.name, solved_count, max_count, '{:.0f}'.format(percent)])
for flag in solved:
somme += flag.ctf.points
pointDatas[cat.name].append([flag.flag_date.timestamp() * 1000, somme])
query = Q()
for user_obj in users:
query |= Q(user=user_obj)
query &= Q(ctf__event=event_info)
solves = CTF_flags.objects.filter(query).order_by('-flag_date')
solved = []
somme = 0
solved.append([event_info.start_date.timestamp() * 1000, 0])
for s in solves.reverse():
somme += s.ctf.points
solved.append([s.flag_date.timestamp() * 1000,somme])
return render(request,'events/team.html', {'users':users, 'solves':solves,'solved':solved,'catsDatas': catsDatas, 'pointDatas': pointDatas,
'rank': rank, 'team':team, 'score':somme, 'event':event_info, 'cats':cats})
@login_required
def manage_team(request, event_slug):
event_info = get_object_or_404(Event, slug=event_slug)
player = EventPlayer.objects.get(user=request.user, event=event_info)
members = EventPlayer.objects.filter(team=player.team, event=event_info)
if request.method == 'POST':
tname = player.team.name
p_form = TeamUpdateForm(request.POST, instance=player.team)
error = None
success = None
if p_form.is_valid():
pname = p_form.cleaned_data['name']
if pname == tname:
pass
else:
if Team.objects.filter(name=pname, event=event_info).exists():
error = _("Name already taken.")
ppassword = p_form.cleaned_data['password']
if error is None:
p_form.save()
success = _("Updated.")
context={'p_form': p_form, 'error':error, 'success' : success, 'player':player, 'members':members}
return render(request, 'events/manage_team.html', context)
else:
p_form = TeamUpdateForm(instance=player.team)
context={'p_form': p_form, 'player':player, 'members':members}
return render(request, 'events/manage_team.html',context)
@login_required
def leave_team(request, event_slug):
event_info = get_object_or_404(Event, slug=event_slug)
player = EventPlayer.objects.get(user=request.user, event=event_info)
team = Team.objects.get(event=event_info, name=player.team.name)
team.score -= player.score
team.save()
player.team = None
solved = CTF_flags.objects.filter(user=player.user, ctf__event=event_info)
player.score = 0
solved.delete()
player.save()
members = EventPlayer.objects.filter(team=team, event=event_info)
if members.count() == 0:
team.delete()
return render(request, 'events/create_team.html', {'event' : event_info, 'logged': True, 'wrongpwd': False, 'registered' : True, 'notexist' : False})
@login_required
def find_team(request, event_slug):
event_info = get_object_or_404(Event, slug=event_slug)
teams = Team.objects.filter(event=event_info, auto=True)
team = None
player = EventPlayer.objects.get(user=request.user, event=event_info)
for t in teams:
if EventPlayer.objects.filter(team=t, event=event_info).count() < event_info.team_size:
team = t
break
if team is None:
teamname = get_random_name()
while Team.objects.filter(name=teamname, event=event_info).exists():
teamname = get_random_name()
team = Team(name=teamname, password="".join([str(randint(0,10)) for _ in range(16)]), event=event_info, auto=True)
team.save()
player.team = team
player.save()
return redirect('events:event_info', event_slug=event_slug)

176
src/events/views/teams.py Normal file
View File

@ -0,0 +1,176 @@
from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.decorators import login_required
from ..forms import TeamUpdateForm
from ..models import Event, EventPlayer, Team
from ctfs.models import CTF, CTF_flags, Category
from django.contrib.auth.models import User
from django.db.models import Q
from django.utils.translation import gettext_lazy as _
from ..utils import get_random_name
from random import randint
@login_required
def create_team(request, event_slug):
response = redirect('events:create_team', event_slug=event_slug)
ev = get_object_or_404(Event, slug=event_slug)
if request.method == 'POST':
if request.user.is_authenticated and ev.team_size > 1:
if Team.objects.filter(name=request.POST.get('teamname'), event=ev).exists():
return render(request, 'events/create_team.html', {'event' : ev, 'logged': True, 'wrongpwd': False, 'registered' : True, 'exist' : True})
new = Team(name=request.POST.get('teamname'), password=request.POST.get('password'), event=ev)
new.save()
player = EventPlayer.objects.get(user=request.user, event=ev)
player.team = new
player.save()
return redirect('events:event_info', event_slug=event_slug)
@login_required
def join_team(request, event_slug):
response = redirect('events:join_team', event_slug=event_slug)
ev = get_object_or_404(Event, slug=event_slug)
if request.method == 'POST':
if request.user.is_authenticated and ev.team_size > 1:
try:
team = Team.objects.get(name=request.POST.get('teamname'), event=ev)
except:
team = None
if team is None:
return render(request, 'events/join_team.html', {'event' : ev, 'logged': True, 'wrongpwd': True, 'registered' : True, 'notexist' : True})
else:
members = EventPlayer.objects.filter(team=team)
if request.POST.get('password') != team.password:
return render(request, 'events/join_team.html', {'event' : ev, 'logged': True, 'wrongpwd': True, 'registered' : True, 'notexist' : False})
if members.count() >= ev.team_size:
return render(request, 'events/join_team.html', {'event' : ev, 'logged': True, 'wrongpwd': False, 'registered' : True, 'notexist' : False, 'max' : True})
else:
player = EventPlayer.objects.get(user=request.user, event=ev)
player.team = team
player.save()
else:
return render(request, 'events/join_team.html', {'event' : ev, 'logged': True, 'wrongpwd': False, 'registered' : True, 'notexist' : False})
return redirect('events:event_info', event_slug=event_slug)
@login_required
def team_info(request, name, event_slug):
event_info = get_object_or_404(Event, slug=event_slug)
team = Team.objects.get(name=name, event=event_info)
catsDatas = []
players = EventPlayer.objects.filter(team=team, event=event_info)
users = [p.user for p in players]
all_teams = list(Team.objects.filter(event=event_info).order_by('-score', 'last_submission_date', 'name'))
rank = all_teams.index(get_object_or_404(Team, id=team.id, event=event_info)) + 1
all_cats = Category.objects.all()
cats = [cat for cat in all_cats if CTF.objects.filter(category__name=cat.name, event=event_info)]
pointDatas = {}
for cat in cats:
# prepare categories
solved_count = 0
solved = []
max_count = CTF.objects.filter(category__name=cat.name, event=event_info).count()
somme = 0
pointDatas[cat.name] = [[event_info.start_date.timestamp()*1000, 0]]
for user_obj in users:
# get datas
solved_count += CTF_flags.objects.filter(user=user_obj, ctf__event=event_info , ctf__category__name=cat.name).count()
solved += CTF_flags.objects.filter(user=user_obj, ctf__category__name=cat.name, ctf__event=event_info).order_by('flag_date')
percent = (solved_count / max_count) * 100
catsDatas.append([cat.name, solved_count, max_count, '{:.0f}'.format(percent)])
for flag in solved:
somme += flag.ctf.points
pointDatas[cat.name].append([flag.flag_date.timestamp() * 1000, somme])
query = Q()
for user_obj in users:
query |= Q(user=user_obj)
query &= Q(ctf__event=event_info)
solves = CTF_flags.objects.filter(query).order_by('-flag_date')
solved = []
somme = 0
solved.append([event_info.start_date.timestamp() * 1000, 0])
for s in solves.reverse():
somme += s.ctf.points
solved.append([s.flag_date.timestamp() * 1000,somme])
return render(request,'events/team.html', {'users':users, 'solves':solves,'solved':solved,'catsDatas': catsDatas, 'pointDatas': pointDatas,
'rank': rank, 'team':team, 'score':somme, 'event':event_info, 'cats':cats})
@login_required
def manage_team(request, event_slug):
event_info = get_object_or_404(Event, slug=event_slug)
player = EventPlayer.objects.get(user=request.user, event=event_info)
members = EventPlayer.objects.filter(team=player.team, event=event_info)
if request.method == 'POST':
tname = player.team.name
p_form = TeamUpdateForm(request.POST, instance=player.team)
error = None
success = None
if p_form.is_valid():
pname = p_form.cleaned_data['name']
if pname == tname:
pass
else:
if Team.objects.filter(name=pname, event=event_info).exists():
error = _("Name already taken.")
ppassword = p_form.cleaned_data['password']
if error is None:
p_form.save()
success = _("Updated.")
context={'p_form': p_form, 'error':error, 'success' : success, 'player':player, 'members':members}
return render(request, 'events/manage_team.html', context)
else:
p_form = TeamUpdateForm(instance=player.team)
context={'p_form': p_form, 'player':player, 'members':members}
return render(request, 'events/manage_team.html',context)
@login_required
def leave_team(request, event_slug):
event_info = get_object_or_404(Event, slug=event_slug)
player = EventPlayer.objects.get(user=request.user, event=event_info)
team = Team.objects.get(event=event_info, name=player.team.name)
team.score -= player.score
team.save()
player.team = None
solved = CTF_flags.objects.filter(user=player.user, ctf__event=event_info)
player.score = 0
solved.delete()
player.save()
members = EventPlayer.objects.filter(team=team, event=event_info)
if members.count() == 0:
team.delete()
return render(request, 'events/create_team.html', {'event' : event_info, 'logged': True, 'wrongpwd': False, 'registered' : True, 'notexist' : False})
@login_required
def find_team(request, event_slug):
event_info = get_object_or_404(Event, slug=event_slug)
teams = Team.objects.filter(event=event_info, auto=True)
team = None
player = EventPlayer.objects.get(user=request.user, event=event_info)
if event_info.auto_match == False:
return redirect('events:event_info', event_slug=event_slug)
for t in teams:
if EventPlayer.objects.filter(team=t, event=event_info).count() < event_info.team_size:
team = t
break
if team is None:
teamname = get_random_name()
while Team.objects.filter(name=teamname, event=event_info).exists():
teamname = get_random_name()
team = Team(name=teamname, password="".join([str(randint(0,10)) for _ in range(16)]), event=event_info, auto=True)
team.save()
player.team = team
player.save()
return redirect('events:event_info', event_slug=event_slug)