forked from mtusi2026/mtusi2026lab4
245 lines
9.2 KiB
Java
245 lines
9.2 KiB
Java
package org.example.service;
|
|
|
|
import lombok.RequiredArgsConstructor;
|
|
import org.example.dto.MessagePage;
|
|
import org.example.dto.create.CreateMessageDto;
|
|
import org.example.dto.update.UpdateMessageDto;
|
|
import org.example.exception.BadRequestException;
|
|
import org.example.exception.ConflictException;
|
|
import org.example.exception.ForbiddenException;
|
|
import org.example.exception.NotFoundException;
|
|
import org.example.model.Attachment;
|
|
import org.example.model.IdempotencyKey;
|
|
import org.example.model.Message;
|
|
import org.example.model.MessageAttachment;
|
|
import org.example.repository.AttachmentRepository;
|
|
import org.example.repository.IdempotencyKeyRepository;
|
|
import org.example.repository.MessageAttachmentRepository;
|
|
import org.example.repository.MessageRepository;
|
|
import org.springframework.dao.DataIntegrityViolationException;
|
|
import org.springframework.data.domain.PageRequest;
|
|
import org.springframework.data.domain.Pageable;
|
|
import org.springframework.stereotype.Service;
|
|
import org.springframework.transaction.annotation.Transactional;
|
|
|
|
import java.time.Instant;
|
|
import java.util.*;
|
|
import java.util.stream.Collectors;
|
|
|
|
import static org.example.config.TokenHasher.sha256;
|
|
|
|
@Service
|
|
@RequiredArgsConstructor
|
|
public class MessageService {
|
|
|
|
private final MessageRepository messageRepository;
|
|
private final IdempotencyKeyRepository idempotencyKeyRepository;
|
|
private final ChatService chatService;
|
|
private final MessageIdempotencyWriter writer;
|
|
private final AttachmentRepository attachmentRepository;
|
|
private final MessageAttachmentRepository messageAttachmentRepository;
|
|
|
|
@Transactional
|
|
public Message sendMessage(
|
|
UUID chatId,
|
|
UUID senderId,
|
|
CreateMessageDto messageObject,
|
|
String idempotencyKey) {
|
|
|
|
chatService.requireMember(chatId);
|
|
if (!chatService.isMember(chatId, senderId)) {
|
|
throw new ForbiddenException("Пользователь не является участником чата");
|
|
}
|
|
|
|
String text = messageObject.getText() == null ? "" : messageObject.getText();
|
|
|
|
List<UUID> attIds = messageObject.getAttachmentIds() == null
|
|
? List.of()
|
|
: messageObject.getAttachmentIds().stream().distinct().toList();
|
|
|
|
if (text.isBlank() && attIds.isEmpty()) {
|
|
throw new BadRequestException("text or attachment_ids required");
|
|
}
|
|
|
|
if (!attIds.isEmpty()) {
|
|
List<Attachment> found = attachmentRepository.findByIdInAndChatId(attIds, chatId);
|
|
if (found.size() != attIds.size()) {
|
|
throw new BadRequestException("Invalid attachment_ids");
|
|
}
|
|
}
|
|
|
|
String key = idempotencyKey.trim();
|
|
String hash = sha256(
|
|
text + "\n" + attIds.stream()
|
|
.map(UUID::toString)
|
|
.sorted()
|
|
.collect(Collectors.joining(","))
|
|
);
|
|
|
|
Optional<IdempotencyKey> exists =
|
|
idempotencyKeyRepository.findByUserIdAndChatIdAndIdempotencyKey(senderId, chatId, key);
|
|
|
|
if (exists.isPresent()) {
|
|
return messageFromIdem(exists.get(), hash);
|
|
}
|
|
|
|
try {
|
|
Message message = writer.insertNew(chatId, senderId, text, attIds, key, hash);
|
|
message.setAttachmentIds(attIds);
|
|
return message;
|
|
} catch (DataIntegrityViolationException e) {
|
|
IdempotencyKey rec = idempotencyKeyRepository
|
|
.findByUserIdAndChatIdAndIdempotencyKey(senderId, chatId, key)
|
|
.orElseThrow(() -> e);
|
|
return messageFromIdem(rec, hash);
|
|
}
|
|
}
|
|
|
|
private Message messageFromIdem(IdempotencyKey row, String hash) {
|
|
if (!row.getRequestHash().equals(hash)) {
|
|
throw new ConflictException("Idempotency key conflict");
|
|
}
|
|
Message message = messageRepository.findById(row.getMessageId())
|
|
.orElseThrow(() -> new IllegalStateException("idempotency message missing"));
|
|
|
|
List<UUID> ids = messageAttachmentRepository.findByMessageId(message.getId())
|
|
.stream()
|
|
.map(MessageAttachment::getAttachmentId)
|
|
.toList();
|
|
message.setAttachmentIds(ids);
|
|
return message;
|
|
}
|
|
|
|
@Transactional(readOnly = true)
|
|
public MessagePage getMessage(UUID chatId, UUID userId, String cursor, int limit) {
|
|
if (limit < 1 || limit > 100) {
|
|
throw new IllegalArgumentException("limit must be between 1 and 100");
|
|
}
|
|
|
|
chatService.requireMember(chatId);
|
|
if (!chatService.isMember(chatId, userId)) {
|
|
throw new NotFoundException("Чат не найден");
|
|
}
|
|
|
|
Pageable pageable = PageRequest.of(0, limit);
|
|
List<Message> items;
|
|
|
|
if (cursor == null || cursor.isBlank()) {
|
|
items = messageRepository.findByChatIdOrderByCreatedAtAscIdAsc(chatId, pageable);
|
|
} else {
|
|
UUID cursorId;
|
|
try {
|
|
cursorId = UUID.fromString(cursor.trim());
|
|
} catch (IllegalArgumentException e) {
|
|
throw new IllegalArgumentException("Invalid cursor");
|
|
}
|
|
|
|
Message cursorMsg = messageRepository.findByIdAndChatId(cursorId, chatId)
|
|
.orElseThrow(() -> new IllegalArgumentException("Invalid cursor"));
|
|
|
|
items = messageRepository.findNextPage(
|
|
chatId,
|
|
cursorMsg.getCreatedAt(),
|
|
cursorMsg.getId(),
|
|
pageable
|
|
);
|
|
}
|
|
|
|
String nextCursor = null;
|
|
if (items.size() == limit && !items.isEmpty()) {
|
|
Message last = items.get(items.size() - 1);
|
|
boolean hasMore = !messageRepository
|
|
.findNextPage(
|
|
chatId,
|
|
last.getCreatedAt(),
|
|
last.getId(),
|
|
PageRequest.of(0, 1)
|
|
)
|
|
.isEmpty();
|
|
if (hasMore) {
|
|
nextCursor = last.getId().toString();
|
|
}
|
|
}
|
|
|
|
if (!items.isEmpty()) {
|
|
List<UUID> msgIds = items.stream().map(Message::getId).toList();
|
|
List<MessageAttachment> links =
|
|
messageAttachmentRepository.findByMessageIdIn(msgIds);
|
|
|
|
Map<UUID, List<UUID>> byMsg = new HashMap<>();
|
|
for (MessageAttachment link : links) {
|
|
byMsg.computeIfAbsent(link.getMessageId(), k -> new ArrayList<>())
|
|
.add(link.getAttachmentId());
|
|
}
|
|
for (Message m : items) {
|
|
m.setAttachmentIds(byMsg.getOrDefault(m.getId(), List.of()));
|
|
}
|
|
} else {
|
|
for (Message m : items) {
|
|
m.setAttachmentIds(List.of());
|
|
}
|
|
}
|
|
|
|
return new MessagePage(items, nextCursor);
|
|
}
|
|
|
|
@Transactional(readOnly = true)
|
|
public MessagePage getMessage(String chatId, String userId, String cursor, int limit){
|
|
return getMessage(parseUuid(chatId, true), parseUuid(userId, false), cursor, limit);
|
|
}
|
|
|
|
@Transactional
|
|
public Message updateMessage(UUID chatId, UUID messageId, UUID userId, UpdateMessageDto object) {
|
|
chatService.requireMember(chatId);
|
|
Message message = messageRepository.findByIdAndChatId(messageId, chatId)
|
|
.orElseThrow(() -> new NotFoundException("Сообщение не найден"));
|
|
if (!message.getSenderId().equals(userId)){
|
|
throw new ForbiddenException("Вы не можете редактировать чужие сообщения");
|
|
}
|
|
message.setText(object.getText());
|
|
return messageRepository.save(message);
|
|
}
|
|
|
|
@Transactional
|
|
public Message updateMessage(String chatId, String messageId, String userId, UpdateMessageDto object) {
|
|
return updateMessage(
|
|
parseUuid(chatId, true),
|
|
parseUuid(messageId, true),
|
|
parseUuid(userId, false),
|
|
object);
|
|
}
|
|
|
|
@Transactional
|
|
public void deleteMessage(UUID chatId, UUID messageId, UUID userId) {
|
|
chatService.getChatById(chatId);
|
|
|
|
Message msg = messageRepository.findByIdAndChatId(messageId, chatId)
|
|
.orElseThrow(() -> new NotFoundException("Сообщение не найдено"));
|
|
|
|
if (!msg.getSenderId().equals(userId)) {
|
|
throw new ForbiddenException("Вы не можете удалять сообщения других участников");
|
|
}
|
|
messageRepository.delete(msg);
|
|
}
|
|
|
|
@Transactional
|
|
public void deleteMessage(String chatId, String messageId, String userId) {
|
|
deleteMessage(
|
|
parseUuid(chatId, true),
|
|
parseUuid(messageId, true),
|
|
parseUuid(userId, false)
|
|
);
|
|
}
|
|
|
|
|
|
private static UUID parseUuid(String value, boolean notFoundOnBad) {
|
|
try {
|
|
return UUID.fromString(value.trim());
|
|
} catch (Exception e) {
|
|
if (notFoundOnBad) {
|
|
throw new NotFoundException("Не найдено");
|
|
}
|
|
throw new IllegalArgumentException("Invalid id");
|
|
}
|
|
}
|
|
} |