How can i fix my chat application users are not able to chat with each other [closed]

i am building a a private chat and calls both voice and video that preach privacy, with full privacy end to end, no message stored or saved to the backend, and every message is encrypted, so no one could breach it, every user has been given the power to thier own chat, now no matter what i do the chat isnt working i feel like my my consumer.py is not well written.

class SecureChatConsumer(AsyncWebsocketConsumer):

        async def connect(self):
        self.user = self.scope['user']
        self.friend_username = self.scope['url_route']['kwargs']['username']

        if not self.user.is_authenticated:
            await self.close()
            return

        try:
            # Create a shared room name between both users for proper communication
            self.room_name = f"chat_{'_'.join(sorted([self.user.username, self.friend_username]))}"
            
            await self.channel_layer.group_add(self.room_name, self.channel_name)
            await self.update_user_status(online=True)
            await self.accept()
            logger.info(f"WebSocket connection established for user {self.user.username} in room {self.room_name}")
        except Exception as e:
            logger.error(f"Error during WebSocket connection: {e}")
            await self.close()

    async def disconnect(self, close_code):
        await self.channel_layer.group_discard(self.room_name, self.channel_name)
        await self.update_user_status(online=False)
        logger.info(f"WebSocket disconnected for user {self.user.username}")

    async def receive(self, text_data):
        """
        Handle incoming WebSocket messages. Distinguish between message events and WebRTC events.
        """
        try:
            data = json.loads(text_data)
            message_type = data.get('type')
            logger.info(f"Received message of type '{message_type}' from {self.user.username}")
        except json.JSONDecodeError as e:
            logger.error(f"Error parsing message data: {e}")
            await self.send_error("Invalid JSON format.")
            return

        if message_type == 'message':
            await self.handle_message_event(data)
        elif message_type in ['call-offer', 'call-answer', 'ice-candidate']:
            await self.handle_webrtc_event(data)
        elif message_type == 'public-key':
            await self.handle_key_exchange(data)
        else:
            logger.warning(f"Unknown message type received: {message_type}")
            await self.send_error("Unknown message type.")

    async def handle_message_event(self, data):
        """
        Handle secure chat message events between two users using end-to-end encryption.
        """
        message = data.get('message')
        recipient_username = data.get('to')

        if message and recipient_username:
            logger.info(f"Forwarding encrypted message from {self.user.username} to {recipient_username}")
            await self.send_encrypted_message(recipient_username, message)

    async def handle_webrtc_event(self, data):
        """
        Handle WebRTC signaling for peer-to-peer voice and video calls.
        """
        recipient_username = data.get('to')
        event_type = data['type']
        event_data = data['data']

        logger.info(f"Forwarding WebRTC signal '{event_type}' from {self.user.username} to {recipient_username}")
        await self.forward_webrtc_signal(recipient_username, event_type, event_data)

    async def handle_key_exchange(self, data):
        """
        Handle the exchange of public keys for secure messaging.
        """
        recipient_username = data.get('to')
        public_key = data.get('publicKey')

        if public_key and recipient_username:
            logger.info(f"Forwarding public key from {self.user.username} to {recipient_username}")
            await self.send_public_key(recipient_username, public_key)

    async def send_encrypted_message(self, recipient_username, message):
        """
        Send an encrypted message to the recipient via the WebSocket group.
        """
        await self.channel_layer.group_send(
            f"chat_{'_'.join(sorted([self.user.username, recipient_username]))}",
            {
                'type': 'chat_message',
                'message': message,
                'sender': self.user.username
            }
        )

    async def chat_message(self, event):
        """
        Deliver the chat message to the WebSocket client.
        """
        await self.send(text_data=json.dumps({
            'type': 'message',
            'message': event['message'],
            'sender': event['sender']
        }))

    async def forward_webrtc_signal(self, recipient_username, signal_type, data):
        """
        Forward WebRTC signaling data to the specified recipient.
        """
        await self.channel_layer.group_send(
            f"chat_{'_'.join(sorted([self.user.username, recipient_username]))}",
            {
                'type': signal_type,
                'data': data,
                'sender': self.user.username
            }
        )

    async def call_offer(self, event):
        """
        Send a WebRTC call offer to the recipient.
        """
        await self.send(text_data=json.dumps({
            'type': 'call-offer',
            'offer': event['data'],
            'from': event['sender']
        }))

    async def call_answer(self, event):
        """
        Send a WebRTC call answer to the recipient.
        """
        await self.send(text_data=json.dumps({
            'type': 'call-answer',
            'answer': event['data'],
            'from': event['sender']
        }))

    async def ice_candidate(self, event):
        """
        Send an ICE candidate to the recipient to assist in the WebRTC connection setup.
        """
        await self.send(text_data=json.dumps({
            'type': 'ice-candidate',
            'candidate': event['data'],
            'from': event['sender']
        }))

    async def send_public_key(self, recipient_username, public_key):
        """
        Send the public key to the recipient via the WebSocket group.
        """
        await self.channel_layer.group_send(
            f"chat_{'_'.join(sorted([self.user.username, recipient_username]))}",
            {
                'type': 'public-key',
                'publicKey': public_key,
                'sender': self.user.username
            }
        )

    async def public_key(self, event):
        """
        Deliver the public key to the WebSocket client.
        """
        await self.send(text_data=json.dumps({
            'type': 'public-key',
            'publicKey': event['publicKey'],
            'sender': event['sender']
        }))

    @database_sync_to_async
    def update_user_status(self, online):
        """
        Update the user's online status in the database.
        """
        try:
            user_profile = UserProfile.objects.get(username=self.user.username)
            user_profile.online = online
            user_profile.save()
        except UserProfile.DoesNotExist:
            logger.error(f"User profile not found for {self.user.username}")

    async def send_error(self, message):
        """
        Send an error message to the client.
        """
        await self.send(text_data=json.dumps({
            'status': 'error',
            'message': message
        }))
Вернуться на верх