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:
SlimusMinus
2026-10-28 22:26:37 +03:00
parent 3eab2f30e0
commit 2f6aa0cd1e
21 changed files with 832 additions and 22 deletions

View File

@@ -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);

View File

@@ -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;
}
}

View File

@@ -13,5 +13,7 @@ public class ChatDto {
private ChatPostDto post;
private String lastMessage;
private LocalDateTime lastMessageAt;
/** Сколько вложений в последнем сообщении — для превью «Фото» без текста. */
private int lastMessageAttachments;
private long unreadCount;
}

View File

@@ -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;
}

View File

@@ -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();
}

View File

@@ -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();
}
}

View File

@@ -0,0 +1,6 @@
package com.krylov.refound.enums;
/** Тип вложения сообщения чата. VIDEO появится вторым этапом. */
public enum AttachmentKind {
PHOTO
}

View File

@@ -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();
}

View File

@@ -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());
}
}
}
}

View File

@@ -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());

View File

@@ -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);

View File

@@ -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 —

View File

@@ -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;
}

View File

@@ -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/**]

View File

@@ -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 }

View File

@@ -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 }

View File

@@ -0,0 +1,28 @@
package com.krylov.refound.controller;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import com.krylov.refound.exception.ApiException;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.springframework.http.HttpStatus;
/** Публичный /api/v1/files не должен отдавать вложения чатов ни напрямую, ни в обход. */
class FileStorageControllerKeyTest {
@Test
void regularKeysPass() {
assertThat(FileStorageController.publicKey("/avatars/cf80aebe.jpg")).isEqualTo("avatars/cf80aebe.jpg");
assertThat(FileStorageController.publicKey("cf80aebe.jpg")).isEqualTo("cf80aebe.jpg");
}
@ParameterizedTest
@ValueSource(strings = {"/chat/7/a.jpg", "chat/7/a.jpg", "//chat/7/a.jpg", "./chat/7/a.jpg",
"avatars/../chat/7/a.jpg", "avatars//../chat/7/a.jpg", "x/./chat/7/a.jpg"})
void chatKeysAreHidden(String objectName) {
assertThatThrownBy(() -> FileStorageController.publicKey(objectName))
.isInstanceOfSatisfying(ApiException.class, e -> assertThat(e.getStatus()).isEqualTo(HttpStatus.NOT_FOUND));
}
}

View File

