From 18ae7e1f9db31ce2c6e776f1ef30d6bbcd6f6392 Mon Sep 17 00:00:00 2001 From: zhiqui Date: Sun, 15 Nov 2026 01:01:57 +0800 Subject: [PATCH] =?UTF-8?q?=E7=AC=AC=E4=BA=8C=E6=89=B9=E5=B0=8F=E5=8A=9F?= =?UTF-8?q?=E8=83=BD:=20=E5=BC=95=E7=94=A8=E5=9B=9E=E5=A4=8D/=E5=A4=8D?= =?UTF-8?q?=E5=88=B6=E6=B6=88=E6=81=AF/=E6=97=B6=E9=97=B4=E6=88=B3/?= =?UTF-8?q?=E4=B8=BB=E9=A2=98=E5=88=87=E6=8D=A2/=E8=B4=A6=E5=8F=B7?= =?UTF-8?q?=E5=85=A8=E9=87=8F=E5=A4=87=E4=BB=BD/=E7=BD=AE=E9=A1=B6?= =?UTF-8?q?=E6=8E=92=E5=BA=8F/=E5=BD=92=E6=A1=A3/=E9=87=8D=E5=91=BD?= =?UTF-8?q?=E5=90=8D/=E5=8F=91=E9=80=81=E9=98=B2=E8=BF=9E=E7=82=B9/?= =?UTF-8?q?=E7=A9=BA=E6=80=81=E6=96=87=E6=A1=88/=E9=9F=B3=E8=89=B2?= =?UTF-8?q?=E8=AF=95=E5=90=AC=20=E7=AD=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/api/routers/chat.py | 9 ++- app/api/routers/extra.py | 28 +++++++++ web/css/glass.css | 9 +++ web/index.html | 4 +- web/js/app.js | 127 ++++++++++++++++++++++++++++++++++++--- 5 files changed, 165 insertions(+), 12 deletions(-) diff --git a/app/api/routers/chat.py b/app/api/routers/chat.py index 0ea5262f..f5cf7055 100644 --- a/app/api/routers/chat.py +++ b/app/api/routers/chat.py @@ -32,6 +32,7 @@ class SendIn(BaseModel): content: str auto_extract: bool = True # 小说模式:自动抽角色 auto_avatar: bool = True + reply_to_id: int | None = None # 引用回复 class MessageIn(BaseModel): @@ -148,7 +149,12 @@ async def get_messages(sid: int, user: User = Depends(current_user), for m in rows: d = {"id": m.id, "role": m.role, "speaker": m.speaker, "starred": m.starred, "active_swipe": m.active_swipe, + "created_at": m.created_at.isoformat() if m.created_at else None, "content": _dec(user, m.content_enc)} + if m.reply_to_id: + q = await db.get(Message, m.reply_to_id) + if q: + d["quote"] = f"{q.speaker or ''}:{_dec(user, q.content_enc)[:60]}" if m.swipes_enc: sw = json.loads(_dec(user, m.swipes_enc)) d["content"] = sw[m.active_swipe] if sw else d["content"] @@ -165,7 +171,8 @@ async def send(sid: int, body: SendIn, user: User = Depends(current_user), narrative_model = models.get("narrative") or "step-3.5-flash" db.add(Message(session_id=sid, user_id=user.id, role="user", - content_enc=_enc(user, body.content))) + content_enc=_enc(user, body.content), + reply_to_id=body.reply_to_id)) await db.commit() history = await repos.MessageRepo.history(db, user.id, sid, limit=80) diff --git a/app/api/routers/extra.py b/app/api/routers/extra.py index d28a7412..107f3aea 100644 --- a/app/api/routers/extra.py +++ b/app/api/routers/extra.py @@ -499,6 +499,34 @@ async def set_prefs(body: dict, user: User = Depends(current_user), db=Depends(g return {"prefs": cur} +@router.get("/me/export") +async def export_my_data(user: User = Depends(current_user), db=Depends(get_db)): + """账号级全量备份(本人密钥可解 → 明文 JSON)""" + import datetime as _dt + key = _key(user) + chars = await repos.CharacterRepo.list_for(db, user.id) + sessions = await repos.SessionRepo.list_for(db, user.id) + data = {"version": 1, "exported_at": str(_dt.datetime.utcnow()), + "username": user.username, + "characters": [{"name": c.name, "persona": repos.dec(key, c.persona), + "greeting": repos.dec(key, c.greeting), "voice": c.voice, + "avatar_url": c.avatar_url, "tags": c.tags, + "source": c.source} for c in chars], + "sessions": [{"mode": s.mode, "title": s.title, + "novel_setting": _dec(user, s.novel_setting_enc or "")} + for s in sessions], + "memories": [], "worldbook": []} + for c in chars: + for m in await repos.MemoryRepo.list_for(db, user.id, c.id): + data["memories"].append({"character": c.name, "kind": m.kind, + "content": _dec(user, m.content_enc)}) + for w in await repos.WorldbookRepo.list_for(db, user.id): + data["worldbook"].append({"keywords": w.keywords, + "content": _dec(user, w.content_enc), + "constant": w.constant}) + return data + + # ============ 补齐:别名/设置/摘要/统计 ============ @router.post("/characters/{cid}/clone") diff --git a/web/css/glass.css b/web/css/glass.css index e038d047..968dd065 100644 --- a/web/css/glass.css +++ b/web/css/glass.css @@ -191,3 +191,12 @@ textarea { min-height: 90px; resize: vertical; } border-radius: 14px; background: rgba(124,154,255,.16); border: 1px solid var(--stroke); font-size: 13px; max-width: 90%; } .speaker { font-size: 11px; color: var(--accent); margin-bottom: 2px; } +/* 第二批 */ +body.theme-light { --glass: rgba(255,255,255,.55); --glass-strong: rgba(255,255,255,.75); + --stroke: rgba(0,0,0,.12); --text: #1a1c2e; --dim: rgba(26,28,46,.55); + background: #e8ecff; } +body.theme-light .bg-blobs i { opacity: .3; } +.bubble .ts { display:block; font-size:10px; color:var(--dim); margin-top:3px; } +.quote { border-left: 2px solid var(--accent); padding-left: 8px; font-size: 12px; + color: var(--dim); margin-bottom: 4px; white-space: nowrap; overflow: hidden; + text-overflow: ellipsis; } diff --git a/web/index.html b/web/index.html index 3b419d4e..c5fc2c97 100644 --- a/web/index.html +++ b/web/index.html @@ -42,7 +42,9 @@

