NDOJ/chat_box/consumers.py

69 lines
2.1 KiB
Python
Raw Normal View History

2020-01-27 20:37:52 +00:00
import json
from channels.generic.websocket import AsyncWebsocketConsumer
2020-03-19 22:51:56 +00:00
from .models import Message
2020-03-21 04:48:04 +00:00
from django.urls import reverse
from django.http import HttpResponse, HttpResponseRedirect
2020-05-23 01:59:19 +00:00
from django.core import serializers
2020-03-19 22:51:56 +00:00
from judge.models.profile import Profile
2020-01-27 20:37:52 +00:00
class ChatConsumer(AsyncWebsocketConsumer):
async def connect(self):
2020-03-19 22:51:56 +00:00
self.room_name = 'room'
2020-01-27 20:37:52 +00:00
self.room_group_name = 'chat_%s' % self.room_name
# Join room group
await self.channel_layer.group_add(
self.room_group_name,
2020-03-21 04:48:04 +00:00
self.channel_name,
2020-01-27 20:37:52 +00:00
)
await self.accept()
async def disconnect(self, close_code):
# Leave room group
await self.channel_layer.group_discard(
self.room_group_name,
2020-03-21 04:48:04 +00:00
self.channel_name,
2020-01-27 20:37:52 +00:00
)
# Receive message from WebSocket
async def receive(self, text_data):
text_data_json = json.loads(text_data)
message = text_data_json['message']
2020-05-22 17:16:42 +00:00
2020-05-23 01:59:19 +00:00
message_saved = save_data_and_return(message)
message['time'] = message_saved[0]['fields']['time']
message['id'] = message_saved[0]['pk']
2020-01-27 20:37:52 +00:00
# Send message to room group
await self.channel_layer.group_send(
self.room_group_name,
{
'type': 'chat_message',
'message': message,
},
)
# Receive message from room group
async def chat_message(self, event):
message = event['message']
# Send message to WebSocket
await self.send(text_data=json.dumps({
'message': message,
}))
2020-03-19 22:51:56 +00:00
# return time
2020-05-23 01:59:19 +00:00
def save_data_and_return(message):
2020-03-19 22:51:56 +00:00
new_message = Message(body=message['body'],
author=Profile.objects
2020-03-21 22:49:54 +00:00
.get(pk=message['author_id']),
2020-03-19 22:51:56 +00:00
)
new_message.save()
2020-05-23 01:59:19 +00:00
json_data = serializers.serialize("json",
Message.objects
.filter(pk=new_message.id)
)
return json.loads(json_data)