Add video attachments to chat messages
- browser uploads the source straight to MinIO via presigned PUT (type and exact size are signed, up to 100 MB); upload is confirmed once by its owner - message is created with a PROCESSING video, transcoded in the background (chatVideoExecutor): H.264/AAC, short side up to 720px, faststart, metadata (incl. location) stripped, poster frame; up to 60 s - the updated message is re-broadcast over WebSocket when READY or FAILED; stuck processing is failed after 30 min - message_attachments: status, poster_key, duration_ms, processing_started_at - chat deletion and orphan cleanup handle video posters; rate limit chat-video Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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<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);
|
||||
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}")
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
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;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package com.krylov.refound.enums;
|
||||
|
||||
/** Тип вложения сообщения чата. VIDEO появится вторым этапом. */
|
||||
/** Тип вложения сообщения чата. */
|
||||
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;
|
||||
|
||||
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<MessageAttach
|
||||
|
||||
Optional<MessageAttachment> findByIdAndChatId(Long id, Long chatId);
|
||||
|
||||
/** Ключи файлов чата — чтобы удалить их из хранилища вместе с чатом. */
|
||||
@Query("select a.objectKey from MessageAttachment a where a.chatId = :chatId")
|
||||
List<String> findObjectKeysByChatId(@Param("chatId") Long chatId);
|
||||
List<MessageAttachment> findByChatId(Long chatId);
|
||||
|
||||
/** Число вложений у сообщений: строки (messageId, count) — для превью в списке чатов. */
|
||||
@Query("select a.messageId, count(a) from MessageAttachment a where a.messageId in :messageIds group by a.messageId")
|
||||
List<Object[]> countByMessageIds(@Param("messageIds") Collection<Long> messageIds);
|
||||
List<MessageAttachment> findByMessageId(Long messageId);
|
||||
|
||||
/** Все ключи вложений — для чистки файлов-сирот. */
|
||||
/** Типы вложений у сообщений: строки (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")
|
||||
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.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.
|
||||
*
|
||||
* <p>Ключи лежат под {@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) {
|
||||
|
||||
@@ -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<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 {
|
||||
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<ChatAttachmentService.StoredPhoto> photos) {
|
||||
List<MessageAttachment> 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<MessageAttachment> attachments = new ArrayList<>();
|
||||
for (int i = 0; i < photos.size(); i++) {
|
||||
ChatAttachmentService.StoredPhoto photo = photos.get(i);
|
||||
MessageAttachment attachment = new MessageAttachment();
|
||||
List<MessageAttachment> 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<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);
|
||||
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<Long, Integer> lastAttachments = new HashMap<>();
|
||||
Map<Long, AttachmentKind> 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;
|
||||
|
||||
@@ -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.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<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 не записывается: такие файлы (вложения чатов) удаляет только их сервис.
|
||||
|
||||
@@ -105,6 +105,7 @@ public class OrphanFileCleanupService {
|
||||
.map(this::toKey)
|
||||
.forEach(keys::add);
|
||||
keys.addAll(attachmentRepository.findAllObjectKeys());
|
||||
keys.addAll(attachmentRepository.findAllPosterKeys());
|
||||
return keys;
|
||||
}
|
||||
|
||||
|
||||
@@ -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/**]
|
||||
|
||||
@@ -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/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 }
|
||||
|
||||
Reference in New Issue
Block a user