677 lines
34 KiB
JavaScript
677 lines
34 KiB
JavaScript
/* 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 =>
|
||
`<div class="mini-card" onclick="openChat(${s.id},'roleplay')">
|
||
<h4>${esc(s.title)}</h4><p><span class="tag">角色扮演</span></p></div>`).join("")
|
||
|| '<p class="hint">还没有会话,点右上角开一个。</p>';
|
||
}
|
||
async function newRoleplaySession() {
|
||
const chars = (await api("/characters")).characters;
|
||
openModal(`<h3>新对话</h3>
|
||
<select id="pick-char">${chars.map(c => `<option value="${c.id}">${esc(c.name)}</option>`).join("")}</select>
|
||
<div class="row" style="margin-top:12px">
|
||
<button class="btn primary" onclick="confirmRoleplay()">开始</button>
|
||
<button class="btn" onclick="closeModal()">取消</button></div>
|
||
${chars.length ? "" : '<p class="hint">还没有角色,先去「角色」页建一个。</p>'}`);
|
||
}
|
||
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 =>
|
||
`<div class="mini-card">
|
||
${c.avatar_url ? `<img class="avatar" src="${c.avatar_url}">` : ""}
|
||
<h4>${esc(c.name)} ${c.source === "novel_auto" ? '<span class="tag">AI生成</span>' : ""}</h4>
|
||
<p>${esc(c.persona || "(无人设)")}</p>
|
||
<div class="row" style="margin-top:8px">
|
||
<button class="btn small" onclick="openChat(null,'roleplay',${c.id})">对话</button>
|
||
<button class="btn small" onclick="editCharacter(${c.id})">编辑</button>
|
||
<button class="btn small" onclick="shareCharacter(${c.id})">分享</button>
|
||
<button class="btn small danger" onclick="delCharacter(${c.id})">删</button>
|
||
</div></div>`).join("") || '<p class="hint">还没有角色。</p>';
|
||
}
|
||
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(`<h3>${id ? "编辑" : "新建"}角色</h3>
|
||
<input id="c-name" placeholder="名字" value="${esc(c.name)}">
|
||
<textarea id="c-persona" placeholder="人设:性格、身份、说话风格…">${esc(c.persona)}</textarea>
|
||
<textarea id="c-greeting" placeholder="开场白">${esc(c.greeting)}</textarea>
|
||
<select id="c-voice">${["tongtong","xiaoyu","xiaochen","laowang","xiaolin"]
|
||
.map(v => `<option ${v === c.voice ? "selected" : ""}>${v}</option>`).join("")}</select>
|
||
<input id="c-avatar" placeholder="立绘 URL(可留空)" value="${esc(c.avatar_url)}">
|
||
<div class="row"><button class="btn primary" onclick="saveCharacter(${id || 0})">保存</button>
|
||
<button class="btn" onclick="closeModal()">取消</button></div>`);
|
||
}
|
||
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 =>
|
||
`<div class="mini-card" onclick="openChat(${s.id},'novel')">
|
||
<h4>${esc(s.title)}</h4><p><span class="tag">动态小说 · AI自主扩列</span></p></div>`).join("")
|
||
|| '<p class="hint">还没有小说。</p>';
|
||
}
|
||
function newNovelSession() {
|
||
openModal(`<h3>开新小说</h3>
|
||
<input id="n-title" placeholder="小说标题">
|
||
<textarea id="n-setting" placeholder="设定:世界观、主角、开篇场景…写多细都行,AI 会照着演"></textarea>
|
||
<div class="row" style="margin-top:12px">
|
||
<button class="btn primary" onclick="confirmNovel()">开写</button>
|
||
<button class="btn" onclick="closeModal()">取消</button></div>`);
|
||
}
|
||
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 `<div class="bubble ${cls}" data-mid="${m.id}">
|
||
${m.speaker ? `<div class="speaker">${esc(m.speaker)}</div>` : ""}${esc(m.content)}
|
||
${sw > 1 ? `<div class="swipe-bar"><button onclick="swipeMsg(${m.id},-1)">‹</button>
|
||
<span>${(m.active_swipe ?? 0) + 1}/${sw}</span>
|
||
<button onclick="swipeMsg(${m.id},1)">›</button></div>` : ""}
|
||
<div class="acts">
|
||
<button onclick="editMsg(${m.id})">✏️</button>
|
||
<button onclick="delMsg(${m.id})">🗑</button>
|
||
<button onclick="starMsg(${m.id})">${m.starred ? "⭐" : "☆"}</button>
|
||
${m.role !== "user" ? `<button onclick="regenMsg(${m.id})">🎲</button>
|
||
<button onclick="ttsMsg(${m.id},this)">🔊</button>` : ""}
|
||
</div></div>`;
|
||
}
|
||
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",
|
||
`<div class="bubble user">${esc(text)}</div>`);
|
||
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",
|
||
`<div class="new-char-banner">✨ 新角色入场:${esc(c.name)}(已自动建档${c.avatar_url ? " + 生成立绘" : ""})</div>`);
|
||
});
|
||
} 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 = '<p class="hint">小说模式请在世界书里看角色。</p>'; return; }
|
||
const d = await api(`/characters/${CUR.characterId}/memories`);
|
||
body.innerHTML = d.memories.map(m =>
|
||
`<div class="mem-item"><span class="kind">${m.kind}</span><br>${esc(m.content)}
|
||
<div class="row"><button class="btn small" onclick="editMemory(${m.id})">改</button>
|
||
<button class="btn small danger" onclick="delMemory(${m.id})">删</button></div></div>`).join("")
|
||
|| '<p class="hint">暂无记忆。聊天中重要事实会被自动记录,你也可以手动添加。</p>';
|
||
body.insertAdjacentHTML("beforeend", `<div class="row">
|
||
<button class="btn small primary" onclick="addMemory('fact')">+ 设定</button>
|
||
<button class="btn small primary" onclick="addMemory('event')">+ 事件</button></div>`);
|
||
} 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 =>
|
||
`<div class="mem-item"><span class="kind">${w.constant ? "常驻" : esc(w.keywords || "关键词")}</span><br>${esc(w.content)}
|
||
<div class="row"><button class="btn small" onclick="editWb(${w.id})">改</button>
|
||
<button class="btn small danger" onclick="delWb(${w.id})">删</button></div></div>`).join("")
|
||
|| '<p class="hint">暂无条目。动态小说中 AI 新建的角色会自动注册进来。</p>';
|
||
body.insertAdjacentHTML("beforeend",
|
||
`<button class="btn small primary" onclick="editWb(null)">+ 新条目</button>`);
|
||
} else {
|
||
$("#drawer-title").textContent = "🎭 角色卡";
|
||
if (!CUR.characterId) { body.innerHTML = '<p class="hint">小说模式暂无单角色卡。</p>'; return; }
|
||
const c = (await api("/characters")).characters.find(x => x.id === CUR.characterId);
|
||
body.innerHTML = `<input value="${esc(c.name)}" disabled>
|
||
<textarea disabled style="margin-top:8px">${esc(c.persona)}</textarea>
|
||
<div class="row" style="margin-top:10px">
|
||
<button class="btn small primary" onclick="editCharacter(${c.id})">编辑角色</button></div>`;
|
||
}
|
||
}
|
||
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 =>
|
||
`<div class="mini-card"><h4>${esc(c.name)} ${c.owner_id ? '<span class="tag">私有</span>' : '<span class="tag">全局</span>'}</h4>
|
||
<p>${esc(c.base_url)}<br>叙事: ${esc((c.models || {}).narrative || "-")}</p>
|
||
<div class="row" style="margin-top:8px">
|
||
<button class="btn small" onclick="testChannel(${c.id},this)">测试</button>
|
||
<button class="btn small" onclick="editChannel(${c.id})">编辑</button>
|
||
<button class="btn small danger" onclick="delChannel(${c.id})">删</button></div></div>`).join("")
|
||
|| '<p class="hint">还没有渠道。添加一个 OpenAI 兼容 API 即可开聊。</p>';
|
||
}
|
||
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(`<h3>${id ? "编辑" : "添加"}渠道</h3>
|
||
<input id="ch-name" placeholder="名称" value="${esc(c.name)}">
|
||
<input id="ch-url" placeholder="Base URL" value="${esc(c.base_url)}">
|
||
<input id="ch-key" type="password" placeholder="API Key${id ? "(留空不改)" : ""}">
|
||
<input id="ch-nar" placeholder="叙事模型" value="${esc((c.models || {}).narrative || "")}">
|
||
<input id="ch-tts" placeholder="TTS 模型" value="${esc((c.models || {}).tts || "")}">
|
||
<input id="ch-img" placeholder="生图模型(可留空)" value="${esc((c.models || {}).image || "")}">
|
||
<div class="row" style="margin-top:12px">
|
||
<button class="btn primary" onclick="saveChannel(${id || 0})">保存</button>
|
||
<button class="btn" onclick="closeModal()">取消</button></div>`);
|
||
}
|
||
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]) =>
|
||
`<div class="row spread" style="margin-bottom:10px"><span>${label}</span>
|
||
<button class="btn small ${s[k] === "true" ? "primary" : ""}" onclick="toggleSetting('${k}',this)">${s[k] === "true" ? "开" : "关"}</button></div>`).join("");
|
||
const u = await api("/admin/users");
|
||
$("#admin-stats").textContent = `用户 ${u.stats.users} · 会话 ${u.stats.sessions}`;
|
||
$("#admin-users").innerHTML = `<button class="btn small primary" onclick="adminGrantChannel()">🔌 渠道分配</button>` + u.users.map(x =>
|
||
`<div class="mem-item"><b>${esc(x.username)}</b> ${x.is_admin ? '<span class="tag">管理员</span>' : ""}
|
||
${x.is_active ? "" : '<span class="tag">已封禁</span>'}
|
||
<div class="row">
|
||
<button class="btn small" onclick="adminPatch(${x.id},{'is_active':${!x.is_active}})">${x.is_active ? "封禁" : "解封"}</button>
|
||
<button class="btn small" onclick="adminPatch(${x.id},{'is_admin':${!x.is_admin}})">${x.is_admin ? "去管理员" : "设管理员"}</button>
|
||
<button class="btn small" onclick="adminResetPwd(${x.id})">重置密码</button>
|
||
</div></div>`).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 = [
|
||
`<h3>第 1 步 · 填 Key</h3><p class="hint">已预填 Step Plan 预设(${preset.base_url}),你只需要粘贴 API Key。</p>
|
||
<input id="g-key" type="password" placeholder="粘贴 Step Plan API Key">`,
|
||
`<h3>第 2 步 · 确认模型</h3><p class="hint">默认:叙事/抽取 ${preset.models.narrative},TTS ${preset.models.tts}。直接下一步就行。</p>`,
|
||
`<h3>第 3 步 · 开聊!</h3><p class="hint">去书架开一个角色对话,或去小说页开一本 AI 自主扩列的动态小说。</p>`];
|
||
$("#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(`<h3>修改密码</h3>
|
||
<p class="hint">加密数据将自动用旧密码解密、新密码重加密,历史记录无损。</p>
|
||
<input id="pw-old" type="password" placeholder="旧密码">
|
||
<input id="pw-new" type="password" placeholder="新密码(至少6位)">
|
||
<div class="row" style="margin-top:12px">
|
||
<button class="btn primary" onclick="savePassword()">确认修改</button>
|
||
<button class="btn" onclick="closeModal()">取消</button></div>`);
|
||
}
|
||
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(`<h3>渠道分配</h3>
|
||
<select id="gr-chan">${chans.map(c => `<option value="${c.id}">${esc(c.name)} (#${c.id})</option>`).join("")}</select>
|
||
<select id="gr-user">${users.filter(u => !u.is_admin).map(u => `<option value="${u.id}">${esc(u.username)}</option>`).join("")}</select>
|
||
<div class="row" style="margin-top:12px">
|
||
<button class="btn primary" onclick="doGrant()">授权</button>
|
||
<button class="btn" onclick="closeModal()">关闭</button></div>
|
||
<div id="gr-list" style="margin-top:12px"></div>`);
|
||
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 `<span class="tag">${esc(u ? u.username : uid)}
|
||
<button class="btn small danger" onclick="revokeGrant(${c},${uid})">✕</button></span>`;
|
||
}).join(" ")
|
||
: '<p class="hint">该渠道尚未授权给任何用户。</p>';
|
||
}
|
||
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(`<h3>新建群聊</h3>
|
||
<input id="gr-title" placeholder="群名(默认:群聊)">
|
||
<div style="max-height:40vh;overflow-y:auto;margin-top:8px">
|
||
${chars.map(c => `<label class="mem-item" style="display:flex;gap:8px;align-items:center">
|
||
<input type="checkbox" class="gr-c" value="${c.id}"> ${esc(c.name)}</label>`).join("")}</div>
|
||
<div class="row" style="margin-top:12px">
|
||
<button class="btn primary" onclick="saveGroup()">开群</button>
|
||
<button class="btn" onclick="closeModal()">取消</button></div>`);
|
||
}
|
||
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 => `
|
||
<div class="mem-item moment-card">
|
||
<div class="row spread"><b>${esc(m.author)}</b><span class="dim">${(m.created_at || "").slice(0, 16)}</span></div>
|
||
<p style="margin:8px 0">${esc(m.content)}</p>
|
||
${m.image_url ? `<img src="${m.image_url}" class="moment-img" loading="lazy">` : ""}
|
||
<div class="row">
|
||
<button class="btn small ${m.liked_by_me ? "primary" : ""}" onclick="likeMoment(${m.id})">❤ ${m.likes}</button>
|
||
<button class="btn small" onclick="commentMoment(${m.id})">评论</button></div>
|
||
${(m.comments || []).map(c => `<p class="hint">💬 <b>${esc(c.author)}</b>: ${esc(c.content)}</p>`).join("")}
|
||
</div>`).join("") : '<p class="hint">还没有动态。点右上角让角色发一条。</p>';
|
||
}
|
||
async function pickMomentChar() {
|
||
const chars = (await api("/characters")).characters;
|
||
openModal(`<h3>谁发动态?</h3>
|
||
<select id="mc-cid">${chars.map(c => `<option value="${c.id}">${esc(c.name)}</option>`).join("")}</select>
|
||
<input id="mc-topic" placeholder="给个话题(留空=自由发挥)">
|
||
<div class="row" style="margin-top:12px">
|
||
<button class="btn primary" onclick="genMoment()">生成</button>
|
||
<button class="btn" onclick="closeModal()">取消</button></div>`);
|
||
}
|
||
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(`<h3>评论</h3><input id="cm-text" placeholder="说点什么…">
|
||
<div class="row" style="margin-top:12px">
|
||
<button class="btn primary" onclick="sendComment(${id})">发送</button>
|
||
<button class="btn" onclick="closeModal()">取消</button></div>`);
|
||
}
|
||
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 => `
|
||
<div class="glass-card card">
|
||
<div class="row"><div class="avatar">${c.avatar_url ? `<img src="${c.avatar_url}">` : "🎭"}</div>
|
||
<div><b>${esc(c.name)}</b><br><span class="dim">${esc(c.tags)}</span></div></div>
|
||
<p class="hint" style="margin-top:8px">${esc((c.persona || "").slice(0, 80))}…</p>
|
||
<div class="row"><span class="dim">使用 ${c.usage_count}</span>
|
||
<button class="btn small primary" onclick="cloneCharacter(${c.id})">领养</button></div>
|
||
</div>`).join("") || '<p class="hint">广场空空如也。去角色页发布你的角色!</p>';
|
||
}
|
||
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(`<h3>分享「${esc(d.name)}」</h3>
|
||
<p class="hint">分享码:<b style="font-size:18px">${d.share_code}</b>(对方在广场点「导入分享码」输入即可)</p>
|
||
<textarea readonly style="height:120px">${esc(JSON.stringify(d.card))}</textarea>
|
||
<div class="row" style="margin-top:12px">
|
||
<button class="btn" onclick="copyJSON()">复制 JSON</button>
|
||
<button class="btn" onclick="closeModal()">关闭</button></div>`);
|
||
window._shareJSON = JSON.stringify(d.card);
|
||
}
|
||
function copyJSON() { navigator.clipboard.writeText(window._shareJSON); toast("已复制"); }
|
||
async function importByCode() {
|
||
openModal(`<h3>导入角色卡</h3>
|
||
<input id="imp-code" placeholder="分享码">
|
||
<textarea id="imp-json" placeholder="或粘贴角色卡 JSON"></textarea>
|
||
<div class="row" style="margin-top:12px">
|
||
<button class="btn primary" onclick="doImport()">导入</button>
|
||
<button class="btn" onclick="closeModal()">取消</button></div>`);
|
||
}
|
||
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 ? `<img src="${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", `<p class="hint">我: ${esc(text)}</p>`);
|
||
try {
|
||
const r = await api(`/sessions/${CALL.sid}/call`, { method: "POST", body: { content: text } });
|
||
$("#call-log").insertAdjacentHTML("beforeend", `<p>${esc(r.reply)}</p>`);
|
||
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 => `
|
||
<div class="mem-item" onclick="openChat(${r.session_id},'roleplay')">
|
||
<b>${esc(r.speaker || r.role)}</b> <span class="dim">${esc(r.snippet)}</span>
|
||
</div>`).join("") : '<p class="hint">没搜到。</p>';
|
||
}
|
||
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(`<h3>外观偏好</h3>
|
||
<label class="hint">字号 <input id="pf-font" type="range" min="12" max="22" value="${p.font_size || 15}"></label>
|
||
<label class="hint">气泡样式
|
||
<select id="pf-bubble"><option value="glass" ${p.bubble === "glass" ? "selected" : ""}>玻璃</option>
|
||
<option value="plain" ${p.bubble === "plain" ? "selected" : ""}>简洁</option></select></label>
|
||
<label class="hint">主色调 <input id="pf-accent" type="color" value="${p.accent || "#7c9aff"}"></label>
|
||
<div class="row" style="margin-top:12px">
|
||
<button class="btn primary" onclick="savePrefs()">保存</button>
|
||
<button class="btn" onclick="closeModal()">取消</button></div>`);
|
||
}
|
||
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"); }
|
||
})();
|