Files
nahodka-back/src/main/java/com/krylov/refound/service/ChatVideoTranscoder.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

290 lines
13 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.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());
}
}
}