|
| 1 | +import json |
| 2 | +from channels.generic.websocket import AsyncWebsocketConsumer |
| 3 | +from channels.db import database_sync_to_async |
| 4 | +from django.utils import timezone |
| 5 | +from django.apps import apps |
| 6 | + |
| 7 | +class PresenceConsumer(AsyncWebsocketConsumer): |
| 8 | + async def connect(self): |
| 9 | + # Accept the WebSocket connection |
| 10 | + await self.accept() |
| 11 | + |
| 12 | + # Store the channel name and user |
| 13 | + self.user = self.scope["user"] |
| 14 | + |
| 15 | + # Handle authentication |
| 16 | + if not self.user.is_authenticated: |
| 17 | + # Close connection if user is not authenticated |
| 18 | + await self.close(code=4001) |
| 19 | + return |
| 20 | + |
| 21 | + # Update user presence |
| 22 | + await self.update_user_presence(True, self.channel_name) |
| 23 | + |
| 24 | + # Add this channel to the group for broadcasting presence updates |
| 25 | + await self.channel_layer.group_add("presence", self.channel_name) |
| 26 | + |
| 27 | + # Broadcast the user's online status to all connected clients |
| 28 | + await self.channel_layer.group_send( |
| 29 | + "presence", |
| 30 | + { |
| 31 | + "type": "presence_update", |
| 32 | + "user_id": self.user.id, |
| 33 | + "status": "online" |
| 34 | + } |
| 35 | + ) |
| 36 | + |
| 37 | + async def disconnect(self, close_code): |
| 38 | + if hasattr(self, 'user') and self.user.is_authenticated: |
| 39 | + await self.update_user_presence(False, "") |
| 40 | + |
| 41 | + # Remove this channel from the group |
| 42 | + await self.channel_layer.group_discard("presence", self.channel_name) |
| 43 | + |
| 44 | + # Broadcast the user's offline status |
| 45 | + await self.channel_layer.group_send( |
| 46 | + "presence", |
| 47 | + { |
| 48 | + "type": "presence_update", |
| 49 | + "user_id": self.user.id, |
| 50 | + "status": "offline" |
| 51 | + } |
| 52 | + ) |
| 53 | + |
| 54 | + async def receive(self, text_data): |
| 55 | + try: |
| 56 | + data = json.loads(text_data) |
| 57 | + if data.get('type') == 'authenticate': |
| 58 | + # Handle authentication if needed |
| 59 | + # The token validation is already handled by Django Channels authentication |
| 60 | + pass |
| 61 | + # Handle other message types if needed |
| 62 | + except json.JSONDecodeError: |
| 63 | + await self.close(code=4000) |
| 64 | + |
| 65 | + async def presence_update(self, event): |
| 66 | + # Send presence update to WebSocket |
| 67 | + await self.send(text_data=json.dumps(event)) |
| 68 | + |
| 69 | + @database_sync_to_async |
| 70 | + def update_user_presence(self, is_online, channel_name): |
| 71 | + UserPresence = apps.get_model('presence', 'UserPresence') |
| 72 | + presence, _ = UserPresence.objects.get_or_create(user=self.user) |
| 73 | + presence.is_online = is_online |
| 74 | + presence.channel_name = channel_name |
| 75 | + presence.last_seen = timezone.now() |
| 76 | + presence.save() |
0 commit comments