forked from mtusi2026/mtusi2026lab4
на 3 готово
This commit is contained in:
@@ -2,6 +2,7 @@ package org.example.controller;
|
|||||||
|
|
||||||
|
|
||||||
import jakarta.servlet.http.HttpServletRequest;
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
|
import jakarta.servlet.http.HttpServletResponse;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import org.example.dto.response.AttachmentResponse;
|
import org.example.dto.response.AttachmentResponse;
|
||||||
import org.example.service.AttachmentService;
|
import org.example.service.AttachmentService;
|
||||||
@@ -25,8 +26,8 @@ public class AttachmentController {
|
|||||||
)
|
)
|
||||||
@ResponseStatus(HttpStatus.CREATED)
|
@ResponseStatus(HttpStatus.CREATED)
|
||||||
public AttachmentResponse uploadAttachment(
|
public AttachmentResponse uploadAttachment(
|
||||||
@PathVariable("chatId") UUID chatId,
|
@PathVariable("chat_id") UUID chatId,
|
||||||
@RequestParam("fileName") String fileName,
|
@RequestParam("filename") String fileName,
|
||||||
@RequestHeader(value = HttpHeaders.CONTENT_TYPE, required = false) String contentType,
|
@RequestHeader(value = HttpHeaders.CONTENT_TYPE, required = false) String contentType,
|
||||||
HttpServletRequest request
|
HttpServletRequest request
|
||||||
) throws IOException {
|
) throws IOException {
|
||||||
@@ -37,4 +38,18 @@ public class AttachmentController {
|
|||||||
request.getInputStream()
|
request.getInputStream()
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@GetMapping("/api/v1/attachments/{attachment_id}")
|
||||||
|
public AttachmentResponse getAttachment(
|
||||||
|
@PathVariable("attachment_id") UUID attachmentId) {
|
||||||
|
return attachmentService.getMeta(attachmentId);
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/api/v1/attachments/{attachment_id}/content")
|
||||||
|
public void downloadAttachment(
|
||||||
|
@PathVariable("attachment_id") UUID attachmentId,
|
||||||
|
@RequestParam(value = "variant", defaultValue = "original") String variant,
|
||||||
|
HttpServletResponse response) throws IOException {
|
||||||
|
attachmentService.writeContent(attachmentId, variant, response);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
package org.example.dto.create;
|
package org.example.dto.create;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||||
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
||||||
import jakarta.validation.constraints.NotBlank;
|
import jakarta.validation.constraints.NotBlank;
|
||||||
import jakarta.validation.constraints.Size;
|
import jakarta.validation.constraints.Size;
|
||||||
@@ -7,10 +8,16 @@ import lombok.Data;
|
|||||||
import org.example.config.CodePointSize;
|
import org.example.config.CodePointSize;
|
||||||
import org.example.config.StrictStringDeserializer;
|
import org.example.config.StrictStringDeserializer;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
@Data
|
@Data
|
||||||
public class CreateMessageDto {
|
public class CreateMessageDto {
|
||||||
@NotBlank(message = "Текст сообщения не может быть пустым")
|
|
||||||
@CodePointSize(min = 1, max = 4000)
|
@CodePointSize(min = 0, max = 4000)
|
||||||
@JsonDeserialize(using = StrictStringDeserializer.class)
|
@JsonDeserialize(using = StrictStringDeserializer.class)
|
||||||
private String text;
|
private String text;
|
||||||
|
|
||||||
|
@JsonProperty("attachment_ids")
|
||||||
|
private List<UUID> attachmentIds;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,21 +5,26 @@ import lombok.Builder;
|
|||||||
import lombok.Value;
|
import lombok.Value;
|
||||||
|
|
||||||
import java.time.Instant;
|
import java.time.Instant;
|
||||||
|
import java.util.List;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
|
|
||||||
|
import org.example.model.VariantResponse;
|
||||||
|
|
||||||
@Value
|
@Value
|
||||||
@Builder
|
@Builder
|
||||||
public class AttachmentResponse {
|
public class AttachmentResponse {
|
||||||
|
|
||||||
|
@JsonProperty("id")
|
||||||
UUID id;
|
UUID id;
|
||||||
|
|
||||||
@JsonProperty("chat_id")
|
@JsonProperty("chat_id")
|
||||||
UUID chatId;
|
UUID chatId;
|
||||||
|
|
||||||
@JsonProperty("uploader_id")
|
@JsonProperty("owner_id")
|
||||||
UUID uploaderId;
|
UUID ownerId;
|
||||||
|
|
||||||
@JsonProperty("original_filename")
|
@JsonProperty("filename")
|
||||||
String originalFilename;
|
String filename;
|
||||||
|
|
||||||
@JsonProperty("content_type")
|
@JsonProperty("content_type")
|
||||||
String contentType;
|
String contentType;
|
||||||
@@ -27,12 +32,21 @@ public class AttachmentResponse {
|
|||||||
@JsonProperty("size_bytes")
|
@JsonProperty("size_bytes")
|
||||||
long sizeBytes;
|
long sizeBytes;
|
||||||
|
|
||||||
@JsonProperty("checksum_sha256")
|
@JsonProperty("sha256")
|
||||||
String checksumSha256;
|
String sha256;
|
||||||
|
|
||||||
Integer width;
|
@JsonProperty("status")
|
||||||
Integer height;
|
String status;
|
||||||
|
|
||||||
|
@JsonProperty("variants")
|
||||||
|
List<VariantResponse> variants;
|
||||||
|
|
||||||
|
@JsonProperty("error_code")
|
||||||
|
String errorCode;
|
||||||
|
|
||||||
@JsonProperty("created_at")
|
@JsonProperty("created_at")
|
||||||
Instant createdAt;
|
Instant createdAt;
|
||||||
|
|
||||||
|
@JsonProperty("updated_at")
|
||||||
|
Instant updatedAt;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import lombok.Data;
|
|||||||
import lombok.NoArgsConstructor;
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
import java.time.Instant;
|
import java.time.Instant;
|
||||||
|
import java.util.List;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
|
|
||||||
@Data
|
@Data
|
||||||
@@ -20,6 +21,8 @@ public class MessageResponse {
|
|||||||
@JsonProperty("sender_id")
|
@JsonProperty("sender_id")
|
||||||
private UUID senderId;
|
private UUID senderId;
|
||||||
private String text;
|
private String text;
|
||||||
|
@JsonProperty("attachment_ids")
|
||||||
|
List<UUID> attachmentIds;
|
||||||
@JsonProperty("created_at")
|
@JsonProperty("created_at")
|
||||||
private Instant createdAt;
|
private Instant createdAt;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -73,6 +73,22 @@ public class GlobalExceptionHandler {
|
|||||||
.body(body);
|
.body(body);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ExceptionHandler(BadRequestException.class)
|
||||||
|
public ResponseEntity<?> handleBadRequest(BadRequestException ex, HttpServletRequest request) {
|
||||||
|
String requestId = resolveRequestId(request); // как у вас в других handler
|
||||||
|
Map<String, Object> body = Map.of(
|
||||||
|
"error", Map.of(
|
||||||
|
"code", "invalid_request",
|
||||||
|
"message", ex.getMessage() != null ? ex.getMessage() : "Bad request",
|
||||||
|
"request_id", requestId
|
||||||
|
)
|
||||||
|
);
|
||||||
|
return ResponseEntity
|
||||||
|
.status(HttpStatus.BAD_REQUEST)
|
||||||
|
.header("X-Request-Id", requestId)
|
||||||
|
.body(body);
|
||||||
|
}
|
||||||
|
|
||||||
@ExceptionHandler(MethodArgumentNotValidException.class)
|
@ExceptionHandler(MethodArgumentNotValidException.class)
|
||||||
public ResponseEntity<ErrorResponse> handleValidationException(
|
public ResponseEntity<ErrorResponse> handleValidationException(
|
||||||
MethodArgumentNotValidException ex,
|
MethodArgumentNotValidException ex,
|
||||||
|
|||||||
@@ -1,10 +1,12 @@
|
|||||||
package org.example.model;
|
package org.example.model;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||||
import jakarta.persistence.*;
|
import jakarta.persistence.*;
|
||||||
import lombok.*;
|
import lombok.*;
|
||||||
import org.hibernate.annotations.CreationTimestamp;
|
import org.hibernate.annotations.CreationTimestamp;
|
||||||
|
|
||||||
import java.time.Instant;
|
import java.time.Instant;
|
||||||
|
import java.util.List;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
|
|
||||||
@Entity
|
@Entity
|
||||||
@@ -19,32 +21,50 @@ public class Attachment {
|
|||||||
@Id
|
@Id
|
||||||
private UUID id;
|
private UUID id;
|
||||||
|
|
||||||
@Column(name = "chat_id", nullable = false)
|
@Column(name = "chat_id")
|
||||||
|
@JsonProperty("chat_id")
|
||||||
private UUID chatId;
|
private UUID chatId;
|
||||||
|
|
||||||
@Column(name = "uploader_id", nullable = false)
|
@Column(name = "uploader_id")
|
||||||
private UUID uploaderId;
|
@JsonProperty("owner_id")
|
||||||
|
private UUID ownerId;
|
||||||
|
|
||||||
@Column(name = "object_key", nullable = false, length = 512)
|
@Column(name = "original_filename")
|
||||||
private String objectKey;
|
@JsonProperty("filename")
|
||||||
|
private String filename;
|
||||||
|
|
||||||
@Column(name = "original_filename", nullable = false)
|
@Column(name = "content_type")
|
||||||
private String originalFilename;
|
@JsonProperty("content_type")
|
||||||
|
|
||||||
@Column(name = "content_type", nullable = false, length = 128)
|
|
||||||
private String contentType;
|
private String contentType;
|
||||||
|
|
||||||
@Column(name = "size_bytes", nullable = false)
|
@Column(name = "size_bytes")
|
||||||
|
@JsonProperty("size_bytes")
|
||||||
private long sizeBytes;
|
private long sizeBytes;
|
||||||
|
|
||||||
@Column(name = "checksum_sha256", nullable = false, length = 64)
|
@Column(name = "checksum_sha256")
|
||||||
private String checksumSha256;
|
@JsonProperty("sha256")
|
||||||
|
private String sha256;
|
||||||
|
|
||||||
private Integer width;
|
@Column(name = "status")
|
||||||
|
@JsonProperty("status")
|
||||||
|
private String status;
|
||||||
|
|
||||||
private Integer height;
|
@Transient
|
||||||
|
@JsonProperty("variants")
|
||||||
|
private List<VariantResponse> variants;
|
||||||
|
|
||||||
@CreationTimestamp
|
@Column(name = "error_code")
|
||||||
@Column(name = "created_at", nullable = false, updatable = false)
|
@JsonProperty("error_code")
|
||||||
|
private String errorCode;
|
||||||
|
|
||||||
|
@Column(name = "created_at")
|
||||||
|
@JsonProperty("created_at")
|
||||||
private Instant createdAt;
|
private Instant createdAt;
|
||||||
|
|
||||||
|
@Column(name = "updated_at")
|
||||||
|
@JsonProperty("updated_at")
|
||||||
|
private Instant updatedAt;
|
||||||
|
|
||||||
|
@Column(name = "object_key")
|
||||||
|
private String objectKey;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import org.hibernate.annotations.CreationTimestamp;
|
|||||||
|
|
||||||
import java.time.Instant;
|
import java.time.Instant;
|
||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
||||||
|
import java.util.List;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
|
|
||||||
@Entity
|
@Entity
|
||||||
@@ -35,6 +36,10 @@ public class Message {
|
|||||||
@Column(nullable = false, columnDefinition = "TEXT")
|
@Column(nullable = false, columnDefinition = "TEXT")
|
||||||
private String text;
|
private String text;
|
||||||
|
|
||||||
|
@Transient
|
||||||
|
@JsonProperty("attachment_ids")
|
||||||
|
private List<UUID> attachmentIds;
|
||||||
|
|
||||||
@CreationTimestamp
|
@CreationTimestamp
|
||||||
@Column(name = "created_at", nullable = false, updatable = false)
|
@Column(name = "created_at", nullable = false, updatable = false)
|
||||||
@JsonProperty("created_at")
|
@JsonProperty("created_at")
|
||||||
|
|||||||
@@ -0,0 +1,35 @@
|
|||||||
|
package org.example.model;
|
||||||
|
|
||||||
|
|
||||||
|
import jakarta.persistence.*;
|
||||||
|
import lombok.*;
|
||||||
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
|
|
||||||
|
import java.io.Serializable;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
@Entity
|
||||||
|
@Table(name = "message_attachments")
|
||||||
|
@Getter
|
||||||
|
@Setter
|
||||||
|
@AllArgsConstructor
|
||||||
|
@NoArgsConstructor
|
||||||
|
@Builder
|
||||||
|
@IdClass(MessageAttachment.PK.class)
|
||||||
|
public class MessageAttachment {
|
||||||
|
|
||||||
|
@Id
|
||||||
|
@Column(name = "message_id", nullable = false)
|
||||||
|
private UUID messageId;
|
||||||
|
|
||||||
|
@Column(name = "attachment_id", nullable = false)
|
||||||
|
private UUID attachmentId;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
public static class PK implements Serializable {
|
||||||
|
private UUID messageId;
|
||||||
|
private UUID attachmentId;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
package org.example.model;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Builder;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@Builder
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
public class VariantResponse {
|
||||||
|
|
||||||
|
@JsonProperty("name")
|
||||||
|
String name;
|
||||||
|
|
||||||
|
@JsonProperty("content_type")
|
||||||
|
String contentType;
|
||||||
|
|
||||||
|
@JsonProperty("size_bytes")
|
||||||
|
long sizeBytes;
|
||||||
|
|
||||||
|
@JsonProperty("width")
|
||||||
|
int width;
|
||||||
|
|
||||||
|
@JsonProperty("height")
|
||||||
|
int height;
|
||||||
|
|
||||||
|
@JsonProperty("sha256")
|
||||||
|
String sha256;
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
package org.example.repository;
|
||||||
|
|
||||||
|
import org.example.model.MessageAttachment;
|
||||||
|
import org.springframework.data.jpa.repository.JpaRepository;
|
||||||
|
|
||||||
|
import java.util.Collection;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
public interface MessageAttachmentRepository extends JpaRepository<MessageAttachment, MessageAttachment.PK> {
|
||||||
|
|
||||||
|
List<MessageAttachment> findByMessageId(UUID messageId);
|
||||||
|
|
||||||
|
List<MessageAttachment> findByMessageIdIn(Collection<UUID> messageIds);
|
||||||
|
}
|
||||||
@@ -1,19 +1,23 @@
|
|||||||
package org.example.service;
|
package org.example.service;
|
||||||
|
|
||||||
|
import jakarta.servlet.http.HttpServletResponse;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import org.example.config.ImageUploadValidator;
|
import org.example.config.ImageUploadValidator;
|
||||||
import org.example.dto.response.AttachmentResponse;
|
import org.example.dto.response.AttachmentResponse;
|
||||||
|
import org.example.exception.BadRequestException;
|
||||||
import org.example.exception.NotFoundException;
|
import org.example.exception.NotFoundException;
|
||||||
import org.example.model.Attachment;
|
import org.example.model.Attachment;
|
||||||
import org.example.model.User;
|
import org.example.model.User;
|
||||||
import org.example.repository.AttachmentRepository;
|
import org.example.repository.AttachmentRepository;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
import org.springframework.transaction.annotation.Transactional;
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
import org.springframework.web.multipart.MultipartFile;
|
|
||||||
|
|
||||||
import java.io.ByteArrayInputStream;
|
import java.io.ByteArrayInputStream;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.io.InputStream;
|
import java.io.InputStream;
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.util.List;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
|
|
||||||
@Service
|
@Service
|
||||||
@@ -51,14 +55,17 @@ public class AttachmentService {
|
|||||||
Attachment saved = attachmentRepository.save(Attachment.builder()
|
Attachment saved = attachmentRepository.save(Attachment.builder()
|
||||||
.id(id)
|
.id(id)
|
||||||
.chatId(chatId)
|
.chatId(chatId)
|
||||||
.uploaderId(user.getId())
|
.ownerId(user.getId())
|
||||||
.objectKey(objectKey)
|
.objectKey(objectKey)
|
||||||
.originalFilename(img.safeFilename())
|
.filename(img.safeFilename())
|
||||||
.contentType(img.contentType())
|
.contentType(img.contentType())
|
||||||
.sizeBytes(img.bytes().length)
|
.sizeBytes(img.bytes().length)
|
||||||
.checksumSha256(img.sha256Hex())
|
.sha256(img.sha256Hex())
|
||||||
.width(img.width())
|
.status("ready")
|
||||||
.height(img.height())
|
.errorCode(null)
|
||||||
|
.variants(List.of())
|
||||||
|
.createdAt(Instant.now())
|
||||||
|
.updatedAt(Instant.now())
|
||||||
.build());
|
.build());
|
||||||
|
|
||||||
return toResponse(saved);
|
return toResponse(saved);
|
||||||
@@ -72,19 +79,47 @@ public class AttachmentService {
|
|||||||
return attachment;
|
return attachment;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Transactional(readOnly = true)
|
||||||
|
public AttachmentResponse getMeta(UUID attachmentId){
|
||||||
|
return toResponse(getForMember(attachmentId));
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@Transactional(readOnly = true)
|
||||||
|
public void writeContent(UUID attachmentId,
|
||||||
|
String variant,
|
||||||
|
HttpServletResponse response) throws IOException {
|
||||||
|
if (variant != null && !variant.isBlank() && !"original".equals(variant)){
|
||||||
|
throw new BadRequestException("Unsupported variant");
|
||||||
|
}
|
||||||
|
|
||||||
|
Attachment attachment = getForMember(attachmentId);
|
||||||
|
response.setStatus(HttpStatus.OK.value());
|
||||||
|
response.setContentType(attachment.getContentType());
|
||||||
|
response.setContentLengthLong(attachment.getSizeBytes());
|
||||||
|
s3StorageService.getTo(attachment.getObjectKey(),
|
||||||
|
response.getOutputStream());
|
||||||
|
response.flushBuffer();
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
static AttachmentResponse toResponse(Attachment a) {
|
static AttachmentResponse toResponse(Attachment a) {
|
||||||
return AttachmentResponse.builder()
|
return AttachmentResponse.builder()
|
||||||
.id(a.getId())
|
.id(a.getId())
|
||||||
.chatId(a.getChatId())
|
.chatId(a.getChatId())
|
||||||
.uploaderId(a.getUploaderId())
|
.ownerId(a.getOwnerId())
|
||||||
.originalFilename(a.getOriginalFilename())
|
.filename(a.getFilename())
|
||||||
.contentType(a.getContentType())
|
.contentType(a.getContentType())
|
||||||
.sizeBytes(a.getSizeBytes())
|
.sizeBytes(a.getSizeBytes())
|
||||||
.checksumSha256(a.getChecksumSha256())
|
.sha256(a.getSha256())
|
||||||
.width(a.getWidth())
|
.status(a.getStatus())
|
||||||
.height(a.getHeight())
|
.variants(a.getVariants() == null ? List.of() : a.getVariants())
|
||||||
|
.errorCode(a.getErrorCode())
|
||||||
.createdAt(a.getCreatedAt())
|
.createdAt(a.getCreatedAt())
|
||||||
|
.updatedAt(a.getUpdatedAt())
|
||||||
.build();
|
.build();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -4,13 +4,16 @@ package org.example.service;
|
|||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import org.example.model.IdempotencyKey;
|
import org.example.model.IdempotencyKey;
|
||||||
import org.example.model.Message;
|
import org.example.model.Message;
|
||||||
|
import org.example.model.MessageAttachment;
|
||||||
import org.example.repository.IdempotencyKeyRepository;
|
import org.example.repository.IdempotencyKeyRepository;
|
||||||
|
import org.example.repository.MessageAttachmentRepository;
|
||||||
import org.example.repository.MessageRepository;
|
import org.example.repository.MessageRepository;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
import org.springframework.transaction.annotation.Propagation;
|
import org.springframework.transaction.annotation.Propagation;
|
||||||
import org.springframework.transaction.annotation.Transactional;
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
import java.time.Instant;
|
import java.time.Instant;
|
||||||
|
import java.util.List;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
|
|
||||||
@Service
|
@Service
|
||||||
@@ -19,12 +22,14 @@ public class MessageIdempotencyWriter {
|
|||||||
|
|
||||||
private final MessageRepository messageRepository;
|
private final MessageRepository messageRepository;
|
||||||
private final IdempotencyKeyRepository idempotencyKeyRepository;
|
private final IdempotencyKeyRepository idempotencyKeyRepository;
|
||||||
|
private final MessageAttachmentRepository messageAttachmentRepository;
|
||||||
|
|
||||||
@Transactional(propagation = Propagation.REQUIRES_NEW)
|
@Transactional(propagation = Propagation.REQUIRES_NEW)
|
||||||
public Message insertNew(
|
public Message insertNew(
|
||||||
UUID chatId,
|
UUID chatId,
|
||||||
UUID senderId,
|
UUID senderId,
|
||||||
String text,
|
String text,
|
||||||
|
List<UUID> attachmentIds,
|
||||||
String key,
|
String key,
|
||||||
String hash) {
|
String hash) {
|
||||||
|
|
||||||
@@ -37,6 +42,17 @@ public class MessageIdempotencyWriter {
|
|||||||
.build()
|
.build()
|
||||||
);
|
);
|
||||||
|
|
||||||
|
if (attachmentIds != null){
|
||||||
|
for(UUID attId : attachmentIds){
|
||||||
|
messageAttachmentRepository.save(
|
||||||
|
MessageAttachment.builder()
|
||||||
|
.messageId(message.getId())
|
||||||
|
.attachmentId(attId)
|
||||||
|
.build()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
idempotencyKeyRepository.saveAndFlush(
|
idempotencyKeyRepository.saveAndFlush(
|
||||||
IdempotencyKey.builder()
|
IdempotencyKey.builder()
|
||||||
.userId(senderId)
|
.userId(senderId)
|
||||||
|
|||||||
@@ -4,12 +4,17 @@ import lombok.RequiredArgsConstructor;
|
|||||||
import org.example.dto.MessagePage;
|
import org.example.dto.MessagePage;
|
||||||
import org.example.dto.create.CreateMessageDto;
|
import org.example.dto.create.CreateMessageDto;
|
||||||
import org.example.dto.update.UpdateMessageDto;
|
import org.example.dto.update.UpdateMessageDto;
|
||||||
|
import org.example.exception.BadRequestException;
|
||||||
import org.example.exception.ConflictException;
|
import org.example.exception.ConflictException;
|
||||||
import org.example.exception.ForbiddenException;
|
import org.example.exception.ForbiddenException;
|
||||||
import org.example.exception.NotFoundException;
|
import org.example.exception.NotFoundException;
|
||||||
|
import org.example.model.Attachment;
|
||||||
import org.example.model.IdempotencyKey;
|
import org.example.model.IdempotencyKey;
|
||||||
import org.example.model.Message;
|
import org.example.model.Message;
|
||||||
|
import org.example.model.MessageAttachment;
|
||||||
|
import org.example.repository.AttachmentRepository;
|
||||||
import org.example.repository.IdempotencyKeyRepository;
|
import org.example.repository.IdempotencyKeyRepository;
|
||||||
|
import org.example.repository.MessageAttachmentRepository;
|
||||||
import org.example.repository.MessageRepository;
|
import org.example.repository.MessageRepository;
|
||||||
import org.springframework.dao.DataIntegrityViolationException;
|
import org.springframework.dao.DataIntegrityViolationException;
|
||||||
import org.springframework.data.domain.PageRequest;
|
import org.springframework.data.domain.PageRequest;
|
||||||
@@ -18,9 +23,8 @@ import org.springframework.stereotype.Service;
|
|||||||
import org.springframework.transaction.annotation.Transactional;
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
import java.time.Instant;
|
import java.time.Instant;
|
||||||
import java.util.List;
|
import java.util.*;
|
||||||
import java.util.Optional;
|
import java.util.stream.Collectors;
|
||||||
import java.util.UUID;
|
|
||||||
|
|
||||||
import static org.example.config.TokenHasher.sha256;
|
import static org.example.config.TokenHasher.sha256;
|
||||||
|
|
||||||
@@ -32,8 +36,10 @@ public class MessageService {
|
|||||||
private final IdempotencyKeyRepository idempotencyKeyRepository;
|
private final IdempotencyKeyRepository idempotencyKeyRepository;
|
||||||
private final ChatService chatService;
|
private final ChatService chatService;
|
||||||
private final MessageIdempotencyWriter writer;
|
private final MessageIdempotencyWriter writer;
|
||||||
|
private final AttachmentRepository attachmentRepository;
|
||||||
|
private final MessageAttachmentRepository messageAttachmentRepository;
|
||||||
|
|
||||||
@Transactional(readOnly = true) // или без write на этом уровне
|
@Transactional
|
||||||
public Message sendMessage(
|
public Message sendMessage(
|
||||||
UUID chatId,
|
UUID chatId,
|
||||||
UUID senderId,
|
UUID senderId,
|
||||||
@@ -45,8 +51,30 @@ public class MessageService {
|
|||||||
throw new ForbiddenException("Пользователь не является участником чата");
|
throw new ForbiddenException("Пользователь не является участником чата");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
String text = messageObject.getText() == null ? "" : messageObject.getText();
|
||||||
|
|
||||||
|
List<UUID> attIds = messageObject.getAttachmentIds() == null
|
||||||
|
? List.of()
|
||||||
|
: messageObject.getAttachmentIds().stream().distinct().toList();
|
||||||
|
|
||||||
|
if (text.isBlank() && attIds.isEmpty()) {
|
||||||
|
throw new BadRequestException("text or attachment_ids required");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!attIds.isEmpty()) {
|
||||||
|
List<Attachment> found = attachmentRepository.findByIdInAndChatId(attIds, chatId);
|
||||||
|
if (found.size() != attIds.size()) {
|
||||||
|
throw new BadRequestException("Invalid attachment_ids");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
String key = idempotencyKey.trim();
|
String key = idempotencyKey.trim();
|
||||||
String hash = sha256(messageObject.getText());
|
String hash = sha256(
|
||||||
|
text + "\n" + attIds.stream()
|
||||||
|
.map(UUID::toString)
|
||||||
|
.sorted()
|
||||||
|
.collect(Collectors.joining(","))
|
||||||
|
);
|
||||||
|
|
||||||
Optional<IdempotencyKey> exists =
|
Optional<IdempotencyKey> exists =
|
||||||
idempotencyKeyRepository.findByUserIdAndChatIdAndIdempotencyKey(senderId, chatId, key);
|
idempotencyKeyRepository.findByUserIdAndChatIdAndIdempotencyKey(senderId, chatId, key);
|
||||||
@@ -56,7 +84,9 @@ public class MessageService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
return writer.insertNew(chatId, senderId, messageObject.getText(), key, hash);
|
Message message = writer.insertNew(chatId, senderId, text, attIds, key, hash);
|
||||||
|
message.setAttachmentIds(attIds);
|
||||||
|
return message;
|
||||||
} catch (DataIntegrityViolationException e) {
|
} catch (DataIntegrityViolationException e) {
|
||||||
IdempotencyKey rec = idempotencyKeyRepository
|
IdempotencyKey rec = idempotencyKeyRepository
|
||||||
.findByUserIdAndChatIdAndIdempotencyKey(senderId, chatId, key)
|
.findByUserIdAndChatIdAndIdempotencyKey(senderId, chatId, key)
|
||||||
@@ -69,8 +99,15 @@ public class MessageService {
|
|||||||
if (!row.getRequestHash().equals(hash)) {
|
if (!row.getRequestHash().equals(hash)) {
|
||||||
throw new ConflictException("Idempotency key conflict");
|
throw new ConflictException("Idempotency key conflict");
|
||||||
}
|
}
|
||||||
return messageRepository.findById(row.getMessageId())
|
Message message = messageRepository.findById(row.getMessageId())
|
||||||
.orElseThrow(() -> new IllegalStateException("idempotency message missing"));
|
.orElseThrow(() -> new IllegalStateException("idempotency message missing"));
|
||||||
|
|
||||||
|
List<UUID> ids = messageAttachmentRepository.findByMessageId(message.getId())
|
||||||
|
.stream()
|
||||||
|
.map(MessageAttachment::getAttachmentId)
|
||||||
|
.toList();
|
||||||
|
message.setAttachmentIds(ids);
|
||||||
|
return message;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Transactional(readOnly = true)
|
@Transactional(readOnly = true)
|
||||||
@@ -124,6 +161,25 @@ public class MessageService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (!items.isEmpty()) {
|
||||||
|
List<UUID> msgIds = items.stream().map(Message::getId).toList();
|
||||||
|
List<MessageAttachment> links =
|
||||||
|
messageAttachmentRepository.findByMessageIdIn(msgIds);
|
||||||
|
|
||||||
|
Map<UUID, List<UUID>> byMsg = new HashMap<>();
|
||||||
|
for (MessageAttachment link : links) {
|
||||||
|
byMsg.computeIfAbsent(link.getMessageId(), k -> new ArrayList<>())
|
||||||
|
.add(link.getAttachmentId());
|
||||||
|
}
|
||||||
|
for (Message m : items) {
|
||||||
|
m.setAttachmentIds(byMsg.getOrDefault(m.getId(), List.of()));
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
for (Message m : items) {
|
||||||
|
m.setAttachmentIds(List.of());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return new MessagePage(items, nextCursor);
|
return new MessagePage(items, nextCursor);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,2 @@
|
|||||||
|
ALTER TABLE messages
|
||||||
|
DROP CONSTRAINT IF EXISTS chk_messages_text_nonempty;
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
CREATE TABLE message_attachments (
|
||||||
|
message_id UUID NOT NULL REFERENCES messages(id) ON DELETE CASCADE,
|
||||||
|
attachment_id UUID NOT NULL REFERENCES attachments(id) ON DELETE RESTRICT,
|
||||||
|
PRIMARY KEY (message_id, attachment_id)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX idx_message_attachments_attachment
|
||||||
|
ON message_attachments (attachment_id);
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
ALTER TABLE attachments
|
||||||
|
ADD COLUMN IF NOT EXISTS status VARCHAR(32) NOT NULL DEFAULT 'ready',
|
||||||
|
ADD COLUMN IF NOT EXISTS error_code VARCHAR(64),
|
||||||
|
ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ NOT NULL DEFAULT now();
|
||||||
Reference in New Issue
Block a user