Add video attachments to chat messages
- browser uploads the source straight to MinIO via presigned PUT (type and exact size are signed, up to 100 MB); upload is confirmed once by its owner - message is created with a PROCESSING video, transcoded in the background (chatVideoExecutor): H.264/AAC, short side up to 720px, faststart, metadata (incl. location) stripped, poster frame; up to 60 s - the updated message is re-broadcast over WebSocket when READY or FAILED; stuck processing is failed after 30 min - message_attachments: status, poster_key, duration_ms, processing_started_at - chat deletion and orphan cleanup handle video posters; rate limit chat-video Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -16,6 +16,7 @@ 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.enums.AttachmentStatus;
|
||||
import com.krylov.refound.entity.Post;
|
||||
import com.krylov.refound.entity.User;
|
||||
import com.krylov.refound.enums.PostStatus;
|
||||
@@ -31,6 +32,7 @@ import java.util.Optional;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.springframework.context.ApplicationEventPublisher;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.mock.web.MockMultipartFile;
|
||||
import org.springframework.transaction.support.TransactionCallback;
|
||||
@@ -46,6 +48,8 @@ class ChatServiceTest {
|
||||
private MessageRepository messageRepository;
|
||||
private MessageAttachmentRepository attachmentRepository;
|
||||
private ChatAttachmentService attachmentService;
|
||||
private ChatVideoUploadService videoUploadService;
|
||||
private ApplicationEventPublisher eventPublisher;
|
||||
private ChatService chatService;
|
||||
|
||||
@BeforeEach
|
||||
@@ -56,10 +60,12 @@ class ChatServiceTest {
|
||||
messageRepository = mock(MessageRepository.class);
|
||||
attachmentRepository = mock(MessageAttachmentRepository.class);
|
||||
attachmentService = mock(ChatAttachmentService.class);
|
||||
videoUploadService = mock(ChatVideoUploadService.class);
|
||||
eventPublisher = mock(ApplicationEventPublisher.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, attachmentRepository, attachmentService, tx);
|
||||
userRepository, postRepository, attachmentRepository, attachmentService, tx, videoUploadService, eventPublisher);
|
||||
|
||||
when(userRepository.existsById(anyLong())).thenReturn(true);
|
||||
when(chatRepository.findByUsersAndPost(any(), any(), any())).thenReturn(List.of());
|
||||
@@ -223,7 +229,8 @@ class ChatServiceTest {
|
||||
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());
|
||||
return new MessageAttachmentDto(a.getId(), a.getKind(), a.getStatus(), "https://minio/" + a.getObjectKey(),
|
||||
null, a.getWidth(), a.getHeight(), null);
|
||||
});
|
||||
|
||||
MessageDto dto = chatService.sendMessageWithPhotos(14L, 7L, null, files);
|
||||
@@ -277,13 +284,18 @@ class ChatServiceTest {
|
||||
@Test
|
||||
void deletingChatDeletesItsFiles() {
|
||||
chatBetween(7L, 14L, 19L);
|
||||
when(attachmentRepository.findObjectKeysByChatId(7L)).thenReturn(List.of("chat/7/a.jpg"));
|
||||
MessageAttachment photo = new MessageAttachment();
|
||||
photo.setObjectKey("chat/7/a.jpg");
|
||||
MessageAttachment video = new MessageAttachment();
|
||||
video.setObjectKey("chat/7/v.mp4");
|
||||
video.setPosterKey("chat/7/v.jpg");
|
||||
when(attachmentRepository.findByChatId(7L)).thenReturn(List.of(photo, video));
|
||||
|
||||
chatService.deleteChat(7L, 19L);
|
||||
|
||||
verify(chatRepository).deleteById(7L);
|
||||
// Без активной транзакции afterCommit выполняется сразу
|
||||
verify(attachmentService).deleteQuietly(List.of("chat/7/a.jpg"));
|
||||
verify(attachmentService).deleteQuietly(List.of("chat/7/a.jpg", "chat/7/v.mp4", "chat/7/v.jpg"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -292,13 +304,93 @@ class ChatServiceTest {
|
||||
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");
|
||||
when(attachmentService.toDto(attachment)).thenReturn(
|
||||
new MessageAttachmentDto(3L, AttachmentKind.PHOTO, AttachmentStatus.READY, "https://minio/signed", null, 1, 1, null));
|
||||
|
||||
assertThat(chatService.getAttachmentUrl(7L, 3L, 14L)).isEqualTo("https://minio/signed");
|
||||
assertThatThrownBy(() -> chatService.getAttachmentUrl(7L, 3L, 99L))
|
||||
assertThat(chatService.getAttachment(7L, 3L, 14L).getUrl()).isEqualTo("https://minio/signed");
|
||||
assertThatThrownBy(() -> chatService.getAttachment(7L, 3L, 99L))
|
||||
.isInstanceOfSatisfying(ApiException.class, e -> assertThat(e.getStatus()).isEqualTo(HttpStatus.FORBIDDEN));
|
||||
// Вложение другого чата по id своего чата не достать
|
||||
assertThatThrownBy(() -> chatService.getAttachmentUrl(7L, 4L, 14L))
|
||||
assertThatThrownBy(() -> chatService.getAttachment(7L, 4L, 14L))
|
||||
.isInstanceOfSatisfying(ApiException.class, e -> assertThat(e.getStatus()).isEqualTo(HttpStatus.NOT_FOUND));
|
||||
}
|
||||
|
||||
@Test
|
||||
void videoMessageIsSavedAsProcessingAndQueuedForTranscoding() {
|
||||
chatBetween(7L, 14L, 19L);
|
||||
when(videoUploadService.claim(7L, 14L, "chat/7/src/v.mov"))
|
||||
.thenReturn(new ChatVideoUploadService.ClaimedSource("chat/7/src/v.mov", "video/quicktime", 5_000_000));
|
||||
when(attachmentRepository.saveAll(any())).thenAnswer(inv -> {
|
||||
List<MessageAttachment> list = inv.getArgument(0);
|
||||
list.get(0).setId(77L);
|
||||
return list;
|
||||
});
|
||||
when(attachmentService.toDto(any())).thenAnswer(inv -> {
|
||||
MessageAttachment a = inv.getArgument(0);
|
||||
return new MessageAttachmentDto(a.getId(), a.getKind(), a.getStatus(), null, null, null, null, null);
|
||||
});
|
||||
|
||||
MessageDto dto = chatService.sendVideoMessage(14L, 7L, "смотрите", "chat/7/src/v.mov");
|
||||
|
||||
assertThat(dto.getContent()).isEqualTo("смотрите");
|
||||
assertThat(dto.getAttachments()).singleElement().satisfies(a -> {
|
||||
assertThat(a.getKind()).isEqualTo(AttachmentKind.VIDEO);
|
||||
assertThat(a.getStatus()).isEqualTo(AttachmentStatus.PROCESSING);
|
||||
// Пока видео не готово, ссылки на исходник не выдаются
|
||||
assertThat(a.getUrl()).isNull();
|
||||
});
|
||||
@SuppressWarnings("unchecked")
|
||||
ArgumentCaptor<List<MessageAttachment>> saved = ArgumentCaptor.forClass(List.class);
|
||||
verify(attachmentRepository).saveAll(saved.capture());
|
||||
assertThat(saved.getValue()).singleElement().satisfies(a -> {
|
||||
assertThat(a.getObjectKey()).isEqualTo("chat/7/src/v.mov");
|
||||
assertThat(a.getProcessingStartedAt()).isNotNull();
|
||||
});
|
||||
verify(eventPublisher).publishEvent(new ChatVideoUploadedEvent(77L));
|
||||
}
|
||||
|
||||
@Test
|
||||
void outsiderCannotRequestVideoUpload() {
|
||||
chatBetween(7L, 14L, 19L);
|
||||
|
||||
assertThatThrownBy(() -> chatService.requestVideoUpload(99L, 7L, "video/mp4", 1000))
|
||||
.isInstanceOfSatisfying(ApiException.class, e -> assertThat(e.getStatus()).isEqualTo(HttpStatus.FORBIDDEN));
|
||||
verify(videoUploadService, never()).requestUpload(any(), any(), any(), anyLong());
|
||||
}
|
||||
|
||||
@Test
|
||||
void videoSourceIsDeletedWhenMessageIsNotSaved() {
|
||||
chatBetween(7L, 14L, 19L);
|
||||
when(videoUploadService.claim(7L, 14L, "chat/7/src/v.mp4"))
|
||||
.thenReturn(new ChatVideoUploadService.ClaimedSource("chat/7/src/v.mp4", "video/mp4", 1000));
|
||||
when(messageRepository.save(any(Message.class))).thenThrow(new IllegalStateException("db down"));
|
||||
|
||||
assertThatThrownBy(() -> chatService.sendVideoMessage(14L, 7L, null, "chat/7/src/v.mp4"))
|
||||
.isInstanceOf(IllegalStateException.class);
|
||||
verify(videoUploadService).deleteQuietly("chat/7/src/v.mp4");
|
||||
verify(eventPublisher, never()).publishEvent(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void chatListPreviewKnowsVideo() {
|
||||
Chat chat = new Chat();
|
||||
chat.setId(1L);
|
||||
chat.setUserOneId(14L);
|
||||
chat.setUserTwoId(19L);
|
||||
when(chatRepository.findAllByUserId(14L)).thenReturn(List.of(chat));
|
||||
when(userRepository.findAllById(any())).thenReturn(List.of());
|
||||
Message last = new Message();
|
||||
last.setId(9L);
|
||||
last.setChatId(1L);
|
||||
last.setContent("");
|
||||
when(messageRepository.findLastMessages(any())).thenReturn(List.of(last));
|
||||
when(messageRepository.countUnreadByChat(any(), org.mockito.ArgumentMatchers.eq(14L))).thenReturn(List.of());
|
||||
when(attachmentRepository.findKindsByMessageIds(any()))
|
||||
.thenReturn(List.<Object[]>of(new Object[] {9L, AttachmentKind.VIDEO}));
|
||||
|
||||
ChatDto dto = chatService.getUserChats(14L).get(0);
|
||||
|
||||
assertThat(dto.getLastMessageAttachments()).isEqualTo(1);
|
||||
assertThat(dto.getLastMessageAttachmentKind()).isEqualTo(AttachmentKind.VIDEO);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,177 @@
|
||||
package com.krylov.refound.service;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.junit.jupiter.api.Assumptions.assumeTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
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.entity.MessageAttachment;
|
||||
import com.krylov.refound.enums.AttachmentStatus;
|
||||
import com.krylov.refound.repository.MessageAttachmentRepository;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.springframework.transaction.support.TransactionCallback;
|
||||
import org.springframework.transaction.support.TransactionTemplate;
|
||||
|
||||
class ChatVideoTranscoderTest {
|
||||
|
||||
/** Путь к ffmpeg: FFMPEG_PATH или ffmpeg из PATH. Тесты с настоящим ffmpeg без него пропускаются. */
|
||||
private static final String FFMPEG = System.getenv().getOrDefault("FFMPEG_PATH", "ffmpeg");
|
||||
|
||||
private MessageAttachmentRepository repository;
|
||||
private FileStorageService storage;
|
||||
private ChatService chatService;
|
||||
private ChatVideoTranscoder transcoder;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
repository = mock(MessageAttachmentRepository.class);
|
||||
storage = mock(FileStorageService.class);
|
||||
chatService = mock(ChatService.class);
|
||||
TransactionTemplate tx = mock(TransactionTemplate.class);
|
||||
when(tx.execute(any())).thenAnswer(inv -> inv.<TransactionCallback<?>>getArgument(0).doInTransaction(null));
|
||||
when(repository.save(any())).thenAnswer(inv -> inv.getArgument(0));
|
||||
transcoder = new ChatVideoTranscoder(repository, storage, chatService, tx, FFMPEG, "");
|
||||
}
|
||||
|
||||
@Test
|
||||
void ffprobeIsFoundNextToFfmpeg() {
|
||||
assertThat(ChatVideoTranscoder.ffprobeNextTo("C:\\ffmpeg\\bin\\ffmpeg.exe")).isEqualTo("C:\\ffmpeg\\bin\\ffprobe.exe");
|
||||
assertThat(ChatVideoTranscoder.ffprobeNextTo("/usr/bin/ffmpeg")).isEqualTo("/usr/bin/ffprobe");
|
||||
assertThat(ChatVideoTranscoder.ffprobeNextTo("ffmpeg")).isEqualTo("ffprobe");
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedVideoIsMarkedSourceDeletedAndChatNotified() {
|
||||
MessageAttachment attachment = processing(5L, "chat/7/src/v.mov");
|
||||
when(repository.findById(5L)).thenReturn(Optional.of(attachment));
|
||||
|
||||
transcoder.markFailed(5L);
|
||||
|
||||
assertThat(attachment.getStatus()).isEqualTo(AttachmentStatus.FAILED);
|
||||
verify(storage).deleteFile("chat/7/src/v.mov");
|
||||
verify(chatService).broadcastMessage(50L);
|
||||
}
|
||||
|
||||
@Test
|
||||
void readyVideoIsNotMarkedFailed() {
|
||||
MessageAttachment attachment = processing(5L, "chat/7/v.mp4");
|
||||
attachment.setStatus(AttachmentStatus.READY);
|
||||
when(repository.findById(5L)).thenReturn(Optional.of(attachment));
|
||||
|
||||
transcoder.markFailed(5L);
|
||||
|
||||
assertThat(attachment.getStatus()).isEqualTo(AttachmentStatus.READY);
|
||||
verify(storage, never()).deleteFile(anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void stuckVideosAreFailed() {
|
||||
MessageAttachment stuck = processing(5L, "chat/7/src/v.mov");
|
||||
when(repository.findByStatusAndProcessingStartedAtBefore(any(), any())).thenReturn(List.of(stuck));
|
||||
when(repository.findById(5L)).thenReturn(Optional.of(stuck));
|
||||
|
||||
transcoder.failStuck();
|
||||
|
||||
assertThat(stuck.getStatus()).isEqualTo(AttachmentStatus.FAILED);
|
||||
}
|
||||
|
||||
@Test
|
||||
void transcodesToMp4WithPosterAndWithoutMetadata(@TempDir Path dir) throws Exception {
|
||||
assumeTrue(ffmpegAvailable(), "ffmpeg не установлен");
|
||||
Path source = dir.resolve("source.mov");
|
||||
generate(source, 2, "1920x1080", "+55.7558+037.6173/");
|
||||
|
||||
ChatVideoTranscoder.Transcoded result = transcoder.process(source, dir);
|
||||
|
||||
// Короткая сторона ужата до 720
|
||||
assertThat(result.width()).isEqualTo(1280);
|
||||
assertThat(result.height()).isEqualTo(720);
|
||||
assertThat(result.durationMs()).isBetween(1800, 2300);
|
||||
assertThat(Files.size(result.poster())).isPositive();
|
||||
assertThat(new String(Files.readAllBytes(source), StandardCharsets.ISO_8859_1)).contains("+55.7558");
|
||||
assertThat(new String(Files.readAllBytes(result.video()), StandardCharsets.ISO_8859_1)).doesNotContain("+55.7558");
|
||||
}
|
||||
|
||||
@Test
|
||||
void portraitVideoKeepsOrientation(@TempDir Path dir) throws Exception {
|
||||
assumeTrue(ffmpegAvailable(), "ffmpeg не установлен");
|
||||
Path source = dir.resolve("source.mp4");
|
||||
generate(source, 1, "1080x1920", null);
|
||||
|
||||
ChatVideoTranscoder.Transcoded result = transcoder.process(source, dir);
|
||||
|
||||
assertThat(result.width()).isEqualTo(720);
|
||||
assertThat(result.height()).isEqualTo(1280);
|
||||
}
|
||||
|
||||
@Test
|
||||
void tooLongVideoIsRejected(@TempDir Path dir) throws Exception {
|
||||
assumeTrue(ffmpegAvailable(), "ffmpeg не установлен");
|
||||
Path source = dir.resolve("long.mp4");
|
||||
generate(source, 65, "160x120", null);
|
||||
|
||||
assertThatThrownBy(() -> transcoder.process(source, dir))
|
||||
.isInstanceOf(IOException.class)
|
||||
.hasMessageContaining("длиннее");
|
||||
}
|
||||
|
||||
@Test
|
||||
void notAVideoIsRejected(@TempDir Path dir) throws Exception {
|
||||
assumeTrue(ffmpegAvailable(), "ffmpeg не установлен");
|
||||
Path source = dir.resolve("fake.mp4");
|
||||
Files.writeString(source, "definitely not a video");
|
||||
|
||||
assertThatThrownBy(() -> transcoder.process(source, dir)).isInstanceOf(IOException.class);
|
||||
}
|
||||
|
||||
private static MessageAttachment processing(Long id, String key) {
|
||||
MessageAttachment attachment = new MessageAttachment();
|
||||
attachment.setId(id);
|
||||
attachment.setMessageId(50L);
|
||||
attachment.setChatId(7L);
|
||||
attachment.setObjectKey(key);
|
||||
attachment.setStatus(AttachmentStatus.PROCESSING);
|
||||
return attachment;
|
||||
}
|
||||
|
||||
private static boolean ffmpegAvailable() {
|
||||
try {
|
||||
Process p = new ProcessBuilder(FFMPEG, "-version").redirectErrorStream(true).start();
|
||||
p.getInputStream().readAllBytes();
|
||||
return p.waitFor(20, TimeUnit.SECONDS) && p.exitValue() == 0;
|
||||
} catch (IOException | InterruptedException e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** Тестовое видео со звуком; location — геометка, как у видео с телефона. */
|
||||
private static void generate(Path target, int seconds, String size, String location) throws Exception {
|
||||
List<String> cmd = new ArrayList<>(List.of(FFMPEG, "-nostdin", "-y",
|
||||
"-f", "lavfi", "-i", "testsrc=duration=" + seconds + ":size=" + size + ":rate=15",
|
||||
"-f", "lavfi", "-i", "sine=frequency=440:duration=" + seconds,
|
||||
"-c:v", "libx264", "-preset", "ultrafast", "-c:a", "aac", "-shortest"));
|
||||
if (location != null) {
|
||||
cmd.addAll(List.of("-metadata", "location=" + location));
|
||||
}
|
||||
cmd.add(target.toString());
|
||||
Process p = new ProcessBuilder(cmd).redirectErrorStream(true).start();
|
||||
p.getInputStream().readAllBytes();
|
||||
assertThat(p.waitFor(120, TimeUnit.SECONDS)).isTrue();
|
||||
assertThat(p.exitValue()).isZero();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
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.anyLong;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.ArgumentMatchers.startsWith;
|
||||
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.exception.ApiException;
|
||||
import java.util.Optional;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.data.redis.core.ValueOperations;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import software.amazon.awssdk.services.s3.model.HeadObjectResponse;
|
||||
|
||||
class ChatVideoUploadServiceTest {
|
||||
|
||||
private FileStorageService storage;
|
||||
private ValueOperations<String, String> redis;
|
||||
private StringRedisTemplate template;
|
||||
private ChatVideoUploadService service;
|
||||
|
||||
@BeforeEach
|
||||
@SuppressWarnings("unchecked")
|
||||
void setUp() {
|
||||
storage = mock(FileStorageService.class);
|
||||
template = mock(StringRedisTemplate.class);
|
||||
redis = mock(ValueOperations.class);
|
||||
when(template.opsForValue()).thenReturn(redis);
|
||||
service = new ChatVideoUploadService(storage, template);
|
||||
when(storage.generatePresignedUploadUrl(anyString(), anyString(), anyLong(), any())).thenReturn("https://minio/put");
|
||||
}
|
||||
|
||||
@Test
|
||||
void uploadUrlIsSignedForTypeAndSizeAndRemembered() {
|
||||
ChatVideoUploadService.UploadTicket ticket = service.requestUpload(7L, 14L, "video/quicktime", 5_000_000);
|
||||
|
||||
assertThat(ticket.uploadUrl()).isEqualTo("https://minio/put");
|
||||
assertThat(ticket.sourceKey()).startsWith("chat/7/src/").endsWith(".mov");
|
||||
verify(storage).generatePresignedUploadUrl(eq(ticket.sourceKey()), eq("video/quicktime"), eq(5_000_000L), any());
|
||||
verify(redis).set(eq("chat:video-upload:" + ticket.sourceKey()), eq("7:14"), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void wrongTypeOrTooBigIsRejected() {
|
||||
assertThatThrownBy(() -> service.requestUpload(7L, 14L, "image/gif", 1000))
|
||||
.isInstanceOfSatisfying(ApiException.class, e -> assertThat(e.getStatus()).isEqualTo(HttpStatus.BAD_REQUEST));
|
||||
assertThatThrownBy(() -> service.requestUpload(7L, 14L, "video/mp4", ChatVideoUploadService.MAX_SOURCE_BYTES + 1))
|
||||
.isInstanceOfSatisfying(ApiException.class, e -> assertThat(e.getStatus()).isEqualTo(HttpStatus.BAD_REQUEST));
|
||||
verify(storage, never()).generatePresignedUploadUrl(anyString(), anyString(), anyLong(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void claimAcceptsOwnUploadOnce() {
|
||||
when(redis.get("chat:video-upload:chat/7/src/v.mp4")).thenReturn("7:14");
|
||||
// Запись удаляется один раз: второй запрос её уже не найдёт
|
||||
when(template.delete("chat:video-upload:chat/7/src/v.mp4")).thenReturn(true).thenReturn(false);
|
||||
when(storage.headObject("chat/7/src/v.mp4"))
|
||||
.thenReturn(Optional.of(HeadObjectResponse.builder().contentLength(1000L).contentType("video/mp4").build()));
|
||||
|
||||
ChatVideoUploadService.ClaimedSource claimed = service.claim(7L, 14L, "chat/7/src/v.mp4");
|
||||
|
||||
assertThat(claimed.sizeBytes()).isEqualTo(1000L);
|
||||
// Повторно ту же загрузку не подтвердить
|
||||
assertThatThrownBy(() -> service.claim(7L, 14L, "chat/7/src/v.mp4")).isInstanceOf(ApiException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
void foreignUploadCannotBeClaimedAndIsNotBurned() {
|
||||
// Ключ выдан пользователю 19 — пользователь 14 его не подтвердит
|
||||
when(redis.get("chat:video-upload:chat/7/src/v.mp4")).thenReturn("7:19");
|
||||
|
||||
assertThatThrownBy(() -> service.claim(7L, 14L, "chat/7/src/v.mp4"))
|
||||
.isInstanceOfSatisfying(ApiException.class, e -> assertThat(e.getStatus()).isEqualTo(HttpStatus.BAD_REQUEST));
|
||||
verify(storage, never()).headObject(anyString());
|
||||
// Чужая попытка не удаляет запись — настоящий отправитель ещё может подтвердить загрузку
|
||||
verify(template, never()).delete(anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void notUploadedOrOversizedSourceIsRejected() {
|
||||
when(redis.get(startsWith("chat:video-upload:"))).thenReturn("7:14");
|
||||
when(template.delete(startsWith("chat:video-upload:"))).thenReturn(true);
|
||||
when(storage.headObject("chat/7/src/missing.mp4")).thenReturn(Optional.empty());
|
||||
when(storage.headObject("chat/7/src/huge.mp4")).thenReturn(Optional.of(
|
||||
HeadObjectResponse.builder().contentLength(ChatVideoUploadService.MAX_SOURCE_BYTES + 1).build()));
|
||||
|
||||
assertThatThrownBy(() -> service.claim(7L, 14L, "chat/7/src/missing.mp4")).isInstanceOf(ApiException.class);
|
||||
assertThatThrownBy(() -> service.claim(7L, 14L, "chat/7/src/huge.mp4")).isInstanceOf(ApiException.class);
|
||||
verify(storage).deleteFile("chat/7/src/huge.mp4");
|
||||
verify(storage, never()).deleteFile("chat/7/src/missing.mp4");
|
||||
}
|
||||
}
|
||||
@@ -32,6 +32,7 @@ class OrphanFileCleanupServiceTest {
|
||||
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/video-poster.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)))
|
||||
@@ -46,6 +47,7 @@ class OrphanFileCleanupServiceTest {
|
||||
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"));
|
||||
when(attachments.findAllPosterKeys()).thenReturn(List.of("chat/5/video-poster.jpg"));
|
||||
FileStorageService storage = mock(FileStorageService.class);
|
||||
|
||||
new OrphanFileCleanupService(s3, properties, images, users, attachments, storage, true, Duration.ofHours(24), 100)
|
||||
@@ -57,6 +59,7 @@ class OrphanFileCleanupServiceTest {
|
||||
verify(storage, never()).deleteFile("fresh.jpg");
|
||||
// Фото чата живёт, пока на него ссылается вложение; файл удалённого чата — сирота
|
||||
verify(storage, never()).deleteFile("chat/5/photo.jpg");
|
||||
verify(storage, never()).deleteFile("chat/5/video-poster.jpg");
|
||||
verify(storage).deleteFile("chat/5/deleted-chat.jpg");
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user