Interlocutors, posts, last messages (one subquery by max id) and unread counts (one GROUP BY) are loaded per list. The last message is now picked by id: createdAt is written in the sender's time zone and is not monotonic between users in different zones. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
305 lines
13 KiB
Java
305 lines
13 KiB
Java
package com.krylov.refound.service;
|
||
|
||
import com.krylov.refound.config.ClusterMessaging;
|
||
import com.krylov.refound.dto.ChatDto;
|
||
import com.krylov.refound.dto.ChatPostDto;
|
||
import com.krylov.refound.dto.MessageDto;
|
||
import com.krylov.refound.entity.Chat;
|
||
import com.krylov.refound.entity.Image;
|
||
import com.krylov.refound.entity.Message;
|
||
import com.krylov.refound.entity.Post;
|
||
import com.krylov.refound.entity.User;
|
||
import com.krylov.refound.enums.ErrorCode;
|
||
import com.krylov.refound.exception.ApiException;
|
||
import com.krylov.refound.repository.ChatRepository;
|
||
import com.krylov.refound.repository.MessageRepository;
|
||
import com.krylov.refound.repository.PostRepository;
|
||
import com.krylov.refound.repository.UserRepository;
|
||
import java.time.LocalDateTime;
|
||
import java.util.Comparator;
|
||
import java.util.List;
|
||
import java.util.Optional;
|
||
import java.util.HashMap;
|
||
import java.util.Map;
|
||
import java.util.Objects;
|
||
import java.util.function.Function;
|
||
import java.util.stream.Collectors;
|
||
import lombok.RequiredArgsConstructor;
|
||
import lombok.extern.slf4j.Slf4j;
|
||
import org.springframework.data.domain.Page;
|
||
import org.springframework.data.domain.Pageable;
|
||
import org.springframework.http.HttpStatus;
|
||
import org.springframework.stereotype.Service;
|
||
import org.springframework.transaction.annotation.Transactional;
|
||
import org.springframework.transaction.support.TransactionSynchronization;
|
||
import org.springframework.transaction.support.TransactionSynchronizationManager;
|
||
|
||
@Slf4j
|
||
@Service
|
||
@RequiredArgsConstructor
|
||
public class ChatService {
|
||
|
||
/** Максимальная длина сообщения в символах. */
|
||
public static final int MAX_MESSAGE_LENGTH = 4000;
|
||
|
||
private final ChatRepository chatRepository;
|
||
private final MessageRepository messageRepository;
|
||
// Рассылка через Redis во все экземпляры: получатель может быть подключён к другому
|
||
private final ClusterMessaging messaging;
|
||
private final UserRepository userRepository;
|
||
private final PostRepository postRepository;
|
||
|
||
/**
|
||
* Ищет существующий чат с пользователем по объявлению, ничего не создавая.
|
||
* Пустой чат «на будущее» не заводим: он появляется только с первым сообщением.
|
||
*/
|
||
@Transactional(readOnly = true)
|
||
public Optional<ChatDto> findChat(Long currentUserId, Long otherUserId, Long postId) {
|
||
Long userId1 = Math.min(currentUserId, otherUserId);
|
||
Long userId2 = Math.max(currentUserId, otherUserId);
|
||
return chatRepository.findByUsersAndPost(userId1, userId2, postId).stream()
|
||
.findFirst()
|
||
.map(chat -> toDto(chat, currentUserId));
|
||
}
|
||
|
||
/**
|
||
* Первое сообщение собеседнику по объявлению: в одной транзакции находит или создаёт
|
||
* чат и сохраняет сообщение. Так в базе не остаётся чатов без сообщений.
|
||
*/
|
||
@Transactional
|
||
public ChatDto startChat(Long currentUserId, Long otherUserId, Long postId, String content) {
|
||
validateContent(content);
|
||
if (currentUserId.equals(otherUserId)) {
|
||
throw new ApiException(ErrorCode.VALIDATION_ERROR, "Нельзя создать чат с самим собой", HttpStatus.BAD_REQUEST);
|
||
}
|
||
if (!userRepository.existsById(otherUserId)) {
|
||
throw new ApiException(ErrorCode.NOT_FOUND, "Пользователь не найден", HttpStatus.NOT_FOUND);
|
||
}
|
||
if (postId != null) {
|
||
// Иначе клиент мог прикрепить к чату любое чужое объявление
|
||
Post post = postRepository.findById(postId)
|
||
.orElseThrow(() -> new ApiException(ErrorCode.NOT_FOUND, "Объявление не найдено", HttpStatus.NOT_FOUND));
|
||
Long ownerId = post.getUser().getId();
|
||
if (!ownerId.equals(currentUserId) && !ownerId.equals(otherUserId)) {
|
||
throw new ApiException(ErrorCode.VALIDATION_ERROR, "Объявление не принадлежит участнику чата", HttpStatus.BAD_REQUEST);
|
||
}
|
||
}
|
||
|
||
Long userId1 = Math.min(currentUserId, otherUserId);
|
||
Long userId2 = Math.max(currentUserId, otherUserId);
|
||
|
||
// Чат отдельный на каждое объявление: иначе обращение к тому же автору по другому
|
||
// объявлению возвращало старый чат с чужим postId (и чужой картинкой в списке чатов)
|
||
Chat chat = chatRepository.findByUsersAndPost(userId1, userId2, postId).stream().findFirst().orElseGet(() -> {
|
||
Chat newChat = new Chat();
|
||
newChat.setUserOneId(userId1);
|
||
newChat.setUserTwoId(userId2);
|
||
newChat.setPostId(postId);
|
||
return chatRepository.save(newChat);
|
||
});
|
||
|
||
saveAndBroadcast(chat, currentUserId, content);
|
||
return toDto(chat, currentUserId);
|
||
}
|
||
|
||
// Все чаты пользователя: сверху чаты с самым свежим сообщением (или самые новые, если сообщений нет)
|
||
@Transactional(readOnly = true)
|
||
public List<ChatDto> getUserChats(Long userId) {
|
||
record ChatWithActivity(ChatDto dto, LocalDateTime lastActivity) {
|
||
}
|
||
|
||
List<Chat> chats = chatRepository.findAllByUserId(userId);
|
||
Map<Long, Chat> byId = chats.stream().collect(Collectors.toMap(Chat::getId, Function.identity()));
|
||
return toDtos(chats, userId).stream()
|
||
.map(dto -> {
|
||
LocalDateTime created = byId.get(dto.getId()).getCreatedAt();
|
||
return new ChatWithActivity(dto, dto.getLastMessageAt() != null ? dto.getLastMessageAt() : created);
|
||
})
|
||
.sorted(Comparator.comparing(ChatWithActivity::lastActivity, Comparator.nullsLast(Comparator.reverseOrder())))
|
||
.map(ChatWithActivity::dto)
|
||
.collect(Collectors.toList());
|
||
}
|
||
|
||
// История сообщений в чате, с пагинацией и проверкой доступа
|
||
@Transactional(readOnly = true)
|
||
public Page<MessageDto> getMessages(Long chatId, Long userId, Pageable pageable) {
|
||
Chat chat = getChatOrThrow(chatId);
|
||
checkParticipant(chat, userId);
|
||
|
||
return messageRepository.findByChatIdOrderByCreatedAtDesc(chatId, pageable).map(this::toMessageDto);
|
||
}
|
||
|
||
// Отправка сообщения (вызывается из WebSocket контроллера)
|
||
@Transactional
|
||
public void sendMessage(Long senderId, Long chatId, String content) {
|
||
validateContent(content);
|
||
|
||
Chat chat = getChatOrThrow(chatId);
|
||
checkParticipant(chat, senderId);
|
||
|
||
saveAndBroadcast(chat, senderId, content);
|
||
}
|
||
|
||
private void validateContent(String content) {
|
||
if (content == null || content.isBlank()) {
|
||
throw new ApiException(ErrorCode.VALIDATION_ERROR, "Пустое сообщение", HttpStatus.BAD_REQUEST);
|
||
}
|
||
if (content.length() > MAX_MESSAGE_LENGTH) {
|
||
throw new ApiException(ErrorCode.VALIDATION_ERROR,
|
||
"Сообщение длиннее " + MAX_MESSAGE_LENGTH + " символов", HttpStatus.BAD_REQUEST);
|
||
}
|
||
}
|
||
|
||
private void saveAndBroadcast(Chat chat, Long senderId, String content) {
|
||
Long chatId = chat.getId();
|
||
Message message = new Message();
|
||
message.setChatId(chatId);
|
||
message.setSenderId(senderId);
|
||
message.setContent(content);
|
||
message = messageRepository.save(message);
|
||
|
||
MessageDto dto = toMessageDto(message);
|
||
|
||
// Уведомляем получателя об непрочитанных
|
||
Long recipientId = chat.getUserOneId().equals(senderId)
|
||
? chat.getUserTwoId()
|
||
: chat.getUserOneId();
|
||
|
||
long unreadCount = messageRepository.countByChatIdAndIsReadFalseAndSenderIdNot(chatId, recipientId);
|
||
|
||
// Рассылаем только после коммита: иначе клиент, получив событие и перезапросив
|
||
// историю, мог не увидеть ещё не закоммиченное сообщение
|
||
afterCommit(() -> {
|
||
messaging.convertAndSend("/topic/chat/" + chatId, dto);
|
||
messaging.convertAndSend(
|
||
"/topic/user/" + recipientId + "/unread",
|
||
Map.of("chatId", chatId, "unreadCount", unreadCount)
|
||
);
|
||
});
|
||
}
|
||
|
||
private static void afterCommit(Runnable action) {
|
||
if (TransactionSynchronizationManager.isSynchronizationActive()) {
|
||
TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
|
||
@Override
|
||
public void afterCommit() {
|
||
action.run();
|
||
}
|
||
});
|
||
} else {
|
||
action.run();
|
||
}
|
||
}
|
||
|
||
@Transactional
|
||
public void deleteChat(Long chatId, Long userId) {
|
||
Chat chat = getChatOrThrow(chatId);
|
||
checkParticipant(chat, userId);
|
||
chatRepository.deleteById(chatId);
|
||
}
|
||
|
||
@Transactional
|
||
public void markAsRead(Long chatId, Long userId) {
|
||
Chat chat = getChatOrThrow(chatId);
|
||
checkParticipant(chat, userId);
|
||
messageRepository.markAsReadByChatIdAndRecipient(chatId, userId);
|
||
}
|
||
|
||
|
||
/**
|
||
* Проверка для STOMP-интерцептора: пользователь состоит в чате или нет.
|
||
* Не бросает исключений — вызывается на этапе авторизации подписки.
|
||
*/
|
||
@Transactional(readOnly = true)
|
||
public boolean isParticipant(Long chatId, Long userId) {
|
||
if (chatId == null || userId == null) {
|
||
return false;
|
||
}
|
||
return chatRepository.isParticipantOfChat(chatId, userId);
|
||
}
|
||
|
||
private Chat getChatOrThrow(Long chatId) {
|
||
return chatRepository.findById(chatId)
|
||
.orElseThrow(() -> new ApiException(ErrorCode.NOT_FOUND, "Чат не найден", HttpStatus.NOT_FOUND));
|
||
}
|
||
|
||
private void checkParticipant(Chat chat, Long userId) {
|
||
if (!chat.getUserOneId().equals(userId) && !chat.getUserTwoId().equals(userId)) {
|
||
throw new ApiException(ErrorCode.FORBIDDEN, "Вы не участник этого чата", HttpStatus.FORBIDDEN);
|
||
}
|
||
}
|
||
|
||
private ChatDto toDto(Chat chat, Long currentUserId) {
|
||
return toDtos(List.of(chat), currentUserId).get(0);
|
||
}
|
||
|
||
/**
|
||
* Собирает ChatDto для списка чатов фиксированным числом запросов (собеседники,
|
||
* объявления, последние сообщения, непрочитанные), а не пятью запросами на чат.
|
||
*/
|
||
private List<ChatDto> toDtos(List<Chat> chats, Long currentUserId) {
|
||
if (chats.isEmpty()) {
|
||
return List.of();
|
||
}
|
||
List<Long> chatIds = chats.stream().map(Chat::getId).toList();
|
||
Map<Long, User> users = userRepository.findAllById(chats.stream()
|
||
.map(chat -> otherUserId(chat, currentUserId)).distinct().toList()).stream()
|
||
.collect(Collectors.toMap(User::getId, Function.identity()));
|
||
Map<Long, Post> posts = postRepository.findAllById(chats.stream()
|
||
.map(Chat::getPostId).filter(Objects::nonNull).distinct().toList()).stream()
|
||
.collect(Collectors.toMap(Post::getId, Function.identity()));
|
||
Map<Long, Message> lastMessages = messageRepository.findLastMessages(chatIds).stream()
|
||
.collect(Collectors.toMap(Message::getChatId, Function.identity()));
|
||
Map<Long, Long> unread = new HashMap<>();
|
||
for (Object[] row : messageRepository.countUnreadByChat(chatIds, currentUserId)) {
|
||
unread.put(((Number) row[0]).longValue(), ((Number) row[1]).longValue());
|
||
}
|
||
|
||
return chats.stream().map(chat -> {
|
||
Long otherUserId = otherUserId(chat, currentUserId);
|
||
ChatDto dto = new ChatDto();
|
||
dto.setId(chat.getId());
|
||
dto.setOtherUserId(otherUserId);
|
||
dto.setPostId(chat.getPostId());
|
||
|
||
User other = users.get(otherUserId);
|
||
if (other != null) {
|
||
dto.setOtherUserName(other.getName() + " " + other.getLastName());
|
||
dto.setOtherUserAvatar(other.getAvatarUrl());
|
||
}
|
||
|
||
Post post = chat.getPostId() == null ? null : posts.get(chat.getPostId());
|
||
if (post != null) {
|
||
ChatPostDto postDto = new ChatPostDto();
|
||
postDto.setId(post.getId());
|
||
postDto.setTitle(post.getTitle());
|
||
postDto.setImages(post.getImages().stream().map(Image::getUrl).toList());
|
||
dto.setPost(postDto);
|
||
}
|
||
|
||
Message last = lastMessages.get(chat.getId());
|
||
if (last != null) {
|
||
dto.setLastMessage(last.getContent());
|
||
dto.setLastMessageAt(last.getCreatedAt());
|
||
}
|
||
dto.setUnreadCount(unread.getOrDefault(chat.getId(), 0L));
|
||
return dto;
|
||
}).toList();
|
||
}
|
||
|
||
private static Long otherUserId(Chat chat, Long currentUserId) {
|
||
return chat.getUserOneId().equals(currentUserId) ? chat.getUserTwoId() : chat.getUserOneId();
|
||
}
|
||
|
||
private MessageDto toMessageDto(Message m) {
|
||
MessageDto dto = new MessageDto();
|
||
dto.setId(m.getId());
|
||
dto.setChatId(m.getChatId());
|
||
dto.setSenderId(m.getSenderId());
|
||
dto.setContent(m.getContent());
|
||
dto.setRead(m.isRead());
|
||
dto.setCreatedAt(m.getCreatedAt());
|
||
return dto;
|
||
}
|
||
}
|