Files
nahodka-front/src/hooks/useChats.js
SlimusMinus b94ef2918c 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>
2026-10-28 23:00:18 +03:00

211 lines
9.6 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { useState, useCallback, useRef } from "react";
import { useTranslation } from 'react-i18next';
import { API_URL } from "../config/authConstants";
import { apiFetch } from "../api/apiClient";
import { readApiError } from "../api/apiErrors";
import { cachePostsFromChats, setPostForChat } from "../stores/chatPostStore";
import { useUnread } from "../context/UnreadContext";
export function useChats() {
const { t } = useTranslation();
const [chats, setChats] = useState([]);
// Стартуем в состоянии загрузки: иначе самый первый рендер успевает показать
// "Нет чатов" до того, как эффект выставит loading — список "моргает".
const [loading, setLoading] = useState(true);
const [error, setError] = useState("");
const { updateFromChats, clearChatUnread } = useUnread();
// fetchChats дёргается и при монтировании, и на каждое изменение totalUnread —
// без guard'а медленный предыдущий ответ воскрешал бы прочитанные счётчики.
const requestIdRef = useRef(0);
// silent=true — фоновое обновление списка (новое сообщение по WS, удаление
// чата и т.п.): не трогаем loading, иначе текущий список на миг подменяется
// экраном загрузки и страница "моргает".
const fetchChats = useCallback(async ({ silent = false } = {}) => {
const requestId = ++requestIdRef.current;
if (!silent) setLoading(true);
setError("");
try {
const res = await apiFetch(`${API_URL}/api/v1/chats`);
if (!res.ok) throw new Error(t('chats.fetchError'));
const data = await res.json();
if (requestId !== requestIdRef.current) return; // устаревший ответ
const list = Array.isArray(data) ? data : (data.items ?? data.content ?? []);
cachePostsFromChats(list);
setChats(list);
updateFromChats(list);
} catch (e) {
if (requestId !== requestIdRef.current) return;
setError(e.message || t('chats.fetchError'));
} finally {
if (requestId === requestIdRef.current && !silent) setLoading(false);
}
}, [updateFromChats, t]);
/**
* Существующий чат с пользователем по объявлению или null, если переписки ещё нет.
* Ничего не создаёт: чат появляется только вместе с первым сообщением (startChat).
*/
const findChat = useCallback(async (otherUserId, postId, postInfo) => {
const res = await apiFetch(chatWithUrl(otherUserId, postId));
if (res.status === 404) return null;
if (!res.ok) {
await logChatError("findChat", res);
throw new Error(t('chats.createError'));
}
const chat = await res.json();
cacheChatPost(chat, postInfo);
return chat;
}, [t]);
/** Отправляет первое сообщение: бэкенд создаёт (или находит) чат вместе с ним. */
const startChat = useCallback(async (otherUserId, postId, content, postInfo) => {
const res = await apiFetch(chatWithUrl(otherUserId, postId, "/messages"), {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ content }),
});
if (!res.ok) {
// ApiError несёт статус и текст сервера: ChatPage покажет «слишком
// много попыток» на 429 и причину отказа на 400
const err = await readApiError(res);
console.warn("startChat failed:", err.status, err.serverMessage);
throw err;
}
const chat = await res.json();
cacheChatPost(chat, postInfo);
return chat;
}, []);
const fetchMessages = useCallback(async (chatId) => {
const res = await apiFetch(`${API_URL}/api/v1/chats/${chatId}/messages`);
// Без этой проверки 5xx с JSON-телом ошибки превращался в пустой список,
// и только что отправленное сообщение выглядело как потерянное.
if (!res.ok) throw new Error(`Error ${res.status}`);
const data = await res.json();
return Array.isArray(data) ? data : (data.items ?? data.content ?? []);
}, []);
const markAsRead = useCallback(async (chatId) => {
clearChatUnread(chatId);
try {
await apiFetch(`${API_URL}/api/v1/chats/${chatId}/read`, {
method: "POST",
});
} catch (e) {
console.error("Failed to mark as read:", e);
}
}, [clearChatUnread]);
/**
* Сообщение с фото (и необязательным текстом) — через REST: файлы по
* WebSocket не передать. Возвращает сохранённое сообщение; собеседнику
* (и нам же) оно придёт и по сокету — дубль отсекается по id.
*/
const sendPhotoMessage = useCallback(async (chatId, content, files) => {
const data = new FormData();
if (content) data.append("content", content);
files.forEach((file) => data.append("files", file, file.name || "photo.jpg"));
const res = await apiFetch(`${API_URL}/api/v1/chats/${chatId}/messages`, {
method: "POST",
body: data,
});
if (!res.ok) {
const err = await readApiError(res);
console.warn("sendPhotoMessage failed:", err.status, err.serverMessage);
throw err;
}
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}`);
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, 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);
return url;
}
// Причину отказа (чат с собой, чужое объявление и т.п.) пишем в консоль,
// иначе 400 выглядит как необъяснимый сбой
async function logChatError(action, res) {
const body = await res.json().catch(() => null);
console.warn(`${action} failed:`, res.status, body?.message);
}
/**
* Объявление чата берём из ответа бэкенда: если чат оказался по другому
* объявлению, postInfo с карточки привязал бы к нему чужую картинку.
* postInfo — только дополнение (emoji) для того же объявления.
*/
function cacheChatPost(chat, postInfo) {
if (!chat?.id) return;
const sameAd = postInfo && (chat.post?.id ?? chat.postId) != null
&& String(chat.post?.id ?? chat.postId) === String(postInfo.id);
if (chat.post) {
setPostForChat(chat.id, { ...(sameAd ? postInfo : {}), ...chat.post });
} else if (sameAd) {
setPostForChat(chat.id, postInfo);
}
}