change ws response

This commit is contained in:
xoliqberdiyev
2026-04-21 14:45:01 +05:00
parent 11605e6e6c
commit 7d6618155f
3 changed files with 27 additions and 22 deletions

View File

@@ -41,7 +41,7 @@ class ChatConsumer(AsyncWebsocketConsumer):
async def receive(self, text_data):
user = self.scope.get("user")
if not user or isinstance(user, AnonymousUser):
await self.close(code=4001)
await self.close(code=401)
return
try:
@@ -53,13 +53,10 @@ class ChatConsumer(AsyncWebsocketConsumer):
message_type = data.get("message_type", "text")
text = (data.get("text") or "").strip()
# Matn xabari uchun text majburiy
if message_type == "text" and not text:
await self.send(text_data=json.dumps({"error": "Matn bo'sh bo'lishi mumkin emas."}))
return
# WS orqali faqat matn + caption saqlanadi.
# Fayl yuklash uchun REST /chat/messages/ POST ishlatiladi.
if message_type != "text":
await self.send(
text_data=json.dumps(
@@ -68,22 +65,29 @@ class ChatConsumer(AsyncWebsocketConsumer):
)
return
# DB ga saqlash — post_save signal WS ga broadcast qiladi
await self._save_message(user, text)
async def chat_message(self, event):
await self.send(
text_data=json.dumps(
{
"id": event["id"],
"message_type": event["message_type"],
"text": event["text"],
"file_url": event["file_url"],
"sender": event["sender"],
"created_at": event["created_at"],
}
)
)
# Uz
# Bu funksiya ishlatilmayapti, shuning uchun commentga olib qoydim, bu funksiya orniga /core/apps/chat/tasks/message.py ichida rest api yordamida message
# yuborilsa ishlatiladigan task bor.
# En
# This function is not used, so I commented it out. Instead, a task is used in /core/apps/chat/tasks/message.py
# to send message when message is added from REST API.
# async def chat_message(self, event):
# await self.send(
# text_data=json.dumps(
# {
# "id": event["id"],
# "message_type": event["message_type"],
# "text": event["text"],
# "file_url": event["file_url"],
# "sender": event["sender"],
# "created_at": event["created_at"],
# }
# )
# )
@database_sync_to_async
def _save_message(self, user, text):