From bd416318ac3af3515d79cb0e67b752a11f0f9610 Mon Sep 17 00:00:00 2001 From: Emmy D'Anello Date: Mon, 29 Apr 2024 00:39:08 +0200 Subject: [PATCH] Fix unread messages count Signed-off-by: Emmy D'Anello --- chat/consumers.py | 12 ++++++------ chat/static/chat.js | 1 + 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/chat/consumers.py b/chat/consumers.py index 5fa30de..168284e 100644 --- a/chat/consumers.py +++ b/chat/consumers.py @@ -3,7 +3,7 @@ from channels.generic.websocket import AsyncJsonWebsocketConsumer from django.contrib.auth.models import User -from django.db.models import Count, Exists, OuterRef, Q +from django.db.models import Count, F, Q from registration.models import Registration from .models import Channel, Message @@ -93,7 +93,9 @@ class ChatConsumer(AsyncJsonWebsocketConsumer): 'unread_messages': channel.unread_messages, } async for channel in self.read_channels.prefetch_related('invited') - .annotate(unread_messages=Count('messages', filter=~Q(messages__users_read=user))).all() + .annotate(total_messages=Count('messages', distinct=True)) + .annotate(read_messages=Count('messages', filter=Q(messages__users_read=user), distinct=True)) + .annotate(unread_messages=F('total_messages') - F('read_messages')).all() ] } await self.send_json(message) @@ -160,8 +162,7 @@ class ChatConsumer(AsyncJsonWebsocketConsumer): messages = Message.objects \ .filter(channel=channel) \ - .annotate(read=Exists(User.objects.filter(pk=self.scope['user'].pk) - .filter(pk=OuterRef('users_read')))) \ + .annotate(read=Count('users_read', filter=Q(users_read=self.scope['user']))) \ .order_by('-created_at')[offset:offset + limit].all() await self.send_json({ 'type': 'fetch_messages', @@ -173,7 +174,7 @@ class ChatConsumer(AsyncJsonWebsocketConsumer): 'author_id': message.author_id, 'author': await message.aget_author_name(), 'content': message.content, - 'read': message.read, + 'read': message.read > 0, } async for message in messages ])) @@ -239,7 +240,6 @@ class ChatConsumer(AsyncJsonWebsocketConsumer): 'content': message['content']}) async def chat_edit_message(self, message) -> None: - print(message) await self.send_json({'type': 'edit_message', 'id': message['id'], 'channel_id': message['channel_id'], 'content': message['content']}) diff --git a/chat/static/chat.js b/chat/static/chat.js index 582098f..89ab947 100644 --- a/chat/static/chat.js +++ b/chat/static/chat.js @@ -157,6 +157,7 @@ function fetchPreviousMessages() { } function receiveFetchedMessages(data) { + console.log(data) let channel_id = data['channel_id'] let new_messages = data['messages']