Skip to content

Commit

Permalink
Merge pull request #33 from SAT-Duel/18-fix-joining-room
Browse files Browse the repository at this point in the history
Add admin status to user views and create tournament endpoint
  • Loading branch information
FarmerJohnsBessie authored Aug 3, 2024
2 parents ab5a348 + 6fbdee8 commit d9685fd
Show file tree
Hide file tree
Showing 7 changed files with 55 additions and 45 deletions.
2 changes: 1 addition & 1 deletion .idea/misc.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion .idea/satduel.iml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 0 additions & 5 deletions api/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -238,11 +238,6 @@ def questionNumber(self):
def participantNumber(self):
return self.tournamentparticipation_set.count()

def save(self, *args, **kwargs):
if self.start_time and self.duration:
self.end_time = self.start_time + self.duration
super(Tournament, self).save(*args, **kwargs)


class TournamentParticipation(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
Expand Down
4 changes: 2 additions & 2 deletions api/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,15 +127,15 @@ class TournamentSerializer(serializers.ModelSerializer):

class Meta:
model = Tournament
fields = ['id', 'name', 'start_time', 'end_time', 'participantNumber', 'questionNumber']
fields = ['id', 'name', 'description', 'duration', 'start_time', 'end_time', 'participantNumber', 'questionNumber']


class TournamentParticipationSerializer(serializers.ModelSerializer):
tournament = TournamentSerializer()

class Meta:
model = TournamentParticipation
fields = ['id', 'user', 'tournament', 'start_time', 'end_time', 'score', 'last_correct_submission']
fields = ['id', 'user', 'tournament', 'start_time', 'end_time', 'score', 'last_correct_submission', 'status']


class TournamentQuestionSerializer(serializers.ModelSerializer):
Expand Down
42 changes: 37 additions & 5 deletions api/tournaments_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,14 @@

from api.models import Tournament, TournamentParticipation, Question, TournamentQuestion, Profile
from api.serializers import TournamentSerializer, TournamentParticipationSerializer, TournamentQuestionSerializer, \
ProfileSerializer, TPSubmitAnswerSerializer
ProfileSerializer, TPSubmitAnswerSerializer, QuestionSerializer


@api_view(['GET', 'POST'])
def tournament_list(request):
if request.method == 'GET':
tournaments = Tournament.objects.all()
# Todo: Add a filter that filters tournament with end time larger than the current time
tournaments = Tournament.objects.filter(private=False)
serializer = TournamentSerializer(tournaments, many=True)
return Response(serializer.data)
elif request.method == 'POST':
Expand All @@ -27,7 +28,6 @@ def tournament_list(request):
@api_view(['GET', 'PUT', 'DELETE'])
def tournament_detail(request, pk):
tournament = get_object_or_404(Tournament, pk=pk)

if request.method == 'GET':
serializer = TournamentSerializer(tournament)
return Response(serializer.data)
Expand All @@ -50,7 +50,9 @@ def join_tournament(request, pk):
duration = tournament.duration

if TournamentParticipation.objects.filter(user=user, tournament=tournament).exists():
return Response({"error": "Already joined this tournament"}, status=status.HTTP_400_BAD_REQUEST)
participation = TournamentParticipation.objects.get(user=user, tournament=tournament)
serializer = TournamentParticipationSerializer(participation)
return Response(serializer.data, status=status.HTTP_200_OK)

participation = TournamentParticipation.objects.create(
user=user,
Expand Down Expand Up @@ -95,7 +97,6 @@ def get_tournament_questions(request, pk):


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def tournament_leaderboard(request, pk):
tournament = get_object_or_404(Tournament, pk=pk)
participations = TournamentParticipation.objects.filter(tournament=tournament).order_by('-score',
Expand Down Expand Up @@ -164,3 +165,34 @@ def update_rating(request):

serializer = ProfileSerializer(profile)
return Response(serializer.data)


@api_view(['POST'])
@permission_classes([IsAuthenticated])
def create_tournament(request):
data = request.data
questions_data = data['questions']
tournament = Tournament.objects.create(
name=data['name'],
description=data['description'],
start_time=data['start_time'],
end_time=data['end_time'],
private=data['private'],
)

for question in questions_data:
question = Question.objects.create(
question=question['question'],
choice_a=question['choice_a'],
choice_b=question['choice_b'],
choice_c=question['choice_c'],
choice_d=question['choice_d'],
answer=question['answer'],
difficulty=question['difficulty'],
question_type=question.get('question_type', ''), # Default empty string if not provided
explanation=question.get('explanation', ''), # Default empty string if not provided
)
tournament.questions.add(question)
tournament.save()
serializer = TournamentSerializer(tournament)
return Response(serializer.data, status=status.HTTP_201_CREATED)
16 changes: 11 additions & 5 deletions api/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from .user_views import CustomRegisterView
from . import trainer_views as trainer_view
from . import tournaments_views

urlpatterns = [
path('questions/', views.get_random_questions, name='get_random_questions'),
path('get_question/', views.get_question, name='get_question'),
Expand All @@ -19,7 +20,8 @@
path('profile/update_streak/', views.update_streak, name='update_streak'),
path('profile/search/', views.search_users, name='search_users'),
path('profile/send_friend_request/', views.send_friend_request, name='send_friend_request'),
path('profile/respond_friend_request/<int:request_id>/', views.respond_friend_request, name='respond_friend_request'),
path('profile/respond_friend_request/<int:request_id>/', views.respond_friend_request,
name='respond_friend_request'),
path('profile/friend_requests/', views.list_friend_requests, name='list_friend_requests'),
path('profile/friends/', views.list_friends, name='list_friends'),
path('profile/view_profile/<int:user_id>/', views.view_profile, name='view_profile'),
Expand All @@ -45,8 +47,10 @@
path('match/set_winner/', views.set_winner, name='set_winner'),
path('match/set_score/', views.set_score, name='set_score'),

path('trainer/infinite_question_stats/', trainer_view.get_infinite_question_stats, name='get_infinite_question_stats'),
path('trainer/set_infinite_question_stats/', trainer_view.set_infinite_question_stats, name='set_infinite_question_stats'),
path('trainer/infinite_question_stats/', trainer_view.get_infinite_question_stats,
name='get_infinite_question_stats'),
path('trainer/set_infinite_question_stats/', trainer_view.set_infinite_question_stats,
name='set_infinite_question_stats'),
path('trainer/power_sprint_stats/', trainer_view.get_power_sprint_stats, name='get_power_sprint_stats'),
path('trainer/set_power_sprint_stats/', trainer_view.set_power_sprint_stats, name='set_power_sprint_stats'),
path('trainer/survival_stats/', trainer_view.get_survival_stats, name='get_survival_stats'),
Expand All @@ -56,12 +60,14 @@
path('tournaments/<int:pk>/', tournaments_views.tournament_detail, name='tournament-detail'),
path('tournaments/<int:pk>/join/', tournaments_views.join_tournament, name='join-tournament'),
path('tournaments/<int:pk>/get_participation_info/', tournaments_views.get_participation, name='get-participation'),
path('tournaments/<int:pk>/questions/', tournaments_views.get_tournament_questions, name='get-tournament-questions'),
path('tournaments/<int:pk>/questions/', tournaments_views.get_tournament_questions,
name='get-tournament-questions'),
path('tournaments/<int:pk>/leaderboard/', tournaments_views.tournament_leaderboard, name='tournament-leaderboard'),
path('tournaments/<int:pk>/submit-answer/', tournaments_views.submit_answer, name='submit-answer'),
path('tournaments/<int:pk>/finish/', tournaments_views.finish_participation, name='finish-participation'),
path('tournaments/create/', tournaments_views.create_tournament, name='create-tournament'),

path('token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
path('token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),

]
]
29 changes: 3 additions & 26 deletions api/user_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ def login_view(request):
'username': user.username,
'email': user.email,
'id': user.id,
'is_admin': user.is_staff,
}, status=200)
else:
return JsonResponse({'error': 'Please verify your email address before logging in'}, status=401)
Expand Down Expand Up @@ -83,6 +84,8 @@ def register(request):
'message': 'User registered and logged in successfully',
'username': user.username,
'email': user.email,
'id': user.id,
'is_admin': user.is_staff,
}, status=201)

else:
Expand All @@ -92,32 +95,6 @@ def register(request):




# @method_decorator(csrf_exempt, name='dispatch')
# class CustomRegisterView(RegisterView):
# serializer_class = CustomRegisterSerializer
#
# def create(self, request, *args, **kwargs):
# serializer = self.get_serializer(data=request.data)
# if serializer.is_valid():
# user = serializer.save(request)
# email_address = EmailAddress.objects.filter(user=user).first()
# response_data = {
# 'id': user.id,
# 'username': user.username,
# 'email': user.email,
# 'first_name': user.first_name,
# 'last_name': user.last_name,
# 'is_active': user.is_active,
# 'email_verified': email_address.verified if email_address else False
# }
# return Response(response_data, status=status.HTTP_201_CREATED)
# return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
#
# def perform_create(self, serializer):
# user = serializer.save(self.request)
# return user

@method_decorator(csrf_exempt, name='dispatch')
class CustomRegisterView(RegisterView):
serializer_class = CustomRegisterSerializer

0 comments on commit d9685fd

Please sign in to comment.