forked from mtusi2026/mtusi2026lab4
Пунк Е загрузка вложений готово
This commit is contained in:
+3
-3
@@ -1,8 +1,8 @@
|
|||||||
.git
|
.git
|
||||||
.github
|
.github
|
||||||
.env
|
Lido/.env
|
||||||
.env.*
|
Lido/.env
|
||||||
!.env.example
|
!Lido/.env
|
||||||
secrets
|
secrets
|
||||||
certs
|
certs
|
||||||
volumes
|
volumes
|
||||||
|
|||||||
@@ -1,20 +0,0 @@
|
|||||||
# Copy to .env for your LOCAL synthetic test environment; never commit .env.
|
|
||||||
# These are logical interface suggestions; map actual framework names in REPORT.md.
|
|
||||||
APP_HOST=0.0.0.0
|
|
||||||
APP_PORT=8080
|
|
||||||
APP_ENV=lab
|
|
||||||
SESSION_TTL_SECONDS=3600
|
|
||||||
# Choose credentials locally. File paths contain no secret values.
|
|
||||||
DATABASE_URL_FILE=/run/secrets/database_url
|
|
||||||
# Optional on 3, required use on 4 in lab2; Redis OR Valkey:
|
|
||||||
SESSION_STORE=postgres
|
|
||||||
CACHE_URL_FILE=/run/secrets/cache_url
|
|
||||||
API_REPLICAS=2
|
|
||||||
IDEMPOTENCY_TTL_SECONDS=86400
|
|
||||||
S3_ENDPOINT=http://s3:9000
|
|
||||||
S3_REGION=us-east-1
|
|
||||||
S3_BUCKET=messenger-attachments
|
|
||||||
S3_ACCESS_KEY_ID_FILE=/run/secrets/s3_access_key_id
|
|
||||||
S3_SECRET_ACCESS_KEY_FILE=/run/secrets/s3_secret_access_key
|
|
||||||
MAX_UPLOAD_BYTES=10485760
|
|
||||||
MAX_IMAGE_PIXELS=40000000
|
|
||||||
+3
-3
@@ -1,7 +1,7 @@
|
|||||||
# Local/private state
|
# Local/private state
|
||||||
.env
|
Lido/.env
|
||||||
.env.*
|
Lido/.env
|
||||||
!.env.example
|
!Lido/.env
|
||||||
secrets/
|
secrets/
|
||||||
certs/private/
|
certs/private/
|
||||||
*.key
|
*.key
|
||||||
|
|||||||
@@ -0,0 +1,7 @@
|
|||||||
|
MINIO_ROOT_USER=minioadmin
|
||||||
|
MINIO_ROOT_PASSWORD=minioadmin_change_me
|
||||||
|
S3_ENDPOINT=http://minio:9000
|
||||||
|
S3_BUCKET=messenger-attachments
|
||||||
|
S3_ACCESS_KEY=minioadmin
|
||||||
|
S3_SECRET_KEY=minioadmin_change_me
|
||||||
|
S3_REGION=eu-east-1
|
||||||
@@ -57,6 +57,11 @@ services:
|
|||||||
SPRING_DATA_REDIS_PORT: "6379"
|
SPRING_DATA_REDIS_PORT: "6379"
|
||||||
SESSION_TTL_SECONDS: "604800"
|
SESSION_TTL_SECONDS: "604800"
|
||||||
SERVER_SHUTDOWN: graceful
|
SERVER_SHUTDOWN: graceful
|
||||||
|
S3_ENDPOINT: http://minio:9000
|
||||||
|
S3_BUCKET: ${S3_BUCKET:-messenger-attachments}
|
||||||
|
S3_ACCESS_KEY: ${S3_ACCESS_KEY}
|
||||||
|
S3_SECRET_KEY: ${S3_SECRET_KEY}
|
||||||
|
S3_REGION: eu-east-1
|
||||||
deploy:
|
deploy:
|
||||||
replicas: 3
|
replicas: 3
|
||||||
healthcheck:
|
healthcheck:
|
||||||
@@ -78,6 +83,23 @@ services:
|
|||||||
- api
|
- api
|
||||||
networks: [ messenger ]
|
networks: [ messenger ]
|
||||||
|
|
||||||
|
minio:
|
||||||
|
image: bitnamilegacy/minio:latest
|
||||||
|
environment:
|
||||||
|
MINIO_ROOT_USER: ${MINIO_ROOT_USER}
|
||||||
|
MINIO_ROOT_PASSWORD: ${MINIO_ROOT_PASSWORD}
|
||||||
|
volumes:
|
||||||
|
- minio_data:/bitnami/minio/data
|
||||||
|
ports:
|
||||||
|
- "127.0.0.1:9000:9000"
|
||||||
|
- "127.0.0.1:9001:9001"
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "curl", "-f", "http://localhost:9000/minio/health/live"]
|
||||||
|
interval: 5s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 5
|
||||||
|
networks: [ messenger ]
|
||||||
|
|
||||||
migrate:
|
migrate:
|
||||||
build: .
|
build: .
|
||||||
environment:
|
environment:
|
||||||
@@ -96,9 +118,27 @@ services:
|
|||||||
db:
|
db:
|
||||||
condition: service_healthy
|
condition: service_healthy
|
||||||
|
|
||||||
|
|
||||||
|
minio-init:
|
||||||
|
image: bitnamilegacy/minio:latest
|
||||||
|
depends_on:
|
||||||
|
minio:
|
||||||
|
condition: service_started
|
||||||
|
env_file: .env
|
||||||
|
entrypoint: >
|
||||||
|
/bin/sh -c "
|
||||||
|
sleep 3;
|
||||||
|
mc alias set local http://minio:9000 $${MINIO_ROOT_USER} $${MINIO_ROOT_PASSWORD};
|
||||||
|
mc mb --ignore-existing local/$${S3_BUCKET:-messenger-attachments};
|
||||||
|
mc anonymous set none local/$${S3_BUCKET:-messenger-attachments};
|
||||||
|
echo bucket-ready
|
||||||
|
"
|
||||||
|
networks: [ messenger ]
|
||||||
|
restart: "no"
|
||||||
volumes:
|
volumes:
|
||||||
messenger_pg_data:
|
messenger_pg_data:
|
||||||
lido_redis_data:
|
lido_redis_data:
|
||||||
|
minio_data:
|
||||||
|
|
||||||
networks:
|
networks:
|
||||||
messenger:
|
messenger:
|
||||||
@@ -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());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -5,6 +5,10 @@ spring:
|
|||||||
fail-on-unknown-properties: true
|
fail-on-unknown-properties: true
|
||||||
lifecycle:
|
lifecycle:
|
||||||
timeout-per-shutdown-phase: 20s
|
timeout-per-shutdown-phase: 20s
|
||||||
|
servlet:
|
||||||
|
multipart:
|
||||||
|
max-file-size: 10MB
|
||||||
|
max-request-size: 12MB
|
||||||
|
|
||||||
spring:
|
spring:
|
||||||
datasource:
|
datasource:
|
||||||
@@ -46,6 +50,13 @@ server:
|
|||||||
|
|
||||||
app:
|
app:
|
||||||
session-ttl-seconds: ${SESSION_TTL_SECONDS:604800}
|
session-ttl-seconds: ${SESSION_TTL_SECONDS:604800}
|
||||||
|
s3:
|
||||||
|
endpoint: ${S3_ENDPOINT:http://minio:9000}
|
||||||
|
region: ${S3_REGION:eu-east-1}
|
||||||
|
bucket: ${S3_BUCKET:messenger-attachments}
|
||||||
|
access-key: ${S3_ACCESS_KEY}
|
||||||
|
secret-key: ${S3_SECRET_KEY}
|
||||||
|
path-style: true
|
||||||
|
|
||||||
logging:
|
logging:
|
||||||
pattern:
|
pattern:
|
||||||
|
|||||||
@@ -0,0 +1,17 @@
|
|||||||
|
CREATE TABLE attachments (
|
||||||
|
id UUID PRIMARY KEY,
|
||||||
|
chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
|
||||||
|
uploader_id UUID NOT NULL REFERENCES users(id),
|
||||||
|
object_key VARCHAR(512) NOT NULL,
|
||||||
|
original_filename VARCHAR(255) NOT NULL,
|
||||||
|
content_type VARCHAR(128) NOT NULL,
|
||||||
|
size_bytes BIGINT NOT NULL CHECK (size_bytes > 0),
|
||||||
|
checksum_sha256 CHAR(64) NOT NULL,
|
||||||
|
width INT,
|
||||||
|
height INT,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
|
CONSTRAINT uq_attachments_object_key UNIQUE (object_key)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX idx_attachments_chat_id ON attachments (chat_id);
|
||||||
|
CREATE INDEX idx_attachments_uploader_id ON attachments (uploader_id);
|
||||||
Reference in New Issue
Block a user