Compare commits
2 Commits
648886c25e
...
6d843723bc
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6d843723bc | ||
|
|
871b16a038 |
@@ -22,4 +22,19 @@ public class AsyncConfig {
|
|||||||
executor.initialize();
|
executor.initialize();
|
||||||
return executor;
|
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;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,12 +1,15 @@
|
|||||||
package com.krylov.refound.controller;
|
package com.krylov.refound.controller;
|
||||||
|
|
||||||
import com.krylov.refound.dto.ChatDto;
|
import com.krylov.refound.dto.ChatDto;
|
||||||
|
import com.krylov.refound.dto.MessageAttachmentDto;
|
||||||
import com.krylov.refound.dto.MessageDto;
|
import com.krylov.refound.dto.MessageDto;
|
||||||
|
import com.krylov.refound.dto.SendVideoRequest;
|
||||||
import com.krylov.refound.dto.StartChatRequest;
|
import com.krylov.refound.dto.StartChatRequest;
|
||||||
|
import com.krylov.refound.dto.VideoUploadRequest;
|
||||||
import com.krylov.refound.service.ChatService;
|
import com.krylov.refound.service.ChatService;
|
||||||
|
import com.krylov.refound.service.ChatVideoUploadService;
|
||||||
import com.krylov.refound.service.UserService;
|
import com.krylov.refound.service.UserService;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import org.springframework.data.domain.Page;
|
import org.springframework.data.domain.Page;
|
||||||
@@ -82,11 +85,37 @@ public class ChatController {
|
|||||||
return chatService.sendMessageWithPhotos(currentUserId, chatId, content, files);
|
return chatService.sendMessageWithPhotos(currentUserId, chatId, content, files);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Свежая временная ссылка на вложение (выданная с сообщением живёт несколько часов). */
|
/**
|
||||||
|
* Свежие временные ссылки на вложение (выданные с сообщением живут несколько
|
||||||
|
* часов): url и, у видео, posterUrl.
|
||||||
|
*/
|
||||||
@GetMapping("/{chatId}/attachments/{attachmentId}/url")
|
@GetMapping("/{chatId}/attachments/{attachmentId}/url")
|
||||||
public Map<String, String> getAttachmentUrl(@PathVariable Long chatId, @PathVariable Long attachmentId, Authentication auth) {
|
public MessageAttachmentDto getAttachmentUrl(@PathVariable Long chatId, @PathVariable Long attachmentId, Authentication auth) {
|
||||||
Long currentUserId = extractUserId(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}")
|
@DeleteMapping("/{chatId}")
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
package com.krylov.refound.dto;
|
package com.krylov.refound.dto;
|
||||||
|
|
||||||
|
import com.krylov.refound.enums.AttachmentKind;
|
||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
||||||
import lombok.Data;
|
import lombok.Data;
|
||||||
|
|
||||||
@@ -15,5 +16,7 @@ public class ChatDto {
|
|||||||
private LocalDateTime lastMessageAt;
|
private LocalDateTime lastMessageAt;
|
||||||
/** Сколько вложений в последнем сообщении — для превью «Фото» без текста. */
|
/** Сколько вложений в последнем сообщении — для превью «Фото» без текста. */
|
||||||
private int lastMessageAttachments;
|
private int lastMessageAttachments;
|
||||||
|
/** Тип вложений последнего сообщения (PHOTO/VIDEO) или null. */
|
||||||
|
private AttachmentKind lastMessageAttachmentKind;
|
||||||
private long unreadCount;
|
private long unreadCount;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,14 +1,16 @@
|
|||||||
package com.krylov.refound.dto;
|
package com.krylov.refound.dto;
|
||||||
|
|
||||||
import com.krylov.refound.enums.AttachmentKind;
|
import com.krylov.refound.enums.AttachmentKind;
|
||||||
|
import com.krylov.refound.enums.AttachmentStatus;
|
||||||
import lombok.AllArgsConstructor;
|
import lombok.AllArgsConstructor;
|
||||||
import lombok.Data;
|
import lombok.Data;
|
||||||
import lombok.NoArgsConstructor;
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Вложение сообщения. url — временная (presigned) ссылка прямо на файл в MinIO:
|
* Вложение сообщения. url (и posterUrl у видео) — временные (presigned) ссылки
|
||||||
* её получают только участники чата вместе с сообщением. Когда ссылка истечёт,
|
* прямо на файлы в MinIO: их получают только участники чата вместе с сообщением.
|
||||||
* свежую выдаёт GET /api/v1/chats/{chatId}/attachments/{id}/url.
|
* Когда ссылка истечёт, свежую выдаёт GET /api/v1/chats/{chatId}/attachments/{id}/url.
|
||||||
|
* Пока видео обрабатывается (status PROCESSING) или не обработалось (FAILED), ссылок нет.
|
||||||
*/
|
*/
|
||||||
@Data
|
@Data
|
||||||
@NoArgsConstructor
|
@NoArgsConstructor
|
||||||
@@ -16,7 +18,10 @@ import lombok.NoArgsConstructor;
|
|||||||
public class MessageAttachmentDto {
|
public class MessageAttachmentDto {
|
||||||
private Long id;
|
private Long id;
|
||||||
private AttachmentKind kind;
|
private AttachmentKind kind;
|
||||||
|
private AttachmentStatus status;
|
||||||
private String url;
|
private String url;
|
||||||
|
private String posterUrl;
|
||||||
private Integer width;
|
private Integer width;
|
||||||
private Integer height;
|
private Integer height;
|
||||||
|
private Integer durationMs;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,5 @@
|
|||||||
|
package com.krylov.refound.dto;
|
||||||
|
|
||||||
|
/** Подтверждение загрузки видео: ключ из ответа upload-url и необязательный текст. */
|
||||||
|
public record SendVideoRequest(String sourceKey, String content) {
|
||||||
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
package com.krylov.refound.dto;
|
||||||
|
|
||||||
|
/** Запрос ссылки на загрузку видео: тип и точный размер файла входят в подпись ссылки. */
|
||||||
|
public record VideoUploadRequest(String contentType, long sizeBytes) {
|
||||||
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
package com.krylov.refound.entity;
|
package com.krylov.refound.entity;
|
||||||
|
|
||||||
import com.krylov.refound.enums.AttachmentKind;
|
import com.krylov.refound.enums.AttachmentKind;
|
||||||
|
import com.krylov.refound.enums.AttachmentStatus;
|
||||||
import com.krylov.refound.util.TimeZoneContext;
|
import com.krylov.refound.util.TimeZoneContext;
|
||||||
import jakarta.persistence.Column;
|
import jakarta.persistence.Column;
|
||||||
import jakarta.persistence.Entity;
|
import jakarta.persistence.Entity;
|
||||||
@@ -11,14 +12,16 @@ import jakarta.persistence.GenerationType;
|
|||||||
import jakarta.persistence.Id;
|
import jakarta.persistence.Id;
|
||||||
import jakarta.persistence.PrePersist;
|
import jakarta.persistence.PrePersist;
|
||||||
import jakarta.persistence.Table;
|
import jakarta.persistence.Table;
|
||||||
|
import java.time.Instant;
|
||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
||||||
import lombok.Getter;
|
import lombok.Getter;
|
||||||
import lombok.Setter;
|
import lombok.Setter;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Вложение сообщения чата. Файл лежит в бакете картинок под ключом
|
* Вложение сообщения чата (фото или видео). Файл лежит в бакете картинок под
|
||||||
* chat/{chatId}/{uuid}.ext; общий /api/v1/files его не отдаёт — ссылку
|
* ключом chat/{chatId}/{uuid}.ext; общий /api/v1/files его не отдаёт — ссылку
|
||||||
* получают только участники чата вместе с сообщением.
|
* получают только участники чата вместе с сообщением. Пока видео
|
||||||
|
* перекодируется, objectKey указывает на исходник (chat/{chatId}/src/...).
|
||||||
*/
|
*/
|
||||||
@Entity
|
@Entity
|
||||||
@Table(name = "message_attachments")
|
@Table(name = "message_attachments")
|
||||||
@@ -52,6 +55,21 @@ public class MessageAttachment {
|
|||||||
|
|
||||||
private Integer height;
|
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, ...). */
|
/** Порядок вложения в сообщении (0, 1, ...). */
|
||||||
@Column(nullable = false)
|
@Column(nullable = false)
|
||||||
private int position;
|
private int position;
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package com.krylov.refound.enums;
|
package com.krylov.refound.enums;
|
||||||
|
|
||||||
/** Тип вложения сообщения чата. VIDEO появится вторым этапом. */
|
/** Тип вложения сообщения чата. */
|
||||||
public enum AttachmentKind {
|
public enum AttachmentKind {
|
||||||
PHOTO
|
PHOTO,
|
||||||
|
VIDEO
|
||||||
}
|
}
|
||||||
|
|||||||
11
src/main/java/com/krylov/refound/enums/AttachmentStatus.java
Normal file
11
src/main/java/com/krylov/refound/enums/AttachmentStatus.java
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
package com.krylov.refound.enums;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Готовность вложения. Фото готовы сразу; видео после загрузки перекодируется
|
||||||
|
* в фоне (PROCESSING) и становится READY или FAILED.
|
||||||
|
*/
|
||||||
|
public enum AttachmentStatus {
|
||||||
|
READY,
|
||||||
|
PROCESSING,
|
||||||
|
FAILED
|
||||||
|
}
|
||||||
@@ -1,6 +1,8 @@
|
|||||||
package com.krylov.refound.repository;
|
package com.krylov.refound.repository;
|
||||||
|
|
||||||
import com.krylov.refound.entity.MessageAttachment;
|
import com.krylov.refound.entity.MessageAttachment;
|
||||||
|
import com.krylov.refound.enums.AttachmentStatus;
|
||||||
|
import java.time.Instant;
|
||||||
import java.util.Collection;
|
import java.util.Collection;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
@@ -15,15 +17,21 @@ public interface MessageAttachmentRepository extends JpaRepository<MessageAttach
|
|||||||
|
|
||||||
Optional<MessageAttachment> findByIdAndChatId(Long id, Long chatId);
|
Optional<MessageAttachment> findByIdAndChatId(Long id, Long chatId);
|
||||||
|
|
||||||
/** Ключи файлов чата — чтобы удалить их из хранилища вместе с чатом. */
|
List<MessageAttachment> findByChatId(Long chatId);
|
||||||
@Query("select a.objectKey from MessageAttachment a where a.chatId = :chatId")
|
|
||||||
List<String> findObjectKeysByChatId(@Param("chatId") Long chatId);
|
|
||||||
|
|
||||||
/** Число вложений у сообщений: строки (messageId, count) — для превью в списке чатов. */
|
List<MessageAttachment> findByMessageId(Long messageId);
|
||||||
@Query("select a.messageId, count(a) from MessageAttachment a where a.messageId in :messageIds group by a.messageId")
|
|
||||||
List<Object[]> countByMessageIds(@Param("messageIds") Collection<Long> messageIds);
|
|
||||||
|
|
||||||
/** Все ключи вложений — для чистки файлов-сирот. */
|
/** Типы вложений у сообщений: строки (messageId, kind) — для превью в списке чатов. */
|
||||||
|
@Query("select a.messageId, a.kind from MessageAttachment a where a.messageId in :messageIds")
|
||||||
|
List<Object[]> findKindsByMessageIds(@Param("messageIds") Collection<Long> messageIds);
|
||||||
|
|
||||||
|
/** Все ключи вложений (и обложек видео) — для чистки файлов-сирот. */
|
||||||
@Query("select a.objectKey from MessageAttachment a")
|
@Query("select a.objectKey from MessageAttachment a")
|
||||||
List<String> findAllObjectKeys();
|
List<String> findAllObjectKeys();
|
||||||
|
|
||||||
|
@Query("select a.posterKey from MessageAttachment a where a.posterKey is not null")
|
||||||
|
List<String> findAllPosterKeys();
|
||||||
|
|
||||||
|
/** Видео, обработка которых началась раньше deadline и так и не закончилась. */
|
||||||
|
List<MessageAttachment> findByStatusAndProcessingStartedAtBefore(AttachmentStatus status, Instant deadline);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ package com.krylov.refound.service;
|
|||||||
|
|
||||||
import com.krylov.refound.dto.MessageAttachmentDto;
|
import com.krylov.refound.dto.MessageAttachmentDto;
|
||||||
import com.krylov.refound.entity.MessageAttachment;
|
import com.krylov.refound.entity.MessageAttachment;
|
||||||
|
import com.krylov.refound.enums.AttachmentStatus;
|
||||||
import com.krylov.refound.enums.ErrorCode;
|
import com.krylov.refound.enums.ErrorCode;
|
||||||
import com.krylov.refound.exception.ApiException;
|
import com.krylov.refound.exception.ApiException;
|
||||||
import com.krylov.refound.util.ImageFormat;
|
import com.krylov.refound.util.ImageFormat;
|
||||||
@@ -17,8 +18,9 @@ import org.springframework.stereotype.Service;
|
|||||||
import org.springframework.web.multipart.MultipartFile;
|
import org.springframework.web.multipart.MultipartFile;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Файлы вложений чата: проверка, перекодирование, загрузка в бакет и выдача
|
* Файлы фото-вложений чата: проверка, перекодирование, загрузка в бакет и выдача
|
||||||
* временных ссылок. Про сообщения и права доступа не знает — это делает ChatService.
|
* временных ссылок (и для видео). Про сообщения и права доступа не знает — это
|
||||||
|
* делает ChatService; видео — ChatVideoUploadService и ChatVideoTranscoder.
|
||||||
*
|
*
|
||||||
* <p>Ключи лежат под {@link #KEY_PREFIX}: общий /api/v1/files такие ключи не
|
* <p>Ключи лежат под {@link #KEY_PREFIX}: общий /api/v1/files такие ключи не
|
||||||
* отдаёт и не удаляет, а чистка сирот сверяет их с message_attachments.
|
* отдаёт и не удаляет, а чистка сирот сверяет их с message_attachments.
|
||||||
@@ -98,9 +100,13 @@ public class ChatAttachmentService {
|
|||||||
return new StoredPhoto(key, image.contentType(), image.content().length, image.width(), image.height());
|
return new StoredPhoto(key, image.contentType(), image.content().length, image.width(), image.height());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Ссылки выдаются только на готовое вложение: исходник видео в обработке не отдаём. */
|
||||||
public MessageAttachmentDto toDto(MessageAttachment attachment) {
|
public MessageAttachmentDto toDto(MessageAttachment attachment) {
|
||||||
return new MessageAttachmentDto(attachment.getId(), attachment.getKind(), url(attachment.getObjectKey()),
|
boolean ready = attachment.getStatus() == AttachmentStatus.READY;
|
||||||
attachment.getWidth(), attachment.getHeight());
|
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) {
|
public String url(String objectKey) {
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ package com.krylov.refound.service;
|
|||||||
import com.krylov.refound.config.ClusterMessaging;
|
import com.krylov.refound.config.ClusterMessaging;
|
||||||
import com.krylov.refound.dto.ChatDto;
|
import com.krylov.refound.dto.ChatDto;
|
||||||
import com.krylov.refound.dto.ChatPostDto;
|
import com.krylov.refound.dto.ChatPostDto;
|
||||||
|
import com.krylov.refound.dto.MessageAttachmentDto;
|
||||||
import com.krylov.refound.dto.MessageDto;
|
import com.krylov.refound.dto.MessageDto;
|
||||||
import com.krylov.refound.entity.Chat;
|
import com.krylov.refound.entity.Chat;
|
||||||
import com.krylov.refound.entity.Image;
|
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.Post;
|
||||||
import com.krylov.refound.entity.User;
|
import com.krylov.refound.entity.User;
|
||||||
import com.krylov.refound.enums.AttachmentKind;
|
import com.krylov.refound.enums.AttachmentKind;
|
||||||
|
import com.krylov.refound.enums.AttachmentStatus;
|
||||||
import com.krylov.refound.enums.ErrorCode;
|
import com.krylov.refound.enums.ErrorCode;
|
||||||
import com.krylov.refound.exception.ApiException;
|
import com.krylov.refound.exception.ApiException;
|
||||||
import com.krylov.refound.repository.ChatRepository;
|
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.MessageRepository;
|
||||||
import com.krylov.refound.repository.PostRepository;
|
import com.krylov.refound.repository.PostRepository;
|
||||||
import com.krylov.refound.repository.UserRepository;
|
import com.krylov.refound.repository.UserRepository;
|
||||||
|
import java.time.Instant;
|
||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.Comparator;
|
import java.util.Comparator;
|
||||||
@@ -30,6 +33,7 @@ import java.util.function.Function;
|
|||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.context.ApplicationEventPublisher;
|
||||||
import org.springframework.data.domain.Page;
|
import org.springframework.data.domain.Page;
|
||||||
import org.springframework.data.domain.Pageable;
|
import org.springframework.data.domain.Pageable;
|
||||||
import org.springframework.http.HttpStatus;
|
import org.springframework.http.HttpStatus;
|
||||||
@@ -57,6 +61,8 @@ public class ChatService {
|
|||||||
private final MessageAttachmentRepository attachmentRepository;
|
private final MessageAttachmentRepository attachmentRepository;
|
||||||
private final ChatAttachmentService attachmentService;
|
private final ChatAttachmentService attachmentService;
|
||||||
private final TransactionTemplate transactionTemplate;
|
private final TransactionTemplate transactionTemplate;
|
||||||
|
private final ChatVideoUploadService videoUploadService;
|
||||||
|
private final ApplicationEventPublisher eventPublisher;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Ищет существующий чат с пользователем по объявлению, ничего не создавая.
|
* Ищет существующий чат с пользователем по объявлению, ничего не создавая.
|
||||||
@@ -165,22 +171,83 @@ public class ChatService {
|
|||||||
checkParticipant(chat, senderId);
|
checkParticipant(chat, senderId);
|
||||||
|
|
||||||
List<ChatAttachmentService.StoredPhoto> stored = attachmentService.storePhotos(chatId, photos);
|
List<ChatAttachmentService.StoredPhoto> stored = attachmentService.storePhotos(chatId, photos);
|
||||||
|
List<MessageAttachment> 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 {
|
try {
|
||||||
return transactionTemplate.execute(status -> saveAndBroadcast(chat, senderId, text, stored));
|
return transactionTemplate.execute(status -> saveAndBroadcast(chat, senderId, text, attachments));
|
||||||
} catch (RuntimeException e) {
|
} catch (RuntimeException e) {
|
||||||
attachmentService.deleteQuietly(stored.stream().map(ChatAttachmentService.StoredPhoto::objectKey).toList());
|
attachmentService.deleteQuietly(stored.stream().map(ChatAttachmentService.StoredPhoto::objectKey).toList());
|
||||||
throw e;
|
throw e;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Свежая ссылка на вложение — когда выданная вместе с сообщением истекла. */
|
/** Свежие ссылки на вложение (у видео — и на обложку), когда выданные с сообщением истекли. */
|
||||||
@Transactional(readOnly = true)
|
@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);
|
Chat chat = getChatOrThrow(chatId);
|
||||||
checkParticipant(chat, userId);
|
checkParticipant(chat, userId);
|
||||||
MessageAttachment attachment = attachmentRepository.findByIdAndChatId(attachmentId, chatId)
|
MessageAttachment attachment = attachmentRepository.findByIdAndChatId(attachmentId, chatId)
|
||||||
.orElseThrow(() -> new ApiException(ErrorCode.NOT_FOUND, "Вложение не найдено", HttpStatus.NOT_FOUND));
|
.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 контроллера)
|
// Отправка сообщения (вызывается из WebSocket контроллера)
|
||||||
@@ -204,8 +271,12 @@ public class ChatService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Сохраняет сообщение с вложениями (у вложений заполнены поля файла; сообщение,
|
||||||
|
* чат и порядок проставляются здесь) и рассылает его после коммита.
|
||||||
|
*/
|
||||||
private MessageDto saveAndBroadcast(Chat chat, Long senderId, String content,
|
private MessageDto saveAndBroadcast(Chat chat, Long senderId, String content,
|
||||||
List<ChatAttachmentService.StoredPhoto> photos) {
|
List<MessageAttachment> newAttachments) {
|
||||||
Long chatId = chat.getId();
|
Long chatId = chat.getId();
|
||||||
Message message = new Message();
|
Message message = new Message();
|
||||||
message.setChatId(chatId);
|
message.setChatId(chatId);
|
||||||
@@ -213,20 +284,12 @@ public class ChatService {
|
|||||||
message.setContent(content);
|
message.setContent(content);
|
||||||
message = messageRepository.save(message);
|
message = messageRepository.save(message);
|
||||||
|
|
||||||
List<MessageAttachment> attachments = new ArrayList<>();
|
List<MessageAttachment> attachments = new ArrayList<>(newAttachments);
|
||||||
for (int i = 0; i < photos.size(); i++) {
|
for (int i = 0; i < attachments.size(); i++) {
|
||||||
ChatAttachmentService.StoredPhoto photo = photos.get(i);
|
MessageAttachment attachment = attachments.get(i);
|
||||||
MessageAttachment attachment = new MessageAttachment();
|
|
||||||
attachment.setMessageId(message.getId());
|
attachment.setMessageId(message.getId());
|
||||||
attachment.setChatId(chatId);
|
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);
|
attachment.setPosition(i);
|
||||||
attachments.add(attachment);
|
|
||||||
}
|
}
|
||||||
if (!attachments.isEmpty()) {
|
if (!attachments.isEmpty()) {
|
||||||
attachments = attachmentRepository.saveAll(attachments);
|
attachments = attachmentRepository.saveAll(attachments);
|
||||||
@@ -272,7 +335,13 @@ public class ChatService {
|
|||||||
checkParticipant(chat, userId);
|
checkParticipant(chat, userId);
|
||||||
// Строки вложений удалит каскад в БД, а файлы — только мы: после коммита,
|
// Строки вложений удалит каскад в БД, а файлы — только мы: после коммита,
|
||||||
// чтобы откат транзакции не оставил чат без фото
|
// чтобы откат транзакции не оставил чат без фото
|
||||||
List<String> keys = attachmentRepository.findObjectKeysByChatId(chatId);
|
List<String> keys = new ArrayList<>();
|
||||||
|
for (MessageAttachment attachment : attachmentRepository.findByChatId(chatId)) {
|
||||||
|
keys.add(attachment.getObjectKey());
|
||||||
|
if (attachment.getPosterKey() != null) {
|
||||||
|
keys.add(attachment.getPosterKey());
|
||||||
|
}
|
||||||
|
}
|
||||||
chatRepository.deleteById(chatId);
|
chatRepository.deleteById(chatId);
|
||||||
if (!keys.isEmpty()) {
|
if (!keys.isEmpty()) {
|
||||||
afterCommit(() -> attachmentService.deleteQuietly(keys));
|
afterCommit(() -> attachmentService.deleteQuietly(keys));
|
||||||
@@ -335,13 +404,18 @@ public class ChatService {
|
|||||||
for (Object[] row : messageRepository.countUnreadByChat(chatIds, currentUserId)) {
|
for (Object[] row : messageRepository.countUnreadByChat(chatIds, currentUserId)) {
|
||||||
unread.put(((Number) row[0]).longValue(), ((Number) row[1]).longValue());
|
unread.put(((Number) row[0]).longValue(), ((Number) row[1]).longValue());
|
||||||
}
|
}
|
||||||
// Сколько фото в последнем сообщении: у сообщения только с фото текста нет,
|
// Вложения последнего сообщения: у сообщения только с фото или видео текста
|
||||||
// и превью в списке чатов показывает «Фото» вместо пустой строки
|
// нет, и превью в списке чатов показывает «Фото»/«Видео» вместо пустой строки
|
||||||
Map<Long, Integer> lastAttachments = new HashMap<>();
|
Map<Long, Integer> lastAttachments = new HashMap<>();
|
||||||
|
Map<Long, AttachmentKind> lastAttachmentKinds = new HashMap<>();
|
||||||
if (!lastMessages.isEmpty()) {
|
if (!lastMessages.isEmpty()) {
|
||||||
for (Object[] row : attachmentRepository.countByMessageIds(
|
for (Object[] row : attachmentRepository.findKindsByMessageIds(
|
||||||
lastMessages.values().stream().map(Message::getId).toList())) {
|
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.setLastMessage(last.getContent());
|
||||||
dto.setLastMessageAt(last.getCreatedAt());
|
dto.setLastMessageAt(last.getCreatedAt());
|
||||||
dto.setLastMessageAttachments(lastAttachments.getOrDefault(last.getId(), 0));
|
dto.setLastMessageAttachments(lastAttachments.getOrDefault(last.getId(), 0));
|
||||||
|
dto.setLastMessageAttachmentKind(lastAttachmentKinds.get(last.getId()));
|
||||||
}
|
}
|
||||||
dto.setUnreadCount(unread.getOrDefault(chat.getId(), 0L));
|
dto.setUnreadCount(unread.getOrDefault(chat.getId(), 0L));
|
||||||
return dto;
|
return dto;
|
||||||
|
|||||||
@@ -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());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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<MessageAttachment> 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<String, String> 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<String, String> 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<String, String> 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<String, String> 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<String> 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<String> 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<String> 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<Path> paths = Files.walk(dir)) {
|
||||||
|
List<Path> all = new ArrayList<>(paths.sorted(Comparator.reverseOrder()).toList());
|
||||||
|
for (Path p : all) {
|
||||||
|
Files.deleteIfExists(p);
|
||||||
|
}
|
||||||
|
} catch (IOException e) {
|
||||||
|
log.warn("Не удалось удалить временную папку {}: {}", dir, e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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 МБ видео не пройдёт), а
|
||||||
|
* потом подтверждает загрузку — и только тогда появляется сообщение.
|
||||||
|
*
|
||||||
|
* <p>Выданный ключ запоминается в 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<String, String> 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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
package com.krylov.refound.service;
|
||||||
|
|
||||||
|
/** Видео-сообщение сохранено — после коммита его вложение ставится в очередь обработки. */
|
||||||
|
public record ChatVideoUploadedEvent(Long attachmentId) {
|
||||||
|
}
|
||||||
@@ -6,9 +6,13 @@ import com.krylov.refound.enums.ErrorCode;
|
|||||||
import com.krylov.refound.exception.ApiException;
|
import com.krylov.refound.exception.ApiException;
|
||||||
import com.krylov.refound.util.ImageFormat;
|
import com.krylov.refound.util.ImageFormat;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
|
import java.io.InputStream;
|
||||||
import java.net.URLDecoder;
|
import java.net.URLDecoder;
|
||||||
import java.net.URLEncoder;
|
import java.net.URLEncoder;
|
||||||
import java.nio.charset.StandardCharsets;
|
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.time.Duration;
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
import java.util.Map;
|
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.core.exception.SdkClientException;
|
||||||
import software.amazon.awssdk.services.s3.presigner.S3Presigner;
|
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.GetObjectPresignRequest;
|
||||||
|
import software.amazon.awssdk.services.s3.presigner.model.PutObjectPresignRequest;
|
||||||
|
|
||||||
@Service
|
@Service
|
||||||
@Slf4j
|
@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<HeadObjectResponse> 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 не записывается: такие файлы (вложения чатов) удаляет только их сервис.
|
* Redis не записывается: такие файлы (вложения чатов) удаляет только их сервис.
|
||||||
|
|||||||
@@ -105,6 +105,7 @@ public class OrphanFileCleanupService {
|
|||||||
.map(this::toKey)
|
.map(this::toKey)
|
||||||
.forEach(keys::add);
|
.forEach(keys::add);
|
||||||
keys.addAll(attachmentRepository.findAllObjectKeys());
|
keys.addAll(attachmentRepository.findAllObjectKeys());
|
||||||
|
keys.addAll(attachmentRepository.findAllPosterKeys());
|
||||||
return keys;
|
return keys;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -182,6 +182,12 @@ rate-limit:
|
|||||||
paths: [/api/v1/chats/*/messages]
|
paths: [/api/v1/chats/*/messages]
|
||||||
limit: 60
|
limit: 60
|
||||||
window: PT1H
|
window: PT1H
|
||||||
|
# Видео в чат: ссылка на загрузку исходника; каждое видео — ffmpeg на сервере
|
||||||
|
- name: chat-video
|
||||||
|
method: POST
|
||||||
|
paths: [/api/v1/chats/*/videos/upload-url]
|
||||||
|
limit: 20
|
||||||
|
window: PT1H
|
||||||
- name: chat-start
|
- name: chat-start
|
||||||
method: POST
|
method: POST
|
||||||
paths: [/api/v1/chats/with/**]
|
paths: [/api/v1/chats/with/**]
|
||||||
|
|||||||
@@ -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 }
|
||||||
@@ -37,3 +37,4 @@ databaseChangeLog:
|
|||||||
- include: { file: db/changelog/add/022-add-closed-at-posts.yaml }
|
- include: { file: db/changelog/add/022-add-closed-at-posts.yaml }
|
||||||
- include: { file: db/changelog/add/023-add-phone-visible-posts.yaml }
|
- include: { file: db/changelog/add/023-add-phone-visible-posts.yaml }
|
||||||
- include: { file: db/changelog/create/024-create-message-attachments.yaml }
|
- include: { file: db/changelog/create/024-create-message-attachments.yaml }
|
||||||
|
- include: { file: db/changelog/add/025-message-attachments-video.yaml }
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ import com.krylov.refound.entity.Chat;
|
|||||||
import com.krylov.refound.entity.Message;
|
import com.krylov.refound.entity.Message;
|
||||||
import com.krylov.refound.entity.MessageAttachment;
|
import com.krylov.refound.entity.MessageAttachment;
|
||||||
import com.krylov.refound.enums.AttachmentKind;
|
import com.krylov.refound.enums.AttachmentKind;
|
||||||
|
import com.krylov.refound.enums.AttachmentStatus;
|
||||||
import com.krylov.refound.entity.Post;
|
import com.krylov.refound.entity.Post;
|
||||||
import com.krylov.refound.entity.User;
|
import com.krylov.refound.entity.User;
|
||||||
import com.krylov.refound.enums.PostStatus;
|
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.BeforeEach;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
import org.mockito.ArgumentCaptor;
|
import org.mockito.ArgumentCaptor;
|
||||||
|
import org.springframework.context.ApplicationEventPublisher;
|
||||||
import org.springframework.http.HttpStatus;
|
import org.springframework.http.HttpStatus;
|
||||||
import org.springframework.mock.web.MockMultipartFile;
|
import org.springframework.mock.web.MockMultipartFile;
|
||||||
import org.springframework.transaction.support.TransactionCallback;
|
import org.springframework.transaction.support.TransactionCallback;
|
||||||
@@ -46,6 +48,8 @@ class ChatServiceTest {
|
|||||||
private MessageRepository messageRepository;
|
private MessageRepository messageRepository;
|
||||||
private MessageAttachmentRepository attachmentRepository;
|
private MessageAttachmentRepository attachmentRepository;
|
||||||
private ChatAttachmentService attachmentService;
|
private ChatAttachmentService attachmentService;
|
||||||
|
private ChatVideoUploadService videoUploadService;
|
||||||
|
private ApplicationEventPublisher eventPublisher;
|
||||||
private ChatService chatService;
|
private ChatService chatService;
|
||||||
|
|
||||||
@BeforeEach
|
@BeforeEach
|
||||||
@@ -56,10 +60,12 @@ class ChatServiceTest {
|
|||||||
messageRepository = mock(MessageRepository.class);
|
messageRepository = mock(MessageRepository.class);
|
||||||
attachmentRepository = mock(MessageAttachmentRepository.class);
|
attachmentRepository = mock(MessageAttachmentRepository.class);
|
||||||
attachmentService = mock(ChatAttachmentService.class);
|
attachmentService = mock(ChatAttachmentService.class);
|
||||||
|
videoUploadService = mock(ChatVideoUploadService.class);
|
||||||
|
eventPublisher = mock(ApplicationEventPublisher.class);
|
||||||
TransactionTemplate tx = mock(TransactionTemplate.class);
|
TransactionTemplate tx = mock(TransactionTemplate.class);
|
||||||
when(tx.execute(any())).thenAnswer(inv -> inv.<TransactionCallback<?>>getArgument(0).doInTransaction(null));
|
when(tx.execute(any())).thenAnswer(inv -> inv.<TransactionCallback<?>>getArgument(0).doInTransaction(null));
|
||||||
chatService = new ChatService(chatRepository, messageRepository, mock(ClusterMessaging.class),
|
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(userRepository.existsById(anyLong())).thenReturn(true);
|
||||||
when(chatRepository.findByUsersAndPost(any(), any(), any())).thenReturn(List.of());
|
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(attachmentRepository.saveAll(any())).thenAnswer(inv -> inv.getArgument(0));
|
||||||
when(attachmentService.toDto(any())).thenAnswer(inv -> {
|
when(attachmentService.toDto(any())).thenAnswer(inv -> {
|
||||||
MessageAttachment a = inv.getArgument(0);
|
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);
|
MessageDto dto = chatService.sendMessageWithPhotos(14L, 7L, null, files);
|
||||||
@@ -277,13 +284,18 @@ class ChatServiceTest {
|
|||||||
@Test
|
@Test
|
||||||
void deletingChatDeletesItsFiles() {
|
void deletingChatDeletesItsFiles() {
|
||||||
chatBetween(7L, 14L, 19L);
|
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);
|
chatService.deleteChat(7L, 19L);
|
||||||
|
|
||||||
verify(chatRepository).deleteById(7L);
|
verify(chatRepository).deleteById(7L);
|
||||||
// Без активной транзакции afterCommit выполняется сразу
|
// Без активной транзакции 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
|
@Test
|
||||||
@@ -292,13 +304,93 @@ class ChatServiceTest {
|
|||||||
MessageAttachment attachment = new MessageAttachment();
|
MessageAttachment attachment = new MessageAttachment();
|
||||||
attachment.setObjectKey("chat/7/a.jpg");
|
attachment.setObjectKey("chat/7/a.jpg");
|
||||||
when(attachmentRepository.findByIdAndChatId(3L, 7L)).thenReturn(Optional.of(attachment));
|
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");
|
assertThat(chatService.getAttachment(7L, 3L, 14L).getUrl()).isEqualTo("https://minio/signed");
|
||||||
assertThatThrownBy(() -> chatService.getAttachmentUrl(7L, 3L, 99L))
|
assertThatThrownBy(() -> chatService.getAttachment(7L, 3L, 99L))
|
||||||
.isInstanceOfSatisfying(ApiException.class, e -> assertThat(e.getStatus()).isEqualTo(HttpStatus.FORBIDDEN));
|
.isInstanceOfSatisfying(ApiException.class, e -> assertThat(e.getStatus()).isEqualTo(HttpStatus.FORBIDDEN));
|
||||||
// Вложение другого чата по id своего чата не достать
|
// Вложение другого чата по id своего чата не достать
|
||||||
assertThatThrownBy(() -> chatService.getAttachmentUrl(7L, 4L, 14L))
|
assertThatThrownBy(() -> chatService.getAttachment(7L, 4L, 14L))
|
||||||
.isInstanceOfSatisfying(ApiException.class, e -> assertThat(e.getStatus()).isEqualTo(HttpStatus.NOT_FOUND));
|
.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("avatars/legacy.jpg").lastModified(old).build(),
|
||||||
S3Object.builder().key("orphan.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/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("chat/5/deleted-chat.jpg").lastModified(old).build(),
|
||||||
S3Object.builder().key("fresh.jpg").lastModified(Instant.now()).build()).build();
|
S3Object.builder().key("fresh.jpg").lastModified(Instant.now()).build()).build();
|
||||||
when(s3.listObjectsV2Paginator(any(ListObjectsV2Request.class)))
|
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"));
|
when(users.findAllAvatarUrls()).thenReturn(List.of("http://minio:9010/refound-images/avatars/legacy.jpg?x=1"));
|
||||||
MessageAttachmentRepository attachments = mock(MessageAttachmentRepository.class);
|
MessageAttachmentRepository attachments = mock(MessageAttachmentRepository.class);
|
||||||
when(attachments.findAllObjectKeys()).thenReturn(List.of("chat/5/photo.jpg"));
|
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);
|
FileStorageService storage = mock(FileStorageService.class);
|
||||||
|
|
||||||
new OrphanFileCleanupService(s3, properties, images, users, attachments, storage, true, Duration.ofHours(24), 100)
|
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("fresh.jpg");
|
||||||
// Фото чата живёт, пока на него ссылается вложение; файл удалённого чата — сирота
|
// Фото чата живёт, пока на него ссылается вложение; файл удалённого чата — сирота
|
||||||
verify(storage, never()).deleteFile("chat/5/photo.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");
|
verify(storage).deleteFile("chat/5/deleted-chat.jpg");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user