@@ -0,0 +1,96 @@
package com.krylov.refound.service;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.startsWith;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.krylov.refound.enums.ErrorCode;
import com.krylov.refound.exception.ApiException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpStatus;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;
class ChatAttachmentServiceTest {
private static final byte[] JPEG = {(byte) 0xFF, (byte) 0xD8, (byte) 0xFF, 0x00};
private FileStorageService storage;
private ImageOptimizer optimizer;
private ChatAttachmentService service;
@BeforeEach
void setUp() throws IOException {
storage = mock(FileStorageService.class);
optimizer = mock(ImageOptimizer.class);
service = new ChatAttachmentService(storage, optimizer);
when(optimizer.reencode(any(), anyString()))
.thenReturn(new ImageOptimizer.ReencodedImage(new byte[] {1, 2}, "image/jpeg", ".jpg", 640, 480));
}
private static MultipartFile photo(byte[] content) {
return new MockMultipartFile("files", "IMG_0001.jpg", "image/jpeg", content);
}
@Test
void photosAreReencodedAndStoredUnderChatPrefix() {
List<ChatAttachmentService.StoredPhoto> stored = service.storePhotos(7L, List.of(photo(JPEG)));
assertThat(stored).singleElement().satisfies(p -> {
assertThat(p.objectKey()).startsWith("chat/7/").endsWith(".jpg");
assertThat(p.width()).isEqualTo(640);
assertThat(p.height()).isEqualTo(480);
assertThat(p.sizeBytes()).isEqualTo(2);
});
verify(storage).putObject(startsWith("chat/7/"), eq(new byte[] {1, 2}), eq("image/jpeg"), eq("IMG_0001.jpg"));
}
@Test
void tooManyPhotosAreRejectedBeforeUpload() {
List<MultipartFile> files = new ArrayList<>();
for (int i = 0; i <= ChatAttachmentService.MAX_PHOTOS_PER_MESSAGE; i++) {
files.add(photo(JPEG));
}
assertThatThrownBy(() -> service.storePhotos(7L, files))
.isInstanceOfSatisfying(ApiException.class, e -> assertThat(e.getStatus()).isEqualTo(HttpStatus.BAD_REQUEST));
verify(storage, never()).putObject(anyString(), any(), anyString(), anyString());
}
@Test
void notAnImageIsRejected() {
assertThatThrownBy(() -> service.storePhotos(7L, List.of(photo("<svg/>".getBytes()))))
.isInstanceOfSatisfying(ApiException.class, e -> assertThat(e.getStatus()).isEqualTo(HttpStatus.BAD_REQUEST));
verify(storage, never()).putObject(anyString(), any(), anyString(), anyString());
}
@Test
void alreadyUploadedPhotosAreRemovedWhenNextOneFails() {
// Первое фото загружается, второе — нет: первое не должно остаться в бакете
doNothing().doThrow(new ApiException(ErrorCode.INTERNAL_ERROR, "s3", HttpStatus.INTERNAL_SERVER_ERROR))
.when(storage).putObject(anyString(), any(), anyString(), anyString());
assertThatThrownBy(() -> service.storePhotos(7L, List.of(photo(JPEG), photo(JPEG))))
.isInstanceOf(ApiException.class);
verify(storage).deleteFile(startsWith("chat/7/"));
}
@Test
void chatKeysAreRecognised() {
assertThat(ChatAttachmentService.isChatKey("chat/7/a.jpg")).isTrue();
assertThat(ChatAttachmentService.isChatKey("avatars/a.jpg")).isFalse();
assertThat(ChatAttachmentService.isChatKey(null)).isFalse();
}
}

View File

