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

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,134 @@
package org.example.config;
import org.example.exception.BadRequestException;
import org.springframework.stereotype.Component;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.util.Set;
@Component
public class ImageUploadValidator {
public static final long MAX_BYTES = 10L * 1024 * 1024;
public static final long MAX_PIXELS = 40_000_000L;
private static final Set<String> ALLOWED = Set.of("image/png", "image/jpeg");
public record ValidatedImage(
byte[] bytes,
String contentType,
String safeFilename,
int width,
int height,
String sha256Hex
) {}
/**
* Raw body (не multipart) + filename из query.
*/
public ValidatedImage validate(String filename, InputStream in) throws IOException {
if (in == null) {
throw new BadRequestException("Empty body");
}
String safeName = sanitizeFilename(filename);
byte[] bytes = in.readNBytes((int) MAX_BYTES + 1);
if (bytes.length == 0) {
throw new BadRequestException("Empty file");
}
if (bytes.length > MAX_BYTES) {
throw new BadRequestException("File too large (max 10 MiB)");
}
String detected = detectMime(bytes);
if (!ALLOWED.contains(detected)) {
throw new BadRequestException("Only PNG and JPEG are allowed");
}
BufferedImage image;
try (InputStream imageIn = new ByteArrayInputStream(bytes)) {
image = ImageIO.read(imageIn);
}
if (image == null) {
throw new BadRequestException("Invalid image");
}
int width = image.getWidth();
int height = image.getHeight();
long pixels = (long) width * (long) height;
if (width <= 0 || height <= 0 || pixels > MAX_PIXELS) {
throw new BadRequestException("Image exceeds pixel limit");
}
return new ValidatedImage(
bytes,
detected,
safeName,
width,
height,
sha256Hex(bytes)
);
}
private static String detectMime(byte[] b) {
if (b.length >= 3
&& (b[0] & 0xFF) == 0xFF
&& (b[1] & 0xFF) == 0xD8
&& (b[2] & 0xFF) == 0xFF) {
return "image/jpeg";
}
if (b.length >= 8
&& (b[0] & 0xFF) == 0x89
&& b[1] == 0x50
&& b[2] == 0x4E
&& b[3] == 0x47
&& b[4] == 0x0D
&& b[5] == 0x0A
&& b[6] == 0x1A
&& b[7] == 0x0A) {
return "image/png";
}
return "application/octet-stream";
}
private static String sanitizeFilename(String name) {
if (name == null || name.isBlank()) {
throw new BadRequestException("filename is required");
}
String base = name.replace('\\', '/').trim();
int slash = base.lastIndexOf('/');
if (slash >= 0) {
base = base.substring(slash + 1);
}
if (base.isEmpty()
|| ".".equals(base)
|| "..".equals(base)
|| base.indexOf('\0') >= 0
|| base.length() > 255) {
throw new BadRequestException("Invalid filename");
}
if (!base.matches("[\\w.\\- ()\\[\\]]+")) {
throw new BadRequestException("Invalid filename");
}
return base;
}
private static String sha256Hex(byte[] data) {
try {
byte[] dig = MessageDigest.getInstance("SHA-256").digest(data);
StringBuilder sb = new StringBuilder(dig.length * 2);
for (byte value : dig) {
sb.append(String.format("%02x", value));
}
return sb.toString();
} catch (Exception e) {
throw new IllegalStateException("SHA-256 not available", e);
}
}
}
@@ -0,0 +1,28 @@
package org.example.config;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import java.net.URI;
@Configuration
@RequiredArgsConstructor
public class S3Config {
private final S3Properties props;
@Bean(destroyMethod = "close")
public S3Client s3Client() {
return S3Client.builder()
.endpointOverride(URI.create(props.getEndpoint()))
.region(Region.of(props.getRegion()))
.credentialsProvider(StaticCredentialsProvider.create(
AwsBasicCredentials.create(props.getAccessKey(), props.getSecretKey())))
.forcePathStyle(props.isPathStyle())
.build();
}
}
@@ -0,0 +1,17 @@
package org.example.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Data
@Component
@ConfigurationProperties(prefix = "app.s3")
public class S3Properties {
private String endpoint;
private String region = "eu-east-1";
private String bucket;
private String accessKey;
private String secretKey;
private boolean pathStyle = true;
}
@@ -0,0 +1,40 @@
package org.example.controller;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.example.dto.response.AttachmentResponse;
import org.example.service.AttachmentService;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
import java.util.UUID;
@RestController
@RequiredArgsConstructor
public class AttachmentController {
private final AttachmentService attachmentService;
@PostMapping(
path = "/api/v1/chats/{chat_id}/attachments",
consumes = { MediaType.IMAGE_PNG_VALUE, MediaType.IMAGE_JPEG_VALUE }
)
@ResponseStatus(HttpStatus.CREATED)
public AttachmentResponse uploadAttachment(
@PathVariable("chatId") UUID chatId,
@RequestParam("fileName") String fileName,
@RequestHeader(value = HttpHeaders.CONTENT_TYPE, required = false) String contentType,
HttpServletRequest request
) throws IOException {
return attachmentService.upload(
chatId,
fileName,
contentType,
request.getInputStream()
);
}
}
@@ -0,0 +1,38 @@
package org.example.dto.response;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Builder;
import lombok.Value;
import java.time.Instant;
import java.util.UUID;
@Value
@Builder
public class AttachmentResponse {
UUID id;
@JsonProperty("chat_id")
UUID chatId;
@JsonProperty("uploader_id")
UUID uploaderId;
@JsonProperty("original_filename")
String originalFilename;
@JsonProperty("content_type")
String contentType;
@JsonProperty("size_bytes")
long sizeBytes;
@JsonProperty("checksum_sha256")
String checksumSha256;
Integer width;
Integer height;
@JsonProperty("created_at")
Instant createdAt;
}
@@ -0,0 +1,7 @@
package org.example.exception;
public class BadRequestException extends RuntimeException {
public BadRequestException(String message) {
super(message);
}
}
@@ -0,0 +1,50 @@
package org.example.model;
import jakarta.persistence.*;
import lombok.*;
import org.hibernate.annotations.CreationTimestamp;
import java.time.Instant;
import java.util.UUID;
@Entity
@Table(name = "attachments")
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class Attachment {
@Id
private UUID id;
@Column(name = "chat_id", nullable = false)
private UUID chatId;
@Column(name = "uploader_id", nullable = false)
private UUID uploaderId;
@Column(name = "object_key", nullable = false, length = 512)
private String objectKey;
@Column(name = "original_filename", nullable = false)
private String originalFilename;
@Column(name = "content_type", nullable = false, length = 128)
private String contentType;
@Column(name = "size_bytes", nullable = false)
private long sizeBytes;
@Column(name = "checksum_sha256", nullable = false, length = 64)
private String checksumSha256;
private Integer width;
private Integer height;
@CreationTimestamp
@Column(name = "created_at", nullable = false, updatable = false)
private Instant createdAt;
}
@@ -0,0 +1,19 @@
package org.example.repository;
import org.example.LidoApplication;
import org.example.model.Attachment;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
public interface AttachmentRepository extends JpaRepository<Attachment, UUID> {
Optional<Attachment> findByIdAndChatId(UUID id, UUID chatId);
List<Attachment> findByIdInAndChatId(Collection<UUID> ids, UUID chatId);
boolean existsByIdAndChatId(UUID id, UUID chatId);
}
@@ -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();
}
}
@@ -0,0 +1,61 @@
package org.example.service;
import lombok.RequiredArgsConstructor;
import org.example.config.S3Properties;
import org.springframework.stereotype.Service;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.core.sync.ResponseTransformer;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.DeleteObjectRequest;
import software.amazon.awssdk.services.s3.model.GetObjectAclRequest;
import software.amazon.awssdk.services.s3.model.GetObjectRequest;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
import java.io.InputStream;
import java.io.OutputStream;
@Service
@RequiredArgsConstructor
public class S3StorageService {
private final S3Client s3Client;
private final S3Properties properties;
public void put(
String objectKey,
InputStream in,
long sizeBytes,
String contentType){
PutObjectRequest request = PutObjectRequest.builder()
.bucket(properties.getBucket())
.key(objectKey)
.contentType(contentType)
.contentLength(sizeBytes)
.build();
s3Client.putObject(request, RequestBody.fromInputStream(in, sizeBytes));
}
public void getTo(String objectKey, OutputStream out){
GetObjectRequest request = GetObjectRequest.builder()
.bucket(properties.getBucket())
.key(objectKey)
.build();
s3Client.getObject(request, ResponseTransformer.toOutputStream(out));
}
public InputStream getStream(String objectKey){
GetObjectRequest request = GetObjectRequest.builder()
.bucket(properties.getBucket())
.key(objectKey)
.build();
return s3Client.getObject(request);
}
public void delete(String objectKey){
s3Client.deleteObject(DeleteObjectRequest.builder()
.bucket(properties.getBucket())
.key(objectKey)
.build());
}
}