/* Open Maopaoya SPA */
const $ = (s) => document.querySelector(s);
const API = "/api";
let TOKEN = localStorage.token || "";
let ME = null;
let CUR = { sessionId: null, mode: "roleplay", characterId: null };
let GUIDE_STEP = 0;
async function api(path, opts = {}) {
const r = await fetch(API + path, {
...opts,
headers: { "Content-Type": "application/json", Authorization: "Bearer " + TOKEN,
...(opts.headers || {}) },
body: opts.body ? JSON.stringify(opts.body) : undefined,
});
if (!r.ok) throw new Error((await r.json().catch(() => ({}))).detail || r.status);
return r.json();
}
function toast(t) { const el = $("#toast"); el.textContent = t; el.classList.remove("hidden");
setTimeout(() => el.classList.add("hidden"), 2200); }
/* ---------- auth ---------- */
async function doLogin() {
try {
const d = await api("/auth/login", { method: "POST",
body: { username: $("#auth-user").value, password: $("#auth-pass").value } });
TOKEN = d.token; localStorage.token = TOKEN;
ME = { username: d.username, is_admin: d.is_admin };
enterApp();
} catch (e) { $("#auth-msg").textContent = e.message; }
}
async function doRegister() {
try {
const d = await api("/auth/register", { method: "POST",
body: { username: $("#auth-user").value, password: $("#auth-pass").value } });
TOKEN = d.token; localStorage.token = TOKEN;
ME = { username: d.username, is_admin: d.is_admin };
enterApp(); GUIDE_STEP = 0; openGuide();
} catch (e) { $("#auth-msg").textContent = e.message; }
}
function logout() { localStorage.removeItem("token"); location.reload(); }
async function enterApp() {
$("#auth-view").classList.add("hidden");
$("#app-view").classList.remove("hidden");
$("#whoami").textContent = ME.username;
if (!ME.is_admin) document.querySelectorAll(".admin-only").forEach(e => e.classList.add("hidden"));
await Promise.all([loadShelf(), loadCharacters(), loadNovels(), loadChannels()]);
if (ME.is_admin) loadAdmin();
}
/* ---------- 导航 ---------- */
document.querySelectorAll(".nav-btn[data-page]").forEach(b =>
b.onclick = () => {
document.querySelectorAll(".nav-btn[data-page]").forEach(x => x.classList.remove("active"));
b.classList.add("active");
document.querySelectorAll(".page").forEach(p => p.classList.add("hidden"));
$("#page-" + b.dataset.page).classList.remove("hidden");
});
/* ---------- 书架 / 会话 ---------- */
async function loadShelf() {
const d = await api("/sessions");
$("#shelf-list").innerHTML = d.sessions.filter(s => s.mode === "roleplay").map(s =>
`
`).join("")
|| '还没有会话,点右上角开一个。
';
}
async function newRoleplaySession() {
const chars = (await api("/characters")).characters;
openModal(`新对话
${chars.length ? "" : '还没有角色,先去「角色」页建一个。
'}`);
}
async function confirmRoleplay() {
const cid = +$("#pick-char").value;
const s = await api("/sessions", { method: "POST",
body: { mode: "roleplay", title: "与角色对话", character_id: cid } });
closeModal(); openChat(s.id, "roleplay", cid);
}
/* ---------- 角色 ---------- */
async function loadCharacters() {
const d = await api("/characters");
$("#chars-grid").innerHTML = d.characters.map(c =>
`
${c.avatar_url ? `

` : ""}
${esc(c.name)} ${c.source === "novel_auto" ? 'AI生成' : ""}
${esc(c.persona || "(无人设)")}
`).join("") || '还没有角色。
';
}
async function editCharacter(id) {
let c = { name: "", persona: "", greeting: "", voice: "tongtong", avatar_url: "" };
if (id) c = (await api("/characters")).characters.find(x => x.id === id);
openModal(`${id ? "编辑" : "新建"}角色
`);
}
async function saveCharacter(id) {
const body = { name: $("#c-name").value, persona: $("#c-persona").value,
greeting: $("#c-greeting").value, voice: $("#c-voice").value,
avatar_url: $("#c-avatar").value };
if (id) await api(`/characters/${id}`, { method: "PATCH", body });
else await api("/characters", { method: "POST", body });
closeModal(); loadCharacters(); toast("已保存");
}
async function delCharacter(id) {
if (!confirm("删除该角色及其记忆?")) return;
await api(`/characters/${id}`, { method: "DELETE" }); loadCharacters();
}
/* ---------- 小说 ---------- */
async function loadNovels() {
const d = await api("/sessions");
$("#novel-list").innerHTML = d.sessions.filter(s => s.mode === "novel").map(s =>
`
${esc(s.title)}
动态小说 · AI自主扩列
`).join("")
|| '还没有小说。
';
}
function newNovelSession() {
openModal(`开新小说
`);
}
async function confirmNovel() {
const s = await api("/sessions", { method: "POST", body: {
mode: "novel", title: $("#n-title").value || "未命名小说",
novel_setting: $("#n-setting").value } });
closeModal(); openChat(s.id, "novel");
}
/* ---------- 聊天 ---------- */
async function openChat(sid, mode, cid) {
CUR = { sessionId: sid, mode, characterId: cid };
$("#app-view").classList.add("hidden");
$("#chat-view").classList.remove("hidden");
const d = await api(`/sessions/${sid}/messages`);
$("#chat-log").innerHTML = d.messages.map(renderBubble).join("");
$("#chat-log").scrollTop = 1e9;
}
function backToShelf() {
$("#chat-view").classList.add("hidden");
$("#app-view").classList.remove("hidden");
loadShelf(); loadCharacters(); loadNovels();
}
function renderBubble(m) {
const cls = m.role === "user" ? "user" : "ai";
return `
${m.speaker ? `
${esc(m.speaker)}
` : ""}${esc(m.content)}
${m.role !== "user" ? `` : ""}
`;
}
async function sendMsg() {
const input = $("#chat-input");
const text = input.value.trim();
if (!text) return;
input.value = "";
$("#chat-log").insertAdjacentHTML("beforeend",
`${esc(text)}
`);
const thinking = document.createElement("div");
thinking.className = "bubble ai"; thinking.textContent = "…";
$("#chat-log").appendChild(thinking);
$("#chat-log").scrollTop = 1e9;
try {
const d = await api(`/sessions/${CUR.sessionId}/send`, { method: "POST", body: { content: text } });
thinking.innerHTML = renderBubble({ id: d.message_id, role: "assistant", content: d.reply });
d.new_characters.forEach(c => {
$("#chat-log").insertAdjacentHTML("beforeend",
`✨ 新角色入场:${esc(c.name)}(已自动建档${c.avatar_url ? " + 生成立绘" : ""})
`);
});
} catch (e) { thinking.textContent = "⚠️ " + e.message; }
$("#chat-log").scrollTop = 1e9;
}
async function editMsg(mid) {
const d = await api(`/sessions/${CUR.sessionId}/messages`);
const m = d.messages.find(x => x.id === mid);
const nv = prompt("编辑消息", m.content);
if (nv === null) return;
await api(`/messages/${mid}`, { method: "PATCH", body: { content: nv } });
openChat(CUR.sessionId, CUR.mode, CUR.characterId);
}
async function delMsg(mid) {
if (!confirm("删除这条消息?")) return;
await api(`/messages/${mid}`, { method: "DELETE" });
openChat(CUR.sessionId, CUR.mode, CUR.characterId);
}
async function ttsMsg(mid, btn) {
btn.textContent = "⏳";
try {
const r = await fetch(`${API}/sessions/${CUR.sessionId}/tts/${mid}`,
{ headers: { Authorization: "Bearer " + TOKEN } });
if (!r.ok) throw new Error(await r.text());
btn.textContent = "🔊";
new Audio(URL.createObjectURL(await r.blob())).play();
} catch (e) { btn.textContent = "🔊"; toast("TTS 失败:" + e.message); }
}
/* ---------- 抽屉:记忆 / 世界书 / 角色卡 ---------- */
async function openDrawer(kind) {
$("#drawer").classList.add("open");
$("#drawer-mask").classList.remove("hidden");
const body = $("#drawer-body");
if (kind === "memory") {
$("#drawer-title").textContent = "🧠 角色记忆(可篡改)";
if (!CUR.characterId) { body.innerHTML = '小说模式请在世界书里看角色。
'; return; }
const d = await api(`/characters/${CUR.characterId}/memories`);
body.innerHTML = d.memories.map(m =>
`${m.kind}${esc(m.content)}
`).join("")
|| '暂无记忆。聊天中重要事实会被自动记录,你也可以手动添加。
';
body.insertAdjacentHTML("beforeend", `
`);
} else if (kind === "worldbook") {
$("#drawer-title").textContent = "🌍 世界书";
const d = await api("/characters/worldbook/all");
const entries = d.entries.filter(e => e.scope === (CUR.mode === "novel" ? "novel" : "character"));
body.innerHTML = entries.map(w =>
`${w.constant ? "常驻" : esc(w.keywords || "关键词")}${esc(w.content)}
`).join("")
|| '暂无条目。动态小说中 AI 新建的角色会自动注册进来。
';
body.insertAdjacentHTML("beforeend",
``);
} else {
$("#drawer-title").textContent = "🎭 角色卡";
if (!CUR.characterId) { body.innerHTML = '小说模式暂无单角色卡。
'; return; }
const c = (await api("/characters")).characters.find(x => x.id === CUR.characterId);
body.innerHTML = `
`;
}
}
function closeDrawer() { $("#drawer").classList.remove("open");
$("#drawer-mask").classList.add("hidden"); }
async function addMemory(kind) {
const c = prompt("记忆内容");
if (!c) return;
await api(`/characters/${CUR.characterId}/memories`, { method: "POST", body: { kind, content: c } });
openDrawer("memory");
}
async function editMemory(mid) {
const d = await api(`/characters/${CUR.characterId}/memories`);
const m = d.memories.find(x => x.id === mid);
const c = prompt("修改记忆", m.content);
if (c === null) return;
await api(`/characters/${CUR.characterId}/memories/${mid}`, { method: "PATCH", body: { kind: m.kind, content: c } });
openDrawer("memory");
}
async function delMemory(mid) {
if (!confirm("删除该记忆?")) return;
await api(`/characters/${CUR.characterId}/memories/${mid}`, { method: "DELETE" });
openDrawer("memory");
}
async function editWb(wid) {
let w = { keywords: "", content: "", constant: false };
if (wid) w = (await api("/characters/worldbook/all")).entries.find(x => x.id === wid);
const scope = CUR.mode === "novel" ? "novel" : "character";
const kw = prompt("触发关键词(逗号分隔,留空=常驻)", w.keywords);
if (kw === null) return;
const ct = prompt("条目内容", w.content);
if (ct === null) return;
const body = { scope, scope_id: CUR.sessionId || 0, keywords: kw, content: ct, constant: !kw, enabled: true };
if (wid) await api(`/characters/worldbook/${wid}`, { method: "PATCH", body });
else await api("/characters/worldbook", { method: "POST", body });
openDrawer("worldbook");
}
async function delWb(wid) {
if (!confirm("删除条目?")) return;
await api(`/characters/worldbook/${wid}`, { method: "DELETE" });
openDrawer("worldbook");
}
/* ---------- 渠道 ---------- */
async function loadChannels() {
const d = await api("/channels");
$("#channel-list").innerHTML = d.channels.map(c =>
`${esc(c.name)} ${c.owner_id ? '私有' : '全局'}
${esc(c.base_url)}
叙事: ${esc((c.models || {}).narrative || "-")}
`).join("")
|| '还没有渠道。添加一个 OpenAI 兼容 API 即可开聊。
';
}
async function editChannel(id) {
const preset = await api("/channels/preset");
let c = { name: preset.name, base_url: preset.base_url, models: preset.models, api_key: "" };
if (id) c = (await api("/channels")).channels.find(x => x.id === id);
openModal(`${id ? "编辑" : "添加"}渠道
`);
}
async function saveChannel(id) {
const body = { name: $("#ch-name").value, base_url: $("#ch-url").value,
api_key: $("#ch-key").value,
models: { narrative: $("#ch-nar").value, extract: $("#ch-nar").value,
tts: $("#ch-tts").value, image: $("#ch-img").value } };
if (id) await api(`/channels/${id}`, { method: "PATCH", body });
else await api("/channels", { method: "POST", body });
closeModal(); loadChannels(); toast("渠道已保存");
}
async function testChannel(id, btn) {
btn.textContent = "⏳";
try { const d = await api(`/channels/${id}/test`, { method: "POST" });
btn.textContent = d.ok ? "✅" : "❌"; toast(d.ok ? "渠道正常:" + d.model : "失败:" + d.message);
} catch (e) { btn.textContent = "❌"; toast(e.message); }
setTimeout(() => btn.textContent = "测试", 3000);
}
async function delChannel(id) {
if (!confirm("删除渠道?")) return;
await api(`/channels/${id}`, { method: "DELETE" }); loadChannels();
}
/* ---------- 后台 ---------- */
async function loadAdmin() {
const s = await api("/admin/settings");
const labels = { allow_register: "允许注册", allow_delete_account: "允许注销",
allow_byok: "允许用户自定义 API 渠道", admin_data_visible: "数据可见(关闭=加密存储,管理员不可读,静默生效)" };
$("#toggles").innerHTML = Object.entries(labels).map(([k, label]) =>
`${label}
`).join("");
const u = await api("/admin/users");
$("#admin-stats").textContent = `用户 ${u.stats.users} · 会话 ${u.stats.sessions}`;
$("#admin-users").innerHTML = u.users.map(x =>
`${esc(x.username)} ${x.is_admin ? '
管理员' : ""}
${x.is_active ? "" : '
已封禁'}
`).join("");
}
async function toggleSetting(key, btn) {
const cur = btn.textContent === "开";
await api(`/admin/settings?key=${key}&value=${!cur}`, { method: "POST" });
loadAdmin();
if (key === "admin_data_visible") toast(!cur ? "已改为明文(用户下次登录时解密存量数据)" : "已改为加密(管理员不可读)");
}
async function adminPatch(id, body) {
await api(`/admin/users/${id}`, { method: "PATCH", body }); loadAdmin();
}
async function adminResetPwd(id) {
const p = prompt("新密码"); if (!p) return;
await api(`/admin/users/${id}`, { method: "PATCH", body: { new_password: p } });
toast("已重置");
}
/* ---------- 引导 ---------- */
function openGuide() { $("#guide").classList.remove("hidden"); renderGuide(); }
function closeGuide() { $("#guide").classList.add("hidden"); }
async function renderGuide() {
const preset = await api("/channels/preset");
const bodies = [
`第 1 步 · 填 Key
已预填 Step Plan 预设(${preset.base_url}),你只需要粘贴 API Key。
`,
`第 2 步 · 确认模型
默认:叙事/抽取 ${preset.models.narrative},TTS ${preset.models.tts}。直接下一步就行。
`,
`第 3 步 · 开聊!
去书架开一个角色对话,或去小说页开一本 AI 自主扩列的动态小说。
`];
$("#guide-body").innerHTML = bodies[GUIDE_STEP];
}
async function guideNext() {
if (GUIDE_STEP === 0) {
const key = $("#g-key") ? $("#g-key").value : "";
if (key) { await api("/channels", { method: "POST", body: {
name: "Step Plan", base_url: (await api("/channels/preset")).base_url,
api_key: key, models: (await api("/channels/preset")).models } }); }
GUIDE_STEP = 1;
} else if (GUIDE_STEP === 2) { closeGuide(); return; }
else GUIDE_STEP++;
renderGuide(); if (GUIDE_STEP === 1) renderGuide();
loadChannels();
}
/* ---------- 通用 ---------- */
function openModal(html) { $("#modal").innerHTML = html; $("#modal").classList.remove("hidden");
$("#modal-mask").classList.remove("hidden"); }
function closeModal() { $("#modal").classList.add("hidden");
$("#modal-mask").classList.add("hidden"); }
function esc(s) { return String(s || "").replace(/[&<>"']/g, c =>
({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c])); }
(async () => {
if (!TOKEN) return;
try { ME = await api("/auth/me"); enterApp(); }
catch (e) { localStorage.removeItem("token"); }
})();