From 871b16a03859bd096228afc6fb101a9e5c691e90 Mon Sep 17 00:00:00 2001 From: SlimusMinus Date: Wed, 28 Oct 2026 23:00:11 +0300 Subject: [PATCH] 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 --- .../krylov/refound/config/AsyncConfig.java | 15 + .../refound/controller/ChatController.java | 37 ++- .../java/com/krylov/refound/dto/ChatDto.java | 3 + .../refound/dto/MessageAttachmentDto.java | 11 +- .../krylov/refound/dto/SendVideoRequest.java | 5 + .../refound/dto/VideoUploadRequest.java | 5 + .../refound/entity/MessageAttachment.java | 24 +- .../krylov/refound/enums/AttachmentKind.java | 5 +- .../refound/enums/AttachmentStatus.java | 11 + .../MessageAttachmentRepository.java | 22 +- .../service/ChatAttachmentService.java | 14 +- .../krylov/refound/service/ChatService.java | 117 +++++-- .../service/ChatVideoEventListener.java | 31 ++ .../refound/service/ChatVideoTranscoder.java | 289 ++++++++++++++++++ .../service/ChatVideoUploadService.java | 119 ++++++++ .../service/ChatVideoUploadedEvent.java | 5 + .../refound/service/FileStorageService.java | 61 ++++ .../service/OrphanFileCleanupService.java | 1 + src/main/resources/application.yaml | 6 + .../add/025-message-attachments-video.yaml | 32 ++ .../db/changelog/db.changelog-master.yaml | 1 + .../refound/service/ChatServiceTest.java | 108 ++++++- .../service/ChatVideoTranscoderTest.java | 177 +++++++++++ .../service/ChatVideoUploadServiceTest.java | 101 ++++++ .../service/OrphanFileCleanupServiceTest.java | 3 + 25 files changed, 1151 insertions(+), 52 deletions(-) create mode 100644 src/main/java/com/krylov/refound/dto/SendVideoRequest.java create mode 100644 src/main/java/com/krylov/refound/dto/VideoUploadRequest.java create mode 100644 src/main/java/com/krylov/refound/enums/AttachmentStatus.java create mode 100644 src/main/java/com/krylov/refound/service/ChatVideoEventListener.java create mode 100644 src/main/java/com/krylov/refound/service/ChatVideoTranscoder.java create mode 100644 src/main/java/com/krylov/refound/service/ChatVideoUploadService.java create mode 100644 src/main/java/com/krylov/refound/service/ChatVideoUploadedEvent.java create mode 100644 src/main/resources/db/changelog/add/025-message-attachments-video.yaml create mode 100644 src/test/java/com/krylov/refound/service/ChatVideoTranscoderTest.java create mode 100644 src/test/java/com/krylov/refound/service/ChatVideoUploadServiceTest.java diff --git a/src/main/java/com/krylov/refound/config/AsyncConfig.java b/src/main/java/com/krylov/refound/config/AsyncConfig.java index 031d701..f1202c8 100644 --- a/src/main/java/com/krylov/refound/config/AsyncConfig.java +++ b/src/main/java/com/krylov/refound/config/AsyncConfig.java @@ -22,4 +22,19 @@ public class AsyncConfig { executor.initialize(); return executor; } + + /** + * Видео из чатов — отдельно от рекламы: очередь пользовательских видео не + * должна задерживать обработку рекламных роликов и наоборот. + */ + @Bean(name = "chatVideoExecutor") + public Executor chatVideoExecutor() { + ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); + executor.setCorePoolSize(2); + executor.setMaxPoolSize(2); + executor.setQueueCapacity(50); + executor.setThreadNamePrefix("chat-video-"); + executor.initialize(); + return executor; + } } diff --git a/src/main/java/com/krylov/refound/controller/ChatController.java b/src/main/java/com/krylov/refound/controller/ChatController.java index a8d547f..01dd974 100644 --- a/src/main/java/com/krylov/refound/controller/ChatController.java +++ b/src/main/java/com/krylov/refound/controller/ChatController.java @@ -1,12 +1,15 @@ package com.krylov.refound.controller; import com.krylov.refound.dto.ChatDto; +import com.krylov.refound.dto.MessageAttachmentDto; import com.krylov.refound.dto.MessageDto; +import com.krylov.refound.dto.SendVideoRequest; import com.krylov.refound.dto.StartChatRequest; +import com.krylov.refound.dto.VideoUploadRequest; import com.krylov.refound.service.ChatService; +import com.krylov.refound.service.ChatVideoUploadService; 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; @@ -82,11 +85,37 @@ public class ChatController { return chatService.sendMessageWithPhotos(currentUserId, chatId, content, files); } - /** Свежая временная ссылка на вложение (выданная с сообщением живёт несколько часов). */ + /** + * Свежие временные ссылки на вложение (выданные с сообщением живут несколько + * часов): url и, у видео, posterUrl. + */ @GetMapping("/{chatId}/attachments/{attachmentId}/url") - public Map getAttachmentUrl(@PathVariable Long chatId, @PathVariable Long attachmentId, Authentication auth) { + public MessageAttachmentDto getAttachmentUrl(@PathVariable Long chatId, @PathVariable Long attachmentId, Authentication auth) { Long currentUserId = extractUserId(auth); - return Map.of("url", chatService.getAttachmentUrl(chatId, attachmentId, currentUserId)); + return chatService.getAttachment(chatId, attachmentId, currentUserId); + } + + /** + * Видео, шаг 1: ссылка для загрузки исходника прямо в MinIO (PUT с тем же + * Content-Type и размером, что указаны в запросе). + */ + @PostMapping("/{chatId}/videos/upload-url") + public ChatVideoUploadService.UploadTicket requestVideoUpload(@PathVariable Long chatId, + @RequestBody VideoUploadRequest request, Authentication auth) { + Long currentUserId = extractUserId(auth); + log.info("requestVideoUpload chatId {} by user {}, {} bytes", chatId, currentUserId, request.sizeBytes()); + return chatService.requestVideoUpload(currentUserId, chatId, request.contentType(), request.sizeBytes()); + } + + /** + * Видео, шаг 2: исходник загружен — создаётся сообщение с видео в обработке. + * Готовое видео придёт по /topic/chat/{chatId} тем же сообщением (тот же id). + */ + @PostMapping("/{chatId}/videos") + public MessageDto sendVideoMessage(@PathVariable Long chatId, @RequestBody SendVideoRequest request, Authentication auth) { + Long currentUserId = extractUserId(auth); + log.info("sendVideoMessage chatId {} by user {}", chatId, currentUserId); + return chatService.sendVideoMessage(currentUserId, chatId, request.content(), request.sourceKey()); } @DeleteMapping("/{chatId}") diff --git a/src/main/java/com/krylov/refound/dto/ChatDto.java b/src/main/java/com/krylov/refound/dto/ChatDto.java index 5042105..840b3e4 100644 --- a/src/main/java/com/krylov/refound/dto/ChatDto.java +++ b/src/main/java/com/krylov/refound/dto/ChatDto.java @@ -1,5 +1,6 @@ package com.krylov.refound.dto; +import com.krylov.refound.enums.AttachmentKind; import java.time.LocalDateTime; import lombok.Data; @@ -15,5 +16,7 @@ public class ChatDto { private LocalDateTime lastMessageAt; /** Сколько вложений в последнем сообщении — для превью «Фото» без текста. */ private int lastMessageAttachments; + /** Тип вложений последнего сообщения (PHOTO/VIDEO) или null. */ + private AttachmentKind lastMessageAttachmentKind; private long unreadCount; } diff --git a/src/main/java/com/krylov/refound/dto/MessageAttachmentDto.java b/src/main/java/com/krylov/refound/dto/MessageAttachmentDto.java index bd6af12..cdbc256 100644 --- a/src/main/java/com/krylov/refound/dto/MessageAttachmentDto.java +++ b/src/main/java/com/krylov/refound/dto/MessageAttachmentDto.java @@ -1,14 +1,16 @@ package com.krylov.refound.dto; import com.krylov.refound.enums.AttachmentKind; +import com.krylov.refound.enums.AttachmentStatus; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; /** - * Вложение сообщения. url — временная (presigned) ссылка прямо на файл в MinIO: - * её получают только участники чата вместе с сообщением. Когда ссылка истечёт, - * свежую выдаёт GET /api/v1/chats/{chatId}/attachments/{id}/url. + * Вложение сообщения. url (и posterUrl у видео) — временные (presigned) ссылки + * прямо на файлы в MinIO: их получают только участники чата вместе с сообщением. + * Когда ссылка истечёт, свежую выдаёт GET /api/v1/chats/{chatId}/attachments/{id}/url. + * Пока видео обрабатывается (status PROCESSING) или не обработалось (FAILED), ссылок нет. */ @Data @NoArgsConstructor @@ -16,7 +18,10 @@ import lombok.NoArgsConstructor; public class MessageAttachmentDto { private Long id; private AttachmentKind kind; + private AttachmentStatus status; private String url; + private String posterUrl; private Integer width; private Integer height; + private Integer durationMs; } diff --git a/src/main/java/com/krylov/refound/dto/SendVideoRequest.java b/src/main/java/com/krylov/refound/dto/SendVideoRequest.java new file mode 100644 index 0000000..c6eff8c --- /dev/null +++ b/src/main/java/com/krylov/refound/dto/SendVideoRequest.java @@ -0,0 +1,5 @@ +package com.krylov.refound.dto; + +/** Подтверждение загрузки видео: ключ из ответа upload-url и необязательный текст. */ +public record SendVideoRequest(String sourceKey, String content) { +} diff --git a/src/main/java/com/krylov/refound/dto/VideoUploadRequest.java b/src/main/java/com/krylov/refound/dto/VideoUploadRequest.java new file mode 100644 index 0000000..c0822b3 --- /dev/null +++ b/src/main/java/com/krylov/refound/dto/VideoUploadRequest.java @@ -0,0 +1,5 @@ +package com.krylov.refound.dto; + +/** Запрос ссылки на загрузку видео: тип и точный размер файла входят в подпись ссылки. */ +public record VideoUploadRequest(String contentType, long sizeBytes) { +} diff --git a/src/main/java/com/krylov/refound/entity/MessageAttachment.java b/src/main/java/com/krylov/refound/entity/MessageAttachment.java index 4be5694..28388e1 100644 --- a/src/main/java/com/krylov/refound/entity/MessageAttachment.java +++ b/src/main/java/com/krylov/refound/entity/MessageAttachment.java @@ -1,6 +1,7 @@ package com.krylov.refound.entity; import com.krylov.refound.enums.AttachmentKind; +import com.krylov.refound.enums.AttachmentStatus; import com.krylov.refound.util.TimeZoneContext; import jakarta.persistence.Column; import jakarta.persistence.Entity; @@ -11,14 +12,16 @@ import jakarta.persistence.GenerationType; import jakarta.persistence.Id; import jakarta.persistence.PrePersist; import jakarta.persistence.Table; +import java.time.Instant; import java.time.LocalDateTime; import lombok.Getter; import lombok.Setter; /** - * Вложение сообщения чата. Файл лежит в бакете картинок под ключом - * chat/{chatId}/{uuid}.ext; общий /api/v1/files его не отдаёт — ссылку - * получают только участники чата вместе с сообщением. + * Вложение сообщения чата (фото или видео). Файл лежит в бакете картинок под + * ключом chat/{chatId}/{uuid}.ext; общий /api/v1/files его не отдаёт — ссылку + * получают только участники чата вместе с сообщением. Пока видео + * перекодируется, objectKey указывает на исходник (chat/{chatId}/src/...). */ @Entity @Table(name = "message_attachments") @@ -52,6 +55,21 @@ public class MessageAttachment { private Integer height; + @Enumerated(EnumType.STRING) + @Column(nullable = false, length = 16) + private AttachmentStatus status = AttachmentStatus.READY; + + /** Кадр-обложка видео (у фото нет). */ + @Column(name = "poster_key") + private String posterKey; + + @Column(name = "duration_ms") + private Integer durationMs; + + /** Когда видео поставлено в обработку — по нему находятся зависшие. */ + @Column(name = "processing_started_at") + private Instant processingStartedAt; + /** Порядок вложения в сообщении (0, 1, ...). */ @Column(nullable = false) private int position; diff --git a/src/main/java/com/krylov/refound/enums/AttachmentKind.java b/src/main/java/com/krylov/refound/enums/AttachmentKind.java index a8d8cea..27eb6bb 100644 --- a/src/main/java/com/krylov/refound/enums/AttachmentKind.java +++ b/src/main/java/com/krylov/refound/enums/AttachmentKind.java @@ -1,6 +1,7 @@ package com.krylov.refound.enums; -/** Тип вложения сообщения чата. VIDEO появится вторым этапом. */ +/** Тип вложения сообщения чата. */ public enum AttachmentKind { - PHOTO + PHOTO, + VIDEO } diff --git a/src/main/java/com/krylov/refound/enums/AttachmentStatus.java b/src/main/java/com/krylov/refound/enums/AttachmentStatus.java new file mode 100644 index 0000000..f37d93c --- /dev/null +++ b/src/main/java/com/krylov/refound/enums/AttachmentStatus.java @@ -0,0 +1,11 @@ +package com.krylov.refound.enums; + +/** + * Готовность вложения. Фото готовы сразу; видео после загрузки перекодируется + * в фоне (PROCESSING) и становится READY или FAILED. + */ +public enum AttachmentStatus { + READY, + PROCESSING, + FAILED +} diff --git a/src/main/java/com/krylov/refound/repository/MessageAttachmentRepository.java b/src/main/java/com/krylov/refound/repository/MessageAttachmentRepository.java index c53e1e6..cdddf04 100644 --- a/src/main/java/com/krylov/refound/repository/MessageAttachmentRepository.java +++ b/src/main/java/com/krylov/refound/repository/MessageAttachmentRepository.java @@ -1,6 +1,8 @@ package com.krylov.refound.repository; import com.krylov.refound.entity.MessageAttachment; +import com.krylov.refound.enums.AttachmentStatus; +import java.time.Instant; import java.util.Collection; import java.util.List; import java.util.Optional; @@ -15,15 +17,21 @@ public interface MessageAttachmentRepository extends JpaRepository findByIdAndChatId(Long id, Long chatId); - /** Ключи файлов чата — чтобы удалить их из хранилища вместе с чатом. */ - @Query("select a.objectKey from MessageAttachment a where a.chatId = :chatId") - List findObjectKeysByChatId(@Param("chatId") Long chatId); + List findByChatId(Long chatId); - /** Число вложений у сообщений: строки (messageId, count) — для превью в списке чатов. */ - @Query("select a.messageId, count(a) from MessageAttachment a where a.messageId in :messageIds group by a.messageId") - List countByMessageIds(@Param("messageIds") Collection messageIds); + List findByMessageId(Long messageId); - /** Все ключи вложений — для чистки файлов-сирот. */ + /** Типы вложений у сообщений: строки (messageId, kind) — для превью в списке чатов. */ + @Query("select a.messageId, a.kind from MessageAttachment a where a.messageId in :messageIds") + List findKindsByMessageIds(@Param("messageIds") Collection messageIds); + + /** Все ключи вложений (и обложек видео) — для чистки файлов-сирот. */ @Query("select a.objectKey from MessageAttachment a") List findAllObjectKeys(); + + @Query("select a.posterKey from MessageAttachment a where a.posterKey is not null") + List findAllPosterKeys(); + + /** Видео, обработка которых началась раньше deadline и так и не закончилась. */ + List findByStatusAndProcessingStartedAtBefore(AttachmentStatus status, Instant deadline); } diff --git a/src/main/java/com/krylov/refound/service/ChatAttachmentService.java b/src/main/java/com/krylov/refound/service/ChatAttachmentService.java index 44dabd8..c8de37e 100644 --- a/src/main/java/com/krylov/refound/service/ChatAttachmentService.java +++ b/src/main/java/com/krylov/refound/service/ChatAttachmentService.java @@ -2,6 +2,7 @@ package com.krylov.refound.service; import com.krylov.refound.dto.MessageAttachmentDto; import com.krylov.refound.entity.MessageAttachment; +import com.krylov.refound.enums.AttachmentStatus; import com.krylov.refound.enums.ErrorCode; import com.krylov.refound.exception.ApiException; import com.krylov.refound.util.ImageFormat; @@ -17,8 +18,9 @@ import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; /** - * Файлы вложений чата: проверка, перекодирование, загрузка в бакет и выдача - * временных ссылок. Про сообщения и права доступа не знает — это делает ChatService. + * Файлы фото-вложений чата: проверка, перекодирование, загрузка в бакет и выдача + * временных ссылок (и для видео). Про сообщения и права доступа не знает — это + * делает ChatService; видео — ChatVideoUploadService и ChatVideoTranscoder. * *

Ключи лежат под {@link #KEY_PREFIX}: общий /api/v1/files такие ключи не * отдаёт и не удаляет, а чистка сирот сверяет их с message_attachments. @@ -98,9 +100,13 @@ public class ChatAttachmentService { 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()); + boolean ready = attachment.getStatus() == AttachmentStatus.READY; + return new MessageAttachmentDto(attachment.getId(), attachment.getKind(), attachment.getStatus(), + ready ? url(attachment.getObjectKey()) : null, + ready && attachment.getPosterKey() != null ? url(attachment.getPosterKey()) : null, + attachment.getWidth(), attachment.getHeight(), attachment.getDurationMs()); } public String url(String objectKey) { diff --git a/src/main/java/com/krylov/refound/service/ChatService.java b/src/main/java/com/krylov/refound/service/ChatService.java index 84b12a3..d5be2c4 100644 --- a/src/main/java/com/krylov/refound/service/ChatService.java +++ b/src/main/java/com/krylov/refound/service/ChatService.java @@ -3,6 +3,7 @@ package com.krylov.refound.service; import com.krylov.refound.config.ClusterMessaging; import com.krylov.refound.dto.ChatDto; import com.krylov.refound.dto.ChatPostDto; +import com.krylov.refound.dto.MessageAttachmentDto; import com.krylov.refound.dto.MessageDto; import com.krylov.refound.entity.Chat; import com.krylov.refound.entity.Image; @@ -11,6 +12,7 @@ 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.AttachmentStatus; import com.krylov.refound.enums.ErrorCode; import com.krylov.refound.exception.ApiException; import com.krylov.refound.repository.ChatRepository; @@ -18,6 +20,7 @@ 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.Instant; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.Comparator; @@ -30,6 +33,7 @@ import java.util.function.Function; import java.util.stream.Collectors; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; +import org.springframework.context.ApplicationEventPublisher; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpStatus; @@ -57,6 +61,8 @@ public class ChatService { private final MessageAttachmentRepository attachmentRepository; private final ChatAttachmentService attachmentService; private final TransactionTemplate transactionTemplate; + private final ChatVideoUploadService videoUploadService; + private final ApplicationEventPublisher eventPublisher; /** * Ищет существующий чат с пользователем по объявлению, ничего не создавая. @@ -165,22 +171,83 @@ public class ChatService { checkParticipant(chat, senderId); List stored = attachmentService.storePhotos(chatId, photos); + List attachments = new ArrayList<>(); + for (ChatAttachmentService.StoredPhoto photo : stored) { + MessageAttachment attachment = new MessageAttachment(); + attachment.setKind(AttachmentKind.PHOTO); + attachment.setObjectKey(photo.objectKey()); + attachment.setContentType(photo.contentType()); + attachment.setSizeBytes(photo.sizeBytes()); + attachment.setWidth(photo.width()); + attachment.setHeight(photo.height()); + attachments.add(attachment); + } try { - return transactionTemplate.execute(status -> saveAndBroadcast(chat, senderId, text, stored)); + return transactionTemplate.execute(status -> saveAndBroadcast(chat, senderId, text, attachments)); } 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) { + public MessageAttachmentDto getAttachment(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()); + return attachmentService.toDto(attachment); + } + + /** Шаг 1 отправки видео: ссылка, по которой браузер загрузит исходник прямо в MinIO. */ + public ChatVideoUploadService.UploadTicket requestVideoUpload(Long userId, Long chatId, String contentType, long sizeBytes) { + Chat chat = getChatOrThrow(chatId); + checkParticipant(chat, userId); + return videoUploadService.requestUpload(chatId, userId, contentType, sizeBytes); + } + + /** + * Шаг 2 отправки видео: исходник загружен — создаём сообщение с вложением в + * статусе PROCESSING и после коммита ставим видео в очередь обработки. Когда + * обработка закончится, сообщение придёт в чат ещё раз — уже с готовым видео. + */ + public MessageDto sendVideoMessage(Long senderId, Long chatId, String content, String sourceKey) { + String text = content == null ? "" : content; + 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); + + ChatVideoUploadService.ClaimedSource source = videoUploadService.claim(chatId, senderId, sourceKey); + MessageAttachment video = new MessageAttachment(); + video.setKind(AttachmentKind.VIDEO); + video.setStatus(AttachmentStatus.PROCESSING); + video.setObjectKey(source.sourceKey()); + video.setContentType(source.contentType() == null ? "application/octet-stream" : source.contentType()); + video.setSizeBytes(source.sizeBytes()); + video.setProcessingStartedAt(Instant.now()); + try { + return transactionTemplate.execute(status -> { + MessageDto dto = saveAndBroadcast(chat, senderId, text, List.of(video)); + eventPublisher.publishEvent(new ChatVideoUploadedEvent(dto.getAttachments().get(0).getId())); + return dto; + }); + } catch (RuntimeException e) { + videoUploadService.deleteQuietly(source.sourceKey()); + throw e; + } + } + + /** Повторно рассылает сообщение в чат — например, когда видео в нём обработалось. */ + @Transactional(readOnly = true) + public void broadcastMessage(Long messageId) { + messageRepository.findById(messageId).ifPresent(message -> { + MessageDto dto = toMessageDto(message, attachmentRepository.findByMessageId(messageId)); + messaging.convertAndSend("/topic/chat/" + message.getChatId(), dto); + }); } // Отправка сообщения (вызывается из WebSocket контроллера) @@ -204,8 +271,12 @@ public class ChatService { } } + /** + * Сохраняет сообщение с вложениями (у вложений заполнены поля файла; сообщение, + * чат и порядок проставляются здесь) и рассылает его после коммита. + */ private MessageDto saveAndBroadcast(Chat chat, Long senderId, String content, - List photos) { + List newAttachments) { Long chatId = chat.getId(); Message message = new Message(); message.setChatId(chatId); @@ -213,20 +284,12 @@ public class ChatService { message.setContent(content); message = messageRepository.save(message); - List attachments = new ArrayList<>(); - for (int i = 0; i < photos.size(); i++) { - ChatAttachmentService.StoredPhoto photo = photos.get(i); - MessageAttachment attachment = new MessageAttachment(); + List attachments = new ArrayList<>(newAttachments); + for (int i = 0; i < attachments.size(); i++) { + MessageAttachment attachment = attachments.get(i); 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); @@ -272,7 +335,13 @@ public class ChatService { checkParticipant(chat, userId); // Строки вложений удалит каскад в БД, а файлы — только мы: после коммита, // чтобы откат транзакции не оставил чат без фото - List keys = attachmentRepository.findObjectKeysByChatId(chatId); + List keys = new ArrayList<>(); + for (MessageAttachment attachment : attachmentRepository.findByChatId(chatId)) { + keys.add(attachment.getObjectKey()); + if (attachment.getPosterKey() != null) { + keys.add(attachment.getPosterKey()); + } + } chatRepository.deleteById(chatId); if (!keys.isEmpty()) { afterCommit(() -> attachmentService.deleteQuietly(keys)); @@ -335,13 +404,18 @@ public class ChatService { for (Object[] row : messageRepository.countUnreadByChat(chatIds, currentUserId)) { unread.put(((Number) row[0]).longValue(), ((Number) row[1]).longValue()); } - // Сколько фото в последнем сообщении: у сообщения только с фото текста нет, - // и превью в списке чатов показывает «Фото» вместо пустой строки + // Вложения последнего сообщения: у сообщения только с фото или видео текста + // нет, и превью в списке чатов показывает «Фото»/«Видео» вместо пустой строки Map lastAttachments = new HashMap<>(); + Map lastAttachmentKinds = new HashMap<>(); if (!lastMessages.isEmpty()) { - for (Object[] row : attachmentRepository.countByMessageIds( + for (Object[] row : attachmentRepository.findKindsByMessageIds( lastMessages.values().stream().map(Message::getId).toList())) { - lastAttachments.put(((Number) row[0]).longValue(), ((Number) row[1]).intValue()); + Long messageId = ((Number) row[0]).longValue(); + lastAttachments.merge(messageId, 1, Integer::sum); + // Видео важнее фото: оно всегда одно и без фото рядом + lastAttachmentKinds.merge(messageId, (AttachmentKind) row[1], + (a, b) -> a == AttachmentKind.VIDEO ? a : b); } } @@ -375,6 +449,7 @@ public class ChatService { dto.setLastMessage(last.getContent()); dto.setLastMessageAt(last.getCreatedAt()); dto.setLastMessageAttachments(lastAttachments.getOrDefault(last.getId(), 0)); + dto.setLastMessageAttachmentKind(lastAttachmentKinds.get(last.getId())); } dto.setUnreadCount(unread.getOrDefault(chat.getId(), 0L)); return dto; diff --git a/src/main/java/com/krylov/refound/service/ChatVideoEventListener.java b/src/main/java/com/krylov/refound/service/ChatVideoEventListener.java new file mode 100644 index 0000000..e2c9ebd --- /dev/null +++ b/src/main/java/com/krylov/refound/service/ChatVideoEventListener.java @@ -0,0 +1,31 @@ +package com.krylov.refound.service; + +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.core.task.TaskRejectedException; +import org.springframework.stereotype.Component; +import org.springframework.transaction.event.TransactionPhase; +import org.springframework.transaction.event.TransactionalEventListener; + +/** + * Ставит видео в очередь только после коммита: иначе фоновая задача могла + * начаться раньше, чем вложение появится в базе. + */ +@Slf4j +@Component +@RequiredArgsConstructor +public class ChatVideoEventListener { + + private final ChatVideoTranscoder transcoder; + + @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT) + public void onVideoUploaded(ChatVideoUploadedEvent event) { + try { + transcoder.transcode(event.attachmentId()); + } catch (TaskRejectedException e) { + // Очередь обработки переполнена — честно говорим, что видео не обработано + log.warn("Очередь обработки видео переполнена, видео {} отклонено", event.attachmentId()); + transcoder.markFailed(event.attachmentId()); + } + } +} diff --git a/src/main/java/com/krylov/refound/service/ChatVideoTranscoder.java b/src/main/java/com/krylov/refound/service/ChatVideoTranscoder.java new file mode 100644 index 0000000..0a51452 --- /dev/null +++ b/src/main/java/com/krylov/refound/service/ChatVideoTranscoder.java @@ -0,0 +1,289 @@ +package com.krylov.refound.service; + +import com.krylov.refound.entity.MessageAttachment; +import com.krylov.refound.enums.AttachmentStatus; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Duration; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.stream.Stream; +import lombok.extern.slf4j.Slf4j; +import net.javacrumbs.shedlock.spring.annotation.SchedulerLock; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.scheduling.annotation.Async; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Service; +import org.springframework.transaction.support.TransactionTemplate; +import com.krylov.refound.repository.MessageAttachmentRepository; + +/** + * Фоновая обработка видео из чата: исходник → ffprobe (длительность) → ffmpeg + * (H.264/AAC, короткая сторона до 720p, faststart, без метаданных — в том числе + * геолокации из mov) → кадр-обложка → загрузка в бакет. По итогу вложение + * становится READY или FAILED, и обновлённое сообщение рассылается в чат. + */ +@Slf4j +@Service +public class ChatVideoTranscoder { + + /** Длиннее не принимаем: чат — не видеохостинг, и сервер не резиновый. */ + public static final Duration MAX_DURATION = Duration.ofSeconds(60); + /** Запас на округление длительности у разных контейнеров. */ + private static final double DURATION_TOLERANCE_SECONDS = 1.5; + private static final long FFMPEG_TIMEOUT_MINUTES = 5; + private static final long FFPROBE_TIMEOUT_SECONDS = 30; + private static final int LOG_TAIL_LINES = 20; + /** Зависшей считается обработка дольше этого (сервер перезапустился, очередь потерялась). */ + static final Duration STUCK_AFTER = Duration.ofMinutes(30); + + private final MessageAttachmentRepository attachmentRepository; + private final FileStorageService fileStorageService; + private final ChatService chatService; + private final TransactionTemplate transactionTemplate; + private final String ffmpegPath; + private final String ffprobePath; + + public ChatVideoTranscoder(MessageAttachmentRepository attachmentRepository, FileStorageService fileStorageService, + ChatService chatService, TransactionTemplate transactionTemplate, + @Value("${ffmpeg.binary-path:ffmpeg}") String ffmpegPath, + @Value("${ffprobe.binary-path:}") String ffprobePath) { + this.attachmentRepository = attachmentRepository; + this.fileStorageService = fileStorageService; + this.chatService = chatService; + this.transactionTemplate = transactionTemplate; + this.ffmpegPath = ffmpegPath; + this.ffprobePath = ffprobePath == null || ffprobePath.isBlank() ? ffprobeNextTo(ffmpegPath) : ffprobePath; + } + + /** ffprobe лежит рядом с ffmpeg: ".../bin/ffmpeg.exe" → ".../bin/ffprobe.exe", "ffmpeg" → "ffprobe". */ + static String ffprobeNextTo(String ffmpeg) { + int slash = Math.max(ffmpeg.lastIndexOf('/'), ffmpeg.lastIndexOf('\\')); + String dir = ffmpeg.substring(0, slash + 1); + String name = ffmpeg.substring(slash + 1); + return dir + name.replaceFirst("(?i)^ffmpeg", "ffprobe"); + } + + /** Результат обработки — то, что попадёт во вложение. */ + record Transcoded(Path video, Path poster, int width, int height, int durationMs) { + } + + @Async("chatVideoExecutor") + public void transcode(Long attachmentId) { + MessageAttachment attachment = attachmentRepository.findById(attachmentId).orElse(null); + if (attachment == null || attachment.getStatus() != AttachmentStatus.PROCESSING) { + return; // чат удалили, пока видео ждало очереди, или его уже обработали + } + String sourceKey = attachment.getObjectKey(); + Path workDir = null; + try { + workDir = Files.createTempDirectory("chat-video-"); + Path source = workDir.resolve("source" + extension(sourceKey)); + fileStorageService.downloadToFile(sourceKey, source); + + Transcoded result = process(source, workDir); + String base = ChatAttachmentService.KEY_PREFIX + attachment.getChatId() + "/" + UUID.randomUUID(); + String videoKey = base + ".mp4"; + String posterKey = base + ".jpg"; + fileStorageService.putFile(videoKey, result.video(), "video/mp4"); + fileStorageService.putFile(posterKey, result.poster(), "image/jpeg"); + + Long messageId = transactionTemplate.execute(status -> attachmentRepository.findById(attachmentId) + .map(current -> { + current.setObjectKey(videoKey); + current.setPosterKey(posterKey); + current.setContentType("video/mp4"); + current.setSizeBytes(sizeOf(result.video())); + current.setWidth(result.width()); + current.setHeight(result.height()); + current.setDurationMs(result.durationMs()); + current.setStatus(AttachmentStatus.READY); + return attachmentRepository.save(current).getMessageId(); + }) + .orElse(null)); + if (messageId == null) { + // Чат удалили во время обработки — результат никому не нужен + deleteQuietly(List.of(videoKey, posterKey)); + } else { + chatService.broadcastMessage(messageId); + log.info("Видео {} обработано: {}x{}, {} мс", attachmentId, result.width(), result.height(), result.durationMs()); + } + deleteQuietly(List.of(sourceKey)); + } catch (Exception e) { + if (e instanceof InterruptedException) { + Thread.currentThread().interrupt(); + } + log.warn("Видео {} не обработано: {}", attachmentId, e.getMessage()); + markFailed(attachmentId); + } finally { + deleteDirectory(workDir); + } + } + + /** + * Помечает видео неудавшимся, удаляет исходник и сообщает в чат. Вызывается и + * когда очередь обработки переполнена — тогда видео даже не начинало обрабатываться. + */ + public void markFailed(Long attachmentId) { + MessageAttachment failed = transactionTemplate.execute(status -> attachmentRepository.findById(attachmentId) + .filter(a -> a.getStatus() == AttachmentStatus.PROCESSING) + .map(a -> { + a.setStatus(AttachmentStatus.FAILED); + return attachmentRepository.save(a); + }) + .orElse(null)); + if (failed != null) { + deleteQuietly(List.of(failed.getObjectKey())); + chatService.broadcastMessage(failed.getMessageId()); + } + } + + /** Видео, которые слишком долго «обрабатываются» (например, сервер перезапустился), — в FAILED. */ + @Scheduled(cron = "${chat.video.stuck-check-cron:0 */10 * * * *}") + @SchedulerLock(name = "failStuckChatVideos", lockAtMostFor = "PT5M", lockAtLeastFor = "PT30S") + public void failStuck() { + List stuck = attachmentRepository + .findByStatusAndProcessingStartedAtBefore(AttachmentStatus.PROCESSING, Instant.now().minus(STUCK_AFTER)); + for (MessageAttachment attachment : stuck) { + log.warn("Видео {} обрабатывается дольше {} — помечаем неудавшимся", attachment.getId(), STUCK_AFTER); + markFailed(attachment.getId()); + } + } + + Transcoded process(Path source, Path workDir) throws IOException, InterruptedException { + Map sourceInfo = probe(source, "format=duration"); + double duration = parseDouble(sourceInfo.get("duration")); + if (duration <= 0) { + throw new IOException("не удалось определить длительность видео"); + } + if (duration > MAX_DURATION.toSeconds() + DURATION_TOLERANCE_SECONDS) { + throw new IOException("видео длиннее " + MAX_DURATION.toSeconds() + " с: " + duration); + } + + Path video = workDir.resolve("video.mp4"); + // Короткая сторона — не больше 720 px (и вертикальное, и горизонтальное видео), + // размеры чётные — этого требует yuv420p. Поворот с телефона ffmpeg применяет сам. + String scale = "scale=w=trunc(iw*min(1\\,720/min(iw\\,ih))/2)*2:h=trunc(ih*min(1\\,720/min(iw\\,ih))/2)*2"; + run(List.of(ffmpegPath, "-nostdin", "-y", "-i", source.toString(), + "-map", "0:v:0", "-map", "0:a:0?", + "-vf", scale, + "-c:v", "libx264", "-preset", "veryfast", "-crf", "26", "-maxrate", "2500k", "-bufsize", "5000k", + "-pix_fmt", "yuv420p", + "-c:a", "aac", "-b:a", "128k", "-ac", "2", + // Без метаданных исходника: в mov с телефона лежат координаты съёмки + "-map_metadata", "-1", "-map_chapters", "-1", + "-movflags", "+faststart", + video.toString()), FFMPEG_TIMEOUT_MINUTES, TimeUnit.MINUTES, workDir); + + Path poster = workDir.resolve("poster.jpg"); + run(List.of(ffmpegPath, "-nostdin", "-y", "-i", video.toString(), "-frames:v", "1", "-q:v", "4", + poster.toString()), FFPROBE_TIMEOUT_SECONDS, TimeUnit.SECONDS, workDir); + + Map out = probe(video, "stream=width,height:format=duration"); + int width = (int) parseDouble(out.get("width")); + int height = (int) parseDouble(out.get("height")); + int durationMs = (int) Math.round(parseDouble(out.get("duration")) * 1000); + if (width <= 0 || height <= 0 || !Files.exists(poster)) { + throw new IOException("ffmpeg не выдал видео или обложку"); + } + return new Transcoded(video, poster, width, height, durationMs); + } + + /** ffprobe → пары key=value (первый видеопоток и/или формат). */ + private Map probe(Path file, String entries) throws IOException, InterruptedException { + String output = run(List.of(ffprobePath, "-v", "error", "-select_streams", "v:0", + "-show_entries", entries, "-of", "default=noprint_wrappers=1", file.toString()), + FFPROBE_TIMEOUT_SECONDS, TimeUnit.SECONDS, file.getParent()); + Map values = new HashMap<>(); + for (String line : output.split("\\R")) { + int eq = line.indexOf('='); + if (eq > 0) { + values.putIfAbsent(line.substring(0, eq).trim(), line.substring(eq + 1).trim()); + } + } + return values; + } + + /** + * Запускает процесс с таймаутом. Вывод пишется в файл, а не читается в этом + * потоке: иначе чтение блокируется до конца процесса и таймаут не срабатывает. + */ + private String run(List command, long timeout, TimeUnit unit, Path workDir) + throws IOException, InterruptedException { + Path logPath = Files.createTempFile(workDir, "proc-", ".log"); + Process process = new ProcessBuilder(command) + .redirectErrorStream(true) + .redirectOutput(logPath.toFile()) + .start(); + if (!process.waitFor(timeout, unit)) { + process.destroyForcibly(); + throw new IOException(command.get(0) + " не уложился в " + timeout + " " + unit + ":\n" + tail(logPath)); + } + String output = Files.readString(logPath); + if (process.exitValue() != 0) { + throw new IOException(command.get(0) + " завершился с кодом " + process.exitValue() + ":\n" + tail(logPath)); + } + return output; + } + + private static String tail(Path logPath) { + try { + List lines = Files.readAllLines(logPath); + return String.join("\n", lines.subList(Math.max(0, lines.size() - LOG_TAIL_LINES), lines.size())); + } catch (IOException | RuntimeException e) { + return "<лог недоступен>"; + } + } + + private static double parseDouble(String value) { + try { + return value == null ? 0 : Double.parseDouble(value); + } catch (NumberFormatException e) { + return 0; + } + } + + private static long sizeOf(Path file) { + try { + return Files.size(file); + } catch (IOException e) { + return 0; + } + } + + private static String extension(String key) { + int dot = key.lastIndexOf('.'); + return dot >= 0 ? key.substring(dot) : ".tmp"; + } + + private void deleteQuietly(List keys) { + for (String key : keys) { + try { + fileStorageService.deleteFile(key); + } catch (RuntimeException e) { + log.warn("Не удалось удалить {}: {}", key, e.getMessage()); + } + } + } + + private static void deleteDirectory(Path dir) { + if (dir == null) { + return; + } + try (Stream paths = Files.walk(dir)) { + List all = new ArrayList<>(paths.sorted(Comparator.reverseOrder()).toList()); + for (Path p : all) { + Files.deleteIfExists(p); + } + } catch (IOException e) { + log.warn("Не удалось удалить временную папку {}: {}", dir, e.getMessage()); + } + } +} diff --git a/src/main/java/com/krylov/refound/service/ChatVideoUploadService.java b/src/main/java/com/krylov/refound/service/ChatVideoUploadService.java new file mode 100644 index 0000000..857cf6d --- /dev/null +++ b/src/main/java/com/krylov/refound/service/ChatVideoUploadService.java @@ -0,0 +1,119 @@ +package com.krylov.refound.service; + +import com.krylov.refound.enums.ErrorCode; +import com.krylov.refound.exception.ApiException; +import java.time.Duration; +import java.util.Map; +import java.util.UUID; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.data.redis.core.StringRedisTemplate; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Service; +import software.amazon.awssdk.services.s3.model.HeadObjectResponse; + +/** + * Загрузка исходника видео для чата: браузер кладёт файл напрямую в MinIO по + * presigned PUT (через бэкенд с лимитом multipart 10 МБ видео не пройдёт), а + * потом подтверждает загрузку — и только тогда появляется сообщение. + * + *

