Files
nahodka-back/src/main/java/com/krylov/refound/controller/ChatWebSocketController.java
SlimusMinus 45c4273ea8 fix chats: one chat per ad, ordering, delivery after commit, errors
A chat was unique per user pair, so contacting the same author about a
second ad returned the old chat with the old post_id, and the chat list
showed the other ad's title and image.

- chats are unique per (user_one_id, user_two_id, post_id); migration 015
  drops the old pair constraint whatever its name and adds the new one
- getOrCreateChat looks the chat up by users and post, and checks that the
  other user exists and the post belongs to one of the participants
- chat list is sorted by last message time (chat creation as fallback)
- WebSocket message and unread events are sent only after commit
- chat errors are ApiException: 404 not found, 403 not a participant,
  400 validation; messages are limited to 4000 characters
- Post.images ordered by id so the cover image is stable everywhere

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-13 01:23:09 +03:00

59 lines
2.0 KiB
Java

package com.krylov.refound.controller;
import com.krylov.refound.dto.SendMessageRequest;
import com.krylov.refound.exception.ApiException;
import com.krylov.refound.service.ChatService;
import com.krylov.refound.util.TimeZoneContext;
import java.util.Map;
import java.util.Objects;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.web.bind.annotation.RestController;
@Slf4j
@RestController
@RequiredArgsConstructor
public class ChatWebSocketController {
private final ChatService chatService;
private final SimpMessagingTemplate messagingTemplate;
// Клиент шлёт сюда: /app/chat.send
@MessageMapping("/chat.send")
public void sendMessage(SendMessageRequest request, SimpMessageHeaderAccessor headerAccessor) {
Map<String, Object> sessionAttributes = headerAccessor.getSessionAttributes();
if (sessionAttributes == null) {
log.warn("sendMessage: sessionAttributes is null");
return;
}
Object userIdObject = sessionAttributes.get("userId");
if (userIdObject == null) {
log.warn("sendMessage: userId missing in session attributes");
return;
}
Long senderId = ((Number) userIdObject).longValue();
if (request.getContent() == null || request.getContent().isBlank()) {
return;
}
try {
Object timezone = sessionAttributes.get(TimeZoneContext.SESSION_ATTRIBUTE);
TimeZoneContext.set(timezone instanceof String tz ? tz : null);
chatService.sendMessage(senderId, request.getChatId(), request.getContent());
} catch (ApiException | IllegalArgumentException e) {
messagingTemplate.convertAndSendToUser(senderId.toString(), "/queue/errors", e.getMessage()
);
} finally {
TimeZoneContext.clear();
}
}
}