@@ -10,14 +10,19 @@ import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.krylov.refound.dto.ChatDto;
import com.krylov.refound.dto.MessageAttachmentDto;
import com.krylov.refound.dto.MessageDto;
import com.krylov.refound.entity.Chat;
import com.krylov.refound.entity.Message;
import com.krylov.refound.entity.MessageAttachment;
import com.krylov.refound.enums.AttachmentKind;
import com.krylov.refound.entity.Post;
import com.krylov.refound.entity.User;
import com.krylov.refound.enums.PostStatus;
import com.krylov.refound.enums.PostType;
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;
@@ -27,6 +32,10 @@ import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.springframework.http.HttpStatus;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.web.multipart.MultipartFile;
import com.krylov.refound.config.ClusterMessaging;
class ChatServiceTest {
@@ -35,6 +44,8 @@ class ChatServiceTest {
private UserRepository userRepository;
private PostRepository postRepository;
private MessageRepository messageRepository;
private MessageAttachmentRepository attachmentRepository;
private ChatAttachmentService attachmentService;
private ChatService chatService;
@BeforeEach
@@ -43,8 +54,12 @@ class ChatServiceTest {
userRepository = mock(UserRepository.class);
postRepository = mock(PostRepository.class);
messageRepository = mock(MessageRepository.class);
attachmentRepository = mock(MessageAttachmentRepository.class);
attachmentService = mock(ChatAttachmentService.class);
TransactionTemplate tx = mock(TransactionTemplate.class);
when(tx.execute(any())).thenAnswer(inv -> inv.<TransactionCallback<?>>getArgument(0).doInTransaction(null));
chatService = new ChatService(chatRepository, messageRepository, mock(ClusterMessaging.class),
userRepository, postRepository);
userRepository, postRepository, attachmentRepository, attachmentService, tx);
when(userRepository.existsById(anyLong())).thenReturn(true);
when(chatRepository.findByUsersAndPost(any(), any(), any())).thenReturn(List.of());
@@ -184,4 +199,106 @@ class ChatServiceTest {
assertThat(second.getPostId()).isEqualTo(42L);
assertThat(second.getPost()).isNull();
}
private Chat chatBetween(long chatId, long userOne, long userTwo) {
Chat chat = new Chat();
chat.setId(chatId);
chat.setUserOneId(userOne);
chat.setUserTwoId(userTwo);
when(chatRepository.findById(chatId)).thenReturn(Optional.of(chat));
return chat;
}
private static MultipartFile photo(String name) {
return new MockMultipartFile("files", name, "image/jpeg", new byte[] {1, 2, 3});
}
@Test
void photoMessageSavesAttachmentsInOrderAndReturnsLinks() {
chatBetween(7L, 14L, 19L);
List<MultipartFile> files = List.of(photo("a.jpg"), photo("b.jpg"));
when(attachmentService.storePhotos(7L, files)).thenReturn(List.of(
new ChatAttachmentService.StoredPhoto("chat/7/a.jpg", "image/jpeg", 100, 800, 600),
new ChatAttachmentService.StoredPhoto("chat/7/b.jpg", "image/jpeg", 200, 600, 800)));
when(attachmentRepository.saveAll(any())).thenAnswer(inv -> inv.getArgument(0));
when(attachmentService.toDto(any())).thenAnswer(inv -> {
MessageAttachment a = inv.getArgument(0);
return new MessageAttachmentDto(a.getId(), a.getKind(), "https://minio/" + a.getObjectKey(), a.getWidth(), a.getHeight());
});
MessageDto dto = chatService.sendMessageWithPhotos(14L, 7L, null, files);
assertThat(dto.getContent()).isEmpty();
assertThat(dto.getAttachments()).extracting(MessageAttachmentDto::getUrl)
.containsExactly("https://minio/chat/7/a.jpg", "https://minio/chat/7/b.jpg");
@SuppressWarnings("unchecked")
ArgumentCaptor<List<MessageAttachment>> saved = ArgumentCaptor.forClass(List.class);
verify(attachmentRepository).saveAll(saved.capture());
assertThat(saved.getValue()).extracting(MessageAttachment::getPosition).containsExactly(0, 1);
assertThat(saved.getValue()).allSatisfy(a -> {
assertThat(a.getMessageId()).isEqualTo(500L);
assertThat(a.getChatId()).isEqualTo(7L);
assertThat(a.getKind()).isEqualTo(AttachmentKind.PHOTO);
});
}
@Test
void outsiderCannotUploadPhotosToChat() {
chatBetween(7L, 14L, 19L);
assertThatThrownBy(() -> chatService.sendMessageWithPhotos(99L, 7L, "привет", List.of(photo("a.jpg"))))
.isInstanceOfSatisfying(ApiException.class, e -> assertThat(e.getStatus()).isEqualTo(HttpStatus.FORBIDDEN));
// Проверка прав — до загрузки, иначе посторонний клал бы файлы в хранилище
verify(attachmentService, never()).storePhotos(any(), any());
}
@Test
void messageWithoutPhotosAndTextIsRejected() {
chatBetween(7L, 14L, 19L);
assertThatThrownBy(() -> chatService.sendMessageWithPhotos(14L, 7L, " ", List.of()))
.isInstanceOf(ApiException.class);
verify(attachmentService, never()).storePhotos(any(), any());
}
@Test
void uploadedPhotosAreDeletedWhenMessageIsNotSaved() {
chatBetween(7L, 14L, 19L);
List<MultipartFile> files = List.of(photo("a.jpg"));
when(attachmentService.storePhotos(7L, files)).thenReturn(List.of(
new ChatAttachmentService.StoredPhoto("chat/7/a.jpg", "image/jpeg", 100, 800, 600)));
when(messageRepository.save(any(Message.class))).thenThrow(new IllegalStateException("db down"));
assertThatThrownBy(() -> chatService.sendMessageWithPhotos(14L, 7L, "", files))
.isInstanceOf(IllegalStateException.class);
verify(attachmentService).deleteQuietly(List.of("chat/7/a.jpg"));
}
@Test
void deletingChatDeletesItsFiles() {
chatBetween(7L, 14L, 19L);
when(attachmentRepository.findObjectKeysByChatId(7L)).thenReturn(List.of("chat/7/a.jpg"));
chatService.deleteChat(7L, 19L);
verify(chatRepository).deleteById(7L);
// Без активной транзакции afterCommit выполняется сразу
verify(attachmentService).deleteQuietly(List.of("chat/7/a.jpg"));
}
@Test
void attachmentLinkOnlyForParticipantsAndOwnChat() {
chatBetween(7L, 14L, 19L);
MessageAttachment attachment = new MessageAttachment();
attachment.setObjectKey("chat/7/a.jpg");
when(attachmentRepository.findByIdAndChatId(3L, 7L)).thenReturn(Optional.of(attachment));
when(attachmentService.url("chat/7/a.jpg")).thenReturn("https://minio/signed");
assertThat(chatService.getAttachmentUrl(7L, 3L, 14L)).isEqualTo("https://minio/signed");
assertThatThrownBy(() -> chatService.getAttachmentUrl(7L, 3L, 99L))
.isInstanceOfSatisfying(ApiException.class, e -> assertThat(e.getStatus()).isEqualTo(HttpStatus.FORBIDDEN));
// Вложение другого чата по id своего чата не достать
assertThatThrownBy(() -> chatService.getAttachmentUrl(7L, 4L, 14L))
.isInstanceOfSatisfying(ApiException.class, e -> assertThat(e.getStatus()).isEqualTo(HttpStatus.NOT_FOUND));
}
}

View File

@@ -1,11 +1,13 @@
package com.krylov.refound.service;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Optional;
import java.util.Random;
import javax.imageio.ImageIO;
@@ -66,6 +68,59 @@ class ImageOptimizerTest {
assertThat(optimizer.optimize(garbage, "image/jpeg")).isEmpty();
}
@Test
void reencodeStripsMetadataEvenFromSmallPhoto() throws IOException {
byte[] plain = encode(noise(200, 150, BufferedImage.TYPE_INT_RGB), "jpg");
byte[] withExif = withExifSegment(plain, "GPS-55.7558-37.6173");
assertThat(new String(withExif, StandardCharsets.ISO_8859_1)).contains("GPS-55.7558");
ImageOptimizer.ReencodedImage result = optimizer.reencode(withExif, "image/jpeg");
assertThat(result.contentType()).isEqualTo("image/jpeg");
assertThat(result.width()).isEqualTo(200);
assertThat(result.height()).isEqualTo(150);
String content = new String(result.content(), StandardCharsets.ISO_8859_1);
assertThat(content).doesNotContain("GPS-55.7558").doesNotContain("Exif");
}
@Test
void reencodeDownscalesLargePhoto() throws IOException {
byte[] source = encode(noise(4032, 3024, BufferedImage.TYPE_INT_RGB), "jpg");
ImageOptimizer.ReencodedImage result = optimizer.reencode(source, "image/jpeg");
assertThat(result.width()).isEqualTo(ImageOptimizer.MAX_DIMENSION);
assertThat(result.height()).isEqualTo(1200);
}
@Test
void reencodeRejectsUnreadableFile() {
byte[] garbage = new byte[1024];
new Random(1).nextBytes(garbage);
assertThatThrownBy(() -> optimizer.reencode(garbage, "image/jpeg")).isInstanceOf(IOException.class);
}
/** Вставляет после SOI сегмент APP1 с минимальным EXIF (пустой IFD) и текстом-меткой. */
private static byte[] withExifSegment(byte[] jpeg, String marker) {
ByteArrayOutputStream payload = new ByteArrayOutputStream();
payload.writeBytes("Exif\0\0".getBytes(StandardCharsets.ISO_8859_1));
payload.writeBytes(new byte[] {'M', 'M', 0, 42, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0});
payload.writeBytes(marker.getBytes(StandardCharsets.ISO_8859_1));
byte[] data = payload.toByteArray();
int length = data.length + 2;
ByteArrayOutputStream out = new ByteArrayOutputStream();
out.write(jpeg, 0, 2);
out.write(0xFF);
out.write(0xE1);
out.write(length >> 8);
out.write(length & 0xFF);
out.writeBytes(data);
out.write(jpeg, 2, jpeg.length - 2);
return out.toByteArray();
}
/** Шум плохо сжимается — так файл гарантированно тяжелее порога. */
private static BufferedImage noise(int width, int height, int type) {
BufferedImage image = new BufferedImage(width, height, type);

View File

@@ -9,6 +9,7 @@ import static org.mockito.Mockito.when;
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;
@@ -30,6 +31,8 @@ class OrphanFileCleanupServiceTest {
S3Object.builder().key("used.jpg").lastModified(old).build(),
S3Object.builder().key("avatars/legacy.jpg").lastModified(old).build(),
S3Object.builder().key("orphan.jpg").lastModified(old).build(),
S3Object.builder().key("chat/5/photo.jpg").lastModified(old).build(),
S3Object.builder().key("chat/5/deleted-chat.jpg").lastModified(old).build(),
S3Object.builder().key("fresh.jpg").lastModified(Instant.now()).build()).build();
when(s3.listObjectsV2Paginator(any(ListObjectsV2Request.class)))
.thenReturn(new ListObjectsV2Iterable(s3, ListObjectsV2Request.builder().build()));
@@ -41,15 +44,20 @@ class OrphanFileCleanupServiceTest {
UserRepository users = mock(UserRepository.class);
// Старая запись аватара хранит полный URL
when(users.findAllAvatarUrls()).thenReturn(List.of("http://minio:9010/refound-images/avatars/legacy.jpg?x=1"));
MessageAttachmentRepository attachments = mock(MessageAttachmentRepository.class);
when(attachments.findAllObjectKeys()).thenReturn(List.of("chat/5/photo.jpg"));
FileStorageService storage = mock(FileStorageService.class);
new OrphanFileCleanupService(s3, properties, images, users, storage, true, Duration.ofHours(24), 100)
new OrphanFileCleanupService(s3, properties, images, users, attachments, storage, true, Duration.ofHours(24), 100)
.cleanupOrphanFiles();
verify(storage).deleteFile("orphan.jpg");
verify(storage, never()).deleteFile("used.jpg");
verify(storage, never()).deleteFile("avatars/legacy.jpg");
verify(storage, never()).deleteFile("fresh.jpg");
// Фото чата живёт, пока на него ссылается вложение; файл удалённого чата — сирота
verify(storage, never()).deleteFile("chat/5/photo.jpg");
verify(storage).deleteFile("chat/5/deleted-chat.jpg");
}
@Test
@@ -58,7 +66,7 @@ class OrphanFileCleanupServiceTest {
FileStorageService storage = mock(FileStorageService.class);
new OrphanFileCleanupService(s3, mock(MinioProperties.class), mock(ImageRepository.class),
mock(UserRepository.class), storage, false, Duration.ofHours(24), 100).cleanupOrphanFiles();
mock(UserRepository.class), mock(MessageAttachmentRepository.class), storage, false, Duration.ofHours(24), 100).cleanupOrphanFiles();
verify(storage, never()).deleteFile(anyString());
}