/* 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();
}
/* ---------- 导航 ---------- */
const PAGE_LOADERS = {
shelf: () => { loadShelf(); },
chars: () => loadCharacters(),
novel: () => loadNovels(),
moments: () => loadMoments(),
plaza: () => loadPlaza(),
channels: () => loadChannels(),
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");
(PAGE_LOADERS[b.dataset.page] || (() => {}))();
});
/* ---------- 书架 / 会话 ---------- */
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";
const sw = m.swipe_count || 0;
return `
${m.speaker ? `
${esc(m.speaker)}
` : ""}${esc(m.content)}
${sw > 1 ? `
${(m.active_swipe ?? 0) + 1}/${sw}
` : ""}
${m.role !== "user" ? `
` : ""}
`;
}
async function swipeMsg(mid, dir) {
await api(`/messages/${mid}/swipe`, { method: "POST", body: { delta: dir } });
refreshChat();
}
async function regenMsg(mid) {
await api(`/messages/${mid}/regenerate`, { method: "POST" });
refreshChat(); toast("已生成新版本,‹ › 切换");
}
async function starMsg(mid) {
await api(`/messages/${mid}/star`, { method: "POST" }); refreshChat();
}
function refreshChat() { openChat(CUR.sessionId, CUR.mode, CUR.characterId); }
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 url = CUR.mode === "group" ? `/sessions/${CUR.sessionId}/send_group` : `/sessions/${CUR.sessionId}/send`;
const d = await api(url, { 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 editPassword() {
openModal(`修改密码
加密数据将自动用旧密码解密、新密码重加密,历史记录无损。
`);
}
async function savePassword() {
try {
await api("/auth/change_password", { method: "POST", body: {
old_password: $("#pw-old").value, new_password: $("#pw-new").value } });
closeModal(); toast("密码已修改,加密数据已重加密");
} catch (e) { toast(e.message); }
}
/* ---------- 后台:渠道分配 ---------- */
async function adminGrantChannel() {
const chans = (await api("/channels")).channels; // 管理员可见全部
const users = (await api("/admin/users")).users;
openModal(`渠道分配
`);
const c = +$("#gr-chan").value;
const g = await api(`/channels/${c}/grants`);
$("#gr-list").innerHTML = g.user_ids.length
? "已授权用户: " + g.user_ids.map(uid => {
const u = users.find(x => x.id === uid);
return `${esc(u ? u.username : uid)}
`;
}).join(" ")
: '该渠道尚未授权给任何用户。
';
}
async function doGrant() {
await api(`/admin/channels/${$("#gr-chan").value}/grant/${$("#gr-user").value}`, { method: "POST" });
adminGrantChannel(); toast("已授权");
}
async function revokeGrant(cid, uid) {
await api(`/admin/channels/${cid}/grant/${uid}`, { method: "DELETE" });
adminGrantChannel();
}
/* ================= 扩展功能 ================= */
/* ---------- 群聊 ---------- */
async function newGroup() {
const chars = (await api("/characters")).characters;
if (chars.length < 2) { toast("先建至少两个角色"); return; }
openModal(`新建群聊
${chars.map(c => ``).join("")}
`);
}
async function saveGroup() {
const ids = [...document.querySelectorAll(".gr-c:checked")].map(x => +x.value);
if (ids.length < 2) { toast("至少选两个角色"); return; }
try {
const s = await api("/groups", { method: "POST", body: {
title: $("#gr-title").value || "群聊", character_ids: ids } });
closeModal(); toast("群已开,艾特谁谁说话"); openChat(s.id, "group");
} catch (e) { toast(e.message); }
}
/* ---------- 朋友圈 ---------- */
async function loadMoments() {
const d = await api("/moments");
$("#moment-feed").innerHTML = d.moments.length ? d.moments.map(m => `
${esc(m.author)}${(m.created_at || "").slice(0, 16)}
${esc(m.content)}
${m.image_url ? `

` : ""}
${(m.comments || []).map(c => `
💬 ${esc(c.author)}: ${esc(c.content)}
`).join("")}
`).join("") : '还没有动态。点右上角让角色发一条。
';
}
async function pickMomentChar() {
const chars = (await api("/characters")).characters;
openModal(`谁发动态?
`);
}
async function genMoment() {
try {
await api("/moments/generate", { method: "POST", body: {
character_id: +$("#mc-cid").value, topic: $("#mc-topic").value } });
closeModal(); loadMoments(); toast("动态已生成");
} catch (e) { toast(e.message); }
}
async function likeMoment(id) {
await api(`/moments/${id}/like`, { method: "POST" }); loadMoments();
}
function commentMoment(id) {
openModal(`评论
`);
}
async function sendComment(id) {
await api(`/moments/${id}/comment`, { method: "POST", body: { content: $("#cm-text").value } });
closeModal(); loadMoments();
}
/* ---------- 广场 ---------- */
async function loadPlaza() {
const q = $("#plaza-q") ? $("#plaza-q").value : "";
const d = await api("/plaza?q=" + encodeURIComponent(q));
$("#plaza-list").innerHTML = d.characters.map(c => `
${c.avatar_url ? `

` : "🎭"}
${esc(c.name)}
${esc(c.tags)}
${esc((c.persona || "").slice(0, 80))}…
使用 ${c.usage_count}
`).join("") || '广场空空如也。去角色页发布你的角色!
';
}
async function cloneCharacter(id) {
const c = await api(`/characters/${id}/clone`, { method: "POST" });
toast("已领养到你的角色库"); loadCharacters();
}
/* ---------- 导入导出 ---------- */
async function shareCharacter(id) {
const d = await api(`/characters/${id}/export`);
openModal(`分享「${esc(d.name)}」
分享码:${d.share_code}(对方在广场点「导入分享码」输入即可)
`);
window._shareJSON = JSON.stringify(d.card);
}
function copyJSON() { navigator.clipboard.writeText(window._shareJSON); toast("已复制"); }
async function importByCode() {
openModal(`导入角色卡
`);
}
async function doImport() {
try {
let payload = $("#imp-json").value.trim();
if (payload) payload = { card: JSON.parse(payload) };
else payload = { share_code: $("#imp-code").value };
await api("/characters/import", { method: "POST", body: payload });
closeModal(); toast("导入成功"); loadCharacters();
} catch (e) { toast(e.message); }
}
/* ---------- 语音通话模式 ---------- */
let CALL = null;
async function startCall(sid) {
const s = CUR; const ch = s.characterName || "角色";
$("#call-name").textContent = ch;
$("#call-avatar").innerHTML = s.characterAvatar ? `
` : "📞";
$("#call-overlay").classList.remove("hidden");
CALL = { sid, t0: Date.now(), timer: setInterval(() => {
const t = Math.floor((Date.now() - CALL.t0) / 1000);
$("#call-timer").textContent =
String(Math.floor(t / 60)).padStart(2, "0") + ":" + String(t % 60).padStart(2, "0");
}, 1000) };
}
function callEnd() { clearInterval(CALL.timer); CALL = null;
$("#call-overlay").classList.add("hidden"); }
async function callSend() {
const text = $("#call-text").value.trim(); if (!text || !CALL) return;
$("#call-text").value = "";
$("#call-log").insertAdjacentHTML("beforeend", `我: ${esc(text)}
`);
try {
const r = await api(`/sessions/${CALL.sid}/call`, { method: "POST", body: { content: text } });
$("#call-log").insertAdjacentHTML("beforeend", `${esc(r.reply)}
`);
if (r.audio_base64) new Audio("data:audio/wav;base64," + r.audio_base64).play();
} catch (e) { toast(e.message); }
}
/* ---------- 搜索 & 收藏 & 导出 ---------- */
async function searchAll() {
const q = $("#search-q").value.trim(); if (!q) return;
const d = await api("/search?q=" + encodeURIComponent(q));
$("#search-results").innerHTML = d.results.length ? d.results.map(r => `
${esc(r.speaker || r.role)} ${esc(r.snippet)}
`).join("") : '没搜到。
';
}
async function exportSession(sid) {
const blob = await fetch(`${API}/sessions/${sid}/export`, {
headers: { Authorization: "Bearer " + TOKEN } }).then(r => r.blob());
const a = document.createElement("a");
a.href = URL.createObjectURL(blob); a.download = `session-${sid}.md`; a.click();
}
/* ---------- 偏好设置 ---------- */
async function openSettings() {
const d = await api("/prefs");
const p = d.prefs || {};
openModal(`外观偏好
`);
}
async function savePrefs() {
const prefs = { font_size: +$("#pf-font").value, bubble: $("#pf-bubble").value,
accent: $("#pf-accent").value };
const d = await api("/prefs", { method: "POST", body: prefs });
applyPrefs(d.prefs); closeModal(); toast("偏好已保存");
}
function applyPrefs(p) {
if (p.font_size) document.documentElement.style.setProperty("--chat-font", p.font_size + "px");
if (p.accent) document.documentElement.style.setProperty("--accent", p.accent);
}
/* ---------- 通用 ---------- */
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"); }
})();