forked from mtusi2026/mtusi2026lab4
phase 2
This commit is contained in:
@@ -0,0 +1,113 @@
|
||||
package ru.mtusi.messenger.service;
|
||||
|
||||
import io.minio.*;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import ru.mtusi.messenger.config.properties.S3Properties;
|
||||
import ru.mtusi.messenger.dto.AttachmentDTO;
|
||||
import ru.mtusi.messenger.mapper.AttachmentMapper;
|
||||
import ru.mtusi.messenger.model.Attachment;
|
||||
import ru.mtusi.messenger.exception.*;
|
||||
import ru.mtusi.messenger.model.Chat;
|
||||
import ru.mtusi.messenger.model.User;
|
||||
import ru.mtusi.messenger.repository.AttachmentRepository;
|
||||
import ru.mtusi.messenger.validation.AttachmentValidator;
|
||||
|
||||
import java.security.MessageDigest;
|
||||
import java.util.UUID;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
public class AttachmentService {
|
||||
private final UserService userService;
|
||||
private final ChatService chatService;
|
||||
private final MinioClient minio;
|
||||
private final AttachmentRepository attachmentRepository;
|
||||
private final S3Properties s3Props;
|
||||
private final AttachmentValidator validator;
|
||||
private final AttachmentMapper attachmentMapper;
|
||||
|
||||
@Transactional
|
||||
public AttachmentDTO upload(UUID chatId, UUID caller, String filename, byte[] body) {
|
||||
Chat chat = chatService.getChat(caller, chatId);
|
||||
String contentType = validator.validate(body, filename);
|
||||
String safeFilename = validator.sanitizeFilename(filename);
|
||||
String objectKey = UUID.randomUUID().toString();
|
||||
String checksum = uploadToS3AndCalculateChecksum(body, objectKey, contentType);
|
||||
User owner = userService.getReferenceUserById(caller);
|
||||
Attachment attachment = attachmentMapper.toEntity(objectKey, safeFilename, contentType, (long) body.length, checksum , chat , owner);
|
||||
attachmentRepository.save(attachment);
|
||||
return attachmentMapper.toDto(attachment);
|
||||
}
|
||||
|
||||
private String uploadToS3AndCalculateChecksum(byte[] body, String objectKey, String contentType) {
|
||||
try {
|
||||
MessageDigest digest = MessageDigest.getInstance("SHA-256");
|
||||
try (var in = new java.security.DigestInputStream(new java.io.ByteArrayInputStream(body), digest)) {
|
||||
minio.putObject(io.minio.PutObjectArgs.builder()
|
||||
.bucket(s3Props.bucket())
|
||||
.object(objectKey)
|
||||
.stream(in, (long) body.length, -1L)
|
||||
.contentType(contentType)
|
||||
.build());
|
||||
}
|
||||
return java.util.HexFormat.of().formatHex(digest.digest());
|
||||
} catch (Exception e) {
|
||||
log.error("S3 upload failed for objectKey: {}", objectKey, e);
|
||||
throw new StorageUnavailableException("S3 upload failed", e);
|
||||
}
|
||||
}
|
||||
|
||||
public AttachmentDTO getMetadata(UUID attachmentId, UUID userId) {
|
||||
Attachment attachment = attachmentRepository.findById(attachmentId)
|
||||
.orElseThrow(() -> new NotFoundException("Attachment not found"));
|
||||
|
||||
assertMember(attachment.getChat().getId(), userId);
|
||||
return attachmentMapper.toDto(attachment);
|
||||
}
|
||||
|
||||
public DownloadedAttachment download(UUID attachmentId, UUID userId, String variant) {
|
||||
Attachment attachment = attachmentRepository.findById(attachmentId)
|
||||
.orElseThrow(() -> new NotFoundException("Attachment not found"));
|
||||
|
||||
assertMember(attachment.getChat().getId(), userId);
|
||||
|
||||
if (!"original".equals(variant)) {
|
||||
throw new NotFoundException("Variant not found");
|
||||
}
|
||||
|
||||
try {
|
||||
var stream = minio.getObject(GetObjectArgs.builder()
|
||||
.bucket(s3Props.bucket())
|
||||
.object(attachment.getObjectKey())
|
||||
.build());
|
||||
|
||||
return new DownloadedAttachment(stream, attachment.getContentType(), attachment.getFilename());
|
||||
} catch (Exception e) {
|
||||
throw translateS3Exception(e, attachmentId, attachment.getObjectKey());
|
||||
}
|
||||
}
|
||||
|
||||
private RuntimeException translateS3Exception(Exception e, UUID attachmentId, String objectKey) {
|
||||
if (e instanceof io.minio.errors.ErrorResponseException minioEx) {
|
||||
if ("NoSuchKey".equals(minioEx.errorResponse().code())) {
|
||||
log.warn("S3 object missing for attachment {}", attachmentId);
|
||||
return new NotFoundException("Attachment content not found");
|
||||
}
|
||||
}
|
||||
log.error("S3 download failed for {}", objectKey, e);
|
||||
return new StorageUnavailableException("S3 download failed", e);
|
||||
}
|
||||
|
||||
public record DownloadedAttachment(java.io.InputStream stream, String contentType, String filename) {}
|
||||
|
||||
private void assertMember(UUID chatId, UUID userId) {
|
||||
boolean isMember = chatService.existsByIdAndMembersId(chatId, userId);
|
||||
if (!isMember) {
|
||||
throw new NotFoundException("Attachment not found");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -127,4 +127,9 @@ public class ChatService {
|
||||
private CursorCodec.PageBoundary boundaryOf(Chat chat) {
|
||||
return new CursorCodec.PageBoundary(chat.getCreatedAt(), chat.getId());
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public boolean existsByIdAndMembersId(UUID chatId, UUID userId){
|
||||
return chatRepository.existsByIdAndMembersId(chatId, userId);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user