Send and play videos in chats

- the attach button accepts one video per message (MP4, MOV, WebM, 3GP);
  type, size (100 MB) and duration (60 s) are checked before upload
- the video is uploaded straight to storage with a progress indicator,
  then confirmed; the message shows "processing" until the server pushes
  the ready (or failed) version over WebSocket
- player with poster and duration in bubbles; fresh links when they expire
- chat list preview shows "Video" for video-only messages

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
SlimusMinus
2026-10-28 23:00:18 +03:00
parent 0e3cac62a4
commit b94ef2918c
11 changed files with 488 additions and 31 deletions

View File

@@ -119,20 +119,68 @@ export function useChats() {
return res.json();
}, []);
/** Свежая ссылка на фото, если выданная вместе с сообщением истекла. */
/** Свежие ссылки на вложение ({ url, posterUrl }), если выданные с сообщением истекли. */
const refreshAttachmentUrl = useCallback(async (chatId, attachmentId) => {
const res = await apiFetch(`${API_URL}/api/v1/chats/${chatId}/attachments/${attachmentId}/url`);
if (!res.ok) throw new Error(`Error ${res.status}`);
const { url } = await res.json();
return url;
return res.json();
}, []);
/**
* Видео: 1) ссылка на загрузку, 2) файл прямо в хранилище (через бэкенд с его
* лимитом 10 МБ видео не пройдёт), 3) подтверждение — сервер создаёт сообщение
* с видео «в обработке», а готовое видео придёт по сокету тем же сообщением.
*/
const sendVideoMessage = useCallback(async (chatId, content, file, onProgress) => {
const ticketRes = await apiFetch(`${API_URL}/api/v1/chats/${chatId}/videos/upload-url`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ contentType: file.type, sizeBytes: file.size }),
});
if (!ticketRes.ok) throw await readApiError(ticketRes);
const { uploadUrl, sourceKey } = await ticketRes.json();
await uploadWithProgress(uploadUrl, file, onProgress);
const res = await apiFetch(`${API_URL}/api/v1/chats/${chatId}/videos`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ sourceKey, content: content || null }),
});
if (!res.ok) {
const err = await readApiError(res);
console.warn("sendVideoMessage failed:", err.status, err.serverMessage);
throw err;
}
return res.json();
}, []);
return {
chats, loading, error, fetchChats, findChat, startChat, fetchMessages, markAsRead,
sendPhotoMessage, refreshAttachmentUrl,
sendPhotoMessage, sendVideoMessage, refreshAttachmentUrl,
};
}
/**
* PUT файла по presigned-ссылке с прогрессом (у fetch прогресса отправки нет).
* Content-Type должен совпасть с подписанным — иначе хранилище ответит 403.
*/
function uploadWithProgress(url, file, onProgress) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open("PUT", url);
xhr.setRequestHeader("Content-Type", file.type);
xhr.upload.onprogress = (e) => {
if (e.lengthComputable) onProgress?.(e.loaded / e.total);
};
xhr.onload = () => (xhr.status >= 200 && xhr.status < 300
? resolve()
: reject(new Error(`Upload failed: ${xhr.status}`)));
xhr.onerror = () => reject(new Error("Upload failed"));
xhr.send(file);
});
}
function chatWithUrl(otherUserId, postId, suffix = "") {
const url = new URL(`${API_URL}/api/v1/chats/with/${otherUserId}${suffix}`);
if (postId) url.searchParams.set("postId", postId);

View File

@@ -0,0 +1,96 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
// Те же ограничения, что на бэкенде (ChatVideoUploadService, ChatVideoTranscoder)
export const VIDEO_TYPES = ["video/mp4", "video/quicktime", "video/webm", "video/3gpp"];
export const MAX_VIDEO_MB = 100;
export const MAX_VIDEO_SECONDS = 60;
/**
* Длительность видео по метаданным. Браузер может не уметь открыть файл
* (например, HEVC из iPhone в Chrome) — тогда null, и длительность проверит сервер.
*/
export function readVideoDuration(file) {
return new Promise((resolve) => {
if (typeof document === "undefined" || typeof URL.createObjectURL !== "function") {
resolve(null);
return;
}
const url = URL.createObjectURL(file);
const video = document.createElement("video");
video.preload = "metadata";
let done = false;
const finish = (value) => {
if (done) return;
done = true;
URL.revokeObjectURL(url);
resolve(value);
};
video.onloadedmetadata = () => finish(Number.isFinite(video.duration) ? video.duration : null);
video.onerror = () => finish(null);
setTimeout(() => finish(null), 5000);
video.src = url;
});
}
/**
* Выбранное для отправки видео (одно на сообщение): проверка формата, размера
* и длительности, превью-ссылка и её освобождение.
*/
export function useVideoAttachment() {
const { t } = useTranslation();
const [video, setVideo] = useState(null);
const [error, setError] = useState("");
const [checking, setChecking] = useState(false);
const videoRef = useRef(null);
videoRef.current = video;
const clearVideo = useCallback(() => {
setVideo((prev) => {
if (prev?.preview) URL.revokeObjectURL(prev.preview);
return null;
});
setError("");
}, []);
/** Проверяет файл и делает его выбранным видео. Возвращает true, если видео принято. */
const selectVideo = useCallback(async (file) => {
setError("");
if (!VIDEO_TYPES.includes(file.type)) {
setError(t("chat.videoBadType"));
return false;
}
if (file.size > MAX_VIDEO_MB * 1024 * 1024) {
setError(t("chat.videoTooLarge", { max: MAX_VIDEO_MB }));
return false;
}
setChecking(true);
try {
const duration = await readVideoDuration(file);
if (duration != null && duration > MAX_VIDEO_SECONDS + 1) {
setError(t("chat.videoTooLong", { max: MAX_VIDEO_SECONDS }));
return false;
}
setVideo((prev) => {
if (prev?.preview) URL.revokeObjectURL(prev.preview);
return { file, preview: URL.createObjectURL(file), duration };
});
return true;
} finally {
setChecking(false);
}
}, [t]);
useEffect(() => () => {
if (videoRef.current?.preview) URL.revokeObjectURL(videoRef.current.preview);
}, []);
return { video, error, setError, checking, selectVideo, clearVideo };
}
/** «0:07», «1:00» — длительность для подписи на видео. */
export function formatDuration(seconds) {
if (seconds == null || !Number.isFinite(seconds)) return "";
const total = Math.round(seconds);
return `${Math.floor(total / 60)}:${String(total % 60).padStart(2, "0")}`;
}