Files
2026-09-30 12:13:29 +03:00

397 lines
12 KiB
JavaScript
Raw Permalink 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 } from "react";
const API_BASE = "http://localhost:8080/api/v1";
function basicAuthorization(username, password) {
const encoded = btoa(
new TextEncoder()
.encode(`${username}:${password}`)
.reduce((value, byte) => value + String.fromCharCode(byte), "")
);
return `Basic ${encoded}`;
}
async function apiFetch(
path,
{
method = "GET",
token,
basicCredentials,
body,
} = {}
) {
const headers = {
Accept: "application/json",
};
if (body !== undefined) {
headers["Content-Type"] = "application/json";
}
if (token) {
headers.Authorization = `Bearer ${token}`;
}
if (basicCredentials) {
headers.Authorization = basicAuthorization(
basicCredentials.username,
basicCredentials.password
);
}
const response = await fetch(`${API_BASE}${path}`, {
method,
headers,
body: body !== undefined ? JSON.stringify(body) : undefined,
});
const requestId = response.headers.get("X-Request-Id");
const raw = await response.text();
const data = raw ? JSON.parse(raw) : null;
if (!response.ok) {
const message = data?.error?.message || `HTTP ${response.status}`;
throw new Error(`${message} (request_id: ${requestId || "unknown"})`);
}
return data;
}
export default function App() {
const [username, setUsername] = useState("");
const [displayName, setDisplayName] = useState("");
const [password, setPassword] = useState("");
const [session, setSession] = useState(null);
const [chat, setChat] = useState(null);
const [memberIdsInput, setMemberIdsInput] = useState("");
const [chatTitle, setChatTitle] = useState("");
const [text, setText] = useState("");
const [messages, setMessages] = useState([]);
const [error, setError] = useState("");
const [loading, setLoading] = useState(false);
const me = session?.user ?? null;
const token = session?.token ?? null;
async function handleRegister() {
setError("");
setLoading(true);
try {
await apiFetch("/users", {
method: "POST",
body: {
username,
display_name: displayName,
password,
},
});
const createdSession = await apiFetch("/auth/sessions", {
method: "POST",
basicCredentials: {
username,
password,
},
});
setSession(createdSession);
setPassword("");
} catch (requestError) {
setError(requestError.message);
} finally {
setLoading(false);
}
}
async function handleCreateChat() {
if (!me || !token) {
return;
}
setError("");
setLoading(true);
try {
const enteredMemberIds = memberIdsInput
.split(",")
.map((value) => value.trim())
.filter(Boolean);
const uniqueMemberIds = [...new Set([me.id, ...enteredMemberIds])];
const created = await apiFetch("/chats", {
method: "POST",
token,
body: {
title: chatTitle,
member_ids: uniqueMemberIds,
},
});
setChat(created);
setMessages([]);
setText("");
} catch (requestError) {
setError(requestError.message);
} finally {
setLoading(false);
}
}
async function handleSendMessage() {
if (!chat || !token) {
return;
}
setError("");
setLoading(true);
try {
const message = await apiFetch(`/chats/${chat.id}/messages`, {
method: "POST",
token,
body: { text },
});
setMessages((previous) => [...previous, message]);
setText("");
} catch (requestError) {
setError(requestError.message);
} finally {
setLoading(false);
}
}
async function handleLoadHistory() {
if (!chat || !token) {
return;
}
setError("");
setLoading(true);
try {
const page = await apiFetch(`/chats/${chat.id}/messages?limit=100`, {
token,
});
setMessages(page.items);
} catch (requestError) {
setError(requestError.message);
} finally {
setLoading(false);
}
}
async function handleLogout() {
if (!token) {
return;
}
setError("");
setLoading(true);
try {
await apiFetch("/auth/sessions/current", {
method: "DELETE",
token,
});
setSession(null);
setChat(null);
setMessages([]);
setText("");
setMemberIdsInput("");
setChatTitle("");
} catch (requestError) {
setError(requestError.message);
// Если token уже истёк или был отозван, локальная сессия всё равно
// недействительна, поэтому её следует очистить.
if (
requestError.message.includes("Authentication") ||
requestError.message.includes("401")
) {
setSession(null);
setChat(null);
setMessages([]);
}
} finally {
setLoading(false);
}
}
return (
<div
style={{
maxWidth: 560,
margin: "2rem auto",
fontFamily: "sans-serif",
}}
>
<h1>Lab2 Messenger — демо-клиент</h1>
{error && (
<p
role="alert"
style={{
color: "#b00020",
background: "#ffe7eb",
padding: "0.75rem",
borderRadius: "0.25rem",
}}
>
{error}
</p>
)}
{!me && (
<section>
<h2>Регистрация и вход</h2>
<p>
После регистрации клиент автоматически создаст сессию через Basic
authentication и начнёт использовать Bearer-token.
</p>
<input
placeholder="username: a-z, 0-9, _"
value={username}
onChange={(event) => setUsername(event.target.value)}
autoComplete="username"
/>
<input
placeholder="display name"
value={displayName}
onChange={(event) => setDisplayName(event.target.value)}
autoComplete="name"
/>
<input
type="password"
placeholder="пароль: 12–128 символов"
value={password}
onChange={(event) => setPassword(event.target.value)}
autoComplete="new-password"
/>
<button
type="button"
onClick={handleRegister}
disabled={loading}
>
{loading ? "Выполняется…" : "Зарегистрироваться и войти"}
</button>
</section>
)}
{me && !chat && (
<section>
<p>
Вошли как <b>{me.username}</b>
</p>
<p style={{ overflowWrap: "anywhere" }}>
ID пользователя: {me.id}
</p>
<button
type="button"
onClick={handleLogout}
disabled={loading}
>
Выйти
</button>
<h2>Создать чат</h2>
<input
placeholder="название чата"
value={chatTitle}
onChange={(event) => setChatTitle(event.target.value)}
/>
<input
placeholder="UUID других участников через запятую"
value={memberIdsInput}
onChange={(event) => setMemberIdsInput(event.target.value)}
/>
<button
type="button"
onClick={handleCreateChat}
disabled={loading}
>
{loading ? "Создаётся…" : "Создать чат"}
</button>
</section>
)}
{me && chat && (
<section>
<p>
Вошли как <b>{me.username}</b>
</p>
<button
type="button"
onClick={handleLogout}
disabled={loading}
>
Выйти
</button>
<h2>Чат: {chat.title}</h2>
<p>
Участники: {chat.member_ids.length}
</p>
<button
type="button"
onClick={handleLoadHistory}
disabled={loading}
>
{loading ? "Загружается…" : "Обновить историю"}
</button>
<ul>
{messages.map((message) => (
<li key={message.id}>
<b>
{message.sender_id === me.id
? "Я"
: message.sender_id}
:
</b>{" "}
{message.text}
</li>
))}
</ul>
<input
placeholder="текст сообщения"
value={text}
onChange={(event) => setText(event.target.value)}
/>
<button
type="button"
onClick={handleSendMessage}
disabled={loading}
>
{loading ? "Отправляется…" : "Отправить"}
</button>
</section>
)}
</div>
);
}