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

@@ -17,7 +17,8 @@ import ChatPhotoViewer from "../components/chat/ChatPhotoViewer";
import ChatPostMeta from "../components/chat/ChatPostMeta";
import PostDetailModal from "../components/PostDetailModal";
import { POST_STATUS_CLOSED } from "../config/postConstants";
import { useImageUpload } from "../hooks/useImageUpload";
import { ACCEPT as IMAGE_ACCEPT, useImageUpload } from "../hooks/useImageUpload";
import { VIDEO_TYPES, useVideoAttachment } from "../hooks/useVideoAttachment";
import Toast from "../components/Toast";
// Тот же лимит, что ChatAttachmentService.MAX_PHOTOS_PER_MESSAGE на бэкенде
@@ -38,7 +39,7 @@ export default function ChatPage({ embedded = false, onActivity } = {}) {
// Черновик (/chats/new): переписки ещё нет, чат создастся с первым сообщением
const draft = chatId ? null : location.state;
const [startingChat, setStartingChat] = useState(false);
const { fetchMessages, markAsRead, startChat, sendPhotoMessage, refreshAttachmentUrl } = useChats();
const { fetchMessages, markAsRead, startChat, sendPhotoMessage, sendVideoMessage, refreshAttachmentUrl } = useChats();
const { clearChatUnread } = useUnread();
const { user, isAuthenticated } = useAuthContext();
const [messages, setMessages] = useState([]);
@@ -51,6 +52,10 @@ export default function ChatPage({ embedded = false, onActivity } = {}) {
const upload = useImageUpload();
const { addFiles: addUploadFiles } = upload;
const [photoLimitError, setPhotoLimitError] = useState("");
const videoAttach = useVideoAttachment();
const { selectVideo } = videoAttach;
// Прогресс загрузки видео в хранилище, 0..1; null — загрузки нет
const [videoProgress, setVideoProgress] = useState(null);
// id вложений, для которых уже запрашивали свежую ссылку, — без повторов по кругу
const refreshedPhotosRef = useRef(new Set());
const messagesEndRef = useRef(null);
@@ -58,10 +63,15 @@ export default function ChatPage({ embedded = false, onActivity } = {}) {
const myUserId = user?.id;
/** Мержит новое сообщение по id — защита от дублей (REST + WS эхо). */
/**
* Мержит сообщение по id — защита от дублей (REST + WS эхо). Уже известное
* сообщение заменяется: так приходит видео, которое закончило обрабатываться.
*/
const addMessage = useCallback((msg) => {
setMessages((prev) => {
if (msg.id != null && prev.some((m) => m.id === msg.id)) return prev;
if (msg.id != null && prev.some((m) => m.id === msg.id)) {
return prev.map((m) => (m.id === msg.id ? { ...m, ...msg } : m));
}
return sortMessages([...prev, msg]);
});
}, []);
@@ -147,6 +157,27 @@ export default function ChatPage({ embedded = false, onActivity } = {}) {
const trimmed = input.trim();
const photos = draft ? [] : upload.getFilesForUpload();
const video = draft ? null : videoAttach.video;
if (video) {
if (sendingPhotos) return;
setSendingPhotos(true);
setVideoProgress(0);
sendVideoMessage(chatId, trimmed, video.file, setVideoProgress)
.then((msg) => {
addMessage(msg);
setInput("");
videoAttach.clearVideo();
onActivity?.();
})
// 429 — лимит видео; 400 — формат, размер; сбой загрузки в хранилище
.catch((err) => setSendError(describeApiError(err, t('chat.videoSendError'))))
.finally(() => {
setSendingPhotos(false);
setVideoProgress(null);
});
return;
}
if (photos.length > 0) {
if (sendingPhotos || upload.compressing) return;
setSendingPhotos(true);
@@ -189,10 +220,30 @@ export default function ChatPage({ embedded = false, onActivity } = {}) {
setInput("");
onActivity?.();
}, [input, sendMessage, t, draft, startingChat, startChat, navigate, onActivity,
upload, sendingPhotos, sendPhotoMessage, chatId, addMessage]);
upload, sendingPhotos, sendPhotoMessage, chatId, addMessage, videoAttach, sendVideoMessage]);
/**
* Выбор файлов: фото (до 10) или одно видео. Видео уходит отдельным
* сообщением — вместе с фото его не отправить.
*/
const addPhotos = useCallback((fileList) => {
const files = Array.from(fileList || []);
const videos = files.filter((f) => f.type.startsWith("video/"));
if (videos.length > 0) {
if (upload.fileInputRef.current) upload.fileInputRef.current.value = "";
if (videos.length > 1 || files.length > videos.length || upload.images.length > 0) {
setPhotoLimitError(t('chat.videoSeparately'));
return;
}
setPhotoLimitError("");
selectVideo(videos[0]);
return;
}
if (videoAttach.video) {
setPhotoLimitError(t('chat.videoSeparately'));
if (upload.fileInputRef.current) upload.fileInputRef.current.value = "";
return;
}
if (upload.images.length + files.length > MAX_PHOTOS_PER_MESSAGE) {
setPhotoLimitError(t('chat.tooManyPhotos', { max: MAX_PHOTOS_PER_MESSAGE }));
if (upload.fileInputRef.current) upload.fileInputRef.current.value = "";
@@ -200,16 +251,16 @@ export default function ChatPage({ embedded = false, onActivity } = {}) {
}
setPhotoLimitError("");
addUploadFiles(files);
}, [upload.images.length, upload.fileInputRef, addUploadFiles, t]);
}, [upload.images.length, upload.fileInputRef, addUploadFiles, t, selectVideo, videoAttach.video]);
// Ссылка на фото временная: если чат долго открыт и она истекла, берём свежую
// Ссылки на фото и видео временные: если чат долго открыт и ссылка истекла, берём свежую
const handlePhotoError = useCallback((message, photo) => {
if (!chatId || photo.id == null || refreshedPhotosRef.current.has(photo.id)) return;
refreshedPhotosRef.current.add(photo.id);
refreshAttachmentUrl(chatId, photo.id)
.then((url) => setMessages((prev) => prev.map((m) => (m.id !== message.id ? m : {
.then(({ url, posterUrl }) => setMessages((prev) => prev.map((m) => (m.id !== message.id ? m : {
...m,
attachments: m.attachments.map((a) => (a.id === photo.id ? { ...a, url } : a)),
attachments: m.attachments.map((a) => (a.id === photo.id ? { ...a, url, posterUrl } : a)),
}))))
.catch(() => {});
}, [chatId, refreshAttachmentUrl]);
@@ -254,7 +305,7 @@ export default function ChatPage({ embedded = false, onActivity } = {}) {
key={m.id}
message={m}
isMine={m.senderId === myUserId}
onOpenPhoto={(msg, index) => setViewer({ photos: msg.attachments, index })}
onOpenPhoto={(photos, index) => setViewer({ photos, index })}
onPhotoError={handlePhotoError}
/>
))}
@@ -274,9 +325,13 @@ export default function ChatPage({ embedded = false, onActivity } = {}) {
addFiles: addPhotos,
removeImage: upload.removeImage,
fileInputRef: upload.fileInputRef,
compressing: upload.compressing,
error: photoLimitError || upload.imgError,
label: t('chat.attachPhoto'),
compressing: upload.compressing || videoAttach.checking,
error: photoLimitError || videoAttach.error || upload.imgError,
accept: [IMAGE_ACCEPT, ...VIDEO_TYPES].join(","),
video: videoAttach.video,
removeVideo: videoAttach.clearVideo,
videoProgress,
label: t('chat.attachMedia'),
removeLabel: t('chat.removePhoto'),
}}
/>