Пунк Е загрузка вложений готово

This commit is contained in:
Dmitry
2026-11-10 23:57:31 +03:00
parent 034d5537cf
commit da12a510bc
17 changed files with 567 additions and 26 deletions
@@ -0,0 +1,92 @@
package org.example.service;
import lombok.RequiredArgsConstructor;
import org.example.config.ImageUploadValidator;
import org.example.dto.response.AttachmentResponse;
import org.example.exception.NotFoundException;
import org.example.model.Attachment;
import org.example.model.User;
import org.example.repository.AttachmentRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;
@Service
@RequiredArgsConstructor
public class AttachmentService {
private final AttachmentRepository attachmentRepository;
private final S3StorageService s3StorageService;
private final ImageUploadValidator validator;
private final ChatService chatService;
private final UserService userService;
@Transactional
public AttachmentResponse upload(
UUID chatId,
String filename,
String contentTypeHeader,
InputStream body
) throws IOException {
User user = userService.getCurrentUser();
chatService.requireMember(chatId);
ImageUploadValidator.ValidatedImage img = validator.validate(filename, body);
UUID id = UUID.randomUUID();
String objectKey = "chats/" + chatId + "/" + id;
s3StorageService.put(
objectKey,
new ByteArrayInputStream(img.bytes()),
img.bytes().length,
img.contentType()
);
Attachment saved = attachmentRepository.save(Attachment.builder()
.id(id)
.chatId(chatId)
.uploaderId(user.getId())
.objectKey(objectKey)
.originalFilename(img.safeFilename())
.contentType(img.contentType())
.sizeBytes(img.bytes().length)
.checksumSha256(img.sha256Hex())
.width(img.width())
.height(img.height())
.build());
return toResponse(saved);
}
@Transactional(readOnly = true)
public Attachment getForMember(UUID attachmentId){
Attachment attachment = attachmentRepository.findById(attachmentId)
.orElseThrow(()-> new NotFoundException("Вложение не найдено"));
chatService.requireMember(attachment.getChatId());
return attachment;
}
static AttachmentResponse toResponse(Attachment a) {
return AttachmentResponse.builder()
.id(a.getId())
.chatId(a.getChatId())
.uploaderId(a.getUploaderId())
.originalFilename(a.getOriginalFilename())
.contentType(a.getContentType())
.sizeBytes(a.getSizeBytes())
.checksumSha256(a.getChecksumSha256())
.width(a.getWidth())
.height(a.getHeight())
.createdAt(a.getCreatedAt())
.build();
}
}