Выданный ключ запоминается в Redis вместе с чатом и пользователем: + * подтвердить можно только свою загрузку в свой чат и только один раз. + * Неподтверждённые исходники через сутки удалит чистка файлов-сирот. + */ +@Slf4j +@Service +@RequiredArgsConstructor +public class ChatVideoUploadService { + + public static final long MAX_SOURCE_BYTES = 100L * 1024 * 1024; + static final Duration UPLOAD_URL_TTL = Duration.ofMinutes(30); + private static final Duration PENDING_TTL = Duration.ofHours(2); + private static final String PENDING_KEY_PREFIX = "chat:video-upload:"; + + /** Что принимаем от телефонов и браузеров; всё равно перекодируется в mp4. */ + static final Map ALLOWED_TYPES = Map.of( + "video/mp4", ".mp4", + "video/quicktime", ".mov", + "video/webm", ".webm", + "video/3gpp", ".3gp"); + + private final FileStorageService fileStorageService; + private final StringRedisTemplate redisTemplate; + + public record UploadTicket(String uploadUrl, String sourceKey, long expiresInMinutes) { + } + + /** Исходник подтверждён: он есть в бакете и укладывается в лимит. */ + public record ClaimedSource(String sourceKey, String contentType, long sizeBytes) { + } + + /** Ссылка на загрузку. Права на чат проверяет вызывающий (ChatService). */ + public UploadTicket requestUpload(Long chatId, Long userId, String contentType, long sizeBytes) { + String extension = contentType == null ? null : ALLOWED_TYPES.get(contentType.toLowerCase()); + if (extension == null) { + throw new ApiException(ErrorCode.VALIDATION_ERROR, "Недопустимый формат видео.", HttpStatus.BAD_REQUEST); + } + if (sizeBytes <= 0 || sizeBytes > MAX_SOURCE_BYTES) { + throw new ApiException(ErrorCode.VALIDATION_ERROR, + "Видео слишком большое (максимум " + MAX_SOURCE_BYTES / 1024 / 1024 + " МБ).", HttpStatus.BAD_REQUEST); + } + + String sourceKey = ChatAttachmentService.KEY_PREFIX + chatId + "/src/" + UUID.randomUUID() + extension; + try { + redisTemplate.opsForValue().set(PENDING_KEY_PREFIX + sourceKey, owner(chatId, userId), PENDING_TTL); + } catch (RuntimeException e) { + // Без записи загрузку потом не подтвердить — лучше отказать сразу + log.error("Не удалось сохранить загрузку видео {}: {}", sourceKey, e.getMessage()); + throw new ApiException(ErrorCode.INTERNAL_ERROR, "Не удалось начать загрузку, попробуйте позже.", + HttpStatus.SERVICE_UNAVAILABLE); + } + String url = fileStorageService.generatePresignedUploadUrl(sourceKey, contentType.toLowerCase(), sizeBytes, UPLOAD_URL_TTL); + return new UploadTicket(url, sourceKey, UPLOAD_URL_TTL.toMinutes()); + } + + /** + * Подтверждает загруженный исходник: ключ выдан этому пользователю для этого + * чата и ещё не использован, файл есть в бакете и не больше лимита. + */ + public ClaimedSource claim(Long chatId, Long userId, String sourceKey) { + // Сначала сверяем владельца и только потом удаляем запись: иначе чужая (отклонённая) + // попытка «сжигала» бы загрузку, и настоящий отправитель уже не смог бы её подтвердить. + // delete() возвращает true только одному из одновременных запросов — подтверждение одноразовое. + boolean claimed; + try { + String key = PENDING_KEY_PREFIX + sourceKey; + String pending = sourceKey == null ? null : redisTemplate.opsForValue().get(key); + claimed = pending != null && pending.equals(owner(chatId, userId)) + && Boolean.TRUE.equals(redisTemplate.delete(key)); + } catch (RuntimeException e) { + log.error("Не удалось проверить загрузку видео {}: {}", sourceKey, e.getMessage()); + throw new ApiException(ErrorCode.INTERNAL_ERROR, "Не удалось проверить загрузку, попробуйте позже.", + HttpStatus.SERVICE_UNAVAILABLE); + } + if (!claimed) { + throw new ApiException(ErrorCode.VALIDATION_ERROR, "Загрузка видео не найдена или устарела.", HttpStatus.BAD_REQUEST); + } + + HeadObjectResponse head = fileStorageService.headObject(sourceKey).orElseThrow(() -> + new ApiException(ErrorCode.VALIDATION_ERROR, "Видео ещё не загружено.", HttpStatus.BAD_REQUEST)); + long size = head.contentLength() == null ? 0 : head.contentLength(); + if (size <= 0 || size > MAX_SOURCE_BYTES) { + deleteQuietly(sourceKey); + throw new ApiException(ErrorCode.VALIDATION_ERROR, "Видео слишком большое.", HttpStatus.BAD_REQUEST); + } + return new ClaimedSource(sourceKey, head.contentType(), size); + } + + public void deleteQuietly(String key) { + try { + fileStorageService.deleteFile(key); + } catch (RuntimeException e) { + log.warn("Не удалось удалить исходник видео {}: {}", key, e.getMessage()); + } + } + + private static String owner(Long chatId, Long userId) { + return chatId + ":" + userId; + } +} diff --git a/src/main/java/com/krylov/refound/service/ChatVideoUploadedEvent.java b/src/main/java/com/krylov/refound/service/ChatVideoUploadedEvent.java new file mode 100644 index 0000000..d9f18ce --- /dev/null +++ b/src/main/java/com/krylov/refound/service/ChatVideoUploadedEvent.java @@ -0,0 +1,5 @@ +package com.krylov.refound.service; + +/** Видео-сообщение сохранено — после коммита его вложение ставится в очередь обработки. */ +public record ChatVideoUploadedEvent(Long attachmentId) { +} diff --git a/src/main/java/com/krylov/refound/service/FileStorageService.java b/src/main/java/com/krylov/refound/service/FileStorageService.java index 37db05e..687a6f3 100644 --- a/src/main/java/com/krylov/refound/service/FileStorageService.java +++ b/src/main/java/com/krylov/refound/service/FileStorageService.java @@ -6,9 +6,13 @@ import com.krylov.refound.enums.ErrorCode; import com.krylov.refound.exception.ApiException; import com.krylov.refound.util.ImageFormat; import java.io.IOException; +import java.io.InputStream; import java.net.URLDecoder; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; import java.time.Duration; import java.util.HashMap; import java.util.Map; @@ -41,6 +45,7 @@ import software.amazon.awssdk.services.s3.model.S3Exception; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.services.s3.presigner.S3Presigner; import software.amazon.awssdk.services.s3.presigner.model.GetObjectPresignRequest; +import software.amazon.awssdk.services.s3.presigner.model.PutObjectPresignRequest; @Service @Slf4j @@ -388,6 +393,62 @@ public class FileStorageService { } } + /** + * Presigned PUT для загрузки файла браузером напрямую в MinIO (видео в чат — + * через бэкенд с его лимитом 10 МБ оно не пройдёт). Тип и размер входят в + * подпись: загрузить другой тип или файл другого размера по ссылке нельзя. + */ + public String generatePresignedUploadUrl(String objectName, String contentType, long contentLength, Duration ttl) { + try { + PutObjectRequest put = PutObjectRequest.builder() + .bucket(properties.bucket()) + .key(objectName) + .contentType(contentType) + .contentLength(contentLength) + .build(); + return s3Presigner.presignPutObject(PutObjectPresignRequest.builder() + .signatureDuration(ttl) + .putObjectRequest(put) + .build()).url().toString(); + } catch (S3Exception | SdkClientException e) { + log.error("Ошибка при генерации presigned PUT для '{}': {}", objectName, e.getMessage(), e); + throw new ApiException(ErrorCode.INTERNAL_ERROR, "Ошибка при формировании ссылки на загрузку.", HttpStatus.INTERNAL_SERVER_ERROR); + } + } + + /** Размер и тип объекта или пусто, если его нет. */ + public Optional headObject(String objectName) { + try { + return Optional.of(s3Client.headObject(HeadObjectRequest.builder() + .bucket(properties.bucket()).key(objectName).build())); + } catch (NoSuchKeyException e) { + return Optional.empty(); + } catch (S3Exception e) { + if (e.statusCode() == 404) { + return Optional.empty(); + } + throw e; + } + } + + /** Скачивает объект во временный файл (для обработки ffmpeg). */ + public void downloadToFile(String objectName, Path target) throws IOException { + try (InputStream in = s3Client.getObject(GetObjectRequest.builder() + .bucket(properties.bucket()).key(objectName).build())) { + Files.copy(in, target, StandardCopyOption.REPLACE_EXISTING); + } + } + + /** Загружает файл с диска в бакет (результат обработки видео). */ + public void putFile(String objectName, Path source, String contentType) { + s3Client.putObject(PutObjectRequest.builder() + .bucket(properties.bucket()) + .key(objectName) + .contentType(contentType) + .build(), RequestBody.fromFile(source)); + log.info("Файл '{}' успешно загружен.", objectName); + } + /** * Кладёт уже подготовленные байты в бакет под заданным ключом. Владелец в * Redis не записывается: такие файлы (вложения чатов) удаляет только их сервис. diff --git a/src/main/java/com/krylov/refound/service/OrphanFileCleanupService.java b/src/main/java/com/krylov/refound/service/OrphanFileCleanupService.java index 322d5ae..e6f86d0 100644 --- a/src/main/java/com/krylov/refound/service/OrphanFileCleanupService.java +++ b/src/main/java/com/krylov/refound/service/OrphanFileCleanupService.java @@ -105,6 +105,7 @@ public class OrphanFileCleanupService { .map(this::toKey) .forEach(keys::add); keys.addAll(attachmentRepository.findAllObjectKeys()); + keys.addAll(attachmentRepository.findAllPosterKeys()); return keys; } diff --git a/src/main/resources/application.yaml b/src/main/resources/application.yaml index 73c068f..8aaf8cf 100644 --- a/src/main/resources/application.yaml +++ b/src/main/resources/application.yaml @@ -182,6 +182,12 @@ rate-limit: paths: [/api/v1/chats/*/messages] limit: 60 window: PT1H + # Видео в чат: ссылка на загрузку исходника; каждое видео — ffmpeg на сервере + - name: chat-video + method: POST + paths: [/api/v1/chats/*/videos/upload-url] + limit: 20 + window: PT1H - name: chat-start method: POST paths: [/api/v1/chats/with/**] diff --git a/src/main/resources/db/changelog/add/025-message-attachments-video.yaml b/src/main/resources/db/changelog/add/025-message-attachments-video.yaml new file mode 100644 index 0000000..b467ce2 --- /dev/null +++ b/src/main/resources/db/changelog/add/025-message-attachments-video.yaml @@ -0,0 +1,32 @@ +databaseChangeLog: + - changeSet: + id: 025-message-attachments-video + author: krylov + comment: > + Видео во вложениях чата. Видео перекодируется в фоне: status PROCESSING → + READY/FAILED (фото сразу READY). poster_key — кадр-обложка, duration_ms — + длительность. processing_started_at хранится с часовым поясом: created_at + пишется в поясе отправителя и для поиска зависших обработок не годится. + preConditions: + onFail: MARK_RAN + not: + columnExists: + tableName: message_attachments + columnName: status + changes: + - addColumn: + tableName: message_attachments + columns: + - column: + name: status + type: VARCHAR(16) + defaultValue: READY + constraints: { nullable: false } + - column: { name: poster_key, type: VARCHAR(255) } + - column: { name: duration_ms, type: INT } + - column: { name: processing_started_at, type: TIMESTAMP WITH TIME ZONE } + - createIndex: + tableName: message_attachments + indexName: idx_message_attachments_status + columns: + - column: { name: status } diff --git a/src/main/resources/db/changelog/db.changelog-master.yaml b/src/main/resources/db/changelog/db.changelog-master.yaml index 6b8839e..0ffe715 100644 --- a/src/main/resources/db/changelog/db.changelog-master.yaml +++ b/src/main/resources/db/changelog/db.changelog-master.yaml @@ -37,3 +37,4 @@ databaseChangeLog: - 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 } + - include: { file: db/changelog/add/025-message-attachments-video.yaml } diff --git a/src/test/java/com/krylov/refound/service/ChatServiceTest.java b/src/test/java/com/krylov/refound/service/ChatServiceTest.java index ecb8e5c..26888f4 100644 --- a/src/test/java/com/krylov/refound/service/ChatServiceTest.java +++ b/src/test/java/com/krylov/refound/service/ChatServiceTest.java @@ -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.>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 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> 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.of(new Object[] {9L, AttachmentKind.VIDEO})); + + ChatDto dto = chatService.getUserChats(14L).get(0); + + assertThat(dto.getLastMessageAttachments()).isEqualTo(1); + assertThat(dto.getLastMessageAttachmentKind()).isEqualTo(AttachmentKind.VIDEO); + } } diff --git a/src/test/java/com/krylov/refound/service/ChatVideoTranscoderTest.java b/src/test/java/com/krylov/refound/service/ChatVideoTranscoderTest.java new file mode 100644 index 0000000..540ebe5 --- /dev/null +++ b/src/test/java/com/krylov/refound/service/ChatVideoTranscoderTest.java @@ -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.>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 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(); + } +} diff --git a/src/test/java/com/krylov/refound/service/ChatVideoUploadServiceTest.java b/src/test/java/com/krylov/refound/service/ChatVideoUploadServiceTest.java new file mode 100644 index 0000000..37c552e --- /dev/null +++ b/src/test/java/com/krylov/refound/service/ChatVideoUploadServiceTest.java @@ -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 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"); + } +} diff --git a/src/test/java/com/krylov/refound/service/OrphanFileCleanupServiceTest.java b/src/test/java/com/krylov/refound/service/OrphanFileCleanupServiceTest.java index 4f46f97..f3239e6 100644 --- a/src/test/java/com/krylov/refound/service/OrphanFileCleanupServiceTest.java +++ b/src/test/java/com/krylov/refound/service/OrphanFileCleanupServiceTest.java @@ -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"); }