Add photo attachments to chat messages
- message_attachments table (cascade with messages); files stored under
chat/{chatId}/ in the images bucket
- POST /api/v1/chats/{chatId}/messages (multipart, up to 10 photos + text);
message is broadcast over WebSocket as before
- photos are always re-encoded so EXIF (geotag, device) never reaches storage
- presigned links (6h) only in participant-checked responses, refresh via
GET /api/v1/chats/{chatId}/attachments/{id}/url
- public /api/v1/files no longer serves or deletes chat/ keys
- chat deletion removes files; orphan cleanup keeps referenced attachments
- rate limit chat-photo: 60/hour
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -6,12 +6,14 @@ import com.krylov.refound.dto.StartChatRequest;
|
||||
import com.krylov.refound.service.ChatService;
|
||||
import com.krylov.refound.service.UserService;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.data.web.PageableDefault;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
@@ -22,6 +24,7 @@ import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
@Slf4j
|
||||
@RestController
|
||||
@@ -65,6 +68,27 @@ public class ChatController {
|
||||
return chatService.getMessages(chatId, currentUserId, pageable);
|
||||
}
|
||||
|
||||
/**
|
||||
* Сообщение с фото (до 10) и необязательным текстом. Текстовые сообщения
|
||||
* по-прежнему идут через WebSocket; это сообщение тоже разошлётся по
|
||||
* /topic/chat/{chatId}, а отправителю вернётся в ответе.
|
||||
*/
|
||||
@PostMapping(value = "/{chatId}/messages", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
|
||||
public MessageDto sendMessageWithPhotos(@PathVariable Long chatId,
|
||||
@RequestParam(value = "content", required = false) String content,
|
||||
@RequestParam(value = "files", required = false) List<MultipartFile> files, Authentication auth) {
|
||||
Long currentUserId = extractUserId(auth);
|
||||
log.info("sendMessageWithPhotos chatId {} by user {}, files {}", chatId, currentUserId, files == null ? 0 : files.size());
|
||||
return chatService.sendMessageWithPhotos(currentUserId, chatId, content, files);
|
||||
}
|
||||
|
||||
/** Свежая временная ссылка на вложение (выданная с сообщением живёт несколько часов). */
|
||||
@GetMapping("/{chatId}/attachments/{attachmentId}/url")
|
||||
public Map<String, String> getAttachmentUrl(@PathVariable Long chatId, @PathVariable Long attachmentId, Authentication auth) {
|
||||
Long currentUserId = extractUserId(auth);
|
||||
return Map.of("url", chatService.getAttachmentUrl(chatId, attachmentId, currentUserId));
|
||||
}
|
||||
|
||||
@DeleteMapping("/{chatId}")
|
||||
public void deleteChat(@PathVariable Long chatId, Authentication auth) {
|
||||
Long currentUserId = extractUserId(auth);
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
package com.krylov.refound.controller;
|
||||
|
||||
import com.krylov.refound.enums.ErrorCode;
|
||||
import com.krylov.refound.exception.ApiException;
|
||||
import com.krylov.refound.service.ChatAttachmentService;
|
||||
import com.krylov.refound.service.FileStorageService;
|
||||
import java.time.Duration;
|
||||
import java.util.Map;
|
||||
@@ -7,6 +10,7 @@ import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.http.CacheControl;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
@@ -40,8 +44,7 @@ public class FileStorageController {
|
||||
|
||||
@GetMapping("/{*objectName}")
|
||||
public ResponseEntity<byte[]> downloadFile(@PathVariable String objectName) {
|
||||
// objectName придёт как "/avatars/cf80aebe-...jpg" — обрежь ведущий слэш
|
||||
String key = objectName.startsWith("/") ? objectName.substring(1) : objectName;
|
||||
String key = publicKey(objectName);
|
||||
return fileStorageService.downloadFile(key);
|
||||
}
|
||||
|
||||
@@ -53,7 +56,7 @@ public class FileStorageController {
|
||||
*/
|
||||
@GetMapping(value = "/{*objectName}", params = "presigned=true")
|
||||
public ResponseEntity<Void> redirectToPresigned(@PathVariable String objectName) {
|
||||
String key = objectName.startsWith("/") ? objectName.substring(1) : objectName;
|
||||
String key = publicKey(objectName);
|
||||
String url = fileStorageService.getCachedPresignedDownloadUrl(key);
|
||||
return ResponseEntity.status(302)
|
||||
.header(HttpHeaders.LOCATION, url)
|
||||
@@ -68,7 +71,7 @@ public class FileStorageController {
|
||||
*/
|
||||
@GetMapping("/url/{*objectName}")
|
||||
public ResponseEntity<Map<String, String>> getPresignedUrl(@PathVariable String objectName, @RequestParam(value = "ttlHours", required = false, defaultValue = "24") long ttlHours) {
|
||||
String key = objectName.startsWith("/") ? objectName.substring(1) : objectName;
|
||||
String key = publicKey(objectName);
|
||||
// SigV4 не подписывает ссылки дольше 7 дней: больший ttlHours ронял presigner с 500
|
||||
Duration ttl = ttlHours > 0 ? Duration.ofHours(Math.min(ttlHours, MAX_PRESIGNED_TTL_HOURS)) : Duration.ofHours(24);
|
||||
String url = fileStorageService.generatePresignedDownloadUrl(key, ttl);
|
||||
@@ -79,8 +82,25 @@ public class FileStorageController {
|
||||
public ResponseEntity<Void> deleteFile(@PathVariable String objectName) {
|
||||
log.info("deleteFile {}", objectName);
|
||||
// objectName может прийти как "/avatars/cf80aebe-...jpg" — обрежем ведущий слэш
|
||||
String key = objectName.startsWith("/") ? objectName.substring(1) : objectName;
|
||||
String key = publicKey(objectName);
|
||||
fileStorageService.deleteFileAsCurrentUser(key);
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Ключ объекта из пути: objectName приходит как "/avatars/cf80aebe-...jpg",
|
||||
* ведущий слэш обрезаем. Вложения чатов этот публичный контроллер не отдаёт и
|
||||
* не удаляет — их ссылки получают только участники через /api/v1/chats.
|
||||
* Отвечаем 404, а не 403, чтобы не подтверждать, что такой файл есть.
|
||||
*/
|
||||
static String publicKey(String objectName) {
|
||||
String key = objectName.replaceFirst("^/+", "");
|
||||
// Ключи — UUID (иногда с папкой), точек-сегментов и двойных слэшей в них нет.
|
||||
// Такие пути отклоняем: хранилище может их нормализовать в chat/...
|
||||
boolean suspicious = key.contains("..") || key.contains("//") || key.startsWith("./") || key.contains("/./");
|
||||
if (suspicious || ChatAttachmentService.isChatKey(key)) {
|
||||
throw new ApiException(ErrorCode.NOT_FOUND, "Файл не найден.", HttpStatus.NOT_FOUND);
|
||||
}
|
||||
return key;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,5 +13,7 @@ public class ChatDto {
|
||||
private ChatPostDto post;
|
||||
private String lastMessage;
|
||||
private LocalDateTime lastMessageAt;
|
||||
/** Сколько вложений в последнем сообщении — для превью «Фото» без текста. */
|
||||
private int lastMessageAttachments;
|
||||
private long unreadCount;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.krylov.refound.dto;
|
||||
|
||||
import com.krylov.refound.enums.AttachmentKind;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
/**
|
||||
* Вложение сообщения. url — временная (presigned) ссылка прямо на файл в MinIO:
|
||||
* её получают только участники чата вместе с сообщением. Когда ссылка истечёт,
|
||||
* свежую выдаёт GET /api/v1/chats/{chatId}/attachments/{id}/url.
|
||||
*/
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class MessageAttachmentDto {
|
||||
private Long id;
|
||||
private AttachmentKind kind;
|
||||
private String url;
|
||||
private Integer width;
|
||||
private Integer height;
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package com.krylov.refound.dto;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
@@ -11,4 +12,6 @@ public class MessageDto {
|
||||
private String content;
|
||||
private boolean isRead;
|
||||
private LocalDateTime createdAt;
|
||||
/** Фото сообщения; пустой список, если вложений нет. */
|
||||
private List<MessageAttachmentDto> attachments = List.of();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
package com.krylov.refound.entity;
|
||||
|
||||
import com.krylov.refound.enums.AttachmentKind;
|
||||
import com.krylov.refound.util.TimeZoneContext;
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.EnumType;
|
||||
import jakarta.persistence.Enumerated;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.PrePersist;
|
||||
import jakarta.persistence.Table;
|
||||
import java.time.LocalDateTime;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
/**
|
||||
* Вложение сообщения чата. Файл лежит в бакете картинок под ключом
|
||||
* chat/{chatId}/{uuid}.ext; общий /api/v1/files его не отдаёт — ссылку
|
||||
* получают только участники чата вместе с сообщением.
|
||||
*/
|
||||
@Entity
|
||||
@Table(name = "message_attachments")
|
||||
@Getter
|
||||
@Setter
|
||||
public class MessageAttachment {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
@Column(name = "message_id", nullable = false)
|
||||
private Long messageId;
|
||||
|
||||
@Column(name = "chat_id", nullable = false)
|
||||
private Long chatId;
|
||||
|
||||
@Enumerated(EnumType.STRING)
|
||||
@Column(nullable = false, length = 16)
|
||||
private AttachmentKind kind;
|
||||
|
||||
@Column(name = "object_key", nullable = false, unique = true)
|
||||
private String objectKey;
|
||||
|
||||
@Column(name = "content_type", nullable = false, length = 64)
|
||||
private String contentType;
|
||||
|
||||
@Column(name = "size_bytes", nullable = false)
|
||||
private long sizeBytes;
|
||||
|
||||
private Integer width;
|
||||
|
||||
private Integer height;
|
||||
|
||||
/** Порядок вложения в сообщении (0, 1, ...). */
|
||||
@Column(nullable = false)
|
||||
private int position;
|
||||
|
||||
@Column(name = "created_at", nullable = false)
|
||||
private LocalDateTime createdAt;
|
||||
|
||||
@PrePersist
|
||||
protected void onCreate() {
|
||||
createdAt = TimeZoneContext.now();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package com.krylov.refound.enums;
|
||||
|
||||
/** Тип вложения сообщения чата. VIDEO появится вторым этапом. */
|
||||
public enum AttachmentKind {
|
||||
PHOTO
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.krylov.refound.repository;
|
||||
|
||||
import com.krylov.refound.entity.MessageAttachment;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
|
||||
public interface MessageAttachmentRepository extends JpaRepository<MessageAttachment, Long> {
|
||||
|
||||
/** Вложения страницы сообщений одним запросом, в порядке внутри сообщения. */
|
||||
List<MessageAttachment> findByMessageIdInOrderByMessageIdAscPositionAsc(Collection<Long> messageIds);
|
||||
|
||||
Optional<MessageAttachment> findByIdAndChatId(Long id, Long chatId);
|
||||
|
||||
/** Ключи файлов чата — чтобы удалить их из хранилища вместе с чатом. */
|
||||
@Query("select a.objectKey from MessageAttachment a where a.chatId = :chatId")
|
||||
List<String> findObjectKeysByChatId(@Param("chatId") Long chatId);
|
||||
|
||||
/** Число вложений у сообщений: строки (messageId, count) — для превью в списке чатов. */
|
||||
@Query("select a.messageId, count(a) from MessageAttachment a where a.messageId in :messageIds group by a.messageId")
|
||||
List<Object[]> countByMessageIds(@Param("messageIds") Collection<Long> messageIds);
|
||||
|
||||
/** Все ключи вложений — для чистки файлов-сирот. */
|
||||
@Query("select a.objectKey from MessageAttachment a")
|
||||
List<String> findAllObjectKeys();
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
package com.krylov.refound.service;
|
||||
|
||||
import com.krylov.refound.dto.MessageAttachmentDto;
|
||||
import com.krylov.refound.entity.MessageAttachment;
|
||||
import com.krylov.refound.enums.ErrorCode;
|
||||
import com.krylov.refound.exception.ApiException;
|
||||
import com.krylov.refound.util.ImageFormat;
|
||||
import java.io.IOException;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
/**
|
||||
* Файлы вложений чата: проверка, перекодирование, загрузка в бакет и выдача
|
||||
* временных ссылок. Про сообщения и права доступа не знает — это делает ChatService.
|
||||
*
|
||||
* <p>Ключи лежат под {@link #KEY_PREFIX}: общий /api/v1/files такие ключи не
|
||||
* отдаёт и не удаляет, а чистка сирот сверяет их с message_attachments.
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class ChatAttachmentService {
|
||||
|
||||
public static final String KEY_PREFIX = "chat/";
|
||||
public static final int MAX_PHOTOS_PER_MESSAGE = 10;
|
||||
|
||||
/**
|
||||
* Ссылка на фото живёт 6 часов и 3 часа отдаётся одна и та же: браузер
|
||||
* берёт картинку из кэша при повторном открытии чата. Короче, чем у фото
|
||||
* объявлений (24 ч): утёкшая ссылка на личное фото быстрее перестаёт работать.
|
||||
*/
|
||||
static final Duration URL_TTL = Duration.ofHours(6);
|
||||
static final Duration URL_CACHE_TTL = Duration.ofHours(3);
|
||||
|
||||
private final FileStorageService fileStorageService;
|
||||
private final ImageOptimizer imageOptimizer;
|
||||
|
||||
/** Готовое к сохранению фото: ключ в бакете и параметры для message_attachments. */
|
||||
public record StoredPhoto(String objectKey, String contentType, long sizeBytes, int width, int height) {
|
||||
}
|
||||
|
||||
public static boolean isChatKey(String objectKey) {
|
||||
return objectKey != null && objectKey.startsWith(KEY_PREFIX);
|
||||
}
|
||||
|
||||
/**
|
||||
* Проверяет и загружает фото сообщения. Каждое фото перекодируется — так из
|
||||
* файла гарантированно уходят EXIF (геометка, модель телефона). Если хоть одно
|
||||
* фото не прошло, уже загруженные удаляются и запрос отклоняется целиком.
|
||||
*/
|
||||
public List<StoredPhoto> storePhotos(Long chatId, List<MultipartFile> files) {
|
||||
if (files.size() > MAX_PHOTOS_PER_MESSAGE) {
|
||||
throw new ApiException(ErrorCode.VALIDATION_ERROR,
|
||||
"Не больше " + MAX_PHOTOS_PER_MESSAGE + " фото в одном сообщении", HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
files.forEach(fileStorageService::validateFile);
|
||||
|
||||
List<StoredPhoto> stored = new ArrayList<>();
|
||||
try {
|
||||
for (MultipartFile file : files) {
|
||||
stored.add(storePhoto(chatId, file));
|
||||
}
|
||||
return stored;
|
||||
} catch (RuntimeException e) {
|
||||
deleteQuietly(stored.stream().map(StoredPhoto::objectKey).toList());
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
private StoredPhoto storePhoto(Long chatId, MultipartFile file) {
|
||||
byte[] source;
|
||||
try {
|
||||
source = file.getBytes();
|
||||
} catch (IOException e) {
|
||||
throw new ApiException(ErrorCode.INTERNAL_ERROR, "Ошибка при обработке файла.", HttpStatus.INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
// Тип берём из содержимого, а не из заголовка запроса
|
||||
ImageFormat format = ImageFormat.detect(source).orElseThrow(() ->
|
||||
new ApiException(ErrorCode.VALIDATION_ERROR, "Недопустимый тип файла.", HttpStatus.BAD_REQUEST));
|
||||
|
||||
ImageOptimizer.ReencodedImage image;
|
||||
try {
|
||||
image = imageOptimizer.reencode(source, format.contentType());
|
||||
} catch (IOException e) {
|
||||
log.warn("Фото для чата {} не удалось прочитать: {}", chatId, e.getMessage());
|
||||
throw new ApiException(ErrorCode.VALIDATION_ERROR, "Не удалось прочитать изображение.", HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
|
||||
String key = KEY_PREFIX + chatId + "/" + UUID.randomUUID() + image.extension();
|
||||
fileStorageService.putObject(key, image.content(), image.contentType(), file.getOriginalFilename());
|
||||
return new StoredPhoto(key, image.contentType(), image.content().length, image.width(), image.height());
|
||||
}
|
||||
|
||||
public MessageAttachmentDto toDto(MessageAttachment attachment) {
|
||||
return new MessageAttachmentDto(attachment.getId(), attachment.getKind(), url(attachment.getObjectKey()),
|
||||
attachment.getWidth(), attachment.getHeight());
|
||||
}
|
||||
|
||||
public String url(String objectKey) {
|
||||
return fileStorageService.getCachedPresignedDownloadUrl(objectKey, URL_TTL, URL_CACHE_TTL);
|
||||
}
|
||||
|
||||
/** Удаляет файлы, не роняя вызывающий код: остатки подберёт ночная чистка сирот. */
|
||||
public void deleteQuietly(List<String> objectKeys) {
|
||||
for (String key : objectKeys) {
|
||||
try {
|
||||
fileStorageService.deleteFile(key);
|
||||
} catch (RuntimeException e) {
|
||||
log.warn("Не удалось удалить вложение {}: {}", key, e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,15 +7,19 @@ import com.krylov.refound.dto.MessageDto;
|
||||
import com.krylov.refound.entity.Chat;
|
||||
import com.krylov.refound.entity.Image;
|
||||
import com.krylov.refound.entity.Message;
|
||||
import com.krylov.refound.entity.MessageAttachment;
|
||||
import com.krylov.refound.entity.Post;
|
||||
import com.krylov.refound.entity.User;
|
||||
import com.krylov.refound.enums.AttachmentKind;
|
||||
import com.krylov.refound.enums.ErrorCode;
|
||||
import com.krylov.refound.exception.ApiException;
|
||||
import com.krylov.refound.repository.ChatRepository;
|
||||
import com.krylov.refound.repository.MessageAttachmentRepository;
|
||||
import com.krylov.refound.repository.MessageRepository;
|
||||
import com.krylov.refound.repository.PostRepository;
|
||||
import com.krylov.refound.repository.UserRepository;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
@@ -33,6 +37,8 @@ import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.transaction.support.TransactionSynchronization;
|
||||
import org.springframework.transaction.support.TransactionSynchronizationManager;
|
||||
import org.springframework.transaction.support.TransactionTemplate;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@@ -48,6 +54,9 @@ public class ChatService {
|
||||
private final ClusterMessaging messaging;
|
||||
private final UserRepository userRepository;
|
||||
private final PostRepository postRepository;
|
||||
private final MessageAttachmentRepository attachmentRepository;
|
||||
private final ChatAttachmentService attachmentService;
|
||||
private final TransactionTemplate transactionTemplate;
|
||||
|
||||
/**
|
||||
* Ищет существующий чат с пользователем по объявлению, ничего не создавая.
|
||||
@@ -98,7 +107,7 @@ public class ChatService {
|
||||
return chatRepository.save(newChat);
|
||||
});
|
||||
|
||||
saveAndBroadcast(chat, currentUserId, content);
|
||||
saveAndBroadcast(chat, currentUserId, content, List.of());
|
||||
return toDto(chat, currentUserId);
|
||||
}
|
||||
|
||||
@@ -126,7 +135,52 @@ public class ChatService {
|
||||
Chat chat = getChatOrThrow(chatId);
|
||||
checkParticipant(chat, userId);
|
||||
|
||||
return messageRepository.findByChatIdOrderByCreatedAtDesc(chatId, pageable).map(this::toMessageDto);
|
||||
Page<Message> page = messageRepository.findByChatIdOrderByCreatedAtDesc(chatId, pageable);
|
||||
// Вложения всей страницы одним запросом, а не по запросу на сообщение
|
||||
Map<Long, List<MessageAttachment>> attachments = page.isEmpty() ? Map.of()
|
||||
: attachmentRepository.findByMessageIdInOrderByMessageIdAscPositionAsc(
|
||||
page.getContent().stream().map(Message::getId).toList()).stream()
|
||||
.collect(Collectors.groupingBy(MessageAttachment::getMessageId));
|
||||
return page.map(m -> toMessageDto(m, attachments.getOrDefault(m.getId(), List.of())));
|
||||
}
|
||||
|
||||
/**
|
||||
* Сообщение с фото (и, возможно, текстом) — через REST, а не WebSocket: файлы
|
||||
* по STOMP не передать. Фото проверяются и загружаются в хранилище до
|
||||
* транзакции, чтобы не держать соединение с БД, пока идёт перекодирование;
|
||||
* если сохранить сообщение не удалось, загруженные файлы удаляются.
|
||||
*/
|
||||
public MessageDto sendMessageWithPhotos(Long senderId, Long chatId, String content, List<MultipartFile> files) {
|
||||
List<MultipartFile> photos = files == null ? List.of() : files.stream().filter(f -> !f.isEmpty()).toList();
|
||||
String text = content == null ? "" : content;
|
||||
if (photos.isEmpty()) {
|
||||
validateContent(text);
|
||||
} else if (text.length() > MAX_MESSAGE_LENGTH) {
|
||||
throw new ApiException(ErrorCode.VALIDATION_ERROR,
|
||||
"Сообщение длиннее " + MAX_MESSAGE_LENGTH + " символов", HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
|
||||
// Права проверяем до загрузки: посторонний не должен класть файлы в чужой чат
|
||||
Chat chat = getChatOrThrow(chatId);
|
||||
checkParticipant(chat, senderId);
|
||||
|
||||
List<ChatAttachmentService.StoredPhoto> stored = attachmentService.storePhotos(chatId, photos);
|
||||
try {
|
||||
return transactionTemplate.execute(status -> saveAndBroadcast(chat, senderId, text, stored));
|
||||
} catch (RuntimeException e) {
|
||||
attachmentService.deleteQuietly(stored.stream().map(ChatAttachmentService.StoredPhoto::objectKey).toList());
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/** Свежая ссылка на вложение — когда выданная вместе с сообщением истекла. */
|
||||
@Transactional(readOnly = true)
|
||||
public String getAttachmentUrl(Long chatId, Long attachmentId, Long userId) {
|
||||
Chat chat = getChatOrThrow(chatId);
|
||||
checkParticipant(chat, userId);
|
||||
MessageAttachment attachment = attachmentRepository.findByIdAndChatId(attachmentId, chatId)
|
||||
.orElseThrow(() -> new ApiException(ErrorCode.NOT_FOUND, "Вложение не найдено", HttpStatus.NOT_FOUND));
|
||||
return attachmentService.url(attachment.getObjectKey());
|
||||
}
|
||||
|
||||
// Отправка сообщения (вызывается из WebSocket контроллера)
|
||||
@@ -137,7 +191,7 @@ public class ChatService {
|
||||
Chat chat = getChatOrThrow(chatId);
|
||||
checkParticipant(chat, senderId);
|
||||
|
||||
saveAndBroadcast(chat, senderId, content);
|
||||
saveAndBroadcast(chat, senderId, content, List.of());
|
||||
}
|
||||
|
||||
private void validateContent(String content) {
|
||||
@@ -150,7 +204,8 @@ public class ChatService {
|
||||
}
|
||||
}
|
||||
|
||||
private void saveAndBroadcast(Chat chat, Long senderId, String content) {
|
||||
private MessageDto saveAndBroadcast(Chat chat, Long senderId, String content,
|
||||
List<ChatAttachmentService.StoredPhoto> photos) {
|
||||
Long chatId = chat.getId();
|
||||
Message message = new Message();
|
||||
message.setChatId(chatId);
|
||||
@@ -158,7 +213,26 @@ public class ChatService {
|
||||
message.setContent(content);
|
||||
message = messageRepository.save(message);
|
||||
|
||||
MessageDto dto = toMessageDto(message);
|
||||
List<MessageAttachment> attachments = new ArrayList<>();
|
||||
for (int i = 0; i < photos.size(); i++) {
|
||||
ChatAttachmentService.StoredPhoto photo = photos.get(i);
|
||||
MessageAttachment attachment = new MessageAttachment();
|
||||
attachment.setMessageId(message.getId());
|
||||
attachment.setChatId(chatId);
|
||||
attachment.setKind(AttachmentKind.PHOTO);
|
||||
attachment.setObjectKey(photo.objectKey());
|
||||
attachment.setContentType(photo.contentType());
|
||||
attachment.setSizeBytes(photo.sizeBytes());
|
||||
attachment.setWidth(photo.width());
|
||||
attachment.setHeight(photo.height());
|
||||
attachment.setPosition(i);
|
||||
attachments.add(attachment);
|
||||
}
|
||||
if (!attachments.isEmpty()) {
|
||||
attachments = attachmentRepository.saveAll(attachments);
|
||||
}
|
||||
|
||||
MessageDto dto = toMessageDto(message, attachments);
|
||||
|
||||
// Уведомляем получателя об непрочитанных
|
||||
Long recipientId = chat.getUserOneId().equals(senderId)
|
||||
@@ -176,6 +250,7 @@ public class ChatService {
|
||||
Map.of("chatId", chatId, "unreadCount", unreadCount)
|
||||
);
|
||||
});
|
||||
return dto;
|
||||
}
|
||||
|
||||
private static void afterCommit(Runnable action) {
|
||||
@@ -195,7 +270,13 @@ public class ChatService {
|
||||
public void deleteChat(Long chatId, Long userId) {
|
||||
Chat chat = getChatOrThrow(chatId);
|
||||
checkParticipant(chat, userId);
|
||||
// Строки вложений удалит каскад в БД, а файлы — только мы: после коммита,
|
||||
// чтобы откат транзакции не оставил чат без фото
|
||||
List<String> keys = attachmentRepository.findObjectKeysByChatId(chatId);
|
||||
chatRepository.deleteById(chatId);
|
||||
if (!keys.isEmpty()) {
|
||||
afterCommit(() -> attachmentService.deleteQuietly(keys));
|
||||
}
|
||||
}
|
||||
|
||||
@Transactional
|
||||
@@ -254,6 +335,15 @@ public class ChatService {
|
||||
for (Object[] row : messageRepository.countUnreadByChat(chatIds, currentUserId)) {
|
||||
unread.put(((Number) row[0]).longValue(), ((Number) row[1]).longValue());
|
||||
}
|
||||
// Сколько фото в последнем сообщении: у сообщения только с фото текста нет,
|
||||
// и превью в списке чатов показывает «Фото» вместо пустой строки
|
||||
Map<Long, Integer> lastAttachments = new HashMap<>();
|
||||
if (!lastMessages.isEmpty()) {
|
||||
for (Object[] row : attachmentRepository.countByMessageIds(
|
||||
lastMessages.values().stream().map(Message::getId).toList())) {
|
||||
lastAttachments.put(((Number) row[0]).longValue(), ((Number) row[1]).intValue());
|
||||
}
|
||||
}
|
||||
|
||||
return chats.stream().map(chat -> {
|
||||
Long otherUserId = otherUserId(chat, currentUserId);
|
||||
@@ -284,6 +374,7 @@ public class ChatService {
|
||||
if (last != null) {
|
||||
dto.setLastMessage(last.getContent());
|
||||
dto.setLastMessageAt(last.getCreatedAt());
|
||||
dto.setLastMessageAttachments(lastAttachments.getOrDefault(last.getId(), 0));
|
||||
}
|
||||
dto.setUnreadCount(unread.getOrDefault(chat.getId(), 0L));
|
||||
return dto;
|
||||
@@ -294,8 +385,9 @@ public class ChatService {
|
||||
return chat.getUserOneId().equals(currentUserId) ? chat.getUserTwoId() : chat.getUserOneId();
|
||||
}
|
||||
|
||||
private MessageDto toMessageDto(Message m) {
|
||||
private MessageDto toMessageDto(Message m, List<MessageAttachment> attachments) {
|
||||
MessageDto dto = new MessageDto();
|
||||
dto.setAttachments(attachments.stream().map(attachmentService::toDto).toList());
|
||||
dto.setId(m.getId());
|
||||
dto.setChatId(m.getChatId());
|
||||
dto.setSenderId(m.getSenderId());
|
||||
|
||||
@@ -206,6 +206,15 @@ public class FileStorageService {
|
||||
* Если Redis недоступен, просто генерируем новую ссылку.
|
||||
*/
|
||||
public String getCachedPresignedDownloadUrl(String objectName) {
|
||||
return getCachedPresignedDownloadUrl(objectName, PRESIGNED_URL_TTL, PRESIGNED_URL_CACHE_TTL);
|
||||
}
|
||||
|
||||
/**
|
||||
* То же с заданными сроками: ссылка живёт ttl, повторно отдаётся cacheTtl.
|
||||
* cacheTtl должен быть заметно меньше ttl — иначе из кэша придёт ссылка,
|
||||
* которая вот-вот истечёт.
|
||||
*/
|
||||
public String getCachedPresignedDownloadUrl(String objectName, Duration ttl, Duration cacheTtl) {
|
||||
String cacheKey = PRESIGNED_KEY_PREFIX + objectName;
|
||||
try {
|
||||
String cached = redisTemplate.opsForValue().get(cacheKey);
|
||||
@@ -216,9 +225,9 @@ public class FileStorageService {
|
||||
log.warn("Не удалось прочитать presigned URL из кэша для '{}': {}", objectName, e.getMessage());
|
||||
}
|
||||
|
||||
String url = generatePresignedDownloadUrl(objectName, PRESIGNED_URL_TTL);
|
||||
String url = generatePresignedDownloadUrl(objectName, ttl);
|
||||
try {
|
||||
redisTemplate.opsForValue().set(cacheKey, url, PRESIGNED_URL_CACHE_TTL);
|
||||
redisTemplate.opsForValue().set(cacheKey, url, cacheTtl);
|
||||
} catch (RuntimeException e) {
|
||||
log.warn("Не удалось сохранить presigned URL в кэш для '{}': {}", objectName, e.getMessage());
|
||||
}
|
||||
@@ -379,7 +388,31 @@ public class FileStorageService {
|
||||
}
|
||||
}
|
||||
|
||||
private void validateFile(MultipartFile file) {
|
||||
/**
|
||||
* Кладёт уже подготовленные байты в бакет под заданным ключом. Владелец в
|
||||
* Redis не записывается: такие файлы (вложения чатов) удаляет только их сервис.
|
||||
*/
|
||||
public void putObject(String objectName, byte[] content, String contentType, String originalFilename) {
|
||||
Map<String, String> metadata = new HashMap<>();
|
||||
if (originalFilename != null && !originalFilename.isBlank()) {
|
||||
metadata.put(ORIGINAL_FILENAME_METADATA_KEY, URLEncoder.encode(originalFilename, StandardCharsets.UTF_8));
|
||||
}
|
||||
try {
|
||||
s3Client.putObject(PutObjectRequest.builder()
|
||||
.bucket(properties.bucket())
|
||||
.key(objectName)
|
||||
.contentType(contentType)
|
||||
.metadata(metadata)
|
||||
.build(), RequestBody.fromBytes(content));
|
||||
log.info("Файл '{}' успешно загружен.", objectName);
|
||||
} catch (S3Exception | SdkClientException e) {
|
||||
log.error("Не удалось загрузить файл '{}' в S3/MinIO: {}", objectName, e.getMessage(), e);
|
||||
throw new ApiException(ErrorCode.INTERNAL_ERROR, "Ошибка при загрузке файла.", HttpStatus.INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
/** Общие проверки загружаемой картинки: не пустая, есть имя, до 10 МБ, заявлен JPEG/PNG/WebP. */
|
||||
public void validateFile(MultipartFile file) {
|
||||
if (file.isEmpty()) {
|
||||
log.warn("Попытка загрузить пустой файл.");
|
||||
throw new ApiException(ErrorCode.VALIDATION_ERROR, "Файл не может быть пустым.", HttpStatus.BAD_REQUEST);
|
||||
|
||||
@@ -39,6 +39,36 @@ public class ImageOptimizer {
|
||||
public record OptimizedImage(byte[] content, String contentType, String extension) {
|
||||
}
|
||||
|
||||
/** Перекодированная картинка вместе с итоговым размером в пикселях. */
|
||||
public record ReencodedImage(byte[] content, String contentType, String extension, int width, int height) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Всегда перекодирует картинку (с поворотом по EXIF и уменьшением до
|
||||
* MAX_DIMENSION), даже маленькую. В отличие от optimize, гарантирует, что
|
||||
* метаданные (геометка, модель телефона) не попадут в хранилище, — для фото,
|
||||
* которые пользователь отправляет в личный чат.
|
||||
*
|
||||
* @throws IOException если картинку не удалось прочитать
|
||||
*/
|
||||
public ReencodedImage reencode(byte[] source, String contentType) throws IOException {
|
||||
Thumbnails.Builder<?> builder = Thumbnails.of(new ByteArrayInputStream(source));
|
||||
builder = maxSide(source) > MAX_DIMENSION
|
||||
? builder.size(MAX_DIMENSION, MAX_DIMENSION)
|
||||
: builder.scale(1.0);
|
||||
BufferedImage image;
|
||||
try {
|
||||
image = builder.asBufferedImage();
|
||||
} catch (RuntimeException e) {
|
||||
throw new IOException("не удалось декодировать картинку", e);
|
||||
}
|
||||
|
||||
boolean keepAlpha = image.getColorModel().hasAlpha() && !"image/jpeg".equals(contentType);
|
||||
return keepAlpha
|
||||
? new ReencodedImage(writePng(image), "image/png", ".png", image.getWidth(), image.getHeight())
|
||||
: new ReencodedImage(writeJpeg(toRgb(image)), "image/jpeg", ".jpg", image.getWidth(), image.getHeight());
|
||||
}
|
||||
|
||||
@PostConstruct
|
||||
void registerImageIoPlugins() {
|
||||
// Плагины TwelveMonkeys (WebP, CMYK-JPEG) лежат внутри fat jar —
|
||||
|
||||
@@ -2,6 +2,7 @@ package com.krylov.refound.service;
|
||||
|
||||
import com.krylov.refound.config.MinioProperties;
|
||||
import com.krylov.refound.repository.ImageRepository;
|
||||
import com.krylov.refound.repository.MessageAttachmentRepository;
|
||||
import com.krylov.refound.repository.UserRepository;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
@@ -19,9 +20,10 @@ import software.amazon.awssdk.services.s3.model.S3Object;
|
||||
|
||||
/**
|
||||
* Ночная чистка «сирот» в бакете картинок: файлов, на которые не ссылаются ни
|
||||
* images.url, ни users.avatar_url. Они появляются, когда фото загружено через
|
||||
* POST /api/v1/files и не прикреплено к объявлению, или когда запрос упал между
|
||||
* загрузкой и сохранением.
|
||||
* images.url, ни users.avatar_url, ни message_attachments.object_key. Они появляются,
|
||||
* когда фото загружено через POST /api/v1/files и не прикреплено к объявлению,
|
||||
* когда запрос упал между загрузкой и сохранением или файлы удалённого чата не
|
||||
* удалились сразу.
|
||||
*
|
||||
* <p>Удаляются только файлы старше {@code storage.orphan-cleanup.min-age}
|
||||
* (по умолчанию сутки) — свежая загрузка может ещё ждать сохранения формы. За
|
||||
@@ -36,13 +38,15 @@ public class OrphanFileCleanupService {
|
||||
private final MinioProperties properties;
|
||||
private final ImageRepository imageRepository;
|
||||
private final UserRepository userRepository;
|
||||
private final MessageAttachmentRepository attachmentRepository;
|
||||
private final FileStorageService fileStorageService;
|
||||
private final boolean enabled;
|
||||
private final Duration minAge;
|
||||
private final int maxDeletes;
|
||||
|
||||
public OrphanFileCleanupService(S3Client s3Client, MinioProperties properties, ImageRepository imageRepository,
|
||||
UserRepository userRepository, FileStorageService fileStorageService,
|
||||
UserRepository userRepository, MessageAttachmentRepository attachmentRepository,
|
||||
FileStorageService fileStorageService,
|
||||
@Value("${storage.orphan-cleanup.enabled:true}") boolean enabled,
|
||||
@Value("${storage.orphan-cleanup.min-age:PT24H}") Duration minAge,
|
||||
@Value("${storage.orphan-cleanup.max-deletes:5000}") int maxDeletes) {
|
||||
@@ -50,6 +54,7 @@ public class OrphanFileCleanupService {
|
||||
this.properties = properties;
|
||||
this.imageRepository = imageRepository;
|
||||
this.userRepository = userRepository;
|
||||
this.attachmentRepository = attachmentRepository;
|
||||
this.fileStorageService = fileStorageService;
|
||||
this.enabled = enabled;
|
||||
this.minAge = minAge;
|
||||
@@ -99,6 +104,7 @@ public class OrphanFileCleanupService {
|
||||
Stream.concat(imageRepository.findAllUrls().stream(), userRepository.findAllAvatarUrls().stream())
|
||||
.map(this::toKey)
|
||||
.forEach(keys::add);
|
||||
keys.addAll(attachmentRepository.findAllObjectKeys());
|
||||
return keys;
|
||||
}
|
||||
|
||||
|
||||
@@ -176,6 +176,12 @@ rate-limit:
|
||||
paths: [/api/v1/files]
|
||||
limit: 60
|
||||
window: PT1H
|
||||
# Сообщения с фото: каждое — до 10 перекодирований на сервере
|
||||
- name: chat-photo
|
||||
method: POST
|
||||
paths: [/api/v1/chats/*/messages]
|
||||
limit: 60
|
||||
window: PT1H
|
||||
- name: chat-start
|
||||
method: POST
|
||||
paths: [/api/v1/chats/with/**]
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
databaseChangeLog:
|
||||
- changeSet:
|
||||
id: 024-create-message-attachments
|
||||
author: krylov
|
||||
comment: >
|
||||
Вложения сообщений чата (пока только фото). Файл лежит в бакете картинок
|
||||
под ключом chat/{chatId}/{uuid}.ext и доступен только участникам чата:
|
||||
ссылка на него выдаётся вместе с сообщением. ON DELETE CASCADE — строки
|
||||
удаляются вместе с сообщением (и чатом), файлы удаляет ChatService.
|
||||
preConditions:
|
||||
onFail: MARK_RAN
|
||||
not:
|
||||
tableExists:
|
||||
tableName: message_attachments
|
||||
changes:
|
||||
- createTable:
|
||||
tableName: message_attachments
|
||||
columns:
|
||||
- column: { name: id, type: BIGSERIAL, constraints: { primaryKey: true } }
|
||||
- column: { name: message_id, type: BIGINT, constraints: { nullable: false } }
|
||||
- column: { name: chat_id, type: BIGINT, constraints: { nullable: false } }
|
||||
- column: { name: kind, type: VARCHAR(16), constraints: { nullable: false } }
|
||||
- column: { name: object_key, type: VARCHAR(255), constraints: { nullable: false, unique: true } }
|
||||
- column: { name: content_type, type: VARCHAR(64), constraints: { nullable: false } }
|
||||
- column: { name: size_bytes, type: BIGINT, constraints: { nullable: false } }
|
||||
- column: { name: width, type: INT }
|
||||
- column: { name: height, type: INT }
|
||||
- column: { name: position, type: INT, constraints: { nullable: false } }
|
||||
- column: { name: created_at, type: TIMESTAMP, constraints: { nullable: false } }
|
||||
- addForeignKeyConstraint:
|
||||
baseTableName: message_attachments
|
||||
baseColumnNames: message_id
|
||||
referencedTableName: messages
|
||||
referencedColumnNames: id
|
||||
constraintName: fk_message_attachments_message
|
||||
onDelete: CASCADE
|
||||
- createIndex:
|
||||
tableName: message_attachments
|
||||
indexName: idx_message_attachments_message
|
||||
columns:
|
||||
- column: { name: message_id }
|
||||
- createIndex:
|
||||
tableName: message_attachments
|
||||
indexName: idx_message_attachments_chat
|
||||
columns:
|
||||
- column: { name: chat_id }
|
||||
@@ -36,3 +36,4 @@ databaseChangeLog:
|
||||
- include: { file: db/changelog/add/021-ad-stats-indexes.yaml }
|
||||
- include: { file: db/changelog/add/022-add-closed-at-posts.yaml }
|
||||
- include: { file: db/changelog/add/023-add-phone-visible-posts.yaml }
|
||||
- include: { file: db/changelog/create/024-create-message-attachments.yaml }
|
||||
|
||||
Reference in New Issue
Block a user