You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
325 lines
12 KiB
325 lines
12 KiB
from django.shortcuts import render, get_object_or_404
|
|
from django.http import HttpResponse
|
|
from django.utils.encoding import force_str
|
|
from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode
|
|
from django.urls import reverse
|
|
from tournaments.models.court import Court
|
|
from tournaments.models.date_interval import DateInterval
|
|
|
|
from .tokens import account_activation_token
|
|
|
|
from tournaments.models import group_stage
|
|
from .serializers import ClubSerializer, CourtSerializer, DateIntervalSerializer, TournamentSerializer, UserSerializer, ChangePasswordSerializer, EventSerializer, RoundSerializer, GroupStageSerializer, MatchSerializer, TeamScoreSerializer, TeamRegistrationSerializer, PlayerRegistrationSerializer, LiveMatchSerializer, PurchaseSerializer, UserUpdateSerializer
|
|
from .models import Club, Tournament, CustomUser, Event, Round, GroupStage, Match, TeamScore, TeamRegistration, PlayerRegistration, Purchase
|
|
from .models import TeamSummon
|
|
from datetime import datetime
|
|
import datetime
|
|
|
|
from rest_framework import viewsets, permissions
|
|
from rest_framework.authtoken.models import Token
|
|
from rest_framework.response import Response
|
|
from rest_framework.decorators import api_view
|
|
from rest_framework import status
|
|
from rest_framework.generics import UpdateAPIView
|
|
from rest_framework.exceptions import MethodNotAllowed
|
|
from rest_framework.permissions import IsAuthenticated
|
|
from .permissions import IsClubOwner
|
|
from django.template import loader
|
|
from datetime import date
|
|
from django.http import JsonResponse
|
|
from django.db.models import Q
|
|
import json
|
|
|
|
from qr_code.qrcode.utils import QRCodeOptions
|
|
|
|
def index(request):
|
|
|
|
today = date.today()
|
|
|
|
club_id = request.GET.get('club')
|
|
q_is_private = Q(is_private=False)
|
|
|
|
q_future = [q_is_private, Q(end_date__isnull=True, start_date__gt=today)]
|
|
q_live = [q_is_private, Q(end_date__isnull=True, start_date__lte=today)]
|
|
q_ended = [q_is_private, Q(end_date__isnull=False)]
|
|
|
|
club = None
|
|
if club_id:
|
|
club = get_object_or_404(Club, pk=club_id)
|
|
|
|
q_club = Q(event__club=club)
|
|
q_future.append(q_club)
|
|
q_live.append(q_club)
|
|
q_ended.append(q_club)
|
|
|
|
future_tournaments = Tournament.objects.filter(*q_future).order_by('start_date')
|
|
live_tournaments = Tournament.objects.filter(*q_live).order_by('start_date')
|
|
ended_tournaments = Tournament.objects.filter(*q_ended).order_by('start_date')
|
|
return render(
|
|
request,
|
|
"tournaments/tournaments.html",
|
|
{
|
|
'future': future_tournaments,
|
|
'live': live_tournaments,
|
|
'ended': ended_tournaments,
|
|
'club': club,
|
|
}
|
|
)
|
|
|
|
def clubs(request):
|
|
clubs = Club.objects.all().order_by('name')
|
|
return render(request, 'tournaments/clubs.html', {
|
|
'clubs': clubs,
|
|
})
|
|
|
|
def club(request, club_id):
|
|
club = get_object_or_404(Club, pk=club_id)
|
|
return render(request, 'tournaments/summons.html', {
|
|
'tournament': tournament,
|
|
'team_summons': team_summons,
|
|
})
|
|
|
|
def tournament(request, tournament_id):
|
|
|
|
tournament = get_object_or_404(Tournament, pk=tournament_id)
|
|
|
|
round_id = request.GET.get('round')
|
|
group_stage_id = request.GET.get('group_stage')
|
|
match_groups = tournament.match_groups(False, group_stage_id, round_id)
|
|
|
|
rounds = tournament.round_set.filter(parent=None).order_by('-index')
|
|
group_stages = tournament.groupstage_set.order_by('index')
|
|
|
|
return render(request, 'tournaments/matches.html', {
|
|
'tournament': tournament,
|
|
'rounds': rounds,
|
|
'group_stages': group_stages,
|
|
'match_groups': match_groups,
|
|
})
|
|
|
|
def tournament_teams(request, tournament_id):
|
|
|
|
tournament = get_object_or_404(Tournament, pk=tournament_id)
|
|
teams = tournament.teams()
|
|
|
|
return render(request, 'tournaments/teams.html', {
|
|
'tournament': tournament,
|
|
'teams': teams,
|
|
})
|
|
|
|
def tournament_summons(request, tournament_id):
|
|
|
|
tournament = get_object_or_404(Tournament, pk=tournament_id)
|
|
team_summons = tournament.team_summons()
|
|
|
|
return render(request, 'tournaments/summons.html', {
|
|
'tournament': tournament,
|
|
'team_summons': team_summons,
|
|
})
|
|
|
|
def tournament_broadcasted_summons(request, tournament_id):
|
|
tournament = get_object_or_404(Tournament, pk=tournament_id)
|
|
return render(request, 'tournaments/broadcasted_summons.html', {
|
|
'tournament': tournament,
|
|
'qr_code_url': qr_code_url(request, tournament_id),
|
|
'qr_code_options': qr_code_options(),
|
|
})
|
|
|
|
def tournament_summons_json(request, tournament_id):
|
|
tournament = get_object_or_404(Tournament, pk=tournament_id)
|
|
team_summons = [summon.to_dict() for summon in tournament.team_summons()]
|
|
data = json.dumps(team_summons)
|
|
return HttpResponse(data, content_type='application/json')
|
|
|
|
def tournament_broadcast_home(request, tournament_id):
|
|
tournament = get_object_or_404(Tournament, pk=tournament_id)
|
|
return render(request, 'tournaments/broadcast.html', {
|
|
'tournament': tournament,
|
|
'qr_code_url': qr_code_url(request, tournament_id),
|
|
'qr_code_options': qr_code_options(),
|
|
})
|
|
|
|
def automatic_broadcast(request, tournament_id):
|
|
tournament = get_object_or_404(Tournament, pk=tournament_id)
|
|
return render(request, 'tournaments/broadcasted_auto.html', {
|
|
'tournament': tournament,
|
|
'qr_code_url': qr_code_url(request, tournament_id),
|
|
'qr_code_options': qr_code_options(),
|
|
})
|
|
|
|
def qr_code_url(request, tournament_id):
|
|
qr_code_url = reverse('tournament', args=[tournament_id])
|
|
return request.build_absolute_uri(qr_code_url)
|
|
|
|
def qr_code_options():
|
|
return QRCodeOptions(size=10, border=4, error_correction='L')
|
|
|
|
def tournament_matches(request, tournament_id):
|
|
tournament = get_object_or_404(Tournament, pk=tournament_id)
|
|
return render(request, 'tournaments/broadcasted_matches.html', {
|
|
'tournament': tournament,
|
|
'qr_code_url': qr_code_url(request, tournament_id),
|
|
'qr_code_options': qr_code_options(),
|
|
})
|
|
|
|
def broadcast_json(request, tournament_id):
|
|
tournament = get_object_or_404(Tournament, pk=tournament_id)
|
|
broadcast = tournament.broadcast_content()
|
|
data = json.dumps(broadcast)
|
|
return HttpResponse(data, content_type='application/json')
|
|
|
|
def tournament_matches_json(request, tournament_id):
|
|
tournament = get_object_or_404(Tournament, pk=tournament_id)
|
|
matches, group_stages = tournament.broadcasted_matches_and_group_stages()
|
|
live_matches = [match.live_match() for match in matches]
|
|
|
|
data = json.dumps(live_matches, default=vars)
|
|
return HttpResponse(data, content_type='application/json')
|
|
|
|
def tournament_group_stages(request, tournament_id):
|
|
tournament = get_object_or_404(Tournament, pk=tournament_id)
|
|
live_group_stages = list(tournament.live_group_stages())
|
|
return render(request, 'tournaments/group_stages.html', {
|
|
'tournament': tournament,
|
|
'group_stages': live_group_stages,
|
|
})
|
|
|
|
def tournament_broadcasted_group_stages(request, tournament_id):
|
|
tournament = get_object_or_404(Tournament, pk=tournament_id)
|
|
return render(request, 'tournaments/broadcasted_group_stages.html', {
|
|
'tournament': tournament,
|
|
'qr_code_url': qr_code_url(request, tournament_id),
|
|
'qr_code_options': qr_code_options(),
|
|
})
|
|
|
|
def tournament_live_group_stage_json(request, tournament_id):
|
|
tournament = get_object_or_404(Tournament, pk=tournament_id)
|
|
|
|
gs_dicts = [gs.to_dict() for gs in tournament.live_group_stages()]
|
|
# group_stages = tournament.live_group_stages()
|
|
data = json.dumps(gs_dicts)
|
|
return HttpResponse(data, content_type='application/json')
|
|
|
|
def players(request):
|
|
return render(request, 'tournaments/test.html')
|
|
|
|
def activate(request, uidb64, token):
|
|
try:
|
|
uid = force_str(urlsafe_base64_decode(uidb64))
|
|
user = CustomUser.objects.get(pk=uid)
|
|
except(TypeError, ValueError, OverflowError, CustomUser.DoesNotExist):
|
|
user = None
|
|
if user is not None and account_activation_token.check_token(user, token):
|
|
user.is_active = True
|
|
user.save()
|
|
return HttpResponse('Thank you for your email confirmation. Now you can login your account.')
|
|
else:
|
|
return HttpResponse('Activation link is invalid!')
|
|
|
|
##### API #####
|
|
|
|
@api_view(['GET'])
|
|
def user_by_token(request):
|
|
# return Response({"message": "Hello for today! See you tomorrow!"})
|
|
# key = request.data['token']
|
|
# token = Token.objects.get(key=key)
|
|
# user = CustomUser.objects.get(username=token.user)
|
|
serializer = UserSerializer(request.user)
|
|
return Response(serializer.data, status=status.HTTP_200_OK)
|
|
|
|
class UserViewSet(viewsets.ModelViewSet):
|
|
queryset = CustomUser.objects.all()
|
|
serializer_class = UserUpdateSerializer
|
|
permission_classes = [] # Users are public whereas the other requests are only for logged users
|
|
|
|
def get_serializer_class(self):
|
|
# Use UserSerializer for other actions (e.g., create, retrieve)
|
|
if self.action in ['create', 'retrieve']:
|
|
return UserSerializer
|
|
return self.serializer_class
|
|
|
|
class ClubViewSet(viewsets.ModelViewSet):
|
|
queryset = Club.objects.all()
|
|
serializer_class = ClubSerializer
|
|
permission_classes = [IsClubOwner] # Clubs are public whereas the other requests are only for logged users
|
|
|
|
class TournamentViewSet(viewsets.ModelViewSet):
|
|
queryset = Tournament.objects.all()
|
|
serializer_class = TournamentSerializer
|
|
|
|
class PurchaseViewSet(viewsets.ModelViewSet):
|
|
queryset = Purchase.objects.all()
|
|
serializer_class = PurchaseSerializer
|
|
|
|
def get_queryset(self):
|
|
if self.request.user:
|
|
return self.queryset.filter(user=self.request.user)
|
|
return []
|
|
|
|
def put(self, request, pk):
|
|
raise MethodNotAllowed('PUT')
|
|
|
|
def patch(self, request, pk):
|
|
raise MethodNotAllowed('PATCH')
|
|
|
|
def delete(self, request, pk):
|
|
raise MethodNotAllowed('DELETE')
|
|
|
|
# class ExpandedTournamentViewSet(viewsets.ModelViewSet):
|
|
# queryset = Tournament.objects.all()
|
|
# serializer_class = ExpandedTournamentSerializer
|
|
|
|
class ChangePasswordView(UpdateAPIView):
|
|
serializer_class = ChangePasswordSerializer
|
|
|
|
def update(self, request, *args, **kwargs):
|
|
serializer = self.get_serializer(data=request.data)
|
|
serializer.is_valid(raise_exception=True)
|
|
user = serializer.save()
|
|
# if using drf authtoken, create a new token
|
|
if hasattr(user, 'auth_token'):
|
|
user.auth_token.delete()
|
|
token, created = Token.objects.get_or_create(user=user)
|
|
# return new token
|
|
return Response({'token': token.key}, status=status.HTTP_200_OK)
|
|
|
|
class EventViewSet(viewsets.ModelViewSet):
|
|
queryset = Event.objects.all()
|
|
serializer_class = EventSerializer
|
|
|
|
def get_queryset(self):
|
|
if self.request.user.is_anonymous:
|
|
return []
|
|
return self.queryset.filter(creator=self.request.user)
|
|
|
|
class RoundViewSet(viewsets.ModelViewSet):
|
|
queryset = Round.objects.all()
|
|
serializer_class = RoundSerializer
|
|
|
|
class GroupStageViewSet(viewsets.ModelViewSet):
|
|
queryset = GroupStage.objects.all()
|
|
serializer_class = GroupStageSerializer
|
|
|
|
class MatchViewSet(viewsets.ModelViewSet):
|
|
queryset = Match.objects.all()
|
|
serializer_class = MatchSerializer
|
|
|
|
class TeamScoreViewSet(viewsets.ModelViewSet):
|
|
queryset = TeamScore.objects.all()
|
|
serializer_class = TeamScoreSerializer
|
|
|
|
class TeamRegistrationViewSet(viewsets.ModelViewSet):
|
|
queryset = TeamRegistration.objects.all()
|
|
serializer_class = TeamRegistrationSerializer
|
|
|
|
class PlayerRegistrationViewSet(viewsets.ModelViewSet):
|
|
queryset = PlayerRegistration.objects.all()
|
|
serializer_class = PlayerRegistrationSerializer
|
|
|
|
class CourtViewSet(viewsets.ModelViewSet):
|
|
queryset = Court.objects.all()
|
|
serializer_class = CourtSerializer
|
|
|
|
class DateIntervalViewSet(viewsets.ModelViewSet):
|
|
queryset = DateInterval.objects.all()
|
|
serializer_class = DateIntervalSerializer
|
|
|