NDOJ/chat_box/consumers.py

66 lines
1.8 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-20 21:34:33 +00:00
from .views import format_time
2020-03-21 04:48:04 +00:00
from django.urls import reverse
from django.http import HttpResponse, HttpResponseRedirect
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']
# 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']
2020-03-19 22:51:56 +00:00
time = save_data_and_get_time(message)
message['time'] = format_time(time)
2020-01-27 20:37:52 +00:00
# Send message to WebSocket
await self.send(text_data=json.dumps({
'message': message,
}))
2020-03-19 22:51:56 +00:00
# return time
def save_data_and_get_time(message):
new_message = Message(body=message['body'],
author=Profile.objects
.get(id=message['author_id']),
)
new_message.save()
2020-03-21 04:48:04 +00:00
HttpResponseRedirect(reverse('chat'))
2020-03-19 22:51:56 +00:00
return new_message.time