Merge pull request #125 from SlimusMinus/feat-chat_video
All checks were successful
deploy-frontend / deploy (push) Successful in 55s

Send and play videos in chats
This commit is contained in:
SlimusMinus
2026-10-28 23:15:38 +03:00
committed by GitHub
11 changed files with 488 additions and 31 deletions

View File

@@ -1,4 +1,5 @@
import { ACCEPT } from "../../hooks/useImageUpload"; import { ACCEPT } from "../../hooks/useImageUpload";
import { formatDuration } from "../../hooks/useVideoAttachment";
import CloseIcon from "../icons/CloseIcon"; import CloseIcon from "../icons/CloseIcon";
// Тот же лимит, что ChatService.MAX_MESSAGE_LENGTH на бэкенде // Тот же лимит, что ChatService.MAX_MESSAGE_LENGTH на бэкенде
@@ -14,9 +15,10 @@ function PaperclipIcon() {
} }
/** /**
* Поле ввода чата. С attach — кнопка-скрепка, превью выбранных фото над полем * Поле ввода чата. С attach — кнопка-скрепка, превью выбранных фото или видео
* и вставка картинок из буфера обмена. attach: { images, addFiles, removeImage, * над полем и вставка картинок из буфера обмена. attach: { images, addFiles,
* fileInputRef, compressing, error, disabled, label, removeLabel }. * removeImage, fileInputRef, compressing, error, disabled, label, removeLabel,
* accept, video, removeVideo, videoProgress }.
*/ */
export default function ChatInputBar({ export default function ChatInputBar({
input, input,
@@ -28,7 +30,9 @@ export default function ChatInputBar({
sending = false, sending = false,
}) { }) {
const images = attach?.images ?? []; 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) => { const handlePaste = (e) => {
if (!attach || attach.disabled) return; if (!attach || attach.disabled) return;
@@ -41,7 +45,7 @@ export default function ChatInputBar({
return ( return (
<div className="chat-input-area"> <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"> <div className="chat-attach-strip">
{images.map((img) => ( {images.map((img) => (
<div key={img.id} className={`chat-attach-thumb${sending ? " is-sending" : ""}`}> <div key={img.id} className={`chat-attach-thumb${sending ? " is-sending" : ""}`}>
@@ -55,6 +59,27 @@ export default function ChatInputBar({
)} )}
</div> </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 && ( {attach.compressing && (
<div className="chat-attach-thumb chat-attach-thumb--busy"><div className="f-spinner" /></div> <div className="chat-attach-thumb chat-attach-thumb--busy"><div className="f-spinner" /></div>
)} )}
@@ -73,7 +98,7 @@ export default function ChatInputBar({
<input <input
ref={attach.fileInputRef} ref={attach.fileInputRef}
type="file" type="file"
accept={ACCEPT} accept={attach.accept || ACCEPT}
multiple multiple
hidden hidden
data-testid="chat-attach-input" 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"]); expect(imgs.map((img) => img.getAttribute("src"))).toEqual(["https://minio/a.jpg", "https://minio/b.jpg"]);
fireEvent.click(screen.getAllByLabelText("Открыть фото")[1]); fireEvent.click(screen.getAllByLabelText("Открыть фото")[1]);
expect(onOpenPhoto).toHaveBeenCalledWith(message, 1); expect(onOpenPhoto).toHaveBeenCalledWith(PHOTOS, 1);
}); });
test("истёкшая ссылка на фото сообщает об ошибке для обновления", () => { 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 { useTranslation } from "react-i18next";
import { formatMessageTime } from "../../utils/chatDisplay"; 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) — сеткой над текстом; клик * Пузырь сообщения. Фото (message.attachments) — сеткой над текстом; клик
* открывает просмотр. width/height приходят с бэкенда: место под фото * открывает просмотр. Видео — плеером с обложкой. width/height приходят с
* резервируется сразу, и лента не прыгает, пока картинки грузятся. * бэкенда: место резервируется сразу, и лента не прыгает, пока файлы грузятся.
*/ */
export default function MessageBubble({ message, isMine, onOpenPhoto, onPhotoError }) { export default function MessageBubble({ message, isMine, onOpenPhoto, onPhotoError }) {
const { t, i18n } = useTranslation(); const { t, i18n } = useTranslation();
const time = formatMessageTime(message.createdAt, i18n.language); 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; const single = photos.length === 1;
return ( 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 && ( {photos.length > 0 && (
<div className={`chat-photos${single ? " chat-photos--single" : ""}`}> <div className={`chat-photos${single ? " chat-photos--single" : ""}`}>
{photos.map((photo, i) => ( {photos.map((photo, i) => (
@@ -24,7 +67,7 @@ export default function MessageBubble({ message, isMine, onOpenPhoto, onPhotoErr
style={single && photo.width && photo.height style={single && photo.width && photo.height
? { aspectRatio: `${photo.width} / ${photo.height}` } ? { aspectRatio: `${photo.width} / ${photo.height}` }
: undefined} : undefined}
onClick={() => onOpenPhoto?.(message, i)} onClick={() => onOpenPhoto?.(photos, i)}
aria-label={t("chat.openPhoto")} aria-label={t("chat.openPhoto")}
> >
<img <img

View File

@@ -119,20 +119,68 @@ export function useChats() {
return res.json(); return res.json();
}, []); }, []);
/** Свежая ссылка на фото, если выданная вместе с сообщением истекла. */ /** Свежие ссылки на вложение ({ url, posterUrl }), если выданные с сообщением истекли. */
const refreshAttachmentUrl = useCallback(async (chatId, attachmentId) => { const refreshAttachmentUrl = useCallback(async (chatId, attachmentId) => {
const res = await apiFetch(`${API_URL}/api/v1/chats/${chatId}/attachments/${attachmentId}/url`); const res = await apiFetch(`${API_URL}/api/v1/chats/${chatId}/attachments/${attachmentId}/url`);
if (!res.ok) throw new Error(`Error ${res.status}`); if (!res.ok) throw new Error(`Error ${res.status}`);
const { url } = await res.json(); return res.json();
return url; }, []);
/**
* Видео: 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 { return {
chats, loading, error, fetchChats, findChat, startChat, fetchMessages, markAsRead, 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 = "") { function chatWithUrl(otherUserId, postId, suffix = "") {
const url = new URL(`${API_URL}/api/v1/chats/with/${otherUserId}${suffix}`); const url = new URL(`${API_URL}/api/v1/chats/with/${otherUserId}${suffix}`);
if (postId) url.searchParams.set("postId", postId); 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")}`;
}

View File

@@ -221,6 +221,15 @@
"removePhoto": "Remove photo", "removePhoto": "Remove photo",
"openPhoto": "Open photo", "openPhoto": "Open photo",
"tooManyPhotos": "No more than {{max}} photos per message", "tooManyPhotos": "No more than {{max}} photos per message",
"videoPreview": "Video",
"attachMedia": "Attach photo or video",
"videoProcessing": "Processing video…",
"videoFailed": "Could not process the video",
"videoSendError": "Could not send the video",
"videoSeparately": "A video is sent as a separate message, without photos",
"videoBadType": "Unsupported video format (use MP4, MOV, WebM or 3GP)",
"videoTooLarge": "Video is larger than {{max}} MB",
"videoTooLong": "Video is longer than {{max}} seconds",
"postInfo": "Listing for this chat", "postInfo": "Listing for this chat",
"postRemoved": "Listing deleted", "postRemoved": "Listing deleted",
"postClosed": "Closed", "postClosed": "Closed",

View File

@@ -221,6 +221,15 @@
"removePhoto": "Убрать фото", "removePhoto": "Убрать фото",
"openPhoto": "Открыть фото", "openPhoto": "Открыть фото",
"tooManyPhotos": "Не больше {{max}} фото в одном сообщении", "tooManyPhotos": "Не больше {{max}} фото в одном сообщении",
"videoPreview": "Видео",
"attachMedia": "Прикрепить фото или видео",
"videoProcessing": "Видео обрабатывается…",
"videoFailed": "Не удалось обработать видео",
"videoSendError": "Не удалось отправить видео",
"videoSeparately": "Видео отправляется отдельным сообщением, без фото",
"videoBadType": "Этот формат видео не поддерживается (нужен MP4, MOV, WebM или 3GP)",
"videoTooLarge": "Видео больше {{max}} МБ",
"videoTooLong": "Видео длиннее {{max}} секунд",
"postInfo": "Объявление этого чата", "postInfo": "Объявление этого чата",
"postRemoved": "Объявление удалено", "postRemoved": "Объявление удалено",
"postClosed": "Закрыто", "postClosed": "Закрыто",

View File

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

View File

@@ -384,6 +384,50 @@ button.chat-header-post:hover .chat-header-title { text-decoration: underline; }
object-fit: cover; object-fit: cover;
} }
/* ── Видео в сообщениях ── */
.chat-video {
position: relative;
width: 100%;
max-height: 60vh;
border-radius: 14px;
overflow: hidden;
background: #000;
}
.chat-video + .chat-photos { margin-top: 3px; }
.chat-video video {
display: block;
width: 100%;
height: 100%;
object-fit: contain;
background: #000;
}
.chat-video-duration {
position: absolute;
top: 8px;
left: 8px;
padding: 2px 7px;
border-radius: 999px;
background: rgba(0, 0, 0, .6);
color: #fff;
font-size: .72rem;
pointer-events: none;
}
.chat-video--pending,
.chat-video--failed {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 10px;
background: var(--bg-input);
color: var(--muted);
font-size: .82rem;
text-align: center;
padding: 12px;
}
.chat-bubble.mine .chat-video--pending,
.chat-bubble.mine .chat-video--failed { background: rgba(255, 255, 255, .18); color: #fff; }
/* ── Выбор фото перед отправкой ── */ /* ── Выбор фото перед отправкой ── */
.chat-attach-btn { .chat-attach-btn {
flex-shrink: 0; flex-shrink: 0;
@@ -419,6 +463,30 @@ button.chat-header-post:hover .chat-header-title { text-decoration: underline; }
} }
.chat-attach-thumb img { width: 100%; height: 100%; object-fit: cover; display: block; } .chat-attach-thumb img { width: 100%; height: 100%; object-fit: cover; display: block; }
.chat-attach-thumb.is-sending { opacity: .5; } .chat-attach-thumb.is-sending { opacity: .5; }
.chat-attach-thumb--video { width: 96px; background: #000; }
.chat-attach-thumb video { width: 100%; height: 100%; object-fit: cover; display: block; }
.chat-attach-duration {
position: absolute;
left: 4px;
bottom: 4px;
padding: 1px 5px;
border-radius: 6px;
background: rgba(0, 0, 0, .6);
color: #fff;
font-size: .68rem;
}
.chat-attach-progress {
position: absolute;
inset: 0;
display: flex;
align-items: center;
justify-content: center;
background: rgba(0, 0, 0, .45);
color: #fff;
font-weight: 800;
font-size: .85rem;
}
.chat-attach-thumb--video.is-sending { opacity: 1; }
.chat-attach-thumb--busy { display: flex; align-items: center; justify-content: center; } .chat-attach-thumb--busy { display: flex; align-items: center; justify-content: center; }
.chat-attach-remove { .chat-attach-remove {
position: absolute; position: absolute;

View File

@@ -63,8 +63,10 @@ export function getChatDisplayInfo(chat, post, unreadMap, t) {
const imgSrc = getImageUrl(post?.images?.[0]); const imgSrc = getImageUrl(post?.images?.[0]);
const emoji = post?.emoji; const emoji = post?.emoji;
const unreadCount = unreadMap[chat.id] ?? chat.unreadCount ?? chat.unreadMessages ?? 0; const unreadCount = unreadMap[chat.id] ?? chat.unreadCount ?? chat.unreadMessages ?? 0;
// У сообщения только с фото текста нет — в превью пишем «Фото» // У сообщения только с фото или видео текста нет — в превью пишем «Фото»/«Видео»
const photoPreview = chat.lastMessageAttachments > 0 ? `📷 ${t('chat.photoPreview')}` : ""; const photoPreview = chat.lastMessageAttachments > 0
? (chat.lastMessageAttachmentKind === "VIDEO" ? `🎬 ${t('chat.videoPreview')}` : `📷 ${t('chat.photoPreview')}`)
: "";
const preview = getLastMessageText(chat) || photoPreview || t('chat.noMessages'); const preview = getLastMessageText(chat) || photoPreview || t('chat.noMessages');
return { title, imgSrc, emoji, unreadCount, preview }; return { title, imgSrc, emoji, unreadCount, preview };