第二批小功能: 引用回复/复制消息/时间戳/主题切换/账号全量备份/置顶排序/归档/重命名/发送防连点/空态文案/音色试听 等

This commit is contained in:
zhiqui
2026-11-15 01:01:57 +08:00
parent 778854796a
commit 18ae7e1f9d
5 changed files with 165 additions and 12 deletions
+8 -1
View File
@@ -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)
+28
View File
@@ -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")
+9
View File
@@ -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; }
+3 -1
View File
@@ -42,7 +42,9 @@
<section id="page-shelf" class="page">
<div class="row spread"><h2>书架</h2>
<div class="row">
<button class="btn" onclick="openSettings()">🎨 偏好</button>
<button class="btn" onclick="openSettings()">🎨</button>
<button class="btn" onclick="toggleTheme()">🌗</button>
<button class="btn" onclick="exportAll()">💾</button>
<button class="btn" onclick="newGroup()">👥 群聊</button>
<button class="btn primary" onclick="newRoleplaySession()">+ 新对话</button></div></div>
<div class="row" style="margin:8px 0"><input id="search-q" placeholder="🔍 搜索所有会话内容"
+117 -10
View File
@@ -71,10 +71,24 @@ document.querySelectorAll(".nav-btn[data-page]").forEach(b =>
/* ---------- 书架 / 会话 ---------- */
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>';
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 `<div class="mini-card" onclick="openChat(${s.id},'${s.mode}')">
<h4>${s.pinned ? "📌 " : ""}${esc(s.title)}</h4>
<p><span class="tag">${tag}</span></p>
<div class="row">
<button class="btn small" onclick="event.stopPropagation();renameSession(${s.id},'${esc(s.title)}')">✏️</button>
<button class="btn small" onclick="event.stopPropagation();archiveSession(${s.id},false)">📦</button>
</div></div>`;}).join("")
|| `<p class="hint">${emptyHint()}</p>`;
const archived = d.sessions.filter(s => s.archived);
if (archived.length)
$("#shelf-list").insertAdjacentHTML("beforeend",
`<h3 style="margin-top:16px">📦 归档 (${archived.length})</h3>` +
archived.map(s => `<div class="mini-card" onclick="openChat(${s.id},'${s.mode}')">
<h4>${esc(s.title)}</h4>
<div class="row"><button class="btn small" onclick="event.stopPropagation();archiveSession(${s.id},true)">取消归档</button></div></div>`).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 `<div class="bubble ${cls}" data-mid="${m.id}">
${m.speaker ? `<div class="speaker">${esc(m.speaker)}</div>` : ""}${esc(m.content)}
${m.quote ? `<div class="quote">↩ ${esc(m.quote)}</div>` : ""}
${m.speaker ? `<div class="speaker">${esc(m.speaker)}</div>` : ""}${esc(m.content)}${ts(m)}
${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="copyMsg(${m.id})">📋</button>
<button onclick="quoteMsg(${m.id})">↩</button>
<button onclick="editMsg(${m.id})">✏️</button>
<button onclick="delMsg(${m.id})">🗑</button>
<button onclick="starMsg(${m.id})">${m.starred ? "⭐" : "☆"}</button>
@@ -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",
`<div class="bubble user">${esc(text)}</div>`);
@@ -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",
`<div class="new-char-banner">✨ 新角色入场:${esc(c.name)}(已自动建档${c.avatar_url ? " + 生成立绘" : ""})</div>`);
});
} 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 `<span class="ts">${t.getHours()}:${String(t.getMinutes()).padStart(2, "0")}</span>`;
}
/* 主题切换 */
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"); }
})();