Перенос кода из ЛР5 в ЛР6 (начало)

This commit is contained in:
2026-11-24 15:44:25 +03:00
parent 470d9d6f1e
commit a1071c87e9
71 changed files with 3179 additions and 0 deletions
@@ -0,0 +1,148 @@
package ru.mtusi.messenger.service;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ru.mtusi.messenger.dto.Attachment;
import ru.mtusi.messenger.entity.AttachmentEntity;
import ru.mtusi.messenger.entity.ChatEntity;
import ru.mtusi.messenger.exception.InvalidRequestException;
import ru.mtusi.messenger.exception.NotFoundException;
import ru.mtusi.messenger.repository.AttachmentRepository;
import ru.mtusi.messenger.repository.ChatRepository;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.security.MessageDigest;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.HexFormat;
import java.util.List;
import java.util.UUID;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import ru.mtusi.messenger.config.RabbitConfig;
@Service
public class AttachmentService {
private final AttachmentRepository attachmentRepository;
private final ChatRepository chatRepository;
private final StorageService storageService;
private static final long MAX_SIZE = 10 * 1024 * 1024; // 10 MiB
private final RabbitTemplate rabbitTemplate;
public AttachmentService(AttachmentRepository attachmentRepository, ChatRepository chatRepository, StorageService storageService, RabbitTemplate rabbitTemplate) {
this.attachmentRepository = attachmentRepository;
this.chatRepository = chatRepository;
this.storageService = storageService;
this.rabbitTemplate = rabbitTemplate;
}
@Transactional
public Attachment upload(UUID callerId, UUID chatId, String filename, String contentType, InputStream inputStream, long size) throws Exception {
verifyAccess(callerId, chatId);
if (size > MAX_SIZE) {
throw new ru.mtusi.messenger.exception.PayloadTooLargeException("File exceeds 10 MiB");
}
if (filename == null || filename.isBlank() || filename.contains("/") || filename.contains("\\") || filename.contains("\0")) {
throw new InvalidRequestException("Invalid filename");
}
// Читаем байты в память (для 10 MiB это безопасно)
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
byte[] data = new byte[8192];
int nRead;
long totalRead = 0;
while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, nRead);
totalRead += nRead;
if (totalRead > MAX_SIZE) throw new ru.mtusi.messenger.exception.PayloadTooLargeException("File exceeds 10 MiB");
}
byte[] bytes = buffer.toByteArray();
// Проверяем MIME по магическим байтам
String detectedMime = detectMime(bytes);
if (!detectedMime.equals("image/png") && !detectedMime.equals("image/jpeg")) {
throw new ru.mtusi.messenger.exception.UnsupportedMediaTypeException("Only PNG and JPEG are allowed");
}
if (!detectedMime.equals(contentType)) {
throw new ru.mtusi.messenger.exception.UnsupportedMediaTypeException("MIME type mismatch");
}
// Считаем SHA-256
MessageDigest digest = MessageDigest.getInstance("SHA-256");
String sha256 = HexFormat.of().formatHex(digest.digest(bytes));
// Загружаем в S3 в папку staging (временное хранилище)
String objectKey = "staging/" + UUID.randomUUID().toString();
storageService.upload(objectKey, new ByteArrayInputStream(bytes), bytes.length, detectedMime);
// Сохраняем метаданные в БД со статусом queued
AttachmentEntity entity = new AttachmentEntity();
entity.setId(UUID.randomUUID());
entity.setChatId(chatId);
entity.setOwnerId(callerId);
entity.setFilename(filename);
entity.setContentType(detectedMime);
entity.setSizeBytes(bytes.length);
entity.setSha256(sha256);
entity.setObjectKey(objectKey);
entity.setStatus("queued");
entity.setErrorCode(null);
OffsetDateTime now = OffsetDateTime.now(ZoneOffset.UTC).truncatedTo(java.time.temporal.ChronoUnit.MILLIS);
entity.setCreatedAt(now);
entity.setUpdatedAt(now);
attachmentRepository.save(entity);
rabbitTemplate.convertAndSend(RabbitConfig.EXCHANGE_NAME, RabbitConfig.ROUTING_KEY, entity.getId().toString());
// TODO: Здесь на Шаге 3 мы будем отправлять сообщение в RabbitMQ
// Пока что просто возвращаем ответ.
return toDto(entity);
}
private void verifyAccess(UUID callerId, UUID chatId) {
ChatEntity chat = chatRepository.findById(chatId)
.orElseThrow(() -> new NotFoundException("Chat not found"));
boolean isMember = chat.getMembers().stream().anyMatch(u -> u.getId().equals(callerId));
if (!isMember) throw new NotFoundException("Chat not found");
}
private String detectMime(byte[] bytes) {
if (bytes.length < 4) return "unknown";
if ((bytes[0] & 0xFF) == 0x89 && bytes[1] == 0x50 && bytes[2] == 0x4E && bytes[3] == 0x47) return "image/png";
if ((bytes[0] & 0xFF) == 0xFF && (bytes[1] & 0xFF) == 0xD8 && (bytes[2] & 0xFF) == 0xFF) return "image/jpeg";
return "unknown";
}
public Attachment toDto(AttachmentEntity e) {
// Маппим варианты из БД (пока их нет, вернется пустой список)
List<Attachment.Variant> variantDtos = e.getVariants().stream()
.map(v -> new Attachment.Variant(
v.getName(),
v.getContentType(),
v.getSizeBytes(),
v.getSha256(),
v.getWidth(),
v.getHeight()
))
.toList();
return new Attachment(
e.getId(), e.getChatId(), e.getOwnerId(), e.getFilename(),
e.getContentType(), e.getSizeBytes(), e.getSha256(),
e.getStatus(),
variantDtos,
e.getErrorCode(),
e.getCreatedAt(),
e.getUpdatedAt()
);
}
}
@@ -0,0 +1,85 @@
package ru.mtusi.messenger.service;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ru.mtusi.messenger.dto.Chat;
import ru.mtusi.messenger.dto.CreateChat;
import ru.mtusi.messenger.entity.ChatEntity;
import ru.mtusi.messenger.entity.UserEntity;
import ru.mtusi.messenger.exception.InvalidRequestException;
import ru.mtusi.messenger.exception.NotFoundException;
import ru.mtusi.messenger.repository.ChatRepository;
import ru.mtusi.messenger.repository.UserRepository;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;
@Service
public class ChatService {
private final ChatRepository chatRepository;
private final UserRepository userRepository;
public ChatService(ChatRepository chatRepository, UserRepository userRepository) {
this.chatRepository = chatRepository;
this.userRepository = userRepository;
}
@Transactional
public Chat createChat(UUID callerId, CreateChat request) {
Set<UUID> uniqueMembers = new HashSet<>(request.memberIds());
if (uniqueMembers.size() != request.memberIds().size()) {
throw new InvalidRequestException("member_ids must be unique");
}
if (!uniqueMembers.contains(callerId)) {
throw new InvalidRequestException("caller must be a member of the chat");
}
List<UserEntity> members = userRepository.findAllById(request.memberIds());
if (members.size() != request.memberIds().size()) {
throw new InvalidRequestException("Some members do not exist");
}
ChatEntity chat = new ChatEntity();
chat.setId(UUID.randomUUID());
chat.setTitle(request.title());
chat.setCreatedAt(OffsetDateTime.now(ZoneOffset.UTC));
chat.setMembers(new HashSet<>(members));
chatRepository.save(chat);
return toDto(chat);
}
@Transactional(readOnly = true)
public Chat getChat(UUID callerId, UUID chatId) {
ChatEntity chat = chatRepository.findById(chatId)
.orElseThrow(() -> new NotFoundException("Chat not found"));
boolean isMember = chat.getMembers().stream().anyMatch(u -> u.getId().equals(callerId));
if (!isMember) throw new NotFoundException("Chat not found");
return toDto(chat);
}
@Transactional(readOnly = true)
public List<Chat> getUserChats(UUID callerId) {
// В реальном проекте лучше сделать кастомный запрос, но для lab2 сойдет
return chatRepository.findAll().stream()
.filter(c -> c.getMembers().stream().anyMatch(u -> u.getId().equals(callerId)))
.map(this::toDto)
.toList();
}
public Chat toDto(ChatEntity entity) {
return new Chat(
entity.getId(),
entity.getTitle(),
entity.getMembers().stream().map(UserEntity::getId).toList(),
entity.getCreatedAt()
);
}
}
@@ -0,0 +1,135 @@
package ru.mtusi.messenger.service;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ru.mtusi.messenger.dto.Message;
import ru.mtusi.messenger.entity.AttachmentEntity;
import ru.mtusi.messenger.entity.ChatEntity;
import ru.mtusi.messenger.entity.MessageEntity;
import ru.mtusi.messenger.exception.ConflictException;
import ru.mtusi.messenger.exception.InvalidRequestException;
import ru.mtusi.messenger.exception.NotFoundException;
import ru.mtusi.messenger.repository.AttachmentRepository;
import ru.mtusi.messenger.repository.ChatRepository;
import ru.mtusi.messenger.repository.IdempotencyRepository;
import ru.mtusi.messenger.repository.MessageRepository;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.List;
import java.util.UUID;
@Service
public class MessageService {
private final MessageRepository messageRepository;
private final ChatRepository chatRepository;
private final IdempotencyRepository idempotencyRepository;
private final AttachmentRepository attachmentRepository;
public MessageService(MessageRepository messageRepository,
ChatRepository chatRepository,
IdempotencyRepository idempotencyRepository,
AttachmentRepository attachmentRepository) {
this.messageRepository = messageRepository;
this.chatRepository = chatRepository;
this.idempotencyRepository = idempotencyRepository;
this.attachmentRepository = attachmentRepository;
}
@Transactional
public Message createMessage(UUID callerId, UUID chatId, String text, List<UUID> attachmentIds, String idempotencyKey) {
verifyAccess(callerId, chatId);
if (text == null) text = "";
if (text.isBlank() && (attachmentIds == null || attachmentIds.isEmpty())) {
throw new InvalidRequestException("Message must have text or attachments");
}
// Проверяем вложения
if (attachmentIds != null && !attachmentIds.isEmpty()) {
for (UUID attId : attachmentIds) {
AttachmentEntity att = attachmentRepository.findById(attId)
.orElseThrow(() -> new NotFoundException("Attachment not found: " + attId));
if (!att.getChatId().equals(chatId)) {
throw new NotFoundException("Attachment not found in this chat");
}
}
}
// Считаем хеш тела запроса
String requestHash = org.springframework.util.DigestUtils.md5DigestAsHex(
(text + attachmentIds).getBytes(java.nio.charset.StandardCharsets.UTF_8));
if (idempotencyKey != null && !idempotencyKey.isBlank()) {
var existing = idempotencyRepository.findById(new ru.mtusi.messenger.entity.IdempotencyId(idempotencyKey, callerId, chatId));
if (existing.isPresent()) {
if (!existing.get().getRequestHash().equals(requestHash)) {
throw new ConflictException("Idempotency key reused with different body");
}
return messageRepository.findById(existing.get().getMessageId())
.map(this::toDto)
.orElseThrow(() -> new NotFoundException("Message not found"));
}
}
MessageEntity msg = new MessageEntity();
msg.setId(UUID.randomUUID());
msg.setChatId(chatId);
msg.setSenderId(callerId);
msg.setText(text);
msg.setCreatedAt(OffsetDateTime.now(ZoneOffset.UTC).truncatedTo(java.time.temporal.ChronoUnit.MILLIS));
messageRepository.save(msg);
// Связываем вложения
if (attachmentIds != null && !attachmentIds.isEmpty()) {
for (UUID attId : attachmentIds) {
messageRepository.linkAttachment(msg.getId(), attId);
}
}
// Сохраняем ключ идемпотентности
if (idempotencyKey != null && !idempotencyKey.isBlank()) {
var idem = new ru.mtusi.messenger.entity.IdempotencyEntity();
idem.setKey(idempotencyKey);
idem.setUserId(callerId);
idem.setChatId(chatId);
idem.setRequestHash(requestHash);
idem.setMessageId(msg.getId());
idem.setCreatedAt(OffsetDateTime.now(ZoneOffset.UTC));
idempotencyRepository.save(idem);
}
return toDto(msg);
}
private void verifyAccess(UUID callerId, UUID chatId) {
ChatEntity chat = chatRepository.findById(chatId)
.orElseThrow(() -> new NotFoundException("Chat not found"));
boolean isMember = chat.getMembers().stream().anyMatch(u -> u.getId().equals(callerId));
if (!isMember) throw new NotFoundException("Chat not found");
}
private Message toDto(MessageEntity e) {
List<UUID> attachments = messageRepository.findAttachmentIdsByMessageId(e.getId());
return new Message(
e.getId(),
e.getChatId(),
e.getSenderId(),
e.getText(),
attachments,
e.getCreatedAt()
);
}
@Transactional(readOnly = true)
public List<Message> getMessagesPage(UUID callerId, UUID chatId, OffsetDateTime lastCreatedAt, UUID lastId, int limit) {
verifyAccess(callerId, chatId);
OffsetDateTime startTime = (lastCreatedAt != null) ? lastCreatedAt : OffsetDateTime.of(1970, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC);
UUID startId = (lastId != null) ? lastId : new UUID(0, 0);
return messageRepository.findNextPage(chatId, startTime, startId, org.springframework.data.domain.PageRequest.of(0, limit))
.stream().map(this::toDto).toList();
}
}
@@ -0,0 +1,64 @@
package ru.mtusi.messenger.service;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ru.mtusi.messenger.dto.SessionResponse;
import ru.mtusi.messenger.entity.SessionEntity;
import ru.mtusi.messenger.entity.UserEntity;
import ru.mtusi.messenger.exception.UnauthorizedException;
import ru.mtusi.messenger.repository.SessionRepository;
import ru.mtusi.messenger.repository.UserRepository;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.UUID;
@Service
public class SessionService {
private final UserRepository userRepository;
private final SessionRepository sessionRepository;
private final PasswordEncoder passwordEncoder;
private final UserService userService;
public SessionService(UserRepository userRepository,
SessionRepository sessionRepository,
PasswordEncoder passwordEncoder,
UserService userService) {
this.userRepository = userRepository;
this.sessionRepository = sessionRepository;
this.passwordEncoder = passwordEncoder;
this.userService = userService;
}
@Transactional
public SessionResponse createSession(String username, String rawPassword) {
// 1. Ищем пользователя
UserEntity user = userRepository.findByUsername(username)
.orElseThrow(() -> new UnauthorizedException("Invalid credentials"));
// 2. Проверяем пароль
if (!passwordEncoder.matches(rawPassword, user.getPasswordHash())) {
throw new UnauthorizedException("Invalid credentials");
}
// 3. Генерируем opaque токен (UUID)
String token = UUID.randomUUID().toString();
// 4. Сохраняем сессию в БД (TTL 1 час)
SessionEntity session = new SessionEntity();
session.setToken(token);
session.setUserId(user.getId());
session.setExpiresAt(OffsetDateTime.now(ZoneOffset.UTC).plusHours(1));
sessionRepository.save(session);
// 5. Возвращаем ответ
return new SessionResponse(
token,
session.getExpiresAt(),
userService.toDto(user)
);
}
}
@@ -0,0 +1,54 @@
package ru.mtusi.messenger.service;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.CreateBucketRequest;
import software.amazon.awssdk.services.s3.model.GetObjectRequest;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
import java.io.InputStream;
@Service
public class StorageService {
private final S3Client s3Client;
private final String bucketName;
public StorageService(S3Client s3Client, @Value("${S3_BUCKET:messenger-attachments}") String bucketName) {
this.s3Client = s3Client;
this.bucketName = bucketName;
ensureBucketExists();
}
private void ensureBucketExists() {
try {
s3Client.headBucket(b -> b.bucket(bucketName));
} catch (Exception e) {
// Бакета нет или нет доступа — пытаемся создать
try {
s3Client.createBucket(CreateBucketRequest.builder().bucket(bucketName).build());
} catch (Exception ex) {
throw new RuntimeException("Failed to create S3 bucket", ex);
}
}
}
public void upload(String objectKey, InputStream inputStream, long contentLength, String contentType) {
PutObjectRequest request = PutObjectRequest.builder()
.bucket(bucketName)
.key(objectKey)
.contentType(contentType)
.build();
s3Client.putObject(request, RequestBody.fromInputStream(inputStream, contentLength));
}
public InputStream download(String objectKey) {
GetObjectRequest request = GetObjectRequest.builder()
.bucket(bucketName)
.key(objectKey)
.build();
return s3Client.getObject(request);
}
}
@@ -0,0 +1,59 @@
package ru.mtusi.messenger.service;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ru.mtusi.messenger.dto.CreateUser;
import ru.mtusi.messenger.dto.User;
import ru.mtusi.messenger.entity.UserEntity;
import ru.mtusi.messenger.exception.ConflictException;
import ru.mtusi.messenger.repository.UserRepository;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.Optional;
import java.util.UUID;
@Service
public class UserService {
private final UserRepository userRepository;
private final PasswordEncoder passwordEncoder;
public UserService(UserRepository userRepository, PasswordEncoder passwordEncoder) {
this.userRepository = userRepository;
this.passwordEncoder = passwordEncoder;
}
@Transactional
public User createUser(CreateUser request) {
// ... проверка username ...
UserEntity entity = new UserEntity();
entity.setId(UUID.randomUUID());
entity.setUsername(request.username());
entity.setDisplayName(request.displayName());
entity.setPasswordHash(passwordEncoder.encode(request.password()));
// ВАЖНО: обрезаем до миллисекунд, чтобы PostgreSQL не изменил точность
OffsetDateTime now = OffsetDateTime.now(ZoneOffset.UTC).truncatedTo(java.time.temporal.ChronoUnit.MILLIS);
entity.setCreatedAt(now);
userRepository.save(entity);
return toDto(entity);
}
@Transactional(readOnly = true)
public Optional<User> findById(UUID id) {
return userRepository.findById(id).map(this::toDto);
}
// Вспомогательный метод для конвертации Entity -> DTO
public User toDto(UserEntity entity) {
return new User(
entity.getId(),
entity.getUsername(),
entity.getDisplayName(),
entity.getCreatedAt()
);
}
}