Skip to content

Commit

Permalink
api: Fixing conversations with AI
Browse files Browse the repository at this point in the history
  • Loading branch information
okbrandon committed Nov 14, 2024
1 parent 1e91d25 commit dccdc4a
Show file tree
Hide file tree
Showing 3 changed files with 62 additions and 6 deletions.
16 changes: 15 additions & 1 deletion backend/api/views/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,14 @@
from rest_framework.decorators import permission_classes
from rest_framework_simplejwt.tokens import RefreshToken

from django.db.models import Count
from django.contrib.auth import login, authenticate
from django.core.exceptions import ValidationError
from django.contrib.auth.hashers import make_password
from django.utils import timezone
from django.contrib.auth.hashers import check_password

from ..models import User, VerificationCode, Relationship
from ..models import User, VerificationCode, Relationship, Conversation
from ..serializers import UserSerializer
from ..util import generate_id, send_verification_email, send_otp_via_email, send_otp_via_sms
from ..backends import AuthBackend
Expand Down Expand Up @@ -60,6 +61,19 @@ def post(self, request, *args, **kwargs):
status=1 # Accepted/friends status
)

# Create the conversation between the user and the AI
friend = User.objects.get(userID='user_ai')
existing_conversation = Conversation.objects.filter(
participants__userID__in=[user.userID, 'user_ai'],
conversationType='private_message'
).annotate(participant_count=Count('participants')).filter(participant_count=2).exists()

if not existing_conversation:
new_conversation = Conversation.objects.create(conversationID=generate_id("conv"), conversationType='private_message')
new_conversation.receipientID = user.userID
new_conversation.participants.add(user, friend)
new_conversation.save()

if not skip_email_verification:
verification_code = generate_id('code')
VerificationCode.objects.create(
Expand Down
49 changes: 44 additions & 5 deletions backend/api/views/conversations.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,57 @@
from rest_framework.response import Response
from rest_framework.views import APIView

from ..models import Conversation
from django.db.models import Count, Q

from asgiref.sync import async_to_sync

from ..models import Conversation, Relationship, User
from ..serializers import ConversationSerializer
from ..util import get_safe_profile
from ..util import get_safe_profile, generate_id

class ConversationListView(APIView):

def ensure_conversations_exist(self, user):
friends = Relationship.objects.filter(
Q(userA=user.userID) | Q(userB=user.userID)
)
friends = friends.exclude(
Q(status=2) | Q(status=0),
Q(userA=user.userID) | Q(userB=user.userID)
)

user = User.objects.get(userID=user.userID)

for relationship in friends:
friend_id = relationship.userA if relationship.userA != user.userID else relationship.userB

try:
friend = User.objects.get(userID=friend_id)
except User.DoesNotExist:
continue

existing_conversation = Conversation.objects.filter(
participants__userID__in=[user.userID, friend_id],
conversationType='private_message'
).annotate(participant_count=Count('participants')).filter(participant_count=2).exists()

if not existing_conversation:
new_conversation = Conversation.objects.create(conversationID=generate_id("conv"), conversationType='private_message')
new_conversation.receipientID = user.userID
new_conversation.participants.add(user, friend)
new_conversation.save()

def get(self, request, *args, **kwargs):
me = request.user

# Ensuring conversations exist for the user
self.ensure_conversations_exist(me)

conversations = me.conversations.all()
serializer = ConversationSerializer(conversations, many=True)

safe_conversations = serializer.data

for conversation in safe_conversations:
# Extract sensitive information from participants
participants = conversation.get('participants', [])
Expand All @@ -27,4 +66,4 @@ def get(self, request, *args, **kwargs):
sender = message.get('sender', {})
message['sender'] = get_safe_profile(sender, me=False)

return Response({'conversations': safe_conversations}, status=status.HTTP_200_OK)
return Response({'conversations': safe_conversations}, status=status.HTTP_200_OK)
3 changes: 3 additions & 0 deletions backend/api/views/tournaments.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,9 @@ def put(self, request, tournamentID):
if Tournament.objects.filter(participants=invitee, status='PENDING').exists():
return Response({"error": f"User {invitee.username} is already subscribed to a tournament"}, status=status.HTTP_400_BAD_REQUEST)

if TournamentInvite.objects.filter(tournament=tournament, invitee=invitee, status='PENDING').exists():
return Response({"error": f"User {invitee.username} is already invited to the tournament"}, status=status.HTTP_400_BAD_REQUEST)

invite = TournamentInvite.objects.create(
inviteID=generate_id("tid"),
tournament=tournament,
Expand Down

0 comments on commit dccdc4a

Please sign in to comment.