2022-01-13 17:08:21 +03:00
|
|
|
from channels.generic.websocket import AsyncWebsocketConsumer
|
2022-01-13 22:22:54 +03:00
|
|
|
from api.logics import Logics
|
|
|
|
from api.models import Order
|
|
|
|
|
2022-01-13 17:08:21 +03:00
|
|
|
import json
|
|
|
|
|
2022-02-17 22:50:10 +03:00
|
|
|
|
2022-01-13 17:08:21 +03:00
|
|
|
class ChatRoomConsumer(AsyncWebsocketConsumer):
|
2022-01-13 22:22:54 +03:00
|
|
|
|
2022-01-13 17:08:21 +03:00
|
|
|
async def connect(self):
|
2022-02-17 22:50:10 +03:00
|
|
|
self.order_id = self.scope["url_route"]["kwargs"]["order_id"]
|
|
|
|
self.room_group_name = f"chat_order_{self.order_id}"
|
2022-01-13 22:22:54 +03: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 17:08:21 +03:00
|
|
|
|
2022-01-13 22:22:54 +03: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-02-17 22:50:10 +03:00
|
|
|
|
|
|
|
await self.channel_layer.group_add(self.room_group_name,
|
|
|
|
self.channel_name)
|
2022-01-13 17:08:21 +03:00
|
|
|
|
|
|
|
await self.accept()
|
|
|
|
|
|
|
|
async def disconnect(self, close_code):
|
2022-02-17 22:50:10 +03:00
|
|
|
await self.channel_layer.group_discard(self.room_group_name,
|
|
|
|
self.channel_name)
|
2022-01-13 17:08:21 +03:00
|
|
|
|
|
|
|
async def receive(self, text_data):
|
|
|
|
text_data_json = json.loads(text_data)
|
2022-02-17 22:50:10 +03:00
|
|
|
message = text_data_json["message"]
|
|
|
|
nick = text_data_json["nick"]
|
2022-01-13 17:08:21 +03:00
|
|
|
|
|
|
|
await self.channel_layer.group_send(
|
|
|
|
self.room_group_name,
|
|
|
|
{
|
2022-02-17 22:50:10 +03:00
|
|
|
"type": "chatroom_message",
|
|
|
|
"message": message,
|
|
|
|
"nick": nick,
|
|
|
|
},
|
2022-01-13 17:08:21 +03:00
|
|
|
)
|
|
|
|
|
|
|
|
async def chatroom_message(self, event):
|
2022-02-17 22:50:10 +03:00
|
|
|
message = event["message"]
|
|
|
|
nick = event["nick"]
|
2022-01-13 22:22:54 +03:00
|
|
|
|
2022-01-13 17:08:21 +03:00
|
|
|
await self.send(text_data=json.dumps({
|
2022-03-02 16:49:12 +03:00
|
|
|
"message": message,
|
2022-02-17 22:50:10 +03:00
|
|
|
"user_nick": nick,
|
2022-01-13 17:08:21 +03:00
|
|
|
}))
|
|
|
|
|
2022-02-17 22:50:10 +03:00
|
|
|
pass
|