NDOJ/chat_box/consumers.py

76 lines
2.3 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
2020-06-15 20:19:00 +00:00
from judge.jinja2.gravatar import gravatar
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-06-15 20:19:00 +00:00
author = self.scope['user']
2020-06-16 02:44:29 +00:00
author = Profile.objects.get(user_id=author.id)
2020-06-15 20:19:00 +00:00
message['author'] = author.username
message['css_class'] = author.css_class
message['image'] = gravatar(author, 32)
message_saved = save_data_and_return(message, author)
2020-05-23 01:59:19 +00:00
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-06-15 20:19:00 +00:00
def save_data_and_return(message, author):
2020-03-19 22:51:56 +00:00
new_message = Message(body=message['body'],
2020-06-15 20:19:00 +00:00
author=author,
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)