mirror of
				https://gitlab.com/animath/si/plateforme.git
				synced 2025-11-04 12:32:18 +01:00 
			
		
		
		
	Properly sort messages and add fetch previous messages ability
Signed-off-by: Emmy D'Anello <emmy.danello@animath.fr>
This commit is contained in:
		@@ -63,7 +63,7 @@ class ChatConsumer(AsyncJsonWebsocketConsumer):
 | 
			
		||||
            case 'send_message':
 | 
			
		||||
                await self.receive_message(content)
 | 
			
		||||
            case 'fetch_messages':
 | 
			
		||||
                await self.fetch_messages(content['channel_id'])
 | 
			
		||||
                await self.fetch_messages(**content)
 | 
			
		||||
            case unknown:
 | 
			
		||||
                print("Unknown message type:", unknown)
 | 
			
		||||
 | 
			
		||||
@@ -109,17 +109,19 @@ class ChatConsumer(AsyncJsonWebsocketConsumer):
 | 
			
		||||
            'content': message.content,
 | 
			
		||||
        })
 | 
			
		||||
 | 
			
		||||
    async def fetch_messages(self, channel_id: int, offset: int = 0, limit: int = 50) -> None:
 | 
			
		||||
    async def fetch_messages(self, channel_id: int, offset: int = 0, limit: int = 50, **_kwargs) -> 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()
 | 
			
		||||
        limit = min(limit, 200)  # Fetch only maximum 200 messages at the time
 | 
			
		||||
 | 
			
		||||
        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': [
 | 
			
		||||
            'messages': list(reversed([
 | 
			
		||||
                {
 | 
			
		||||
                    'id': message.id,
 | 
			
		||||
                    'timestamp': message.created_at.isoformat(),
 | 
			
		||||
@@ -127,7 +129,7 @@ class ChatConsumer(AsyncJsonWebsocketConsumer):
 | 
			
		||||
                    'content': message.content,
 | 
			
		||||
                }
 | 
			
		||||
                async for message in messages
 | 
			
		||||
            ]
 | 
			
		||||
            ]))
 | 
			
		||||
        })
 | 
			
		||||
 | 
			
		||||
    async def chat_send_message(self, message) -> None:
 | 
			
		||||
 
 | 
			
		||||
		Reference in New Issue
	
	Block a user