from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import authentication, permissions, status from rest_framework.authentication import SessionAuthentication from .models import ChannelModel, MemberModel, MessageModel from django.core import serializers class ChatView(APIView): permission_classes = (permissions.IsAuthenticated,) authentication_classes = (SessionAuthentication,) def get(self, request, pk): if (ChannelModel.objects.filter(pk=pk)): return Response({'channel_id': pk}, status=status.HTTP_200_OK) else: return Response("Channel doesn't exist", status=status.HTTP_404_NOT_FOUND) def delete(self, request, pk): ChannelModel.objects.filter(pk=pk).delete() MessageModel.objects.filter(pk=pk).delete() MemberModel.objects.filter(pk=pk).delete() return Response({'channel_id': pk}, status=status.HTTP_200_OK) class ChatsView(APIView): def post(self, request): data: dict = request.data users_id = request.data.get("users_id", []) if len(users_id) < 2: return Response('Not enought members to create the channel', status=status.HTTP_400_BAD_REQUEST) if users_id[0] == users_id[1]: return Response('Same member', status=status.HTTP_400_BAD_REQUEST) for user_id1 in users_id: for member1 in MemberModel.objects.filter(member_id=user_id1): for user_id2 in users_id: if user_id1 == user_id2: continue for member2 in MemberModel.objects.filter(member_id=user_id2): if (member1.channel_id == member2.channel_id): messages = MessageModel.objects.filter(channel_id=member1.channel_id).order_by("time") messages = serializers.serialize("json", messages) return Response({'channel_id': member1.channel_id, 'messages':messages}, status=status.HTTP_200_OK) new_channel = ChannelModel() new_channel.save() for user_id in users_id: new_member = MemberModel() new_member.channel_id = new_channel.pk new_member.member_id = user_id new_member.save() return Response({'channel_id': new_channel.pk}, status=status.HTTP_201_CREATED) def delete(self, request): data: dict = request.data users_id = request.data.get("users_id", []) #print(list(MemberModel.objects.all())) for user_id1 in users_id: for member1 in MemberModel.objects.filter(member_id=user_id1): for user_id2 in users_id: if user_id1 == user_id2: break for member2 in MemberModel.objects.filter(member_id=user_id2): if (member1.channel_id == member2.channel_id): MessageModel.objects.filter(channel_id=member1.channel_id).delete() member1.delete() member2.delete() ChannelModel.objects.get(pk=member1.channel_id).delete() return Response("Channel removed", status=status.HTTP_200_OK) return Response("Channel doesn't exist", status=status.HTTP_404_NOT_FOUND)