Лабораторная 2 на 5 готово

This commit is contained in:
Dmitry
2026-10-21 20:50:08 +03:00
parent 65003b6119
commit 5eb4db24a8
63 changed files with 2752 additions and 31 deletions
@@ -0,0 +1,151 @@
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.ForbiddenException;
import org.example.exception.NotFoundException;
import org.example.model.Message;
import org.example.repository.MessageRepository;
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.List;
import java.util.UUID;
@Service
@RequiredArgsConstructor
public class MessageService {
private final MessageRepository messageRepository;
private final ChatService chatService;
@Transactional
public Message sendMessage(UUID chatId, UUID senderId, CreateMessageDto messageObject) {
chatService.requireMember(chatId);
if (!chatService.isMember(chatId, senderId)){
throw new ForbiddenException("Пользователь не является участником чата");
}
Message message = Message.builder()
.chatId(chatId)
.senderId(senderId)
.text(messageObject.getText())
.createdAt(Instant.now())
.build();
return messageRepository.save(message);
}
@Transactional(readOnly = true)
public MessagePage getMessage(UUID chatId, UUID userId, String cursor, int limit) {
if (limit < 1) {
throw new IllegalArgumentException("Лимит должен быть больше 0");
}
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.findByChatIdOrderByCreatedAtDescIdDesc(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)
.orElse(null);
if (cursorMsg == null) {
throw new IllegalArgumentException("Invalid cursor");
}
items = messageRepository.findNextPage(
chatId,
cursorMsg.getCreatedAt(),
cursorMsg.getId(),
pageable
);
}
String nextCursor = null;
if (items.size() == limit && !items.isEmpty()) {
nextCursor = items.get(items.size() - 1).getId().toString();
}
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");
}
}
}