2023-12-12 04:05:13 -05:00
|
|
|
from rest_framework.views import APIView
|
|
|
|
from rest_framework.response import Response
|
2023-12-27 10:14:39 -05:00
|
|
|
from rest_framework import permissions, status
|
2023-12-12 04:05:13 -05:00
|
|
|
from rest_framework.authentication import SessionAuthentication
|
2023-11-27 17:31:31 -05:00
|
|
|
|
2023-12-27 10:14:39 -05:00
|
|
|
from django.http import HttpRequest
|
|
|
|
from django.contrib.auth import login
|
|
|
|
from django.db.models import QuerySet
|
|
|
|
from django.core import serializers
|
2023-12-15 14:32:43 -05:00
|
|
|
|
|
|
|
|
2023-12-27 10:14:39 -05:00
|
|
|
from .models import ChatChannelModel, ChatMemberModel, ChatMessageModel
|
|
|
|
from .serializers import ChatChannelSerializer, ChatMessageSerializer
|
2023-12-15 14:32:43 -05:00
|
|
|
|
2023-12-27 10:14:39 -05:00
|
|
|
class ChannelView(APIView):
|
|
|
|
|
|
|
|
queryset = ChatChannelModel.objects
|
|
|
|
serializer_class = ChatChannelSerializer
|
|
|
|
permission_classes = (permissions.IsAuthenticated,)
|
|
|
|
authentication_classes = (SessionAuthentication,)
|
2023-12-15 14:32:43 -05:00
|
|
|
|
|
|
|
def post(self, request):
|
2023-12-12 04:05:13 -05:00
|
|
|
|
2023-12-27 10:14:39 -05:00
|
|
|
serializer = self.serializer_class(data = request.data)
|
|
|
|
|
|
|
|
serializer.is_valid(raise_exception=True)
|
2023-12-15 14:32:43 -05:00
|
|
|
|
2023-12-27 10:14:39 -05:00
|
|
|
data: dict = serializer.validated_data
|
2023-12-15 14:32:43 -05:00
|
|
|
|
2023-12-27 10:14:39 -05:00
|
|
|
members_id = data.get("members_id")
|
|
|
|
if self.request.user.pk not in members_id:
|
|
|
|
return Response({"detail": "You are trying to create a chat group without you."}, status = status.HTTP_400_BAD_REQUEST)
|
2023-12-15 14:32:43 -05:00
|
|
|
|
2023-12-27 10:14:39 -05:00
|
|
|
for member_channel in ChatMemberModel.objects.filter(member_id = members_id[0]):
|
|
|
|
channel_id: int = member_channel.channel_id
|
|
|
|
if not ChatChannelModel.objects.filter(pk = channel_id).exists():
|
|
|
|
continue
|
|
|
|
channel: ChatChannelModel = ChatChannelModel.objects.get(pk = channel_id)
|
|
|
|
if set(channel.get_members_id()) == set(members_id):
|
|
|
|
messages = ChatMessageModel.objects.filter(channel_id = channel_id).order_by("time")
|
|
|
|
messages = serializers.serialize("json", messages)
|
|
|
|
return Response({'channel_id': channel_id, 'messages': messages}, status=status.HTTP_200_OK)
|
2023-12-15 14:32:43 -05:00
|
|
|
|
2023-12-27 10:14:39 -05:00
|
|
|
new_channel_id = ChatChannelModel().create(members_id)
|
|
|
|
return Response({'channel_id': new_channel_id}, status=status.HTTP_201_CREATED)
|