forked from mtusi2026/mtusi2026lab2
158 lines
5.6 KiB
Java
158 lines
5.6 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.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 || 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();
|
|
}
|
|
}
|
|
|
|
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");
|
|
}
|
|
}
|
|
} |