Files
mtusi2026lab2/web/app.js
T

455 lines
13 KiB
JavaScript

const STORAGE_KEY = "relay.lab2.session";
const state = {
token: null,
expiresAt: null,
user: null,
chats: [],
activeChatId: null,
messages: [],
nextCursor: null,
pollTimer: null,
knownUsers: new Map(), // id -> {username, display_name}
};
const el = {
gate: document.getElementById("gate"),
shell: document.getElementById("shell"),
gateError: document.getElementById("gate-error"),
formLogin: document.getElementById("form-login"),
formRegister: document.getElementById("form-register"),
readyPill: document.getElementById("ready-pill"),
readyLabel: document.getElementById("ready-label"),
meDisplay: document.getElementById("me-display"),
meUsername: document.getElementById("me-username"),
meId: document.getElementById("me-id"),
meExpires: document.getElementById("me-expires"),
chatList: document.getElementById("chat-list"),
chatsEmpty: document.getElementById("chats-empty"),
stageEmpty: document.getElementById("stage-empty"),
stageChat: document.getElementById("stage-chat"),
chatTitle: document.getElementById("chat-title"),
chatMembers: document.getElementById("chat-members"),
messages: document.getElementById("messages"),
formMessage: document.getElementById("form-message"),
dialogChat: document.getElementById("dialog-chat"),
formChat: document.getElementById("form-chat"),
chatError: document.getElementById("chat-error"),
toast: document.getElementById("toast"),
};
function toast(text) {
el.toast.hidden = false;
el.toast.textContent = text;
clearTimeout(toast._t);
toast._t = setTimeout(() => {
el.toast.hidden = true;
}, 2400);
}
function saveSession() {
if (!state.token) {
sessionStorage.removeItem(STORAGE_KEY);
return;
}
sessionStorage.setItem(
STORAGE_KEY,
JSON.stringify({
token: state.token,
expiresAt: state.expiresAt,
user: state.user,
})
);
}
function loadSession() {
try {
const raw = sessionStorage.getItem(STORAGE_KEY);
if (!raw) return false;
const data = JSON.parse(raw);
state.token = data.token;
state.expiresAt = data.expiresAt;
state.user = data.user;
if (state.user?.id) rememberUser(state.user);
return Boolean(state.token);
} catch {
return false;
}
}
function rememberUser(user) {
if (!user?.id) return;
state.knownUsers.set(user.id, {
username: user.username,
display_name: user.display_name,
});
}
function labelUser(id) {
const u = state.knownUsers.get(id);
if (!u) return id.slice(0, 8);
return u.display_name || u.username || id.slice(0, 8);
}
async function api(path, options = {}) {
const headers = new Headers(options.headers || {});
if (options.json !== undefined) {
headers.set("Content-Type", "application/json");
}
if (state.token && options.auth !== false) {
headers.set("Authorization", `Bearer ${state.token}`);
}
const res = await fetch(path, {
method: options.method || "GET",
headers,
body: options.json !== undefined ? JSON.stringify(options.json) : options.body,
});
const text = await res.text();
let data = null;
if (text) {
try {
data = JSON.parse(text);
} catch {
data = { raw: text };
}
}
if (!res.ok) {
const err = new Error(data?.error?.message || `HTTP ${res.status}`);
err.status = res.status;
err.code = data?.error?.code;
err.payload = data;
throw err;
}
return { status: res.status, data, headers: res.headers };
}
function showGate() {
el.gate.classList.remove("hidden");
el.shell.classList.add("hidden");
stopPoll();
}
function showShell() {
el.gate.classList.add("hidden");
el.shell.classList.remove("hidden");
el.meDisplay.textContent = state.user?.display_name || "—";
el.meUsername.textContent = `@${state.user?.username || "—"}`;
el.meId.textContent = state.user?.id || "—";
el.meExpires.textContent = state.expiresAt
? new Date(state.expiresAt).toLocaleString()
: "—";
}
async function refreshReady() {
try {
const res = await fetch("/health/ready");
const ok = res.status === 200;
el.readyPill.classList.toggle("is-ok", ok);
el.readyPill.classList.toggle("is-bad", !ok);
el.readyLabel.textContent = ok ? "ready" : `not ready (${res.status})`;
} catch {
el.readyPill.classList.remove("is-ok");
el.readyPill.classList.add("is-bad");
el.readyLabel.textContent = "api down";
}
}
async function bootstrapAuth() {
if (!loadSession()) {
showGate();
return;
}
try {
const { data } = await api("/api/v1/users/me");
state.user = data;
rememberUser(data);
saveSession();
showShell();
await loadChats();
startPoll();
} catch (err) {
state.token = null;
state.user = null;
saveSession();
showGate();
if (err.status === 401) {
el.gateError.hidden = false;
el.gateError.textContent = "Сессия истекла или отозвана — войдите снова.";
}
}
}
async function loadChats() {
const { data } = await api("/api/v1/chats?limit=100");
state.chats = data.items || [];
renderChats();
if (state.activeChatId) {
const still = state.chats.find((c) => c.id === state.activeChatId);
if (!still) {
state.activeChatId = null;
showEmptyStage();
} else {
selectChat(state.activeChatId, { silent: true });
}
}
}
function renderChats() {
el.chatList.innerHTML = "";
el.chatsEmpty.classList.toggle("hidden", state.chats.length > 0);
for (const chat of state.chats) {
const li = document.createElement("li");
const btn = document.createElement("button");
btn.type = "button";
btn.className = chat.id === state.activeChatId ? "is-active" : "";
btn.innerHTML = `<span class="title"></span><span class="sub"></span>`;
btn.querySelector(".title").textContent = chat.title;
btn.querySelector(".sub").textContent = `${chat.member_ids?.length || 0} members · ${chat.id.slice(0, 8)}`;
btn.addEventListener("click", () => selectChat(chat.id));
li.appendChild(btn);
el.chatList.appendChild(li);
}
}
function showEmptyStage() {
el.stageEmpty.classList.remove("hidden");
el.stageChat.classList.add("hidden");
}
async function selectChat(chatId, { silent = false } = {}) {
state.activeChatId = chatId;
renderChats();
const chat = state.chats.find((c) => c.id === chatId);
if (!chat) {
showEmptyStage();
return;
}
el.stageEmpty.classList.add("hidden");
el.stageChat.classList.remove("hidden");
el.chatTitle.textContent = chat.title;
el.chatMembers.textContent = (chat.member_ids || [])
.map((id) => `${labelUser(id)} (${id.slice(0, 8)}…)`)
.join(" · ");
await loadMessages(chatId, { silent });
}
async function loadMessages(chatId, { silent = false } = {}) {
const { data } = await api(`/api/v1/chats/${chatId}/messages?limit=100`);
state.messages = data.items || [];
state.nextCursor = data.next_cursor;
// Догружаем следующие страницы, если история длинная (для демо обычно мало).
let guard = 0;
while (state.nextCursor && guard < 20) {
const page = await api(
`/api/v1/chats/${chatId}/messages?limit=100&cursor=${encodeURIComponent(state.nextCursor)}`
);
state.messages.push(...(page.data.items || []));
state.nextCursor = page.data.next_cursor;
guard += 1;
}
renderMessages();
if (!silent) {
el.messages.scrollTop = el.messages.scrollHeight;
} else {
const nearBottom =
el.messages.scrollHeight - el.messages.scrollTop - el.messages.clientHeight < 80;
if (nearBottom) el.messages.scrollTop = el.messages.scrollHeight;
}
}
function renderMessages() {
el.messages.innerHTML = "";
for (const msg of state.messages) {
const mine = msg.sender_id === state.user?.id;
const div = document.createElement("article");
div.className = `bubble ${mine ? "mine" : "theirs"}`;
div.innerHTML = `<p class="who"></p><p class="text"></p><p class="when"></p>`;
div.querySelector(".who").textContent = mine ? "вы" : labelUser(msg.sender_id);
div.querySelector(".text").textContent = msg.text;
div.querySelector(".when").textContent = new Date(msg.created_at).toLocaleString();
el.messages.appendChild(div);
}
}
function startPoll() {
stopPoll();
state.pollTimer = setInterval(async () => {
await refreshReady();
if (!state.token) return;
try {
await loadChats();
if (state.activeChatId) {
await loadMessages(state.activeChatId, { silent: true });
}
} catch (err) {
if (err.status === 401) {
state.token = null;
saveSession();
showGate();
el.gateError.hidden = false;
el.gateError.textContent = "Сессия больше недействительна (TTL / logout / Redis).";
}
}
}, 4000);
}
function stopPoll() {
if (state.pollTimer) clearInterval(state.pollTimer);
state.pollTimer = null;
}
// Tabs
document.querySelectorAll(".tab").forEach((tab) => {
tab.addEventListener("click", () => {
document.querySelectorAll(".tab").forEach((t) => {
t.classList.toggle("is-active", t === tab);
t.setAttribute("aria-selected", t === tab ? "true" : "false");
});
const which = tab.dataset.tab;
el.formLogin.classList.toggle("hidden", which !== "login");
el.formRegister.classList.toggle("hidden", which !== "register");
el.gateError.hidden = true;
});
});
el.formRegister.addEventListener("submit", async (e) => {
e.preventDefault();
el.gateError.hidden = true;
const fd = new FormData(el.formRegister);
try {
await api("/api/v1/users", {
method: "POST",
auth: false,
json: {
username: String(fd.get("username")).trim(),
display_name: String(fd.get("display_name")).trim(),
password: String(fd.get("password")),
},
});
toast("Пользователь создан — теперь войдите");
document.querySelector('.tab[data-tab="login"]').click();
el.formLogin.username.value = String(fd.get("username")).trim();
el.formLogin.password.value = String(fd.get("password"));
} catch (err) {
el.gateError.hidden = false;
el.gateError.textContent = err.message;
}
});
el.formLogin.addEventListener("submit", async (e) => {
e.preventDefault();
el.gateError.hidden = true;
const fd = new FormData(el.formLogin);
const username = String(fd.get("username")).trim();
const password = String(fd.get("password"));
const basic = btoa(unescape(encodeURIComponent(`${username}:${password}`)));
try {
const { data } = await api("/api/v1/auth/sessions", {
method: "POST",
auth: false,
headers: { Authorization: `Basic ${basic}` },
body: "",
});
state.token = data.token;
state.expiresAt = data.expires_at;
state.user = data.user;
rememberUser(data.user);
saveSession();
showShell();
await loadChats();
startPoll();
toast("Bearer-сессия выдана");
} catch (err) {
el.gateError.hidden = false;
el.gateError.textContent = err.status === 401 ? "Неверный логин или пароль" : err.message;
}
});
document.getElementById("btn-logout").addEventListener("click", async () => {
try {
await api("/api/v1/auth/sessions/current", { method: "DELETE" });
} catch {
/* сессия могла уже истечь */
}
state.token = null;
state.user = null;
state.chats = [];
state.activeChatId = null;
saveSession();
showGate();
toast("Сессия отозвана");
});
document.getElementById("btn-copy-id").addEventListener("click", async () => {
if (!state.user?.id) return;
await navigator.clipboard.writeText(state.user.id);
toast("user id скопирован");
});
document.getElementById("btn-new-chat").addEventListener("click", () => {
el.chatError.hidden = true;
el.formChat.reset();
el.dialogChat.showModal();
});
document.getElementById("btn-cancel-chat").addEventListener("click", () => {
el.dialogChat.close();
});
el.formChat.addEventListener("submit", async (e) => {
e.preventDefault();
el.chatError.hidden = true;
const fd = new FormData(el.formChat);
const title = String(fd.get("title")).trim();
const raw = String(fd.get("member_ids") || "");
const extra = raw
.split(/[\s,;]+/)
.map((s) => s.trim())
.filter(Boolean);
const member_ids = Array.from(new Set([state.user.id, ...extra]));
try {
const { data } = await api("/api/v1/chats", {
method: "POST",
json: { title, member_ids },
});
el.dialogChat.close();
await loadChats();
await selectChat(data.id);
toast("Чат создан");
} catch (err) {
el.chatError.hidden = false;
el.chatError.textContent = err.message;
}
});
el.formMessage.addEventListener("submit", async (e) => {
e.preventDefault();
if (!state.activeChatId) return;
const fd = new FormData(el.formMessage);
const text = String(fd.get("text"));
try {
await api(`/api/v1/chats/${state.activeChatId}/messages`, {
method: "POST",
json: { text },
});
el.formMessage.reset();
await loadMessages(state.activeChatId);
} catch (err) {
toast(err.message);
}
});
document.getElementById("btn-refresh").addEventListener("click", async () => {
try {
await loadChats();
if (state.activeChatId) await loadMessages(state.activeChatId);
toast("Обновлено");
} catch (err) {
toast(err.message);
}
});
refreshReady();
setInterval(refreshReady, 5000);
bootstrapAuth();