From 34259a4e466683d91a51bc995251032f73a39edd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=98=D0=B3=D0=BE=D1=80=D1=8C=20=D0=9D=D0=B0=D0=B4=D0=B5?= =?UTF-8?q?=D0=B8=D0=BD?= Date: Fri, 28 Nov 2025 08:06:45 +0300 Subject: [PATCH] =?UTF-8?q?Feature:=20=D0=BE=D1=82=D0=BF=D1=80=D0=B0=D0=B2?= =?UTF-8?q?=D0=BA=D0=B0=20=D1=81=D0=BE=D0=BE=D0=B1=D1=89=D0=B5=D0=BD=D0=B8?= =?UTF-8?q?=D0=B9=20=D1=81=20=D1=84=D0=B0=D0=B9=D0=BB=D0=B0=D0=BC=D0=B8=20?= =?UTF-8?q?=D1=87=D0=B5=D1=80=D0=B5=D0=B7=20WebSocket?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Добавлена отправка сообщения через WebSocket после создания в API - Используется channel_layer.group_send для рассылки всем участникам - Сообщение с вложениями теперь появляется в чате мгновенно - Не требуется перезагрузка страницы Импорты: - async_to_sync для синхронного вызова асинхронного кода - get_channel_layer для доступа к WebSocket - serialize_message для форматирования данных --- backend/api/v1/communications/views.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/backend/api/v1/communications/views.py b/backend/api/v1/communications/views.py index 2accf370..efa95050 100644 --- a/backend/api/v1/communications/views.py +++ b/backend/api/v1/communications/views.py @@ -1,6 +1,8 @@ # backend/api/v1/communications/views.py """API views для чатов и сообщений""" +from asgiref.sync import async_to_sync +from channels.layers import get_channel_layer from django.contrib.auth.decorators import login_required from django.db import transaction from django.http import JsonResponse @@ -14,6 +16,7 @@ from communications.models import ( Message, MessageAttachment, ) +from communications.consumers import serialize_message @csrf_protect @@ -126,6 +129,22 @@ def upload_message_with_attachments(request): 'mime_type': attachment.mime_type }) + # Отправляем сообщение через WebSocket всем участникам чата + channel_layer = get_channel_layer() + group_name = f"chat_{chat.id}" + + # Сериализуем сообщение для WebSocket + message_data = serialize_message(message) + + async_to_sync(channel_layer.group_send)( + group_name, + { + "type": "chat.message", + "chat_id": chat.id, + "payload": message_data + } + ) + avatar_url = None if hasattr(request.user, 'avatar') and request.user.avatar: avatar_url = request.user.avatar.url