Files
nahodka-back/src/main/java/com/krylov/refound/service/ChatVideoUploadService.java
SlimusMinus 871b16a038 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>
2026-10-28 23:00:11 +03:00

120 lines
6.5 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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