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

@@ -1,4 +1,5 @@
import { ACCEPT } from "../../hooks/useImageUpload";
import { formatDuration } from "../../hooks/useVideoAttachment";
import CloseIcon from "../icons/CloseIcon";
// Тот же лимит, что ChatService.MAX_MESSAGE_LENGTH на бэкенде
@@ -14,9 +15,10 @@ function PaperclipIcon() {
}
/**
* Поле ввода чата. С attach — кнопка-скрепка, превью выбранных фото над полем
* и вставка картинок из буфера обмена. attach: { images, addFiles, removeImage,
* fileInputRef, compressing, error, disabled, label, removeLabel }.
* Поле ввода чата. С attach — кнопка-скрепка, превью выбранных фото или видео
* над полем и вставка картинок из буфера обмена. attach: { images, addFiles,
* removeImage, fileInputRef, compressing, error, disabled, label, removeLabel,
* accept, video, removeVideo, videoProgress }.
*/
export default function ChatInputBar({
input,
@@ -28,7 +30,9 @@ export default function ChatInputBar({
sending = false,
}) {
const images = attach?.images ?? [];
const canSend = connected && !sending && !attach?.compressing && (input.trim() || images.length > 0);
const video = attach?.video ?? null;
const progress = attach?.videoProgress;
const canSend = connected && !sending && !attach?.compressing && (input.trim() || images.length > 0 || video);
const handlePaste = (e) => {
if (!attach || attach.disabled) return;
@@ -41,7 +45,7 @@ export default function ChatInputBar({
return (
<div className="chat-input-area">
{attach && (images.length > 0 || attach.compressing || attach.error) && (
{attach && (images.length > 0 || video || attach.compressing || attach.error) && (
<div className="chat-attach-strip">
{images.map((img) => (
<div key={img.id} className={`chat-attach-thumb${sending ? " is-sending" : ""}`}>
@@ -55,6 +59,27 @@ export default function ChatInputBar({
)}
</div>
))}
{video && (
<div className={`chat-attach-thumb chat-attach-thumb--video${sending ? " is-sending" : ""}`}>
<video src={video.preview} muted playsInline preload="metadata" />
{video.duration != null && (
<span className="chat-attach-duration">{formatDuration(video.duration)}</span>
)}
{progress != null && (
<span className="chat-attach-progress" role="progressbar" aria-valuemin={0} aria-valuemax={100}
aria-valuenow={Math.round(progress * 100)}>
{Math.round(progress * 100)}%
</span>
)}
{!sending && (
<button type="button" className="chat-attach-remove"
onClick={attach.removeVideo}
aria-label={attach.removeLabel} title={attach.removeLabel}>
<CloseIcon />
</button>
)}
</div>
)}
{attach.compressing && (
<div className="chat-attach-thumb chat-attach-thumb--busy"><div className="f-spinner" /></div>
)}
@@ -73,7 +98,7 @@ export default function ChatInputBar({
<input
ref={attach.fileInputRef}
type="file"
accept={ACCEPT}
accept={attach.accept || ACCEPT}
multiple
hidden
data-testid="chat-attach-input"

View File

@@ -29,7 +29,7 @@ test("фото сообщения показываются и открывают
expect(imgs.map((img) => img.getAttribute("src"))).toEqual(["https://minio/a.jpg", "https://minio/b.jpg"]);
fireEvent.click(screen.getAllByLabelText("Открыть фото")[1]);
expect(onOpenPhoto).toHaveBeenCalledWith(message, 1);
expect(onOpenPhoto).toHaveBeenCalledWith(PHOTOS, 1);
});
test("истёкшая ссылка на фото сообщает об ошибке для обновления", () => {

View File

@@ -0,0 +1,102 @@
/**
* Видео в чатах: состояния в пузыре (обрабатывается / готово / не вышло),
* превью выбранного видео с прогрессом загрузки, подпись «Видео» в списке
* чатов и проверки файла до отправки.
*/
import { createRef } from "react";
import { render, screen, renderHook, act } from "@testing-library/react";
import "@testing-library/jest-dom";
import i18n from "../../i18n";
import MessageBubble from "./MessageBubble";
import ChatInputBar from "./ChatInputBar";
import { getChatDisplayInfo } from "../../utils/chatDisplay";
import { formatDuration, useVideoAttachment, MAX_VIDEO_MB } from "../../hooks/useVideoAttachment";
const t = i18n.t.bind(i18n);
beforeAll(() => i18n.changeLanguage("ru"));
const video = (extra) => ({ id: 3, kind: "VIDEO", width: 1280, height: 720, ...extra });
test("видео в обработке — заглушка без плеера", () => {
render(<MessageBubble message={{ id: 1, content: "", attachments: [video({ status: "PROCESSING" })] }} isMine />);
expect(screen.getByText("Видео обрабатывается…")).toBeInTheDocument();
expect(document.querySelector("video")).toBeNull(); // eslint-disable-line testing-library/no-node-access
});
test("готовое видео — плеер с обложкой и длительностью", () => {
render(<MessageBubble isMine={false} message={{
id: 1, content: "вот", attachments: [video({
status: "READY", url: "https://minio/v.mp4", posterUrl: "https://minio/v.jpg", durationMs: 7400,
})],
}} />);
// eslint-disable-next-line testing-library/no-node-access
const player = document.querySelector("video");
expect(player).toHaveAttribute("src", "https://minio/v.mp4");
expect(player).toHaveAttribute("poster", "https://minio/v.jpg");
expect(screen.getByText("0:07")).toBeInTheDocument();
expect(screen.getByText("вот")).toBeInTheDocument();
});
test("видео не обработалось — понятное сообщение", () => {
render(<MessageBubble message={{ id: 1, content: "", attachments: [video({ status: "FAILED" })] }} isMine />);
expect(screen.getByText("Не удалось обработать видео")).toBeInTheDocument();
});
test("выбранное видео показывается с длительностью и прогрессом загрузки", () => {
const attach = {
images: [],
video: { file: new File(["x"], "v.mp4", { type: "video/mp4" }), preview: "blob:v", duration: 12.4 },
videoProgress: 0.42,
addFiles: jest.fn(),
removeImage: jest.fn(),
removeVideo: jest.fn(),
fileInputRef: createRef(),
compressing: false,
error: "",
label: "Прикрепить фото или видео",
removeLabel: "Убрать",
};
render(<ChatInputBar input="" onInputChange={() => {}} onSend={() => {}} connected placeholder=""
attach={attach} sending />);
expect(screen.getByText("0:12")).toBeInTheDocument();
expect(screen.getByRole("progressbar")).toHaveTextContent("42%");
// Во время отправки видео не убрать
expect(screen.queryByLabelText("Убрать")).toBeNull();
});
test("превью в списке чатов: «Видео» для сообщения только с видео", () => {
const info = getChatDisplayInfo(
{ id: 1, lastMessage: "", lastMessageAttachments: 1, lastMessageAttachmentKind: "VIDEO" }, null, {}, t);
expect(info.preview).toBe("🎬 Видео");
});
test("неподходящий формат и слишком большое видео отклоняются до загрузки", async () => {
const { result } = renderHook(() => useVideoAttachment());
let accepted;
await act(async () => {
accepted = await result.current.selectVideo(new File(["x"], "clip.avi", { type: "video/x-msvideo" }));
});
expect(accepted).toBe(false);
expect(result.current.error).toMatch(/формат/);
const huge = new File(["x"], "big.mp4", { type: "video/mp4" });
Object.defineProperty(huge, "size", { value: (MAX_VIDEO_MB + 1) * 1024 * 1024 });
await act(async () => {
accepted = await result.current.selectVideo(huge);
});
expect(accepted).toBe(false);
expect(result.current.error).toMatch(/МБ/);
expect(result.current.video).toBeNull();
});
test("длительность форматируется как м:сс", () => {
expect(formatDuration(7.4)).toBe("0:07");
expect(formatDuration(60)).toBe("1:00");
expect(formatDuration(null)).toBe("");
});

View File

@@ -1,19 +1,62 @@
import { useTranslation } from "react-i18next";
import { formatMessageTime } from "../../utils/chatDisplay";
import { formatDuration } from "../../hooks/useVideoAttachment";
/** Видео сообщения: пока обрабатывается — заглушка, не обработалось — сообщение об ошибке. */
function ChatVideo({ video, onError, t }) {
const ratio = video.width && video.height ? `${video.width} / ${video.height}` : "16 / 9";
if (video.status === "PROCESSING") {
return (
<div className="chat-video chat-video--pending" style={{ aspectRatio: ratio }} role="status">
<div className="f-spinner" />
<span>{t("chat.videoProcessing")}</span>
</div>
);
}
if (video.status === "FAILED" || !video.url) {
return (
<div className="chat-video chat-video--failed" style={{ aspectRatio: ratio }} role="status">
<span>{t("chat.videoFailed")}</span>
</div>
);
}
return (
<div className="chat-video" style={{ aspectRatio: ratio }}>
<video
src={video.url}
poster={video.posterUrl || undefined}
controls
playsInline
preload="metadata"
onError={onError}
/>
{video.durationMs != null && (
<span className="chat-video-duration">{formatDuration(video.durationMs / 1000)}</span>
)}
</div>
);
}
/**
* Пузырь сообщения. Фото (message.attachments) — сеткой над текстом; клик
* открывает просмотр. width/height приходят с бэкенда: место под фото
* резервируется сразу, и лента не прыгает, пока картинки грузятся.
* открывает просмотр. Видео — плеером с обложкой. width/height приходят с
* бэкенда: место резервируется сразу, и лента не прыгает, пока файлы грузятся.
*/
export default function MessageBubble({ message, isMine, onOpenPhoto, onPhotoError }) {
const { t, i18n } = useTranslation();
const time = formatMessageTime(message.createdAt, i18n.language);
const photos = Array.isArray(message.attachments) ? message.attachments : [];
const attachments = Array.isArray(message.attachments) ? message.attachments : [];
// Старые ответы бэкенда без kind — это фото
const photos = attachments.filter((a) => (a.kind ?? "PHOTO") === "PHOTO");
const videos = attachments.filter((a) => a.kind === "VIDEO");
const single = photos.length === 1;
return (
<div className={`chat-bubble${isMine ? " mine" : ""}${photos.length ? " has-photos" : ""}`}>
<div className={`chat-bubble${isMine ? " mine" : ""}${attachments.length ? " has-photos" : ""}`}>
{videos.map((video) => (
<ChatVideo key={video.id} video={video} t={t} onError={() => onPhotoError?.(message, video)} />
))}
{photos.length > 0 && (
<div className={`chat-photos${single ? " chat-photos--single" : ""}`}>
{photos.map((photo, i) => (
@@ -24,7 +67,7 @@ export default function MessageBubble({ message, isMine, onOpenPhoto, onPhotoErr
style={single && photo.width && photo.height
? { aspectRatio: `${photo.width} / ${photo.height}` }
: undefined}
onClick={() => onOpenPhoto?.(message, i)}
onClick={() => onOpenPhoto?.(photos, i)}
aria-label={t("chat.openPhoto")}
>
<img