import { recordDefenseRequest, updateDefenseSession, updateDefenseHistory } from "/defense.js"; import { setMascotMood, celebrateMascots } from "/mascots.js"; import { configureScenarios, updateScenarioAccess } from "/scenarios.js"; const $ = id => document.getElementById(id); const storageKey = "linia.session"; const state = { session: null, chats: [], chatsCursor: null, current: null, messages: new Map(), serverIds: new Set(), members: new Map(), olderCursor: null, historyReady: false, epoch: 0, syncing: false, sending: false, drafts: new Map() }; let toastTimer; class ApiError extends Error { constructor(message, status = 0) { super(message); this.status = status; } } function notice(id, message, success = false) { const element = $(id); element.textContent = message; element.hidden = !message; element.classList.toggle("success", success); } function toast(message, error = false) { clearTimeout(toastTimer); $("toast").textContent = message; $("toast").classList.toggle("error", error); $("toast").hidden = false; toastTimer = setTimeout(() => { $("toast").hidden = true; }, error ? 6500 : 3000); } async function request(path, { method = "GET", body, headers = {}, auth = true, background = false } = {}) { const started = performance.now(); let httpStatus = null, requestId = null, outcome = "network"; const controller = new AbortController(); const timer = setTimeout(() => controller.abort(), 12000); // Authorization is explicit; disable the browser's implicit Basic-auth handling. const options = { method, headers: { Accept: "application/json", ...headers }, signal: controller.signal, cache: "no-store", credentials: "omit" }; if (auth && state.session) options.headers.Authorization = "Bearer " + state.session.token; if (body !== undefined) { options.body = JSON.stringify(body); options.headers["Content-Type"] = "application/json"; } try { const response = await fetch(path, options); httpStatus = response.status; requestId = response.headers.get("X-Request-Id"); outcome = "unreadable"; const data = response.status === 204 ? null : await response.json(); outcome = response.ok ? "success" : "http_error"; if (!response.ok) { if (response.status === 401 && auth) endSession("Сессия закончилась. Войдите снова."); throw new ApiError(data?.error?.message || "Не удалось выполнить запрос.", response.status); } return data; } catch (error) { if (error instanceof ApiError) throw error; throw new ApiError("Нет ответа от сервера. Проверьте соединение и попробуйте позже."); } finally { clearTimeout(timer); recordDefenseRequest({ method, path, status: httpStatus, requestId, outcome, background, durationMs: Math.round(performance.now() - started), authorization: options.headers.Authorization?.split(" ")[0] || "Без авторизации" }); } } function basic(username, password) { const bytes = new TextEncoder().encode(username + ":" + password); return "Basic " + btoa(Array.from(bytes, byte => String.fromCharCode(byte)).join("")); } function selectAuthTab(register) { $("register-panel").hidden = !register; $("login-panel").hidden = register; $("tab-register").classList.toggle("active", register); $("tab-login").classList.toggle("active", !register); $("tab-register").setAttribute("aria-pressed", String(register)); $("tab-login").setAttribute("aria-pressed", String(!register)); notice("auth-notice", ""); } function setFormBusy(form, busy) { form.querySelectorAll("input, textarea, button").forEach(element => { element.disabled = busy; }); } function persistSession(session) { try { sessionStorage.setItem(storageKey, JSON.stringify(session)); } catch { /* session still works in memory */ } } async function enterSession(session) { state.epoch++; state.session = session; updateScenarioAccess(); updateDefenseSession({ name: session.user.display_name, expiresAt: session.expires_at }); updateDefenseHistory(null); state.current = null; state.messages.clear(); state.serverIds.clear(); state.chats = []; state.chatsCursor = null; state.drafts.clear(); state.syncing = false; state.sending = false; persistSession(session); $("auth-screen").hidden = true; $("app-screen").hidden = false; $("app-screen").classList.remove("chat-open"); $("welcome").hidden = false; $("conversation").hidden = true; $("profile-name").textContent = session.user.display_name; $("profile-username").textContent = "@" + session.user.username; $("profile-avatar").textContent = initials(session.user.display_name); $("chat-search").value = ""; renderChats(); try { await loadChats(false, true); } catch (error) { toast(error.message, true); } } function endSession(message = "") { state.epoch++; state.session = null; updateScenarioAccess(); updateDefenseSession(null); updateDefenseHistory(null); state.current = null; state.chats = []; state.messages.clear(); state.serverIds.clear(); state.drafts.clear(); try { sessionStorage.removeItem(storageKey); } catch { /* storage unavailable */ } document.querySelectorAll("dialog[open]").forEach(dialog => dialog.close()); $("message-list").replaceChildren(); $("chat-list").replaceChildren(); $("message-input").value = ""; $("app-screen").hidden = true; $("auth-screen").hidden = false; $("login-password").value = ""; selectAuthTab(false); notice("auth-notice", message); } $("tab-login").addEventListener("click", () => selectAuthTab(false)); $("tab-register").addEventListener("click", () => selectAuthTab(true)); $("login-form").addEventListener("submit", async event => { event.preventDefault(); const form = event.currentTarget; const username = $("login-username").value.trim(); const password = $("login-password").value; setFormBusy(form, true); setMascotMood("pending"); notice("auth-notice", ""); try { const session = await request("/api/v1/auth/sessions", { method: "POST", auth: false, headers: { Authorization: basic(username, password) } }); form.reset(); await celebrateMascots(); await enterSession(session); } catch (error) { setMascotMood("error"); notice("auth-notice", error.status === 401 ? "Неверный логин или пароль." : error.message); } finally { setFormBusy(form, false); } }); $("register-form").addEventListener("submit", async event => { event.preventDefault(); const form = event.currentTarget; const username = $("register-username").value.trim(); const displayName = $("register-name").value.trim(); const password = $("register-password").value; if (Array.from(displayName).length > 100) return notice("auth-notice", "Имя должно содержать от 1 до 100 символов."); if (Array.from(password).length < 12 || Array.from(password).length > 128 || !password.trim()) { setMascotMood("short"); return notice("auth-notice", "Пароль должен содержать от 12 до 128 символов."); } setFormBusy(form, true); setMascotMood("pending"); notice("auth-notice", ""); let registered = false; try { await request("/api/v1/users", { method: "POST", auth: false, body: { username, display_name: displayName, password } }); registered = true; const session = await request("/api/v1/auth/sessions", { method: "POST", auth: false, headers: { Authorization: basic(username, password) } }); form.reset(); await celebrateMascots(); await enterSession(session); toast("Добро пожаловать, " + session.user.display_name + "!"); } catch (error) { setMascotMood("error"); if (registered) { form.reset(); selectAuthTab(false); $("login-username").value = username; notice("auth-notice", "Аккаунт создан. Войдите, когда сервер будет доступен."); } else notice("auth-notice", error.status === 409 ? "Это имя пользователя уже занято. Выберите другое." : error.message); } finally { setFormBusy(form, false); } }); function initials(value) { return (value.match(/[\p{L}\p{N}]+/gu) || []).slice(0, 2).map(part => Array.from(part)[0]).join("").toUpperCase(); } function memberCount(count) { const n = count % 100, d = count % 10; return count + " " + (n >= 11 && n <= 14 ? "участников" : d === 1 ? "участник" : d >= 2 && d <= 4 ? "участника" : "участников"); } function avatarTone(id) { return "tone-" + (parseInt(id.slice(0, 4), 16) % 4); } async function loadChats(more = false, background = false) { const token = state.session?.token; const cursor = more ? state.chatsCursor : null; const data = await request("/api/v1/chats?limit=100" + (cursor ? "&cursor=" + encodeURIComponent(cursor) : ""), { background }); if (token !== state.session?.token) return; state.chats = more ? [...state.chats, ...data.items.filter(chat => !state.chats.some(existing => existing.id === chat.id))] : data.items; state.chatsCursor = data.next_cursor; renderChats(); } function renderChats() { const query = $("chat-search").value.trim().toLocaleLowerCase("ru-RU"); const chats = [...state.chats].sort((a, b) => b.created_at.localeCompare(a.created_at) || b.id.localeCompare(a.id)) .filter(chat => chat.title.toLocaleLowerCase("ru-RU").includes(query)); $("chat-count").textContent = state.chats.length || ""; $("more-chats").hidden = !state.chatsCursor; const nodes = chats.map(chat => { const button = document.createElement("button"); button.className = "chat-row" + (chat.id === state.current?.id ? " active" : ""); button.setAttribute("aria-pressed", String(chat.id === state.current?.id)); const avatar = document.createElement("span"); avatar.className = "avatar " + avatarTone(chat.id); avatar.textContent = initials(chat.title); const description = document.createElement("span"); description.className = "chat-row-text"; const title = document.createElement("strong"); title.textContent = chat.title; const members = document.createElement("small"); members.textContent = memberCount(chat.member_ids.length); description.append(title, members); button.append(avatar, description); button.addEventListener("click", () => selectChat(chat)); return button; }); if (!nodes.length) { const empty = document.createElement("p"); empty.className = "list-empty"; empty.textContent = query ? "Чаты не найдены." : "Пока нет чатов."; nodes.push(empty); } $("chat-list").replaceChildren(...nodes); } $("chat-search").addEventListener("input", renderChats); $("refresh-chats").addEventListener("click", async () => { try { await loadChats(); } catch (error) { toast(error.message, true); } }); $("more-chats").addEventListener("click", async () => { try { await loadChats(true); } catch (error) { toast(error.message, true); } }); async function selectChat(chat) { if (state.current?.id === chat.id) { $("app-screen").classList.add("chat-open"); return; } if (state.current) state.drafts.set(state.current.id, $("message-input").value); state.epoch++; state.current = chat; state.members = new Map([[state.session.user.id, state.session.user]]); renderChats(); state.messages = new Map(); state.serverIds = new Set(); state.olderCursor = null; state.historyReady = false; updateDefenseHistory({ title: chat.title, loaded: 0, hasOlder: false, ready: false }); state.syncing = false; $("current-title").textContent = chat.title; $("current-members").textContent = memberCount(chat.member_ids.length); $("current-avatar").textContent = initials(chat.title); $("current-avatar").className = "avatar chat-avatar " + avatarTone(chat.id); $("welcome").hidden = true; $("conversation").hidden = false; $("app-screen").classList.add("chat-open"); $("message-input").value = state.drafts.get(chat.id) || ""; updateComposer(); $("message-list").replaceChildren(); $("empty-conversation").hidden = true; $("older-messages").hidden = true; try { await Promise.all([syncRecent(true), loadMembers(state.epoch, chat.id)]); } catch (error) { toast(error.message, true); } } async function loadMembers(epoch, chatId) { const data = await request(`/api/ui/chats/${chatId}/members`, { background: true }); if (epoch !== state.epoch) return; state.members = new Map(data.items.map(user => [user.id, user])); renderMessages(); } async function syncRecent(initial = false, background = false) { if (!state.current || !state.session || state.syncing) return; const epoch = state.epoch, chatId = state.current.id; state.syncing = true; try { const page = await request(`/api/ui/chats/${chatId}/messages?limit=50`, { background }); if (epoch !== state.epoch) return; state.historyReady = true; const overlap = page.items.some(item => state.serverIds.has(item.id)); // On a large burst, the older button pages through the newly discovered gap. if (initial || (!overlap && page.items.length === 50)) state.olderCursor = page.next_cursor; page.items.forEach(item => { state.messages.set(item.id, item); state.serverIds.add(item.id); }); renderMessages(initial ? "bottom" : "preserve"); } finally { if (epoch === state.epoch) state.syncing = false; } } $("older-messages").addEventListener("click", async () => { if (!state.olderCursor || !state.current) return; const epoch = state.epoch; $("older-messages").disabled = true; try { const page = await request(`/api/ui/chats/${state.current.id}/messages?limit=50&cursor=${encodeURIComponent(state.olderCursor)}`); if (epoch !== state.epoch) return; page.items.forEach(item => { state.messages.set(item.id, item); state.serverIds.add(item.id); }); state.olderCursor = page.next_cursor; renderMessages("prepend"); } catch (error) { toast(error.message, true); } finally { $("older-messages").disabled = false; } }); function renderMessages(mode = "preserve") { const scroll = $("message-scroll"), oldHeight = scroll.scrollHeight, oldTop = scroll.scrollTop; const atBottom = oldHeight - oldTop - scroll.clientHeight < 85; const messages = [...state.messages.values()].sort((a, b) => a.created_at.localeCompare(b.created_at) || a.id.localeCompare(b.id)); const nodes = []; let previousDay = ""; for (const message of messages) { const date = new Date(message.created_at); const day = date.toLocaleDateString("ru-RU", { day: "numeric", month: "long", year: "numeric" }); if (day !== previousDay) { const divider = document.createElement("div"); divider.className = "date-separator"; divider.textContent = day; nodes.push(divider); previousDay = day; } const mine = message.sender_id === state.session?.user.id; const article = document.createElement("article"); article.className = "message" + (mine ? " mine" : ""); if (!mine) { const author = document.createElement("span"); author.className = "message-author"; author.textContent = state.members.get(message.sender_id)?.display_name || "Участник " + message.sender_id.slice(0, 8); author.title = message.sender_id; article.append(author); } const bubble = document.createElement("div"); bubble.className = "message-bubble"; const text = document.createElement("p"); text.className = "message-text"; text.textContent = message.text; const stamp = document.createElement("time"); stamp.className = "message-time"; stamp.dateTime = message.created_at; stamp.textContent = date.toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit" }); bubble.append(text, stamp); article.append(bubble); nodes.push(article); } $("message-list").replaceChildren(...nodes); $("empty-conversation").hidden = messages.length !== 0; $("older-messages").hidden = !state.olderCursor; updateDefenseHistory({ title: state.current?.title, loaded: messages.length, hasOlder: Boolean(state.olderCursor), ready: state.historyReady }); if (mode === "bottom" || (mode === "preserve" && atBottom)) scroll.scrollTop = scroll.scrollHeight; else if (mode === "prepend") scroll.scrollTop = oldTop + scroll.scrollHeight - oldHeight; else scroll.scrollTop = oldTop; } function updateComposer() { const text = $("message-input").value, count = Array.from(text).length; $("message-count").textContent = `${count} / 4000`; $("message-count").classList.toggle("over-limit", count > 4000); $("send-message").disabled = state.sending || !text.trim() || count > 4000; $("message-input").style.height = "auto"; const height = $("message-input").scrollHeight + 2; $("message-input").style.height = Math.min(140, height) + "px"; $("message-input").style.overflowY = height > 140 ? "auto" : "hidden"; if (state.current) state.drafts.set(state.current.id, text); } $("message-input").addEventListener("input", updateComposer); $("message-input").addEventListener("keydown", event => { if (event.key === "Enter" && !event.shiftKey && !event.isComposing) { event.preventDefault(); if (!$("send-message").disabled) $("message-form").requestSubmit(); } }); $("message-form").addEventListener("submit", async event => { event.preventDefault(); if (state.sending || !state.current || $("send-message").disabled) return; const epoch = state.epoch, chatId = state.current.id, text = $("message-input").value; state.sending = true; updateComposer(); try { const message = await request(`/api/v1/chats/${chatId}/messages`, { method: "POST", body: { text } }); if (epoch !== state.epoch) return; state.messages.set(message.id, message); if ($("message-input").value === text) $("message-input").value = ""; renderMessages("bottom"); await syncRecent(false, true); } catch (error) { toast(error.status === 0 ? "Отправка не подтверждена. Обновите чат перед повторной отправкой." : error.message, true); } finally { state.sending = false; updateComposer(); } }); function openNewChat() { $("new-chat-form").reset(); notice("chat-dialog-notice", ""); $("new-chat-dialog").showModal(); $("new-chat-title").focus(); } $("new-chat").addEventListener("click", openNewChat); $("welcome-new-chat").addEventListener("click", openNewChat); document.querySelectorAll("[data-close-dialog]").forEach(button => button.addEventListener("click", () => button.closest("dialog").close())); $("new-chat-form").addEventListener("submit", async event => { event.preventDefault(); const form = event.currentTarget, token = state.session?.token; const title = $("new-chat-title").value.trim(); if (!title || Array.from(title).length > 100) return notice("chat-dialog-notice", "Название должно содержать от 1 до 100 символов."); const ids = $("new-chat-members").value.split(/[\s,;]+/u).filter(Boolean); if (ids.some(id => !/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(id))) return notice("chat-dialog-notice", "Проверьте ID участников: нужен полный ID из профиля."); const members = [...new Set([state.session.user.id, ...ids.map(id => id.toLowerCase())])]; if (members.length > 100) return notice("chat-dialog-notice", "В чате может быть не более 100 участников."); setFormBusy(form, true); notice("chat-dialog-notice", ""); try { const chat = await request("/api/v1/chats", { method: "POST", body: { title, member_ids: members } }); if (token !== state.session?.token) return; $("new-chat-dialog").close(); state.chats.push(chat); renderChats(); await selectChat(chat); toast("Чат создан."); } catch (error) { notice("chat-dialog-notice", error.message); } finally { setFormBusy(form, false); } }); $("open-profile").addEventListener("click", () => { $("profile-details").textContent = state.session.user.display_name + " · @" + state.session.user.username; $("my-id").value = state.session.user.id; $("profile-dialog").showModal(); }); $("copy-id").addEventListener("click", async () => { try { await navigator.clipboard.writeText(state.session.user.id); toast("ID скопирован."); } catch { $("my-id").select(); toast("Выделили ID. Скопируйте его сочетанием ⌘C или Ctrl+C."); } }); $("show-members").addEventListener("click", () => { $("members-list").replaceChildren(...state.current.member_ids.map(id => { const item = document.createElement("div"); item.className = "member-item"; const label = document.createElement("strong"); label.textContent = (state.members.get(id)?.display_name || "Участник") + (id === state.session.user.id ? " (вы)" : ""); const code = document.createElement("code"); code.textContent = id; item.append(label, code); return item; })); $("members-dialog").showModal(); }); $("logout").addEventListener("click", async () => { $("logout").disabled = true; try { await request("/api/v1/auth/sessions/current", { method: "DELETE" }); endSession(); } catch (error) { if (error.status !== 401) toast(error.message, true); } finally { $("logout").disabled = false; } }); $("back-to-chats").addEventListener("click", () => $("app-screen").classList.remove("chat-open")); $("refresh-messages").addEventListener("click", async () => { try { await syncRecent(); } catch (error) { toast(error.message, true); } }); setInterval(async () => { if (!state.session || document.hidden) return; if (new Date(state.session.expires_at).getTime() <= Date.now()) return endSession("Сессия закончилась. Войдите снова."); if (state.current) { try { await syncRecent(false, true); } catch { /* manual actions still show errors */ } } }, 4000); async function resume() { try { const stored = sessionStorage.getItem(storageKey); if (!stored) return; const session = JSON.parse(stored); if (!session?.token || !session.user || !(new Date(session.expires_at).getTime() > Date.now())) return endSession(); state.session = session; const user = await request("/api/v1/users/me"); await enterSession({ ...session, user }); } catch (error) { state.session = null; if (error instanceof ApiError) notice("auth-notice", error.message); else { try { sessionStorage.removeItem(storageKey); } catch { /* storage unavailable */ } } } } configureScenarios({ getActor: () => state.session ? { id: state.session.user.id, token: state.session.token } : null, openChat: async (chat, owner) => { await loadChats(false, true); if (state.session?.token !== owner.token) throw new Error("Основной вход изменился. Откройте демочат из списка после входа."); await selectChat(chat); } }); void resume();