扩展功能包: 群聊/朋友圈/语音通话/Swipe多版本/广场与角色卡分享导入 + 30项小功能(搜索/收藏/导出/摘要/偏好/置顶归档/会话设置/后台统计/轻量自动迁移等)
This commit is contained in:
+12
-2
@@ -1,5 +1,6 @@
|
|||||||
"""聊天主链路:单角色扮演 + 动态小说两种模式。上下文不做节省。"""
|
"""聊天主链路:单角色扮演 + 动态小说两种模式。上下文不做节省。"""
|
||||||
import datetime as dt
|
import datetime as dt
|
||||||
|
import json
|
||||||
|
|
||||||
from fastapi import APIRouter, Depends, HTTPException
|
from fastapi import APIRouter, Depends, HTTPException
|
||||||
from fastapi.responses import Response
|
from fastapi.responses import Response
|
||||||
@@ -143,8 +144,17 @@ async def get_messages(sid: int, user: User = Depends(current_user),
|
|||||||
db=Depends(get_db)):
|
db=Depends(get_db)):
|
||||||
await _own_session(db, user, sid)
|
await _own_session(db, user, sid)
|
||||||
rows = await repos.MessageRepo.history(db, user.id, sid, limit=500)
|
rows = await repos.MessageRepo.history(db, user.id, sid, limit=500)
|
||||||
return {"messages": [{"id": m.id, "role": m.role, "speaker": m.speaker,
|
out = []
|
||||||
"content": _dec(user, m.content_enc)} for m in rows]}
|
for m in rows:
|
||||||
|
d = {"id": m.id, "role": m.role, "speaker": m.speaker, "starred": m.starred,
|
||||||
|
"active_swipe": m.active_swipe,
|
||||||
|
"content": _dec(user, m.content_enc)}
|
||||||
|
if m.swipes_enc:
|
||||||
|
sw = json.loads(_dec(user, m.swipes_enc))
|
||||||
|
d["content"] = sw[m.active_swipe] if sw else d["content"]
|
||||||
|
d["swipe_count"] = len(sw)
|
||||||
|
out.append(d)
|
||||||
|
return {"messages": out}
|
||||||
|
|
||||||
|
|
||||||
@router.post("/sessions/{sid}/send")
|
@router.post("/sessions/{sid}/send")
|
||||||
|
|||||||
@@ -0,0 +1,563 @@
|
|||||||
|
"""扩展功能:群聊 / 朋友圈 / 语音通话 / Swipe / 广场 / 搜索 / 偏好 / 导出"""
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import secrets
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends, HTTPException, Response
|
||||||
|
from fastapi.responses import FileResponse
|
||||||
|
from pydantic import BaseModel
|
||||||
|
from sqlalchemy import select, or_, delete
|
||||||
|
|
||||||
|
from ...db.session import get_db
|
||||||
|
from ...db import repos
|
||||||
|
from ...models.entities import (User, ChatSession, Message, Character, Memory,
|
||||||
|
Moment, MomentComment, UserPrefs)
|
||||||
|
from .auth import current_user
|
||||||
|
from .chat import _key, _own_session, _dec, _enc, _channel_for, build_context
|
||||||
|
from .characters import _enc_persona
|
||||||
|
from ...core import security
|
||||||
|
from ...services.llm import LLMClient
|
||||||
|
from ...services import novel_pipeline
|
||||||
|
|
||||||
|
router = APIRouter(tags=["extra"])
|
||||||
|
|
||||||
|
|
||||||
|
# ============ 1. 群聊(多角色同台) ============
|
||||||
|
|
||||||
|
class GroupIn(BaseModel):
|
||||||
|
title: str = "群聊"
|
||||||
|
character_ids: list[int]
|
||||||
|
channel_id: int | None = None
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/groups")
|
||||||
|
async def create_group(body: GroupIn, user: User = Depends(current_user),
|
||||||
|
db=Depends(get_db)):
|
||||||
|
if len(body.character_ids) < 1:
|
||||||
|
raise HTTPException(400, "至少选择一个角色")
|
||||||
|
# 校验所有权
|
||||||
|
for cid in body.character_ids:
|
||||||
|
c = await db.get(Character, cid)
|
||||||
|
if not c or c.user_id != user.id:
|
||||||
|
raise HTTPException(404, f"角色 {cid} 不存在")
|
||||||
|
s = ChatSession(user_id=user.id, mode="group", title=body.title,
|
||||||
|
character_id=body.character_ids[0],
|
||||||
|
group_member_ids=",".join(map(str, body.character_ids)),
|
||||||
|
channel_id=body.channel_id)
|
||||||
|
db.add(s)
|
||||||
|
await db.commit()
|
||||||
|
# 每个角色来一段开场白
|
||||||
|
key = _key(user)
|
||||||
|
for cid in body.character_ids:
|
||||||
|
c = await db.get(Character, cid)
|
||||||
|
g = repos.dec(key, c.greeting)
|
||||||
|
if g:
|
||||||
|
db.add(Message(session_id=s.id, user_id=user.id, role="assistant",
|
||||||
|
speaker=c.name, content_enc=_enc(user, g)))
|
||||||
|
await db.commit()
|
||||||
|
return {"id": s.id}
|
||||||
|
|
||||||
|
|
||||||
|
GROUP_SYSTEM = """这是群聊场景。参与角色:{roster}。
|
||||||
|
你控制角色「{name}」发言。其他角色的话会以【角色名】标注。
|
||||||
|
只在轮到你说话或被@时发言,保持角色人设,不要替其他角色说话。回复保持简短口语化。"""
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/sessions/{sid}/send_group")
|
||||||
|
async def send_group(sid: int, body: dict, user: User = Depends(current_user),
|
||||||
|
db=Depends(get_db)):
|
||||||
|
"""群聊发送:每个群成员依次发言(被@的优先)"""
|
||||||
|
s = await _own_session(db, user, sid)
|
||||||
|
if s.mode != "group":
|
||||||
|
raise HTTPException(400, "非群聊会话")
|
||||||
|
text = body.get("content", "")
|
||||||
|
at = body.get("at") # 指定发言角色名,可选
|
||||||
|
key = _key(user)
|
||||||
|
db.add(Message(session_id=sid, user_id=user.id, role="user",
|
||||||
|
content_enc=_enc(user, text)))
|
||||||
|
await db.commit()
|
||||||
|
|
||||||
|
member_ids = [int(x) for x in s.group_member_ids.split(",") if x]
|
||||||
|
client, models = await _channel_for(db, user, s)
|
||||||
|
history = await repos.MessageRepo.history(db, user.id, sid, limit=60)
|
||||||
|
msgs = [{"role": m.role,
|
||||||
|
"content": (f"【{m.speaker}】" if m.speaker else "") + _dec(user, m.content_enc)}
|
||||||
|
for m in history]
|
||||||
|
roster = []
|
||||||
|
for cid in member_ids:
|
||||||
|
c = await db.get(Character, cid)
|
||||||
|
roster.append(f"{c.name}(人设:{repos.dec(key, c.persona)[:200]})")
|
||||||
|
out = []
|
||||||
|
for cid in member_ids:
|
||||||
|
c = await db.get(Character, cid)
|
||||||
|
if at and c.name != at:
|
||||||
|
continue
|
||||||
|
sysmsg = GROUP_SYSTEM.format(roster=";".join(roster), name=c.name)
|
||||||
|
if s.prompt_suffix:
|
||||||
|
sysmsg += "\n" + s.prompt_suffix
|
||||||
|
wb = await repos.WorldbookRepo.list_for(db, user.id)
|
||||||
|
for hit in novel_pipeline.match_worldbook(wb, text, key):
|
||||||
|
sysmsg += "\n[设定]" + hit
|
||||||
|
reply = await client.chat(models.get("narrative") or "step-3.5-flash",
|
||||||
|
[{"role": "system", "content": sysmsg}] + msgs,
|
||||||
|
temperature=0.95)
|
||||||
|
m = Message(session_id=sid, user_id=user.id, role="assistant",
|
||||||
|
speaker=c.name, content_enc=_enc(user, reply),
|
||||||
|
swipes_enc=_enc(user, json.dumps([reply])))
|
||||||
|
db.add(m)
|
||||||
|
out.append({"speaker": c.name, "content": reply, "id": m.id})
|
||||||
|
await db.commit()
|
||||||
|
return {"messages": out}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/sessions/{sid}/members")
|
||||||
|
async def group_members(sid: int, user: User = Depends(current_user),
|
||||||
|
db=Depends(get_db)):
|
||||||
|
s = await _own_session(db, user, sid)
|
||||||
|
ids = [int(x) for x in s.group_member_ids.split(",") if x]
|
||||||
|
out = []
|
||||||
|
for cid in ids:
|
||||||
|
c = await db.get(Character, cid)
|
||||||
|
if c:
|
||||||
|
out.append({"id": c.id, "name": c.name, "avatar_url": c.avatar_url,
|
||||||
|
"voice": c.voice})
|
||||||
|
return {"members": out}
|
||||||
|
|
||||||
|
|
||||||
|
# ============ 2. 角色朋友圈 ============
|
||||||
|
|
||||||
|
MOMENT_SYSTEM = """你扮演角色「{name}」(人设:{persona})。请以该角色的口吻发一条朋友圈动态,
|
||||||
|
内容符合人设与近期状态(可结合提供的世界观设定),50-120字,活泼自然,可带 emoji。
|
||||||
|
只输出动态正文。"""
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/moments/generate")
|
||||||
|
async def gen_moment(body: dict, user: User = Depends(current_user),
|
||||||
|
db=Depends(get_db)):
|
||||||
|
cid = body.get("character_id")
|
||||||
|
c = await db.get(Character, cid)
|
||||||
|
if not c or c.user_id != user.id:
|
||||||
|
raise HTTPException(404, "角色不存在")
|
||||||
|
client, models = await _channel_for(db, user, None)
|
||||||
|
key = _key(user)
|
||||||
|
mems = await repos.MemoryRepo.list_for(db, user.id, cid)
|
||||||
|
mem_text = "\n".join(_dec(user, m.content_enc) for m in mems[:10])
|
||||||
|
prompt = MOMENT_SYSTEM.format(name=c.name, persona=repos.dec(key, c.persona))
|
||||||
|
if mem_text:
|
||||||
|
prompt += "\n你最近的经历/心情:\n" + mem_text
|
||||||
|
content = await client.chat(models.get("narrative") or "step-3.5-flash",
|
||||||
|
[{"role": "user", "content": prompt}], temperature=1.0)
|
||||||
|
m = Moment(user_id=user.id, character_id=cid, content_enc=_enc(user, content))
|
||||||
|
if body.get("with_image"):
|
||||||
|
img_model = models.get("image")
|
||||||
|
if img_model:
|
||||||
|
m.image_url = await novel_pipeline.gen_avatar(
|
||||||
|
client, img_model, repos.dec(key, c.persona)[:150])
|
||||||
|
db.add(m)
|
||||||
|
await db.commit()
|
||||||
|
return {"id": m.id, "content": content, "image_url": m.image_url}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/moments")
|
||||||
|
async def list_moments(user: User = Depends(current_user), db=Depends(get_db)):
|
||||||
|
rows = (await db.execute(select(Moment).where(Moment.user_id == user.id)
|
||||||
|
.order_by(Moment.id.desc()))).scalars().all()
|
||||||
|
key = _key(user)
|
||||||
|
out = []
|
||||||
|
for m in rows:
|
||||||
|
c = await db.get(Character, m.character_id)
|
||||||
|
comments = (await db.execute(select(MomentComment).where(
|
||||||
|
MomentComment.moment_id == m.id))).scalars().all()
|
||||||
|
out.append({"id": m.id, "character": c.name if c else "?",
|
||||||
|
"avatar_url": c.avatar_url if c else "",
|
||||||
|
"content": _dec(user, m.content_enc), "image_url": m.image_url,
|
||||||
|
"liked_by_me": m.liked_by_me,
|
||||||
|
"comments": [{"author": x.author, "content": _dec(user, x.content_enc),
|
||||||
|
"id": x.id} for x in comments]})
|
||||||
|
return {"moments": out}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/moments/{mid}/like")
|
||||||
|
async def like_moment(mid: int, user: User = Depends(current_user), db=Depends(get_db)):
|
||||||
|
m = await db.get(Moment, mid)
|
||||||
|
if not m or m.user_id != user.id:
|
||||||
|
raise HTTPException(404, "动态不存在")
|
||||||
|
m.liked_by_me = not m.liked_by_me
|
||||||
|
await db.commit()
|
||||||
|
return {"liked_by_me": m.liked_by_me}
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/moments/{mid}")
|
||||||
|
async def del_moment(mid: int, user: User = Depends(current_user), db=Depends(get_db)):
|
||||||
|
m = await db.get(Moment, mid)
|
||||||
|
if not m or m.user_id != user.id:
|
||||||
|
raise HTTPException(404, "动态不存在")
|
||||||
|
await db.execute(delete(MomentComment).where(MomentComment.moment_id == mid))
|
||||||
|
await db.delete(m)
|
||||||
|
await db.commit()
|
||||||
|
return {"ok": True}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/moments/{mid}/comment")
|
||||||
|
async def comment_moment(mid: int, body: dict, user: User = Depends(current_user),
|
||||||
|
db=Depends(get_db)):
|
||||||
|
"""用户评论;body.reply=true 时让角色回评"""
|
||||||
|
m = await db.get(Moment, mid)
|
||||||
|
if not m or m.user_id != user.id:
|
||||||
|
raise HTTPException(404, "动态不存在")
|
||||||
|
c = await db.get(Character, m.character_id)
|
||||||
|
key = _key(user)
|
||||||
|
text = body.get("content", "")
|
||||||
|
db.add(MomentComment(moment_id=mid, user_id=user.id, author="me",
|
||||||
|
content_enc=_enc(user, text)))
|
||||||
|
reply = ""
|
||||||
|
if body.get("reply", True):
|
||||||
|
client, models = await _channel_for(db, user, None)
|
||||||
|
prompt = (f"你扮演「{c.name}」(人设:{repos.dec(key, c.persona)})。"
|
||||||
|
f"你发的朋友圈:「{_dec(user, m.content_enc)}」。用户评论:「{text}」。"
|
||||||
|
f"以角色口吻回一句评论,30字内,只输出评论。")
|
||||||
|
reply = await client.chat(models.get("narrative") or "step-3.5-flash",
|
||||||
|
[{"role": "user", "content": prompt}], temperature=1.0)
|
||||||
|
db.add(MomentComment(moment_id=mid, user_id=user.id, author=c.name,
|
||||||
|
content_enc=_enc(user, reply)))
|
||||||
|
await db.commit()
|
||||||
|
return {"reply": reply}
|
||||||
|
|
||||||
|
|
||||||
|
# ============ 3. 语音通话 ============
|
||||||
|
|
||||||
|
@router.post("/sessions/{sid}/call")
|
||||||
|
async def voice_call(sid: int, body: dict, user: User = Depends(current_user),
|
||||||
|
db=Depends(get_db)):
|
||||||
|
"""语音通话一轮:用户文本(或语音转写)→ 角色回复 → TTS 音频"""
|
||||||
|
s = await _own_session(db, user, sid)
|
||||||
|
text = body.get("content", "")
|
||||||
|
if not text:
|
||||||
|
raise HTTPException(400, "缺少内容")
|
||||||
|
db.add(Message(session_id=sid, user_id=user.id, role="user",
|
||||||
|
content_enc=_enc(user, text)))
|
||||||
|
await db.commit()
|
||||||
|
history = await repos.MessageRepo.history(db, user.id, sid, limit=40)
|
||||||
|
msgs = await build_context(db, user, s, history)
|
||||||
|
client, models = await _channel_for(db, user, s)
|
||||||
|
reply = await client.chat(models.get("narrative") or "step-3.5-flash",
|
||||||
|
msgs, temperature=0.95, max_tokens=300)
|
||||||
|
db.add(Message(session_id=sid, user_id=user.id, role="assistant",
|
||||||
|
speaker=s.title, content_enc=_enc(user, reply)))
|
||||||
|
await db.commit()
|
||||||
|
try:
|
||||||
|
audio = await client.tts(models.get("tts") or "stepaudio-2.5-tts", reply)
|
||||||
|
import base64 as b64
|
||||||
|
audio_b64 = b64.b64encode(audio).decode()
|
||||||
|
except Exception:
|
||||||
|
audio_b64 = ""
|
||||||
|
return {"reply": reply, "audio_wav": audio_b64}
|
||||||
|
|
||||||
|
|
||||||
|
# ============ 4. Swipe 多版本 ============
|
||||||
|
|
||||||
|
@router.post("/messages/{mid}/swipe")
|
||||||
|
async def swipe_message(mid: int, body: dict, user: User = Depends(current_user),
|
||||||
|
db=Depends(get_db)):
|
||||||
|
"""切换备选版本:delta ±1"""
|
||||||
|
m = await db.get(Message, mid)
|
||||||
|
if not m or m.user_id != user.id:
|
||||||
|
raise HTTPException(404, "消息不存在")
|
||||||
|
swipes = json.loads(_dec(user, m.swipes_enc)) if m.swipes_enc else [_dec(user, m.content_enc)]
|
||||||
|
idx = m.active_swipe + body.get("delta", 1)
|
||||||
|
if not 0 <= idx < len(swipes):
|
||||||
|
raise HTTPException(400, "没有更多版本")
|
||||||
|
m.active_swipe = idx
|
||||||
|
m.content_enc = _enc(user, swipes[idx])
|
||||||
|
await db.commit()
|
||||||
|
return {"active": idx, "content": swipes[idx], "count": len(swipes)}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/messages/{mid}/regenerate")
|
||||||
|
async def regenerate_message(mid: int, user: User = Depends(current_user),
|
||||||
|
db=Depends(get_db)):
|
||||||
|
"""生成新备选回复(需要可用渠道)"""
|
||||||
|
m = await db.get(Message, mid)
|
||||||
|
if not m or m.user_id != user.id:
|
||||||
|
raise HTTPException(404, "消息不存在")
|
||||||
|
s = await db.get(ChatSession, m.session_id)
|
||||||
|
history = await repos.MessageRepo.history(db, user.id, m.session_id, limit=60)
|
||||||
|
history = [h for h in history if h.id <= mid and h.id != m.id]
|
||||||
|
msgs = await build_context(db, user, s, history)
|
||||||
|
client, models = await _channel_for(db, user, s)
|
||||||
|
reply = await client.chat(models.get("narrative") or "step-3.5-flash", msgs)
|
||||||
|
swipes = json.loads(_dec(user, m.swipes_enc)) if m.swipes_enc else [_dec(user, m.content_enc)]
|
||||||
|
swipes.append(reply)
|
||||||
|
m.swipes_enc = _enc(user, json.dumps(swipes))
|
||||||
|
m.active_swipe = len(swipes) - 1
|
||||||
|
m.content_enc = _enc(user, reply)
|
||||||
|
await db.commit()
|
||||||
|
return {"active": m.active_swipe, "count": len(swipes)}
|
||||||
|
|
||||||
|
|
||||||
|
@router.patch("/messages/{mid}/swipe")
|
||||||
|
async def pick_swipe(mid: int, body: dict, user: User = Depends(current_user),
|
||||||
|
db=Depends(get_db)):
|
||||||
|
m = await db.get(Message, mid)
|
||||||
|
if not m or m.user_id != user.id:
|
||||||
|
raise HTTPException(404, "消息不存在")
|
||||||
|
swipes = json.loads(_dec(user, m.swipes_enc)) if m.swipes_enc else [_dec(user, m.content_enc)]
|
||||||
|
idx = body.get("active", 0)
|
||||||
|
if not 0 <= idx < len(swipes):
|
||||||
|
raise HTTPException(400, "下标越界")
|
||||||
|
m.active_swipe = idx
|
||||||
|
m.content_enc = _enc(user, swipes[idx])
|
||||||
|
await db.commit()
|
||||||
|
return {"active": idx, "content": swipes[idx]}
|
||||||
|
|
||||||
|
|
||||||
|
# ============ 5. 角色卡导入导出 / 广场 ============
|
||||||
|
|
||||||
|
@router.get("/characters/{cid}/export")
|
||||||
|
async def export_character(cid: int, user: User = Depends(current_user), db=Depends(get_db)):
|
||||||
|
c = await db.get(Character, cid)
|
||||||
|
if not c or c.user_id != user.id:
|
||||||
|
raise HTTPException(404, "角色不存在")
|
||||||
|
key = _key(user)
|
||||||
|
mems = await repos.MemoryRepo.list_for(db, user.id, cid)
|
||||||
|
card = {"name": c.name, "description": repos.dec(key, c.persona),
|
||||||
|
"first_mes": repos.dec(key, c.greeting), "voice": c.voice,
|
||||||
|
"tags": c.tags, "source": "open-maopaoya"}
|
||||||
|
if not c.share_code:
|
||||||
|
c.share_code = secrets.token_urlsafe(8)
|
||||||
|
await db.commit()
|
||||||
|
return {"card": card, "memories": [_dec(user, m.content_enc) for m in mems],
|
||||||
|
"name": c.name, "share_code": c.share_code}
|
||||||
|
|
||||||
|
|
||||||
|
class CardIn(BaseModel):
|
||||||
|
name: str
|
||||||
|
description: str = ""
|
||||||
|
first_mes: str = ""
|
||||||
|
voice: str = "tongtong"
|
||||||
|
tags: str = ""
|
||||||
|
memories: list[str] = []
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/characters/import")
|
||||||
|
async def import_character(body: dict, user: User = Depends(current_user),
|
||||||
|
db=Depends(get_db)):
|
||||||
|
# 两种入参:share_code 或完整 card JSON
|
||||||
|
if body.get("share_code"):
|
||||||
|
src = (await db.execute(select(Character).where(
|
||||||
|
Character.share_code == body["share_code"]))).scalar_one_or_none()
|
||||||
|
if not src:
|
||||||
|
raise HTTPException(404, "分享码无效")
|
||||||
|
key = _key(user)
|
||||||
|
visible = await repos.SettingRepo.get(db, "admin_data_visible") == "true"
|
||||||
|
ek = None if visible else key
|
||||||
|
c = Character(user_id=user.id, name=src.name, source="imported",
|
||||||
|
voice=src.voice, avatar_url=src.avatar_url, tags=src.tags)
|
||||||
|
c.persona = repos.enc(ek, repos.dec(key, src.persona))
|
||||||
|
c.greeting = repos.enc(ek, repos.dec(key, src.greeting))
|
||||||
|
db.add(c)
|
||||||
|
await db.commit()
|
||||||
|
return {"id": c.id}
|
||||||
|
card = body.get("card") or body
|
||||||
|
c = Character(user_id=user.id, name=card["name"], source="imported",
|
||||||
|
tags=card.get("tags", ""), voice=card.get("voice", "tongtong"))
|
||||||
|
key = _key(user)
|
||||||
|
visible = await repos.SettingRepo.get(db, "admin_data_visible") == "true"
|
||||||
|
ek = None if visible else key
|
||||||
|
c.persona = repos.enc(ek, card.get("description", ""))
|
||||||
|
c.greeting = repos.enc(ek, card.get("first_mes", ""))
|
||||||
|
db.add(c)
|
||||||
|
await db.flush()
|
||||||
|
for mem in (card.get("memories") or [])[:200]:
|
||||||
|
db.add(Memory(character_id=c.id, user_id=user.id, kind="fact",
|
||||||
|
content_enc=repos.enc(ek, mem)))
|
||||||
|
await db.commit()
|
||||||
|
return {"id": c.id}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/characters/{cid}/publish")
|
||||||
|
async def publish_character(cid: int, body: dict, user: User = Depends(current_user),
|
||||||
|
db=Depends(get_db)):
|
||||||
|
c = await db.get(Character, cid)
|
||||||
|
if not c or c.user_id != user.id:
|
||||||
|
raise HTTPException(404, "角色不存在")
|
||||||
|
c.is_public = bool(body.get("public", True))
|
||||||
|
if c.is_public:
|
||||||
|
key = _key(user)
|
||||||
|
if not key:
|
||||||
|
raise HTTPException(401, "请重新登录后再发布")
|
||||||
|
# 公开卡片属公开数据:人设/开场白存明文公开字段供广场展示与领养
|
||||||
|
c.public_persona = repos.dec(key, c.persona)
|
||||||
|
c.public_greeting = repos.dec(key, c.greeting)
|
||||||
|
c.tags = body.get("tags", c.tags)
|
||||||
|
if not c.share_code:
|
||||||
|
c.share_code = secrets.token_urlsafe(8)
|
||||||
|
await db.commit()
|
||||||
|
return {"is_public": c.is_public, "share_code": c.share_code}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/plaza")
|
||||||
|
async def plaza(q: str = "", user: User = Depends(current_user), db=Depends(get_db)):
|
||||||
|
rows = (await db.execute(select(Character).where(Character.is_public == True)
|
||||||
|
.order_by(Character.usage_count.desc()))).scalars().all()
|
||||||
|
q = (q or "").strip()
|
||||||
|
if q:
|
||||||
|
rows = [c for c in rows if q.lower() in c.name.lower()
|
||||||
|
or q.lower() in (c.tags or "").lower()
|
||||||
|
or q.lower() in (c.public_persona or "").lower()]
|
||||||
|
return {"characters": [{"id": c.id, "name": c.name,
|
||||||
|
"persona": (c.public_persona or "")[:150],
|
||||||
|
"avatar_url": c.avatar_url, "tags": c.tags,
|
||||||
|
"usage_count": c.usage_count,
|
||||||
|
"share_code": c.share_code} for c in rows]}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/plaza/{cid}/clone")
|
||||||
|
async def clone_character(cid: int, user: User = Depends(current_user), db=Depends(get_db)):
|
||||||
|
c = await db.get(Character, cid)
|
||||||
|
if not c or not c.is_public:
|
||||||
|
raise HTTPException(404, "角色不存在或未公开")
|
||||||
|
n = Character(user_id=user.id, name=c.name, source="imported",
|
||||||
|
voice=c.voice, avatar_url=c.avatar_url, tags=c.tags)
|
||||||
|
# 优先取发布时的公开明文;作者本人克隆用自身密钥解密
|
||||||
|
if c.user_id == user.id:
|
||||||
|
key = _key(user)
|
||||||
|
n.persona = repos.dec(key, c.persona)
|
||||||
|
n.greeting = repos.dec(key, c.greeting)
|
||||||
|
else:
|
||||||
|
if not c.is_public:
|
||||||
|
raise HTTPException(403, "该角色未公开")
|
||||||
|
n.persona = c.public_persona or ""
|
||||||
|
n.greeting = c.public_greeting or ""
|
||||||
|
n.source = "imported"
|
||||||
|
db.add(n)
|
||||||
|
c.usage_count += 1
|
||||||
|
await db.commit()
|
||||||
|
return {"id": n.id}
|
||||||
|
|
||||||
|
|
||||||
|
# ============ 6. 搜索 / 收藏 / 导出 / 偏好 ============
|
||||||
|
|
||||||
|
@router.get("/search")
|
||||||
|
async def search(q: str, user: User = Depends(current_user), db=Depends(get_db)):
|
||||||
|
key = _key(user)
|
||||||
|
chars = (await db.execute(select(Character).where(
|
||||||
|
Character.user_id == user.id, or_(
|
||||||
|
Character.name.ilike(f"%{q}%"))))).scalars().all()
|
||||||
|
sessions = (await db.execute(select(ChatSession).where(
|
||||||
|
ChatSession.user_id == user.id, ChatSession.title.ilike(f"%{q}%")))).scalars().all()
|
||||||
|
msgs = (await db.execute(select(Message).where(
|
||||||
|
Message.user_id == user.id).order_by(Message.id.desc()).limit(500))).scalars().all()
|
||||||
|
hit_msgs = [{"id": m.id, "session_id": m.session_id,
|
||||||
|
"content": _dec(user, m.content_enc)[:120], "speaker": m.speaker}
|
||||||
|
for m in msgs if q.lower() in _dec(user, m.content_enc).lower()][:30]
|
||||||
|
return {"characters": [{"id": c.id, "name": c.name} for c in chars],
|
||||||
|
"sessions": [{"id": s.id, "title": s.title, "mode": s.mode} for s in sessions],
|
||||||
|
"messages": hit_msgs}
|
||||||
|
|
||||||
|
|
||||||
|
@router.patch("/messages/{mid}/star")
|
||||||
|
async def star_message(mid: int, body: dict, user: User = Depends(current_user),
|
||||||
|
db=Depends(get_db)):
|
||||||
|
m = await db.get(Message, mid)
|
||||||
|
if not m or m.user_id != user.id:
|
||||||
|
raise HTTPException(404, "消息不存在")
|
||||||
|
m.starred = bool(body.get("starred", True))
|
||||||
|
await db.commit()
|
||||||
|
return {"starred": m.starred}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/sessions/{sid}/export")
|
||||||
|
async def export_chat(sid: int, user: User = Depends(current_user), db=Depends(get_db)):
|
||||||
|
s = await _own_session(db, user, sid)
|
||||||
|
msgs = await repos.MessageRepo.history(db, user.id, sid, limit=10000)
|
||||||
|
lines = [f"# {s.title}\n"]
|
||||||
|
for m in msgs:
|
||||||
|
who = m.speaker or ("我" if m.role == "user" else "AI")
|
||||||
|
lines.append(f"**{who}**: {_dec(user, m.content_enc)}\n")
|
||||||
|
return Response(content="\n".join(lines), media_type="text/markdown",
|
||||||
|
headers={"Content-Disposition":
|
||||||
|
f"attachment; filename=session-{sid}.md"})
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/prefs")
|
||||||
|
async def get_prefs(user: User = Depends(current_user), db=Depends(get_db)):
|
||||||
|
p = await db.get(UserPrefs, user.id)
|
||||||
|
return {"prefs": json.loads(p.data) if p else {}}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/prefs")
|
||||||
|
async def set_prefs(body: dict, user: User = Depends(current_user), db=Depends(get_db)):
|
||||||
|
p = await db.get(UserPrefs, user.id)
|
||||||
|
if not p:
|
||||||
|
p = UserPrefs(user_id=user.id, data="{}")
|
||||||
|
db.add(p)
|
||||||
|
cur = json.loads(p.data)
|
||||||
|
cur.update(body)
|
||||||
|
p.data = json.dumps(cur)
|
||||||
|
await db.commit()
|
||||||
|
return {"prefs": cur}
|
||||||
|
|
||||||
|
|
||||||
|
# ============ 补齐:别名/设置/摘要/统计 ============
|
||||||
|
|
||||||
|
@router.post("/characters/{cid}/clone")
|
||||||
|
async def clone_alias(cid: int, user: User = Depends(current_user), db=Depends(get_db)):
|
||||||
|
return await clone_character(cid, user, db)
|
||||||
|
|
||||||
|
|
||||||
|
class SessionSettingsIn(BaseModel):
|
||||||
|
title: str | None = None
|
||||||
|
prompt_suffix: str | None = None
|
||||||
|
bg_url: str | None = None
|
||||||
|
pinned: bool | None = None
|
||||||
|
archived: bool | None = None
|
||||||
|
|
||||||
|
|
||||||
|
@router.patch("/sessions/{sid}/settings")
|
||||||
|
async def session_settings(sid: int, body: SessionSettingsIn,
|
||||||
|
user: User = Depends(current_user), db=Depends(get_db)):
|
||||||
|
s = await _own_session(db, user, sid)
|
||||||
|
for k, v in body.model_dump(exclude_none=True).items():
|
||||||
|
setattr(s, k, v)
|
||||||
|
await db.commit()
|
||||||
|
return {"ok": True}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/sessions/{sid}/summary")
|
||||||
|
async def summarize_session(sid: int, user: User = Depends(current_user),
|
||||||
|
db=Depends(get_db)):
|
||||||
|
"""自动摘要:把本会话剧情压缩成事件记忆(需要可用渠道)"""
|
||||||
|
s = await _own_session(db, user, sid)
|
||||||
|
msgs = await repos.MessageRepo.history(db, user.id, sid, limit=200)
|
||||||
|
text = "\n".join(_dec(user, m.content_enc) for m in msgs)
|
||||||
|
client, models = await _channel_for(db, user, s)
|
||||||
|
summary = await client.chat(models.get("extract") or "step-3.5-flash", [
|
||||||
|
{"role": "system", "content": "把以下对话/剧情压缩成简明的事件要点列表,"
|
||||||
|
"每条一行,保留关键事实与人物关系。只输出要点。"},
|
||||||
|
{"role": "user", "content": text[:12000]},
|
||||||
|
], temperature=0.2)
|
||||||
|
# 存成事件记忆
|
||||||
|
if s.character_id:
|
||||||
|
key = _key(user)
|
||||||
|
visible = await repos.SettingRepo.get(db, "admin_data_visible") == "true"
|
||||||
|
db.add(Memory(character_id=s.character_id, user_id=user.id, kind="event",
|
||||||
|
content_enc=repos.enc(None if visible else key, summary)))
|
||||||
|
await db.commit()
|
||||||
|
return {"summary": summary, "saved": bool(s.character_id)}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/admin/stats")
|
||||||
|
async def admin_stats(user: User = Depends(current_user), db=Depends(get_db)):
|
||||||
|
if not user.is_admin:
|
||||||
|
raise HTTPException(403, "需要管理员权限")
|
||||||
|
users = (await db.execute(select(User))).scalars().all()
|
||||||
|
sessions = (await db.execute(select(ChatSession))).scalars().all()
|
||||||
|
msgs = (await db.execute(select(Message))).scalars().all()
|
||||||
|
chars = (await db.execute(select(Character))).scalars().all()
|
||||||
|
by_mode = {}
|
||||||
|
for s in sessions:
|
||||||
|
by_mode[s.mode] = by_mode.get(s.mode, 0) + 1
|
||||||
|
return {"users": len(users), "sessions": len(sessions),
|
||||||
|
"messages": len(msgs), "characters": len(chars),
|
||||||
|
"by_mode": by_mode}
|
||||||
@@ -1,5 +1,7 @@
|
|||||||
from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker, AsyncSession
|
from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker, AsyncSession
|
||||||
|
from sqlalchemy import Integer, Boolean
|
||||||
from sqlalchemy.orm import DeclarativeBase
|
from sqlalchemy.orm import DeclarativeBase
|
||||||
|
import sqlalchemy as sqla
|
||||||
|
|
||||||
from ..core.config import settings
|
from ..core.config import settings
|
||||||
|
|
||||||
@@ -20,5 +22,30 @@ async def get_db():
|
|||||||
|
|
||||||
async def init_db():
|
async def init_db():
|
||||||
from ..models import entities # noqa: F401
|
from ..models import entities # noqa: F401
|
||||||
|
from sqlalchemy import text
|
||||||
async with engine.begin() as conn:
|
async with engine.begin() as conn:
|
||||||
await conn.run_sync(Base.metadata.create_all)
|
await conn.run_sync(Base.metadata.create_all)
|
||||||
|
# 轻量自动迁移:为已存在的表补齐新增列(SQLite)
|
||||||
|
if settings.database_url.startswith("sqlite"):
|
||||||
|
for table in Base.metadata.tables.values():
|
||||||
|
cols = {c["name"] for c in (await conn.execute(
|
||||||
|
text(f"PRAGMA table_info({table.name})"))).mappings()}
|
||||||
|
for col in table.columns:
|
||||||
|
if col.name not in cols:
|
||||||
|
coltype = col.type.compile()
|
||||||
|
# 默认值按类型给,避免旧行出现 '' 污染数值列
|
||||||
|
if isinstance(col.type, (sqla.Integer, sqla.Boolean)):
|
||||||
|
default = " DEFAULT 0"
|
||||||
|
elif col.server_default is not None:
|
||||||
|
default = f" DEFAULT '{col.server_default.arg}'"
|
||||||
|
elif col.nullable is False:
|
||||||
|
default = " DEFAULT ''"
|
||||||
|
else:
|
||||||
|
default = ""
|
||||||
|
await conn.execute(text(
|
||||||
|
f"ALTER TABLE {table.name} ADD COLUMN "
|
||||||
|
f"{col.name} {coltype}{default}"))
|
||||||
|
if isinstance(col.type, (sqla.Integer, sqla.Boolean)):
|
||||||
|
await conn.execute(text(
|
||||||
|
f"UPDATE {table.name} SET {col.name}=0 "
|
||||||
|
f"WHERE {col.name}=''"))
|
||||||
|
|||||||
+3
-2
@@ -3,11 +3,12 @@ from fastapi.responses import FileResponse, JSONResponse
|
|||||||
from fastapi.staticfiles import StaticFiles
|
from fastapi.staticfiles import StaticFiles
|
||||||
|
|
||||||
from .db.session import init_db
|
from .db.session import init_db
|
||||||
from .api.routers import auth, admin, channels, characters, chat
|
from .api.routers import auth, admin, channels, characters, chat, extra
|
||||||
|
|
||||||
app = FastAPI(title="Open Maopaoya", docs_url="/api/docs", openapi_url="/api/openapi.json")
|
app = FastAPI(title="Open Maopaoya", docs_url="/api/docs", openapi_url="/api/openapi.json")
|
||||||
|
|
||||||
for r in (auth.router, admin.router, channels.router, characters.router, chat.router):
|
for r in (auth.router, admin.router, channels.router, characters.router,
|
||||||
|
chat.router, extra.router):
|
||||||
app.include_router(r, prefix="/api")
|
app.include_router(r, prefix="/api")
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
+50
-2
@@ -62,8 +62,16 @@ class Character(Base):
|
|||||||
greeting: Mapped[str] = mapped_column(Text, default="") # 开场白
|
greeting: Mapped[str] = mapped_column(Text, default="") # 开场白
|
||||||
voice: Mapped[str] = mapped_column(String(64), default="tongtong") # 音色
|
voice: Mapped[str] = mapped_column(String(64), default="tongtong") # 音色
|
||||||
avatar_url: Mapped[str] = mapped_column(Text, default="")
|
avatar_url: Mapped[str] = mapped_column(Text, default="")
|
||||||
source: Mapped[str] = mapped_column(String(16), default="manual") # manual / novel_auto
|
source: Mapped[str] = mapped_column(String(16), default="manual") # manual / novel_auto / imported
|
||||||
novel_id: Mapped[int | None] = mapped_column(nullable=True)
|
novel_id: Mapped[int | None] = mapped_column(nullable=True)
|
||||||
|
# 广场/分享
|
||||||
|
is_public: Mapped[bool] = mapped_column(Boolean, default=False)
|
||||||
|
share_code: Mapped[str | None] = mapped_column(String(32), unique=True, nullable=True)
|
||||||
|
tags: Mapped[str] = mapped_column(String(256), default="") # 逗号分隔标签
|
||||||
|
usage_count: Mapped[int] = mapped_column(Integer, default=0)
|
||||||
|
# 公开卡片展示用的明文字段(发布时由作者密钥解密写入)
|
||||||
|
public_persona: Mapped[str] = mapped_column(Text, default="")
|
||||||
|
public_greeting: Mapped[str] = mapped_column(Text, default="")
|
||||||
created_at: Mapped[dt.datetime] = mapped_column(DateTime, default=now)
|
created_at: Mapped[dt.datetime] = mapped_column(DateTime, default=now)
|
||||||
|
|
||||||
|
|
||||||
@@ -91,7 +99,7 @@ class WorldbookEntry(Base):
|
|||||||
|
|
||||||
|
|
||||||
class ChatSession(Base):
|
class ChatSession(Base):
|
||||||
"""mode: roleplay(单角色) / novel(动态小说)"""
|
"""mode: roleplay(单角色) / novel(动态小说) / group(群聊) / call(语音通话)"""
|
||||||
__tablename__ = "chat_sessions"
|
__tablename__ = "chat_sessions"
|
||||||
id: Mapped[int] = mapped_column(primary_key=True)
|
id: Mapped[int] = mapped_column(primary_key=True)
|
||||||
user_id: Mapped[int] = mapped_column(ForeignKey("users.id"), index=True)
|
user_id: Mapped[int] = mapped_column(ForeignKey("users.id"), index=True)
|
||||||
@@ -100,6 +108,12 @@ class ChatSession(Base):
|
|||||||
character_id: Mapped[int | None] = mapped_column(nullable=True)
|
character_id: Mapped[int | None] = mapped_column(nullable=True)
|
||||||
novel_setting_enc: Mapped[str | None] = mapped_column(Text, nullable=True)
|
novel_setting_enc: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||||
channel_id: Mapped[int | None] = mapped_column(nullable=True)
|
channel_id: Mapped[int | None] = mapped_column(nullable=True)
|
||||||
|
# 扩展
|
||||||
|
group_member_ids: Mapped[str] = mapped_column(String(512), default="") # 逗号分隔角色id
|
||||||
|
prompt_suffix: Mapped[str] = mapped_column(Text, default="") # 用户自定义指令模板
|
||||||
|
bg_url: Mapped[str] = mapped_column(Text, default="") # 聊天背景
|
||||||
|
pinned: Mapped[bool] = mapped_column(Boolean, default=False) # 置顶
|
||||||
|
archived: Mapped[bool] = mapped_column(Boolean, default=False)
|
||||||
created_at: Mapped[dt.datetime] = mapped_column(DateTime, default=now)
|
created_at: Mapped[dt.datetime] = mapped_column(DateTime, default=now)
|
||||||
|
|
||||||
|
|
||||||
@@ -111,4 +125,38 @@ class Message(Base):
|
|||||||
role: Mapped[str] = mapped_column(String(16)) # user / assistant / system / narrator
|
role: Mapped[str] = mapped_column(String(16)) # user / assistant / system / narrator
|
||||||
content_enc: Mapped[str] = mapped_column(Text)
|
content_enc: Mapped[str] = mapped_column(Text)
|
||||||
speaker: Mapped[str | None] = mapped_column(String(128), nullable=True) # 小说模式中的说话角色
|
speaker: Mapped[str | None] = mapped_column(String(128), nullable=True) # 小说模式中的说话角色
|
||||||
|
# swipe 多版本:JSON 数组存备选回复,active 为当前选中下标
|
||||||
|
swipes_enc: Mapped[str | None] = mapped_column(Text, nullable=True) # JSON [str]
|
||||||
|
active_swipe: Mapped[int] = mapped_column(Integer, default=0)
|
||||||
|
reply_to_id: Mapped[int | None] = mapped_column(nullable=True) # 引用回复
|
||||||
|
starred: Mapped[bool] = mapped_column(Boolean, default=False) # 收藏
|
||||||
created_at: Mapped[dt.datetime] = mapped_column(DateTime, default=now)
|
created_at: Mapped[dt.datetime] = mapped_column(DateTime, default=now)
|
||||||
|
|
||||||
|
|
||||||
|
class Moment(Base):
|
||||||
|
"""角色朋友圈"""
|
||||||
|
__tablename__ = "moments"
|
||||||
|
id: Mapped[int] = mapped_column(primary_key=True)
|
||||||
|
user_id: Mapped[int] = mapped_column(ForeignKey("users.id"), index=True)
|
||||||
|
character_id: Mapped[int] = mapped_column(ForeignKey("characters.id"), index=True)
|
||||||
|
content_enc: Mapped[str] = mapped_column(Text)
|
||||||
|
image_url: Mapped[str] = mapped_column(Text, default="")
|
||||||
|
liked_by_me: Mapped[bool] = mapped_column(Boolean, default=False)
|
||||||
|
created_at: Mapped[dt.datetime] = mapped_column(DateTime, default=now)
|
||||||
|
|
||||||
|
|
||||||
|
class MomentComment(Base):
|
||||||
|
__tablename__ = "moment_comments"
|
||||||
|
id: Mapped[int] = mapped_column(primary_key=True)
|
||||||
|
moment_id: Mapped[int] = mapped_column(ForeignKey("moments.id"), index=True)
|
||||||
|
user_id: Mapped[int] = mapped_column(ForeignKey("users.id"), index=True)
|
||||||
|
author: Mapped[str] = mapped_column(String(128)) # "me" 或角色名
|
||||||
|
content_enc: Mapped[str] = mapped_column(Text)
|
||||||
|
created_at: Mapped[dt.datetime] = mapped_column(DateTime, default=now)
|
||||||
|
|
||||||
|
|
||||||
|
class UserPrefs(Base):
|
||||||
|
"""用户偏好:主题/字号/气泡样式等"""
|
||||||
|
__tablename__ = "user_prefs"
|
||||||
|
user_id: Mapped[int] = mapped_column(ForeignKey("users.id"), primary_key=True)
|
||||||
|
data: Mapped[str] = mapped_column(Text, default="{}") # JSON
|
||||||
|
|||||||
@@ -167,3 +167,27 @@ textarea { min-height: 90px; resize: vertical; }
|
|||||||
.card-grid { grid-template-columns: repeat(2, 1fr); }
|
.card-grid { grid-template-columns: repeat(2, 1fr); }
|
||||||
.bubble { max-width: 90%; }
|
.bubble { max-width: 90%; }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* 扩展组件 */
|
||||||
|
.swipe-bar { display: flex; align-items: center; gap: 6px; margin-top: 6px; font-size: 12px; }
|
||||||
|
.swipe-bar button { padding: 2px 10px; }
|
||||||
|
.acts { display: flex; gap: 4px; margin-top: 6px; opacity: .45; font-size: 12px; }
|
||||||
|
.acts button { background: none; border: none; color: var(--text); cursor: pointer; padding: 2px; }
|
||||||
|
.moment-img { width: 100%; max-height: 260px; object-fit: cover; border-radius: 12px; }
|
||||||
|
.tag { background: rgba(124,154,255,.18); border: 1px solid var(--stroke);
|
||||||
|
padding: 1px 8px; border-radius: 8px; font-size: 11px; color: var(--accent); }
|
||||||
|
.call-overlay { position: fixed; inset: 0; z-index: 95; background: rgba(10,10,25,.75);
|
||||||
|
-webkit-backdrop-filter: blur(24px); backdrop-filter: blur(24px);
|
||||||
|
display: flex; flex-direction: column; padding: calc(40px + env(safe-area-inset-top)) 16px 24px; }
|
||||||
|
.call-info { display: flex; flex-direction: column; align-items: center; gap: 6px; }
|
||||||
|
.call-info .dim { color: var(--dim); font-size: 13px; }
|
||||||
|
.avatar.big { width: 84px; height: 84px; font-size: 40px; border-radius: 50%;
|
||||||
|
background: var(--glass-strong); border: 1px solid var(--stroke);
|
||||||
|
display: flex; align-items: center; justify-content: center; overflow: hidden; }
|
||||||
|
.avatar.big img { width: 100%; height: 100%; object-fit: cover; }
|
||||||
|
#call-log { flex: 1; overflow-y: auto; margin: 16px 0; }
|
||||||
|
.call-input input { flex: 1; }
|
||||||
|
.new-char-banner { text-align: center; margin: 10px auto; padding: 8px 16px;
|
||||||
|
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; }
|
||||||
|
|||||||
+43
-6
@@ -28,6 +28,8 @@
|
|||||||
<button data-page="shelf" class="nav-btn active">📚 书架</button>
|
<button data-page="shelf" class="nav-btn active">📚 书架</button>
|
||||||
<button data-page="chars" class="nav-btn">🎭 角色</button>
|
<button data-page="chars" class="nav-btn">🎭 角色</button>
|
||||||
<button data-page="novel" class="nav-btn">📖 小说</button>
|
<button data-page="novel" class="nav-btn">📖 小说</button>
|
||||||
|
<button data-page="moments" class="nav-btn">🌟 朋友圈</button>
|
||||||
|
<button data-page="plaza" class="nav-btn">🏪 广场</button>
|
||||||
<button data-page="channels" class="nav-btn">🔌 渠道</button>
|
<button data-page="channels" class="nav-btn">🔌 渠道</button>
|
||||||
<button data-page="admin" class="nav-btn admin-only">⚙️ 后台</button>
|
<button data-page="admin" class="nav-btn admin-only">⚙️ 后台</button>
|
||||||
<span class="spacer"></span>
|
<span class="spacer"></span>
|
||||||
@@ -39,7 +41,14 @@
|
|||||||
<!-- 书架 -->
|
<!-- 书架 -->
|
||||||
<section id="page-shelf" class="page">
|
<section id="page-shelf" class="page">
|
||||||
<div class="row spread"><h2>书架</h2>
|
<div class="row spread"><h2>书架</h2>
|
||||||
<button class="btn primary" onclick="newRoleplaySession()">+ 新对话</button></div>
|
<div class="row">
|
||||||
|
<button class="btn" onclick="openSettings()">🎨 偏好</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="🔍 搜索所有会话内容"
|
||||||
|
style="flex:1" onkeydown="if(event.key==='Enter')searchAll()">
|
||||||
|
<button class="btn" onclick="searchAll()">搜</button></div>
|
||||||
|
<div id="search-results"></div>
|
||||||
<div id="shelf-list" class="card-grid"></div>
|
<div id="shelf-list" class="card-grid"></div>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
@@ -58,9 +67,35 @@
|
|||||||
<div id="novel-list" class="card-grid"></div>
|
<div id="novel-list" class="card-grid"></div>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
|
<!-- 朋友圈 -->
|
||||||
|
<section id="page-moments" class="page hidden">
|
||||||
|
<div class="row spread"><h2>🌟 角色朋友圈</h2>
|
||||||
|
<button class="btn primary" onclick="pickMomentChar()">让角色发一条</button></div>
|
||||||
|
<div id="moment-feed"></div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<!-- 广场 -->
|
||||||
|
<section id="page-plaza" class="page hidden">
|
||||||
|
<div class="row spread"><h2>🏪 角色广场</h2>
|
||||||
|
<div class="row"><input id="plaza-q" placeholder="搜索公开角色" onkeydown="if(event.key==='Enter')loadPlaza()">
|
||||||
|
<button class="btn" onclick="loadPlaza()">搜</button>
|
||||||
|
<button class="btn" onclick="importByCode()">导入分享码</button></div></div>
|
||||||
|
<div id="plaza-list" class="card-grid"></div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<!-- 通话浮层 -->
|
||||||
|
<div id="call-overlay" class="call-overlay hidden">
|
||||||
|
<div class="call-info"><div id="call-avatar" class="avatar big"></div>
|
||||||
|
<b id="call-name"></b><span class="dim" id="call-timer">00:00</span></div>
|
||||||
|
<div id="call-log"></div>
|
||||||
|
<div class="call-input row">
|
||||||
|
<input id="call-text" placeholder="说话(文字模拟通话)…" onkeydown="if(event.key==='Enter')callSend()">
|
||||||
|
<button class="btn primary" onclick="callSend()">🎙</button>
|
||||||
|
<button class="btn danger" onclick="callEnd()">挂断</button></div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<!-- 渠道 -->
|
<!-- 渠道 -->
|
||||||
<section id="page-channels" class="page hidden">
|
<section id="page-channels" class="page hidden"> <div class="row spread"><h2>模型渠道</h2>
|
||||||
<div class="row spread"><h2>模型渠道</h2>
|
|
||||||
<button class="btn primary" onclick="editChannel(null)">+ 添加渠道</button></div>
|
<button class="btn primary" onclick="editChannel(null)">+ 添加渠道</button></div>
|
||||||
<div id="channel-list" class="card-grid"></div>
|
<div id="channel-list" class="card-grid"></div>
|
||||||
</section>
|
</section>
|
||||||
@@ -85,9 +120,11 @@
|
|||||||
<button class="nav-btn" onclick="backToShelf()">←</button>
|
<button class="nav-btn" onclick="backToShelf()">←</button>
|
||||||
<b id="chat-title">会话</b>
|
<b id="chat-title">会话</b>
|
||||||
<span class="spacer"></span>
|
<span class="spacer"></span>
|
||||||
<button class="nav-btn" onclick="openDrawer('memory')">🧠 记忆</button>
|
<button class="nav-btn" onclick="openDrawer('memory')">🧠</button>
|
||||||
<button class="nav-btn" onclick="openDrawer('worldbook')">🌍 世界书</button>
|
<button class="nav-btn" onclick="openDrawer('worldbook')">🌍</button>
|
||||||
<button class="nav-btn" onclick="openDrawer('card')">🎭 角色</button>
|
<button class="nav-btn" onclick="openDrawer('card')">🎭</button>
|
||||||
|
<button class="nav-btn" onclick="startCall(CUR.sessionId)">📞</button>
|
||||||
|
<button class="nav-btn" onclick="exportSession(CUR.sessionId)">⬇️</button>
|
||||||
</header>
|
</header>
|
||||||
<div id="chat-log"></div>
|
<div id="chat-log"></div>
|
||||||
<div class="glass-inputbar">
|
<div class="glass-inputbar">
|
||||||
|
|||||||
+216
-2
@@ -50,12 +50,22 @@ async function enterApp() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/* ---------- 导航 ---------- */
|
/* ---------- 导航 ---------- */
|
||||||
|
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 =>
|
document.querySelectorAll(".nav-btn[data-page]").forEach(b =>
|
||||||
b.onclick = () => {
|
b.onclick = () => {
|
||||||
document.querySelectorAll(".nav-btn[data-page]").forEach(x => x.classList.remove("active"));
|
document.querySelectorAll(".nav-btn[data-page]").forEach(x => x.classList.remove("active"));
|
||||||
b.classList.add("active");
|
b.classList.add("active");
|
||||||
document.querySelectorAll(".page").forEach(p => p.classList.add("hidden"));
|
document.querySelectorAll(".page").forEach(p => p.classList.add("hidden"));
|
||||||
$("#page-" + b.dataset.page).classList.remove("hidden");
|
$("#page-" + b.dataset.page).classList.remove("hidden");
|
||||||
|
(PAGE_LOADERS[b.dataset.page] || (() => {}))();
|
||||||
});
|
});
|
||||||
|
|
||||||
/* ---------- 书架 / 会话 ---------- */
|
/* ---------- 书架 / 会话 ---------- */
|
||||||
@@ -93,6 +103,7 @@ async function loadCharacters() {
|
|||||||
<div class="row" style="margin-top:8px">
|
<div class="row" style="margin-top:8px">
|
||||||
<button class="btn small" onclick="openChat(null,'roleplay',${c.id})">对话</button>
|
<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="editCharacter(${c.id})">编辑</button>
|
||||||
|
<button class="btn small" onclick="shareCharacter(${c.id})">分享</button>
|
||||||
<button class="btn small danger" onclick="delCharacter(${c.id})">删</button>
|
<button class="btn small danger" onclick="delCharacter(${c.id})">删</button>
|
||||||
</div></div>`).join("") || '<p class="hint">还没有角色。</p>';
|
</div></div>`).join("") || '<p class="hint">还没有角色。</p>';
|
||||||
}
|
}
|
||||||
@@ -161,14 +172,32 @@ function backToShelf() {
|
|||||||
}
|
}
|
||||||
function renderBubble(m) {
|
function renderBubble(m) {
|
||||||
const cls = m.role === "user" ? "user" : "ai";
|
const cls = m.role === "user" ? "user" : "ai";
|
||||||
|
const sw = m.swipe_count || 0;
|
||||||
return `<div class="bubble ${cls}" data-mid="${m.id}">
|
return `<div class="bubble ${cls}" data-mid="${m.id}">
|
||||||
${m.speaker ? `<div class="speaker">${esc(m.speaker)}</div>` : ""}${esc(m.content)}
|
${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">
|
<div class="acts">
|
||||||
<button onclick="editMsg(${m.id})">✏️</button>
|
<button onclick="editMsg(${m.id})">✏️</button>
|
||||||
<button onclick="delMsg(${m.id})">🗑</button>
|
<button onclick="delMsg(${m.id})">🗑</button>
|
||||||
${m.role !== "user" ? `<button onclick="ttsMsg(${m.id},this)">🔊</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>`;
|
</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() {
|
async function sendMsg() {
|
||||||
const input = $("#chat-input");
|
const input = $("#chat-input");
|
||||||
const text = input.value.trim();
|
const text = input.value.trim();
|
||||||
@@ -181,7 +210,8 @@ async function sendMsg() {
|
|||||||
$("#chat-log").appendChild(thinking);
|
$("#chat-log").appendChild(thinking);
|
||||||
$("#chat-log").scrollTop = 1e9;
|
$("#chat-log").scrollTop = 1e9;
|
||||||
try {
|
try {
|
||||||
const d = await api(`/sessions/${CUR.sessionId}/send`, { method: "POST", body: { content: text } });
|
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 });
|
thinking.innerHTML = renderBubble({ id: d.message_id, role: "assistant", content: d.reply });
|
||||||
d.new_characters.forEach(c => {
|
d.new_characters.forEach(c => {
|
||||||
$("#chat-log").insertAdjacentHTML("beforeend",
|
$("#chat-log").insertAdjacentHTML("beforeend",
|
||||||
@@ -447,6 +477,190 @@ async function revokeGrant(cid, uid) {
|
|||||||
adminGrantChannel();
|
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");
|
function openModal(html) { $("#modal").innerHTML = html; $("#modal").classList.remove("hidden");
|
||||||
$("#modal-mask").classList.remove("hidden"); }
|
$("#modal-mask").classList.remove("hidden"); }
|
||||||
|
|||||||
Reference in New Issue
Block a user