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:
@@ -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);
|
||||
|
||||
Reference in New Issue
Block a user