c3lf-system-3/core/notify_sessions/consumers.py

58 lines
2.2 KiB
Python
Raw Normal View History

2023-11-23 22:17:20 +00:00
import logging
2023-11-22 22:55:00 +00:00
from json.decoder import JSONDecodeError
from json import loads as json_loads
from json import dumps as json_dumps
from channels.generic.websocket import AsyncWebsocketConsumer
class NotifyConsumer(AsyncWebsocketConsumer):
2023-11-23 22:17:20 +00:00
def __init__(self, *args, **kwargs):
super().__init__(args, kwargs)
2023-11-23 22:17:20 +00:00
self.log = logging.getLogger("server.log")
2023-11-22 22:55:00 +00:00
self.room_group_name = "general"
async def connect(self):
# Join room group
await self.channel_layer.group_add(self.room_group_name, self.channel_name)
2023-11-23 22:17:20 +00:00
self.log.info(f"Added {self.channel_name} channel to {self.room_group_name} group")
await self.accept()
async def disconnect(self, close_code):
# Leave room group
await self.channel_layer.group_discard(self.room_group_name, self.channel_name)
# Receive message from WebSocket
2023-11-23 22:17:20 +00:00
async def receive(self, text_data=None, bytes_data=None):
self.log.info(f"Received message: {text_data}")
2023-11-22 22:55:00 +00:00
try:
text_data_json = json_loads(text_data)
message = text_data_json["message"]
# Send message to room group
await self.channel_layer.group_send(
2023-11-23 22:17:20 +00:00
self.room_group_name,
{"type": "generic.event", "message": message, "name": "send_message_to_frontend", "event_id": 1}
2023-11-22 22:55:00 +00:00
)
2023-11-23 22:17:20 +00:00
except JSONDecodeError as e:
2023-11-22 22:55:00 +00:00
await self.send(text_data=json_dumps({"message": "error", "error": "malformed json"}))
2023-11-23 22:17:20 +00:00
self.log.error(e)
2023-11-22 22:55:00 +00:00
except KeyError as e:
await self.send(text_data=json_dumps({"message": "error", "error": f"missing key: {str(e)}"}))
2023-11-23 22:17:20 +00:00
self.log.error(e)
2023-11-22 22:55:00 +00:00
except Exception as e:
await self.send(text_data=json_dumps({"message": "error", "error": "unknown error"}))
2023-11-23 22:17:20 +00:00
self.log.error(e)
2023-11-22 22:55:00 +00:00
raise e
# Receive message from room group
2023-11-23 22:17:20 +00:00
async def generic_event(self, event):
self.log.info(f"Received event: {event}")
message = event["message"]
2023-11-23 22:17:20 +00:00
name = event["name"]
event_id = event["event_id"]
# Send message to WebSocket
2023-11-23 22:17:20 +00:00
await self.send(text_data=json_dumps({"message": message, "name": name, "event_id": event_id}))