2022-01-13 14:08:21 +00:00
|
|
|
from channels.generic.websocket import AsyncWebsocketConsumer
|
2022-01-13 19:22:54 +00:00
|
|
|
from api.logics import Logics
|
|
|
|
from api.models import Order
|
|
|
|
|
2022-01-13 14:08:21 +00:00
|
|
|
import json
|
|
|
|
|
|
|
|
class ChatRoomConsumer(AsyncWebsocketConsumer):
|
|
|
|
|
2022-01-13 19:22:54 +00:00
|
|
|
|
2022-01-13 14:08:21 +00:00
|
|
|
async def connect(self):
|
|
|
|
self.order_id = self.scope['url_route']['kwargs']['order_id']
|
|
|
|
self.room_group_name = f'chat_order_{self.order_id}'
|
2022-01-13 19:22:54 +00:00
|
|
|
self.user = self.scope["user"]
|
|
|
|
self.user_nick = str(self.user)
|
|
|
|
|
|
|
|
# Forbit if user is not part of the order
|
|
|
|
# Does not work Async
|
|
|
|
# order = Order.objects.get(id=self.order_id)
|
2022-01-13 14:08:21 +00:00
|
|
|
|
2022-01-13 19:22:54 +00:00
|
|
|
# # Check if user is participant on the order.
|
|
|
|
# if not (Logics.is_buyer(order[0], self.user) or Logics.is_seller(order[0], self.user)):
|
|
|
|
# print ("Outta this chat")
|
|
|
|
# return False
|
2022-01-16 21:54:42 +00:00
|
|
|
|
2022-01-13 14:08:21 +00:00
|
|
|
await self.channel_layer.group_add(
|
|
|
|
self.room_group_name,
|
|
|
|
self.channel_name
|
|
|
|
)
|
|
|
|
|
|
|
|
await self.accept()
|
|
|
|
|
|
|
|
async def disconnect(self, close_code):
|
|
|
|
await self.channel_layer.group_discard(
|
|
|
|
self.room_group_name,
|
|
|
|
self.channel_name
|
|
|
|
)
|
|
|
|
|
|
|
|
async def receive(self, text_data):
|
|
|
|
text_data_json = json.loads(text_data)
|
|
|
|
message = text_data_json['message']
|
2022-01-13 19:22:54 +00:00
|
|
|
nick = text_data_json['nick']
|
2022-01-13 14:08:21 +00:00
|
|
|
|
|
|
|
await self.channel_layer.group_send(
|
|
|
|
self.room_group_name,
|
|
|
|
{
|
|
|
|
'type': 'chatroom_message',
|
|
|
|
'message': message,
|
2022-01-13 19:22:54 +00:00
|
|
|
'nick': nick,
|
2022-01-13 14:08:21 +00:00
|
|
|
}
|
|
|
|
)
|
|
|
|
|
|
|
|
async def chatroom_message(self, event):
|
|
|
|
message = event['message']
|
2022-01-13 19:22:54 +00:00
|
|
|
nick = event['nick']
|
|
|
|
|
2022-01-14 00:43:26 +00:00
|
|
|
# Insert a white space in words longer than 22 characters.
|
|
|
|
# Helps when messages overflow in a single line.
|
|
|
|
words = message.split(' ')
|
|
|
|
fix_message = ''
|
|
|
|
for word in words:
|
|
|
|
word = ' '.join(word[i:i+22] for i in range(0, len(word), 22))
|
|
|
|
fix_message = fix_message +' '+ word
|
|
|
|
|
2022-01-13 14:08:21 +00:00
|
|
|
await self.send(text_data=json.dumps({
|
2022-01-14 00:43:26 +00:00
|
|
|
'message': fix_message,
|
2022-01-13 19:22:54 +00:00
|
|
|
'user_nick': nick,
|
2022-01-13 14:08:21 +00:00
|
|
|
}))
|
|
|
|
|
|
|
|
pass
|