ЛР5: реализована асинхронная обработка изображений (оценка 3)

This commit is contained in:
2026-11-21 23:40:03 +03:00
parent 276dbdad8a
commit a644acc600
72 changed files with 3290 additions and 22 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()
);
}
}