书架

- + + +
/* ---------- 书架 / 会话 ---------- */ async function loadShelf() { const d = await api("/sessions"); - $("#shelf-list").innerHTML = d.sessions.filter(s => s.mode === "roleplay").map(s => - `
-

${esc(s.title)}

角色扮演

`).join("") - || '

还没有会话,点右上角开一个。

'; + const list = sortSessions(d.sessions.filter(s => !s.archived)); + $("#shelf-list").innerHTML = list.map(s => { + const tag = { roleplay: "角色扮演", novel: "动态小说 · AI自主扩列", group: "群聊", call: "通话" }[s.mode] || s.mode; + return `
+

${s.pinned ? "📌 " : ""}${esc(s.title)}

+

${tag}

+
+ + +
`;}).join("") + || `

${emptyHint()}

`; + const archived = d.sessions.filter(s => s.archived); + if (archived.length) + $("#shelf-list").insertAdjacentHTML("beforeend", + `

📦 归档 (${archived.length})

` + + archived.map(s => `
+

${esc(s.title)}

+
`).join("")); } async function newRoleplaySession() { const chars = (await api("/characters")).characters; @@ -174,11 +188,14 @@ 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)} + ${m.quote ? `
↩ ${esc(m.quote)}
` : ""} + ${m.speaker ? `
${esc(m.speaker)}
` : ""}${esc(m.content)}${ts(m)} ${sw > 1 ? `
${(m.active_swipe ?? 0) + 1}/${sw}
` : ""}
+ + @@ -201,7 +218,10 @@ function refreshChat() { openChat(CUR.sessionId, CUR.mode, CUR.characterId); } async function sendMsg() { const input = $("#chat-input"); const text = input.value.trim(); - if (!text) return; + if (!text || SENDING) return; + SENDING = true; + const replyTo = REPLY_TO; REPLY_TO = null; + input.placeholder = "说点什么…"; input.value = ""; $("#chat-log").insertAdjacentHTML("beforeend", `
${esc(text)}
`); @@ -211,13 +231,14 @@ async function sendMsg() { $("#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 }); + const d = await api(url, { method: "POST", body: { content: text, reply_to_id: replyTo } }); + thinking.innerHTML = renderBubble({ id: d.message_id, role: "assistant", content: d.reply, created_at: new Date().toISOString() }); d.new_characters.forEach(c => { $("#chat-log").insertAdjacentHTML("beforeend", `
✨ 新角色入场:${esc(c.name)}(已自动建档${c.avatar_url ? " + 生成立绘" : ""})
`); }); } catch (e) { thinking.textContent = "⚠️ " + e.message; } + finally { SENDING = false; } $("#chat-log").scrollTop = 1e9; } async function editMsg(mid) { @@ -477,7 +498,93 @@ async function revokeGrant(cid, uid) { adminGrantChannel(); } -/* ================= 扩展功能 ================= */ +/* ================= 第二批小功能 ================= */ + +/* 复制消息 */ +function copyMsg(mid) { + const el = document.querySelector(`[data-mid="${mid}"]`); + navigator.clipboard.writeText(el.textContent.trim()); + toast("已复制"); +} + +/* 时间戳渲染 */ +function ts(m) { + const t = m.created_at ? new Date(m.created_at + "Z") : new Date(); + return `${t.getHours()}:${String(t.getMinutes()).padStart(2, "0")}`; +} + +/* 主题切换 */ +async function toggleTheme() { + const light = document.body.classList.toggle("theme-light"); + await api("/prefs", { method: "POST", body: { theme: light ? "light" : "dark" } }); +} +async function applySavedPrefs() { + try { + const d = await api("/prefs"); + const p = d.prefs || {}; + applyPrefs(p); + if (p.theme === "light") document.body.classList.add("theme-light"); + } catch (e) {} +} + +/* 全量数据导出(账号级备份) */ +async function exportAll() { + const blob = await fetch(`${API}/me/export`, { + headers: { Authorization: "Bearer " + TOKEN } }).then(r => r.json()); + const a = document.createElement("a"); + a.href = URL.createObjectURL(new Blob([JSON.stringify(blob, null, 2)], + { type: "application/json" })); + a.download = "maopaoya-backup.json"; a.click(); + toast("备份已下载"); +} + +/* 置顶排序 + 归档过滤 */ +function sortSessions(list) { + return [...list].sort((a, b) => (b.pinned - a.pinned) || (b.id - a.id)); +} + +/* 会话重命名 */ +async function renameSession(sid, old) { + const nv = prompt("新标题", old || ""); + if (!nv) return; + await api(`/sessions/${sid}/settings`, { method: "PATCH", body: { title: nv } }); + toast("已改名"); backToShelf(); +} + +/* 归档会话 */ +async function archiveSession(sid, cur) { + await api(`/sessions/${sid}/settings`, { method: "PATCH", body: { archived: !cur } }); + toast(cur ? "已取消归档" : "已归档"); backToShelf(); +} + +/* 引用回复 */ +let REPLY_TO = null; +function quoteMsg(mid) { + REPLY_TO = mid; + const el = document.querySelector(`[data-mid="${mid}"] .speaker`); + $("#chat-input").placeholder = "回复 " + (el ? el.textContent : "消息") + "…"; + $("#chat-input").focus(); +} + +/* 发送防连点 */ +let SENDING = false; + +/* 音色试听 */ +async function testVoice(voice) { + const chars = (await api("/characters")).characters; + const sid = CUR.sessionId; + if (!sid) { toast("先进入一个会话"); return; } + toast("试听中…"); + try { + const r = await fetch(`${API}/sessions/${sid}/tts/${(await api(`/sessions/${sid}/messages`)).messages.at(-1).id}`, + { headers: { Authorization: "Bearer " + TOKEN } }); + new Audio(URL.createObjectURL(await r.blob())).play(); + } catch (e) { toast("试听失败:" + e.message); } +} + +/* 空态随机文案 */ +const EMPTY_LINES = ["这里空空如也,像冒泡鸭的池塘冬天。", "先去建个角色?", "万物起始于一根手指的点击。"]; +function emptyHint() { return EMPTY_LINES[Math.floor(Math.random() * EMPTY_LINES.length)]; } /* ---------- 群聊 ---------- */ async function newGroup() { @@ -671,6 +778,6 @@ function esc(s) { return String(s || "").replace(/[&<>"']/g, c => (async () => { if (!TOKEN) return; - try { ME = await api("/auth/me"); enterApp(); } + try { ME = await api("/auth/me"); await enterApp(); await applySavedPrefs(); } catch (e) { localStorage.removeItem("token"); } })();