1
0
mirror of https://gitlab.com/animath/si/plateforme.git synced 2025-06-30 06:31:12 +02:00

Fetching last messages is working

Signed-off-by: Emmy D'Anello <emmy.danello@animath.fr>
This commit is contained in:
Emmy D'Anello
2024-04-27 13:27:27 +02:00
parent 4a78e80399
commit d59bb75dce
2 changed files with 101 additions and 15 deletions

View File

@ -62,6 +62,8 @@ class ChatConsumer(AsyncJsonWebsocketConsumer):
await self.fetch_channels()
case 'send_message':
await self.receive_message(content)
case 'fetch_messages':
await self.fetch_messages(content['channel_id'])
case unknown:
print("Unknown message type:", unknown)
@ -101,11 +103,34 @@ class ChatConsumer(AsyncJsonWebsocketConsumer):
await self.channel_layer.group_send(f'chat-{channel.id}', {
'type': 'chat.send_message',
'id': message.id,
'channel_id': channel.id,
'timestamp': message.created_at.isoformat(),
'author': await message.aget_author_name(),
'content': message.content,
})
async def fetch_messages(self, channel_id: int, offset: int = 0, limit: int = 50) -> None:
channel = await Channel.objects.aget(id=channel_id)
read_channels = await Channel.get_accessible_channels(self.scope['user'], 'read')
if not await read_channels.acontains(channel):
return
messages = Message.objects.filter(channel=channel).order_by('created_at')[offset:offset + limit].all()
await self.send_json({
'type': 'fetch_messages',
'channel_id': channel_id,
'messages': [
{
'id': message.id,
'timestamp': message.created_at.isoformat(),
'author': await message.aget_author_name(),
'content': message.content,
}
async for message in messages
]
})
async def chat_send_message(self, message) -> None:
await self.send_json({'type': 'send_message', 'id': message['id'], 'timestamp': message['timestamp'],
'author': message['author'], 'content': message['content']})
await self.send_json({'type': 'send_message', 'id': message['id'], 'channel_id': message['channel_id'],
'timestamp': message['timestamp'], 'author': message['author'],
'content': message['content']})