Compare commits
10
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
388e9a5605 | ||
|
|
8af6f890d5 | ||
|
|
998766c75c | ||
|
|
da01294e38 | ||
|
|
ea7c2529e9 | ||
|
|
513b53672e | ||
|
|
11978abeb0 | ||
|
|
495083f9b4 | ||
|
|
18ae7e1f9d | ||
|
|
778854796a |
@@ -4,3 +4,6 @@ __pycache__/
|
||||
.venv/
|
||||
*.pyc
|
||||
.alembic/
|
||||
node_modules/
|
||||
.uvcache/
|
||||
frontend-uni/dist/
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 Open Maopaoya Contributors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -1,35 +1,26 @@
|
||||
# Open Maopaoya 🦆
|
||||
# 🦆 Open Maopaoya
|
||||
|
||||
冒泡鸭开源复刻:AI 角色扮演平台 + 动态小说引擎(AI 编剧自主扩列建角色)。
|
||||
冒泡鸭(阶跃星辰角色扮演 App,2025-11 停运)的开源复刻。
|
||||
|
||||
## 快速启动
|
||||
单角色扮演 · 动态小说引擎(AI 自主扩列建档生成立绘)· 群聊 · 角色朋友圈 · 语音通话 ·
|
||||
消息 Swipe 多版本 · 角色广场与分享码 · 多模型渠道 · 多用户权限 · AES 数据加密 ·
|
||||
uni-app 前端(H5/小程序/App 一套代码)· 商业化 v1 API 预留。
|
||||
|
||||
## 快速开始
|
||||
```bash
|
||||
uv sync
|
||||
uv run uvicorn app.main:app --port 8820
|
||||
# 打开 http://localhost:8820
|
||||
# 默认管理员: admin / maopaoya-admin(首次登录后请改)
|
||||
uv sync # 依赖(可选 --extra mysql / --extra postgres 切商用库)
|
||||
uvicorn app.main:app --port 46711
|
||||
```
|
||||
|
||||
## 功能
|
||||
- 单角色扮演:角色卡 / 记忆(完全透明可篡改)/ 世界书 / TTS
|
||||
- 动态小说:AI 自主引入新角色 → 自动建档 → 生成立绘 → 注册世界书 → 新角色可单独对话
|
||||
- 多渠道:OpenAI 兼容 API,内置 Step Plan 预设(叙事/抽取 step-3.5-flash,TTS stepaudio-2.5-tts,生图槽位留空可接任意兼容接口)
|
||||
- 多用户:注册/注销开关、BYOK 开关、渠道分配、用户数据硬隔离
|
||||
- 管理后台:用户管理、权限开关、「数据可见」开关
|
||||
- 数据可见 OFF → 用户数据 AES-GCM 加密落库(密钥由用户密码派生,服务器不存明文),管理员只读密文
|
||||
- OFF→ON → 存量密文在用户下次登录时自动解密转明文,静默不告知用户
|
||||
- 修改密码时自动重加密;注销删除全部数据不可恢复
|
||||
|
||||
## 配置(.env,均带 OMO_ 前缀)
|
||||
首个管理员凭环境变量注入:
|
||||
```
|
||||
OMO_DATABASE_URL=sqlite+aiosqlite:///./data.db # 商用切: mysql+aiomysql://... / postgresql+asyncpg://...
|
||||
OMO_JWT_SECRET=change-me
|
||||
OMO_FIRST_ADMIN_USER=admin
|
||||
OMO_FIRST_ADMIN_PASS=maopaoya-admin
|
||||
```
|
||||
|
||||
## 商用扩展
|
||||
- 数据库切换只需改 DATABASE_URL(可选依赖: `uv sync --extra mysql` 或 `--extra postgres`)
|
||||
- 数据访问统一走 `app/db/repos.py` 仓储层
|
||||
- Alembic 迁移: `uv run alembic init migrations` 后接入 `app.db.session.Base.metadata`
|
||||
## 结构
|
||||
- `app/` FastAPI 后端(路由 / 仓储层 / 加密 / LLM 服务)
|
||||
- `web-legacy/` 旧版单页前端
|
||||
- `frontend-uni/` uni-app Vue3 前端(`npm run build:h5`)
|
||||
|
||||
## 协议
|
||||
MIT
|
||||
|
||||
+20
-3
@@ -1,5 +1,6 @@
|
||||
"""聊天主链路:单角色扮演 + 动态小说两种模式。上下文不做节省。"""
|
||||
import datetime as dt
|
||||
import json
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from fastapi.responses import Response
|
||||
@@ -31,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):
|
||||
@@ -143,8 +145,22 @@ async def get_messages(sid: int, user: User = Depends(current_user),
|
||||
db=Depends(get_db)):
|
||||
await _own_session(db, user, sid)
|
||||
rows = await repos.MessageRepo.history(db, user.id, sid, limit=500)
|
||||
return {"messages": [{"id": m.id, "role": m.role, "speaker": m.speaker,
|
||||
"content": _dec(user, m.content_enc)} for m in rows]}
|
||||
out = []
|
||||
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"]
|
||||
d["swipe_count"] = len(sw)
|
||||
out.append(d)
|
||||
return {"messages": out}
|
||||
|
||||
|
||||
@router.post("/sessions/{sid}/send")
|
||||
@@ -155,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)
|
||||
|
||||
@@ -0,0 +1,591 @@
|
||||
"""扩展功能:群聊 / 朋友圈 / 语音通话 / 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.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")
|
||||
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}
|
||||
+165
@@ -0,0 +1,165 @@
|
||||
"""商业化预留 v1 API:API Key 认证 + 限流 + 用量账本。
|
||||
|
||||
设计原则:
|
||||
- /v1/* 稳定契约:只加字段不改语义,向前兼容
|
||||
- key 只存 sha256;明文只返回一次
|
||||
- scope 分级:chat / full;rate_limit 按 key 限流
|
||||
- 用量落 usage_logs,将来接计费系统零改造
|
||||
"""
|
||||
import hashlib
|
||||
import secrets
|
||||
import time
|
||||
import datetime as dt
|
||||
from collections import defaultdict, deque
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request
|
||||
from pydantic import BaseModel
|
||||
from sqlalchemy import select
|
||||
|
||||
from ..db.session import get_db
|
||||
from ..db import repos
|
||||
from ..models.entities import ApiKey, UsageLog, User, Message
|
||||
from ..api.routers.auth import current_user
|
||||
from ..api.routers.chat import (_dec, _enc, _own_session, _key, build_context,
|
||||
_channel_for)
|
||||
|
||||
router = APIRouter(prefix="/v1", tags=["v1-commercial"])
|
||||
|
||||
|
||||
# ---------- API Key 认证 ----------
|
||||
|
||||
def _hash_key(raw: str) -> str:
|
||||
return hashlib.sha256(raw.encode()).hexdigest()
|
||||
|
||||
|
||||
async def api_key_auth(request: Request, db=Depends(get_db)) -> tuple[User, ApiKey]:
|
||||
raw = request.headers.get("X-API-Key", "")
|
||||
if not raw:
|
||||
raise HTTPException(401, "缺少 X-API-Key")
|
||||
row = (await db.execute(select(ApiKey).where(
|
||||
ApiKey.key_hash == _hash_key(raw), ApiKey.revoked == False))).scalar_one_or_none()
|
||||
if not row:
|
||||
raise HTTPException(401, "API Key 无效或已吊销")
|
||||
user = await db.get(User, row.user_id)
|
||||
if not user or not user.is_active:
|
||||
raise HTTPException(401, "账户无效")
|
||||
return user, row
|
||||
|
||||
|
||||
# ---------- 限流(滑动窗口,进程内;多实例部署换 Redis) ----------
|
||||
|
||||
_buckets: dict[int, deque] = defaultdict(deque)
|
||||
|
||||
|
||||
def check_rate_limit(key_row: ApiKey):
|
||||
b = _buckets[key_row.id]
|
||||
now = time.time()
|
||||
while b and b[0] < now - 60:
|
||||
b.popleft()
|
||||
if len(b) >= key_row.rate_limit:
|
||||
raise HTTPException(429, f"超过限流 {key_row.rate_limit}/min")
|
||||
b.append(now)
|
||||
|
||||
|
||||
async def log_usage(db, user: User, key_row: ApiKey, endpoint: str):
|
||||
db.add(UsageLog(user_id=user.id, api_key_id=key_row.id,
|
||||
endpoint=endpoint, cost_units=1))
|
||||
key_row.last_used_at = dt.datetime.utcnow()
|
||||
await db.commit()
|
||||
|
||||
|
||||
# ---------- Key 管理(JWT 鉴权) ----------
|
||||
|
||||
|
||||
class KeyIn(BaseModel):
|
||||
name: str = "default"
|
||||
scope: str = "chat" # chat / full
|
||||
rate_limit: int = 60
|
||||
|
||||
|
||||
@router.post("/keys")
|
||||
async def create_key(body: KeyIn, user: User = Depends(current_user),
|
||||
db=Depends(get_db)):
|
||||
raw = "omk_" + secrets.token_urlsafe(24)
|
||||
row = ApiKey(user_id=user.id, key_hash=_hash_key(raw),
|
||||
name=body.name, scope=body.scope, rate_limit=body.rate_limit)
|
||||
db.add(row)
|
||||
await db.commit()
|
||||
return {"key": raw, "id": row.id, "notice": "明文仅此一次,请立即保存"}
|
||||
|
||||
|
||||
@router.get("/keys")
|
||||
async def list_keys(user: User = Depends(current_user), db=Depends(get_db)):
|
||||
rows = (await db.execute(select(ApiKey).where(
|
||||
ApiKey.user_id == user.id, ApiKey.revoked == False))).scalars().all()
|
||||
return {"keys": [{"id": k.id, "name": k.name, "scope": k.scope,
|
||||
"rate_limit": k.rate_limit,
|
||||
"last_used": str(k.last_used_at or "")} for k in rows]}
|
||||
|
||||
|
||||
@router.delete("/keys/{kid}")
|
||||
async def revoke_key(kid: int, user: User = Depends(current_user), db=Depends(get_db)):
|
||||
row = await db.get(ApiKey, kid)
|
||||
if not row or row.user_id != user.id:
|
||||
raise HTTPException(404, "不存在")
|
||||
row.revoked = True
|
||||
await db.commit()
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@router.get("/usage")
|
||||
async def my_usage(user: User = Depends(current_user), db=Depends(get_db)):
|
||||
rows = (await db.execute(select(UsageLog).where(
|
||||
UsageLog.user_id == user.id).order_by(UsageLog.id.desc()).limit(500))).scalars().all()
|
||||
by_ep = {}
|
||||
for r in rows:
|
||||
by_ep[r.endpoint] = by_ep.get(r.endpoint, 0) + 1
|
||||
return {"recent_calls": len(rows), "by_endpoint": by_ep}
|
||||
|
||||
|
||||
# ---------- v1 稳定接口 ----------
|
||||
|
||||
|
||||
@router.get("/ping")
|
||||
async def ping():
|
||||
"""健康检查,无鉴权"""
|
||||
return {"ok": True, "service": "open-maopaoya", "version": "v1"}
|
||||
|
||||
|
||||
@router.get("/characters")
|
||||
async def v1_characters(pair: tuple = Depends(api_key_auth), db=Depends(get_db)):
|
||||
user, key_row = pair
|
||||
if key_row.scope != "full":
|
||||
raise HTTPException(403, "scope 不足,需要 full")
|
||||
from ..db.repos import dec
|
||||
rows = await repos.CharacterRepo.list_for(db, user.id)
|
||||
await log_usage(db, user, key_row, "/v1/characters")
|
||||
k = _key(user)
|
||||
return {"data": [{"id": c.id, "name": c.name,
|
||||
"persona": dec(k, c.persona), "voice": c.voice} for c in rows]}
|
||||
|
||||
|
||||
class V1ChatIn(BaseModel):
|
||||
session_id: int
|
||||
content: str
|
||||
|
||||
|
||||
@router.post("/chat")
|
||||
async def v1_chat(body: V1ChatIn, pair: tuple = Depends(api_key_auth),
|
||||
db=Depends(get_db)):
|
||||
"""以 API Key 驱动一次对话(走用户自己的渠道配置)"""
|
||||
user, key_row = pair
|
||||
check_rate_limit(key_row)
|
||||
s = await _own_session(db, user, body.session_id)
|
||||
db.add(Message(session_id=s.id, user_id=user.id, role="user",
|
||||
content_enc=_enc(user, body.content)))
|
||||
await db.commit()
|
||||
history = await repos.MessageRepo.history(db, user.id, s.id, limit=80)
|
||||
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)
|
||||
db.add(Message(session_id=s.id, user_id=user.id, role="assistant",
|
||||
content_enc=_enc(user, reply)))
|
||||
await log_usage(db, user, key_row, "/v1/chat")
|
||||
await db.commit()
|
||||
return {"reply": reply, "session_id": s.id}
|
||||
+13
-2
@@ -36,11 +36,18 @@ class SettingRepo:
|
||||
"allow_byok": "true",
|
||||
"admin_data_visible": "true", # 默认明文;关闭后加密落库
|
||||
}
|
||||
_cache: dict | None = None # 进程内缓存(读多写少),写入即失效
|
||||
|
||||
@staticmethod
|
||||
async def get(db: AsyncSession, key: str) -> str:
|
||||
v = (await db.execute(select(E.SiteSetting).where(E.SiteSetting.key == key))).scalar_one_or_none()
|
||||
return v.value if v else SettingRepo.DEFAULTS.get(key, "")
|
||||
cache = SettingRepo._cache
|
||||
if cache is not None:
|
||||
return cache.get(key, SettingRepo.DEFAULTS.get(key, ""))
|
||||
rows = (await db.execute(select(E.SiteSetting))).scalars().all()
|
||||
cache = dict(SettingRepo.DEFAULTS)
|
||||
cache.update({r.key: r.value for r in rows})
|
||||
SettingRepo._cache = cache
|
||||
return cache.get(key, "")
|
||||
|
||||
@staticmethod
|
||||
async def set(db: AsyncSession, key: str, value: str):
|
||||
@@ -50,12 +57,16 @@ class SettingRepo:
|
||||
else:
|
||||
db.add(E.SiteSetting(key=key, value=value))
|
||||
await db.commit()
|
||||
SettingRepo._cache = None
|
||||
|
||||
@staticmethod
|
||||
async def all(db: AsyncSession) -> dict:
|
||||
if SettingRepo._cache is not None:
|
||||
return SettingRepo._cache
|
||||
rows = (await db.execute(select(E.SiteSetting))).scalars().all()
|
||||
out = dict(SettingRepo.DEFAULTS)
|
||||
out.update({r.key: r.value for r in rows})
|
||||
SettingRepo._cache = out
|
||||
return out
|
||||
|
||||
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker, AsyncSession
|
||||
from sqlalchemy import Integer, Boolean
|
||||
from sqlalchemy.orm import DeclarativeBase
|
||||
import sqlalchemy as sqla
|
||||
|
||||
from ..core.config import settings
|
||||
|
||||
@@ -20,5 +22,36 @@ async def get_db():
|
||||
|
||||
async def init_db():
|
||||
from ..models import entities # noqa: F401
|
||||
from sqlalchemy import text
|
||||
async with engine.begin() as conn:
|
||||
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}=''"))
|
||||
# 旧表补建索引(create_all 只对新建表生效)
|
||||
for table in Base.metadata.tables.values():
|
||||
for idx in table.indexes:
|
||||
await conn.execute(text(
|
||||
f'CREATE INDEX IF NOT EXISTS "{idx.name}" ON "{table.name}" '
|
||||
f'({", ".join(f"\'{c.name}\'" for c in idx.columns)})'))
|
||||
|
||||
+11
-2
@@ -3,11 +3,20 @@ from fastapi.responses import FileResponse, JSONResponse
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
|
||||
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
|
||||
from .api import v1
|
||||
|
||||
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):
|
||||
# 性能:响应压缩
|
||||
from starlette.middleware.gzip import GZipMiddleware
|
||||
app.add_middleware(GZipMiddleware, minimum_size=1024)
|
||||
|
||||
# API 路由(/v1 为商业化稳定契约,独立前缀不随 /api 演进)
|
||||
app.include_router(v1.router)
|
||||
|
||||
for r in (auth.router, admin.router, channels.router, characters.router,
|
||||
chat.router, extra.router):
|
||||
app.include_router(r, prefix="/api")
|
||||
|
||||
|
||||
|
||||
+83
-3
@@ -2,7 +2,7 @@
|
||||
import datetime as dt
|
||||
|
||||
from sqlalchemy import (String, Boolean, Integer, Text, DateTime, ForeignKey,
|
||||
JSON, UniqueConstraint)
|
||||
JSON, UniqueConstraint, Index)
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from ..db.session import Base
|
||||
@@ -62,14 +62,23 @@ class Character(Base):
|
||||
greeting: Mapped[str] = mapped_column(Text, default="") # 开场白
|
||||
voice: Mapped[str] = mapped_column(String(64), default="tongtong") # 音色
|
||||
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)
|
||||
# 广场/分享
|
||||
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)
|
||||
|
||||
|
||||
class Memory(Base):
|
||||
"""角色记忆,双轨: fact(设定类) / event(事件类)。全部可查可改。"""
|
||||
__tablename__ = "memories"
|
||||
__table_args__ = (Index("ix_mem_user_char", "user_id", "character_id"),)
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
character_id: Mapped[int] = mapped_column(ForeignKey("characters.id"), index=True)
|
||||
user_id: Mapped[int] = mapped_column(ForeignKey("users.id"), index=True)
|
||||
@@ -91,8 +100,9 @@ class WorldbookEntry(Base):
|
||||
|
||||
|
||||
class ChatSession(Base):
|
||||
"""mode: roleplay(单角色) / novel(动态小说)"""
|
||||
"""mode: roleplay(单角色) / novel(动态小说) / group(群聊) / call(语音通话)"""
|
||||
__tablename__ = "chat_sessions"
|
||||
__table_args__ = (Index("ix_sess_user_pin", "user_id", "pinned", "id"),)
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
user_id: Mapped[int] = mapped_column(ForeignKey("users.id"), index=True)
|
||||
mode: Mapped[str] = mapped_column(String(16), default="roleplay")
|
||||
@@ -100,15 +110,85 @@ class ChatSession(Base):
|
||||
character_id: Mapped[int | None] = mapped_column(nullable=True)
|
||||
novel_setting_enc: Mapped[str | None] = mapped_column(Text, 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)
|
||||
|
||||
|
||||
class Message(Base):
|
||||
__tablename__ = "messages"
|
||||
__table_args__ = (
|
||||
Index("ix_msg_sess_user_time", "session_id", "user_id", "id"),
|
||||
Index("ix_msg_user_time", "user_id", "id"),
|
||||
)
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
session_id: Mapped[int] = mapped_column(ForeignKey("chat_sessions.id"), index=True)
|
||||
user_id: Mapped[int] = mapped_column(ForeignKey("users.id"), index=True)
|
||||
role: Mapped[str] = mapped_column(String(16)) # user / assistant / system / narrator
|
||||
content_enc: Mapped[str] = mapped_column(Text)
|
||||
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)
|
||||
|
||||
|
||||
class Moment(Base):
|
||||
"""角色朋友圈"""
|
||||
__tablename__ = "moments"
|
||||
__table_args__ = (Index("ix_moment_user_time", "user_id", "id"),)
|
||||
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
|
||||
|
||||
|
||||
class ApiKey(Base):
|
||||
"""商业化预留:第三方 API 密钥。scope: chat / characters / full"""
|
||||
__tablename__ = "api_keys"
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
user_id: Mapped[int] = mapped_column(ForeignKey("users.id"), index=True)
|
||||
key_hash: Mapped[str] = mapped_column(String(64), unique=True) # sha256,不存明文
|
||||
name: Mapped[str] = mapped_column(String(128), default="default")
|
||||
scope: Mapped[str] = mapped_column(String(32), default="chat") # chat / full
|
||||
rate_limit: Mapped[int] = mapped_column(Integer, default=60) # req/min
|
||||
revoked: Mapped[bool] = mapped_column(Boolean, default=False)
|
||||
created_at: Mapped[dt.datetime] = mapped_column(DateTime, default=now)
|
||||
last_used_at: Mapped[dt.datetime | None] = mapped_column(DateTime, nullable=True)
|
||||
|
||||
|
||||
class UsageLog(Base):
|
||||
"""商业化预留:API 用量账本(计费/配额的数据底座)"""
|
||||
__tablename__ = "usage_logs"
|
||||
__table_args__ = (Index("ix_usage_user_time", "user_id", "id"),)
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
user_id: Mapped[int] = mapped_column(ForeignKey("users.id"), index=True)
|
||||
api_key_id: Mapped[int | None] = mapped_column(nullable=True)
|
||||
endpoint: Mapped[str] = mapped_column(String(128))
|
||||
cost_units: Mapped[int] = mapped_column(Integer, default=1) # 计费单位(暂为次数)
|
||||
|
||||
+43
-29
@@ -1,8 +1,23 @@
|
||||
"""OpenAI 兼容客户端:聊天、生图、TTS,全部按渠道转发。"""
|
||||
"""OpenAI 兼容客户端:聊天、生图、TTS,全部按渠道转发。
|
||||
|
||||
性能:全局共享 AsyncClient(连接池复用,避免每请求握手)。
|
||||
"""
|
||||
import base64
|
||||
|
||||
import httpx
|
||||
|
||||
# 进程级共享连接池; comercial 场景下量大可调 max_connections
|
||||
_shared_client: httpx.AsyncClient | None = None
|
||||
|
||||
|
||||
def get_http() -> httpx.AsyncClient:
|
||||
global _shared_client
|
||||
if _shared_client is None or _shared_client.is_closed:
|
||||
_shared_client = httpx.AsyncClient(
|
||||
timeout=httpx.Timeout(180, connect=10),
|
||||
limits=httpx.Limits(max_connections=100, max_keepalive_connections=20))
|
||||
return _shared_client
|
||||
|
||||
|
||||
class LLMClient:
|
||||
def __init__(self, base_url: str, api_key: str):
|
||||
@@ -11,39 +26,38 @@ class LLMClient:
|
||||
|
||||
async def chat(self, model: str, messages: list[dict], temperature: float = 0.9,
|
||||
max_tokens: int = 2048) -> str:
|
||||
async with httpx.AsyncClient(timeout=120) as c:
|
||||
r = await c.post(f"{self.base_url}/chat/completions",
|
||||
headers={"Authorization": f"Bearer {self.api_key}"},
|
||||
json={"model": model, "messages": messages,
|
||||
"temperature": temperature, "max_tokens": max_tokens})
|
||||
r.raise_for_status()
|
||||
return r.json()["choices"][0]["message"]["content"] or ""
|
||||
r = await get_http().post(
|
||||
f"{self.base_url}/chat/completions",
|
||||
headers={"Authorization": f"Bearer {self.api_key}"},
|
||||
json={"model": model, "messages": messages,
|
||||
"temperature": temperature, "max_tokens": max_tokens})
|
||||
r.raise_for_status()
|
||||
return r.json()["choices"][0]["message"]["content"] or ""
|
||||
|
||||
async def image(self, model: str, prompt: str, size: str = "1024x1024") -> str:
|
||||
async with httpx.AsyncClient(timeout=180) as c:
|
||||
r = await c.post(f"{self.base_url}/images/generations",
|
||||
headers={"Authorization": f"Bearer {self.api_key}"},
|
||||
json={"model": model, "prompt": prompt,
|
||||
"size": size, "n": 1, "response_format": "url"})
|
||||
r.raise_for_status()
|
||||
d = r.json()["data"][0]
|
||||
return d.get("url") or ("data:image/png;base64," + d.get("b64_json", ""))
|
||||
r = await get_http().post(
|
||||
f"{self.base_url}/images/generations",
|
||||
headers={"Authorization": f"Bearer {self.api_key}"},
|
||||
json={"model": model, "prompt": prompt,
|
||||
"size": size, "n": 1, "response_format": "url"})
|
||||
r.raise_for_status()
|
||||
d = r.json()["data"][0]
|
||||
return d.get("url") or ("data:image/png;base64," + d.get("b64_json", ""))
|
||||
|
||||
async def tts(self, model: str, text: str, voice: str) -> bytes:
|
||||
"""优先 OpenAI 兼容 /audio/speech;失败回落阶跃 stepaudio TTS 格式。"""
|
||||
async with httpx.AsyncClient(timeout=120) as c:
|
||||
headers = {"Authorization": f"Bearer {self.api_key}"}
|
||||
try:
|
||||
r = await c.post(f"{self.base_url}/audio/speech", headers=headers,
|
||||
json={"model": model, "input": text, "voice": voice})
|
||||
r.raise_for_status()
|
||||
return r.content
|
||||
except httpx.HTTPError:
|
||||
r = await c.post(f"{self.base_url}/audio/speech", headers=headers,
|
||||
json={"model": model, "text": text, "voice": voice,
|
||||
"response_format": "wav"})
|
||||
r.raise_for_status()
|
||||
return r.content
|
||||
headers = {"Authorization": f"Bearer {self.api_key}"}
|
||||
try:
|
||||
r = await get_http().post(f"{self.base_url}/audio/speech", headers=headers,
|
||||
json={"model": model, "input": text, "voice": voice})
|
||||
r.raise_for_status()
|
||||
return r.content
|
||||
except httpx.HTTPError:
|
||||
r = await get_http().post(f"{self.base_url}/audio/speech", headers=headers,
|
||||
json={"model": model, "text": text, "voice": voice,
|
||||
"response_format": "wav"})
|
||||
r.raise_for_status()
|
||||
return r.content
|
||||
|
||||
async def ping(self, model: str) -> tuple[bool, str]:
|
||||
try:
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no,viewport-fit=cover" />
|
||||
<title>Open Maopaoya</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
<script type="module" src="/src/main.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
Generated
+12305
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"name": "omo-uni",
|
||||
"version": "1.0.0",
|
||||
"scripts": {
|
||||
"dev:h5": "uni",
|
||||
"build:h5": "uni build"
|
||||
},
|
||||
"dependencies": {
|
||||
"@dcloudio/uni-app": "3.0.0-alpha-5030620261112001",
|
||||
"@dcloudio/uni-components": "3.0.0-alpha-5030620261112001",
|
||||
"@dcloudio/uni-h5": "3.0.0-alpha-5030620261112001",
|
||||
"vue": "^3.4.21",
|
||||
"vuex": "^4.1.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@dcloudio/uni-automator": "3.0.0-alpha-5030620261112001",
|
||||
"@dcloudio/vite-plugin-uni": "3.0.0-alpha-5030620261112001",
|
||||
"vite": "^5.2.8"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
<script>
|
||||
export default { onLaunch() {} };
|
||||
</script>
|
||||
<style>
|
||||
page { background: #0d0e18; color: #f2f4ff; font-size: 15px;
|
||||
font-family: -apple-system, "PingFang SC", sans-serif; }
|
||||
.glass { background: rgba(255,255,255,.08); border: 1px solid rgba(255,255,255,.22);
|
||||
border-radius: 20px; padding: 14px; margin-bottom: 12px; }
|
||||
.btn { background: rgba(124,154,255,.25); border: 1px solid rgba(255,255,255,.22);
|
||||
color: #f2f4ff; border-radius: 14px; padding: 8px 16px; font-size: 14px; display: inline-block; }
|
||||
.btn.primary { background: #7c9aff; color: #0d0e18; }
|
||||
.btn.small { padding: 4px 10px; font-size: 12px; }
|
||||
.btn.danger { background: rgba(255,90,90,.3); }
|
||||
input, textarea, select { background: rgba(255,255,255,.06); border: 1px solid rgba(255,255,255,.2);
|
||||
border-radius: 12px; color: #f2f4ff; padding: 10px; font-size: 14px; width: 100%;
|
||||
box-sizing: border-box; margin-bottom: 10px; }
|
||||
.hint { color: rgba(242,244,255,.55); font-size: 12px; }
|
||||
.row { display: flex; gap: 8px; align-items: center; }
|
||||
.spread { justify-content: space-between; }
|
||||
.tag { background: rgba(124,154,255,.18); border-radius: 8px; padding: 1px 8px;
|
||||
font-size: 11px; color: #7c9aff; }
|
||||
</style>
|
||||
@@ -0,0 +1,3 @@
|
||||
import App from "./App.vue";
|
||||
import { createSSRApp } from "vue";
|
||||
export function createApp() { const app = createSSRApp(App); return { app }; }
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"name": "Open Maopaoya",
|
||||
"appid": "",
|
||||
"vueVersion": "3",
|
||||
"h5": { "router": { "mode": "hash" }, "title": "Open Maopaoya" }
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"pages": [
|
||||
{ "path": "pages/login/index", "style": { "navigationStyle": "custom" } },
|
||||
{ "path": "pages/shelf/index", "style": { "navigationBarTitleText": "书架" } },
|
||||
{ "path": "pages/characters/index","style": { "navigationBarTitleText": "角色" } },
|
||||
{ "path": "pages/novels/index", "style": { "navigationBarTitleText": "动态小说" } },
|
||||
{ "path": "pages/chat/index", "style": { "navigationBarTitleText": "对话" } },
|
||||
{ "path": "pages/moments/index", "style": { "navigationBarTitleText": "朋友圈" } },
|
||||
{ "path": "pages/plaza/index", "style": { "navigationBarTitleText": "广场" } },
|
||||
{ "path": "pages/channels/index", "style": { "navigationBarTitleText": "渠道" } },
|
||||
{ "path": "pages/admin/index", "style": { "navigationBarTitleText": "后台" } }
|
||||
],
|
||||
"globalStyle": { "navigationBarTextStyle": "white", "navigationBarBackgroundColor": "#141528", "backgroundColor": "#0d0e18" }
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
<template>
|
||||
<view style="padding:14px">
|
||||
<view class="glass"><text style="font-weight:600">权限开关</text>
|
||||
<view v-for="(v, k) in toggles" :key="k" class="row spread" style="margin-top:8px">
|
||||
<text>{{ labels[k] || k }}</text>
|
||||
<button class="btn small" :class="v === 'true' ? 'primary' : ''" @click="toggle(k, v)">
|
||||
{{ v === 'true' ? '开' : '关' }}</button>
|
||||
</view>
|
||||
</view>
|
||||
<view class="glass"><view class="row spread"><text style="font-weight:600">用户管理</text>
|
||||
<text class="hint">用户 {{ stats.users }} · 会话 {{ stats.sessions }}</text></view>
|
||||
<view class="row" style="margin:8px 0">
|
||||
<button class="btn small primary" @click="createUser">+ 新建用户</button>
|
||||
</view>
|
||||
<view v-for="x in users" :key="x.id" class="row spread" style="margin-bottom:6px">
|
||||
<text>{{ x.username }} {{ x.is_admin ? '(管理员)' : '' }}{{ x.is_active ? '' : ' [封禁]' }}</text>
|
||||
<view class="row">
|
||||
<button class="btn small" @click="patch(x.id, { is_active: !x.is_active })">
|
||||
{{ x.is_active ? '封禁' : '解封' }}</button>
|
||||
<button class="btn small" @click="resetPwd(x)">改密</button>
|
||||
</view>
|
||||
</view>
|
||||
</view>
|
||||
</view>
|
||||
</template>
|
||||
<script setup>
|
||||
import { ref } from "vue";
|
||||
import { api, toast } from "../../utils/api";
|
||||
const toggles = ref({}), users = ref([]), stats = ref({});
|
||||
const labels = { allow_register: "允许注册", allow_delete_account: "允许注销",
|
||||
allow_byok: "允许自定义API", admin_data_visible: "数据可见(关=加密)" };
|
||||
async function load() {
|
||||
toggles.value = await api("/admin/settings");
|
||||
const u = await api("/admin/users");
|
||||
users.value = u.users; stats.value = u.stats;
|
||||
}
|
||||
load();
|
||||
async function toggle(k, cur) {
|
||||
await api(`/admin/settings?key=${k}&value=${cur === 'true' ? 'false' : 'true'}`, { method: "POST" });
|
||||
load();
|
||||
}
|
||||
async function patch(id, body) { await api(`/admin/users/${id}`, { method: "PATCH", body }); load(); }
|
||||
function createUser() {
|
||||
uni.showModal({ editable: true, placeholderText: "用户名,密码",
|
||||
success: async m => { if (!m.content) return;
|
||||
const [username, password] = m.content.split(",");
|
||||
try { await api("/admin/users", { method: "POST", body: { username, password } });
|
||||
load(); toast("已创建"); } catch (e) { toast(e.message); } } });
|
||||
}
|
||||
function resetPwd(x) {
|
||||
uni.showModal({ editable: true, placeholderText: "新密码",
|
||||
success: async m => { if (!m.content) return;
|
||||
await api(`/admin/users/${x.id}`, { method: "PATCH", body: { new_password: m.content } });
|
||||
toast("已重置"); } });
|
||||
}
|
||||
</script>
|
||||
@@ -0,0 +1,38 @@
|
||||
<template>
|
||||
<view style="padding:14px">
|
||||
<button class="btn primary" @click="adding = true">+ 添加渠道</button>
|
||||
<view v-if="adding" class="glass">
|
||||
<input v-model="f.name" placeholder="渠道名" />
|
||||
<input v-model="f.base_url" placeholder="Base URL (OpenAI兼容)" />
|
||||
<input v-model="f.api_key" password placeholder="API Key" />
|
||||
<view class="row"><button class="btn primary" @click="save">保存</button>
|
||||
<button class="btn" @click="adding = false">取消</button></view>
|
||||
</view>
|
||||
<view v-for="c in chans" :key="c.id" class="glass">
|
||||
<view class="row spread"><text style="font-weight:600">{{ c.name }}</text>
|
||||
<text class="tag">{{ c.visibility }}</text></view>
|
||||
<view class="hint">{{ c.base_url }}</view>
|
||||
<view class="row" style="margin-top:6px">
|
||||
<button class="btn small" @click="test(c)">测试</button>
|
||||
<button class="btn small danger" @click="del(c)">删</button>
|
||||
</view>
|
||||
</view>
|
||||
</view>
|
||||
</template>
|
||||
<script setup>
|
||||
import { ref } from "vue";
|
||||
import { api, toast } from "../../utils/api";
|
||||
const chans = ref([]), adding = ref(false);
|
||||
const f = ref({ name: "", base_url: "", api_key: "" });
|
||||
async function load() { chans.value = (await api("/channels")).channels; }
|
||||
load();
|
||||
async function save() {
|
||||
await api("/channels", { method: "POST", body: { ...f.value, models: {}, visibility: "admin" } });
|
||||
adding.value = false; load(); toast("已保存");
|
||||
}
|
||||
async function test(c) {
|
||||
try { const d = await api(`/channels/${c.id}/test`); toast(d.ok ? "✅ 通" : "❌ " + d.message); }
|
||||
catch (e) { toast(e.message); }
|
||||
}
|
||||
async function del(c) { await api(`/channels/${c.id}`, { method: "DELETE" }); load(); }
|
||||
</script>
|
||||
@@ -0,0 +1,48 @@
|
||||
<template>
|
||||
<view style="padding:14px">
|
||||
<button class="btn primary" @click="edit(0)">+ 新建角色</button>
|
||||
<view v-for="c in chars" :key="c.id" class="glass">
|
||||
<view class="row spread"><text style="font-weight:600">{{ c.name }}</text>
|
||||
<text v-if="c.source!=='manual'" class="tag">{{ c.source==='novel_auto'?'AI生成':'导入' }}</text></view>
|
||||
<view class="hint" style="margin:6px 0">{{ c.persona || '(无人设)' }}</view>
|
||||
<view class="row">
|
||||
<button class="btn small primary" @click="startChat(c)">对话</button>
|
||||
<button class="btn small" @click="edit(c.id)">编辑</button>
|
||||
<button class="btn small" @click="share(c)">分享</button>
|
||||
<button class="btn small danger" @click="del(c)">删</button>
|
||||
</view>
|
||||
</view>
|
||||
</view>
|
||||
</template>
|
||||
<script setup>
|
||||
import { ref } from "vue";
|
||||
import { api, toast } from "../../utils/api";
|
||||
const chars = ref([]);
|
||||
async function load() { chars.value = (await api("/characters")).characters; }
|
||||
load();
|
||||
function startChat(c) {
|
||||
api("/sessions", { method: "POST", body: { mode: "roleplay", character_id: c.id } })
|
||||
.then(s => uni.navigateTo({ url: `/pages/chat/index?sid=${s.id}&mode=roleplay` }));
|
||||
}
|
||||
function edit(id) {
|
||||
api("/characters").then(d => {
|
||||
const c = d.characters.find(x => x.id === id) || { name: "", persona: "", greeting: "", voice: "tongtong" };
|
||||
uni.showModal({ editable: true, placeholderText: "名字,人设,开场白(逗号分隔)",
|
||||
content: [c.name, c.persona, c.greeting].join(","),
|
||||
success: async m => { if (!m.content) return;
|
||||
const [name, persona = "", greeting = ""] = m.content.split(",");
|
||||
const body = { name, persona, greeting, voice: c.voice, avatar_url: c.avatar_url || "" };
|
||||
if (id) await api(`/characters/${id}`, { method: "PATCH", body });
|
||||
else await api("/characters", { method: "POST", body });
|
||||
load(); } });
|
||||
});
|
||||
}
|
||||
async function share(c) {
|
||||
const d = await api(`/characters/${c.id}/export`);
|
||||
toast("分享码: " + d.share_code);
|
||||
}
|
||||
async function del(c) {
|
||||
uni.showModal({ content: "删除 " + c.name + "?", success: async m => {
|
||||
if (m.confirm) { await api(`/characters/${c.id}`, { method: "DELETE" }); load(); } } });
|
||||
}
|
||||
</script>
|
||||
@@ -0,0 +1,72 @@
|
||||
<template>
|
||||
<view style="padding:14px;display:flex;flex-direction:column;height:100vh;box-sizing:border-box">
|
||||
<scroll-view scroll-y style="flex:1" :scroll-top="scrollTop" scroll-anchoring>
|
||||
<view v-for="m in msgs" :key="m.id" class="bubble" :class="m.role === 'user' ? 'me' : ''">
|
||||
<view v-if="m.speaker" class="hint">{{ m.speaker }}</view>
|
||||
<text>{{ m.content }}</text>
|
||||
<view class="row" style="margin-top:4px;opacity:.5">
|
||||
<text class="mini" @click="star(m)">{{ m.starred ? '⭐' : '☆' }}</text>
|
||||
<text v-if="m.role !== 'user'" class="mini" @click="regen(m)">🎲</text>
|
||||
<text v-if="m.role !== 'user'" class="mini" @click="tts(m)">🔊</text>
|
||||
<text v-if="(m.swipe_count || 0) > 1" class="mini">{{ m.active_swipe + 1 }}/{{ m.swipe_count }}
|
||||
<text @click="swipe(m, -1)">‹</text><text @click="swipe(m, 1)">›</text></text>
|
||||
</view>
|
||||
</view>
|
||||
<view v-if="sending" class="bubble">…</view>
|
||||
</scroll-view>
|
||||
<view class="row" style="padding-top:10px">
|
||||
<input v-model="text" placeholder="说点什么…" style="flex:1" @confirm="send" />
|
||||
<button class="btn primary" @click="send">发</button>
|
||||
</view>
|
||||
</view>
|
||||
</template>
|
||||
<script setup>
|
||||
import { ref } from "vue";
|
||||
import { onLoad } from "@dcloudio/uni-app";
|
||||
import { api, token, toast } from "../../utils/api";
|
||||
const msgs = ref([]), text = ref(""), sending = ref(false), scrollTop = ref(0);
|
||||
let sid = 0, mode = "roleplay";
|
||||
onLoad(o => { sid = +o.sid; mode = o.mode || "roleplay"; load(); });
|
||||
async function load() {
|
||||
const d = await api(`/sessions/${sid}/messages`);
|
||||
msgs.value = d.messages; scrollTop.value = msgs.value.length * 500;
|
||||
}
|
||||
async function send() {
|
||||
const t = text.value.trim(); if (!t || sending.value) return;
|
||||
sending.value = true; text.value = "";
|
||||
try {
|
||||
const url = mode === "group" ? `/sessions/${sid}/send_group` : `/sessions/${sid}/send`;
|
||||
const d = await api(url, { method: "POST", body: { content: t } });
|
||||
await load();
|
||||
(d.new_characters || []).forEach(c =>
|
||||
toast("✨ 新角色入场: " + c.name));
|
||||
} catch (e) { toast(e.message); }
|
||||
sending.value = false;
|
||||
}
|
||||
async function regen(m) {
|
||||
await api(`/messages/${m.id}/regenerate`, { method: "POST" }); load();
|
||||
}
|
||||
async function swipe(m, delta) {
|
||||
await api(`/messages/${m.id}/swipe`, { method: "POST", body: { delta } }); load();
|
||||
}
|
||||
async function star(m) {
|
||||
await api(`/messages/${m.id}/star`, { method: "POST", body: { starred: !m.starred } }); load();
|
||||
}
|
||||
async function tts(m) {
|
||||
const r = await uni.request({
|
||||
url: `/api/sessions/${sid}/tts/${m.id}`,
|
||||
header: { Authorization: "Bearer " + token() }, responseType: "arraybuffer" });
|
||||
// H5 环境:转 base64 播放
|
||||
let bin = ""; const bytes = new Uint8Array(r.data);
|
||||
for (let i = 0; i < bytes.length; i++) bin += String.fromCharCode(bytes[i]);
|
||||
const audio = uni.createInnerAudioContext();
|
||||
audio.src = "data:audio/wav;base64," + uni.arrayBufferToBase64(r.data);
|
||||
audio.play();
|
||||
}
|
||||
</script>
|
||||
<style>
|
||||
.bubble { background: rgba(255,255,255,.08); border: 1px solid rgba(255,255,255,.2);
|
||||
border-radius: 16px; padding: 10px 12px; margin-bottom: 8px; max-width: 85%; }
|
||||
.bubble.me { margin-left: auto; background: rgba(124,154,255,.25); }
|
||||
.mini { font-size: 12px; margin-right: 8px; }
|
||||
</style>
|
||||
@@ -0,0 +1,32 @@
|
||||
<template>
|
||||
<view class="wrap">
|
||||
<view class="glass card">
|
||||
<view style="font-size:26px;text-align:center">🦆 Open Maopaoya</view>
|
||||
<view class="hint" style="text-align:center;margin:6px 0 14px">冒泡鸭开源复刻 · 动态小说引擎</view>
|
||||
<input v-model="u" placeholder="用户名" />
|
||||
<input v-model="p" password placeholder="密码" />
|
||||
<view class="row" style="margin-top:6px">
|
||||
<button class="btn primary" style="flex:1" @click="doLogin">登录</button>
|
||||
<button class="btn" style="flex:1" @click="doRegister">注册</button>
|
||||
</view>
|
||||
</view>
|
||||
</view>
|
||||
</template>
|
||||
<script setup>
|
||||
import { ref } from "vue";
|
||||
import { api, toast } from "../../utils/api";
|
||||
const u = ref(""), p = ref("");
|
||||
async function _auth(path) {
|
||||
try {
|
||||
const d = await api(path, { method: "POST", body: { username: u.value, password: p.value } });
|
||||
uni.setStorageSync("token", d.token);
|
||||
uni.reLaunch({ url: "/pages/shelf/index" });
|
||||
} catch (e) { toast(e.message); }
|
||||
}
|
||||
const doLogin = () => _auth("/auth/login");
|
||||
const doRegister = () => _auth("/auth/register");
|
||||
</script>
|
||||
<style>
|
||||
.wrap { min-height: 100vh; display: flex; align-items: center; justify-content: center; padding: 20px; }
|
||||
.card { width: 100%; max-width: 420px; }
|
||||
</style>
|
||||
@@ -0,0 +1,39 @@
|
||||
<template>
|
||||
<view style="padding:14px">
|
||||
<button class="btn primary" @click="pick">让角色发一条</button>
|
||||
<view v-for="m in feed" :key="m.id" class="glass">
|
||||
<view class="row spread"><text style="font-weight:600">{{ m.author }}</text></view>
|
||||
<view style="margin:8px 0">{{ m.content }}</view>
|
||||
<image v-if="m.image_url" :src="m.image_url" mode="widthFix" style="width:100%;border-radius:12px" />
|
||||
<view class="row">
|
||||
<button class="btn small" :class="m.liked_by_me ? 'primary' : ''" @click="like(m)">❤</button>
|
||||
<button class="btn small" @click="comment(m)">评论</button>
|
||||
</view>
|
||||
<view v-for="(cm, i) in m.comments || []" :key="i" class="hint">💬 {{ cm.author }}: {{ cm.content }}</view>
|
||||
</view>
|
||||
</view>
|
||||
</template>
|
||||
<script setup>
|
||||
import { ref } from "vue";
|
||||
import { api, toast } from "../../utils/api";
|
||||
const feed = ref([]);
|
||||
async function load() { feed.value = (await api("/moments")).moments; }
|
||||
load();
|
||||
async function pick() {
|
||||
const d = await api("/characters");
|
||||
uni.showActionSheet({
|
||||
itemList: d.characters.slice(0, 6).map(c => c.name),
|
||||
success: async r => {
|
||||
await api("/moments/generate", { method: "POST", body: {
|
||||
character_id: d.characters[r.tapIndex].id, topic: "" } });
|
||||
load();
|
||||
} });
|
||||
}
|
||||
async function like(m) { await api(`/moments/${m.id}/like`, { method: "POST" }); load(); }
|
||||
function comment(m) {
|
||||
uni.showModal({ editable: true, placeholderText: "说点什么…",
|
||||
success: async r => { if (r.content) {
|
||||
await api(`/moments/${m.id}/comment`, { method: "POST", body: { content: r.content } });
|
||||
load(); } } });
|
||||
}
|
||||
</script>
|
||||
@@ -0,0 +1,31 @@
|
||||
<template>
|
||||
<view style="padding:14px">
|
||||
<button class="btn primary" @click="creating = true">📖 开新小说</button>
|
||||
<view class="hint" style="margin:8px 0">AI 编剧自主写剧情、引入新角色并自动建档生成立绘。</view>
|
||||
<view v-if="creating" class="glass">
|
||||
<input v-model="t" placeholder="小说标题" />
|
||||
<textarea v-model="s" placeholder="设定:世界观、主角、开篇场景…" style="height:100px" />
|
||||
<view class="row"><button class="btn primary" @click="create">开写</button>
|
||||
<button class="btn" @click="creating = false">取消</button></view>
|
||||
</view>
|
||||
<view v-for="n in novels" :key="n.id" class="glass" @click="open(n)">
|
||||
<text>{{ n.title }}</text> <text class="tag">AI自主扩列</text>
|
||||
</view>
|
||||
</view>
|
||||
</template>
|
||||
<script setup>
|
||||
import { ref } from "vue";
|
||||
import { api } from "../../utils/api";
|
||||
const novels = ref([]), creating = ref(false), t = ref(""), s = ref("");
|
||||
async function load() {
|
||||
const d = await api("/sessions");
|
||||
novels.value = d.sessions.filter(x => x.mode === "novel");
|
||||
}
|
||||
load();
|
||||
async function create() {
|
||||
const r = await api("/sessions", { method: "POST", body: {
|
||||
mode: "novel", title: t.value || "未命名小说", novel_setting: s.value } });
|
||||
uni.navigateTo({ url: `/pages/chat/index?sid=${r.id}&mode=novel` });
|
||||
}
|
||||
function open(n) { uni.navigateTo({ url: `/pages/chat/index?sid=${n.id}&mode=novel` }); }
|
||||
</script>
|
||||
@@ -0,0 +1,25 @@
|
||||
<template>
|
||||
<view style="padding:14px">
|
||||
<view class="row"><input v-model="q" placeholder="搜索公开角色" style="flex:1" @confirm="load" />
|
||||
<button class="btn" @click="load">搜</button></view>
|
||||
<view v-for="c in chars" :key="c.id" class="glass">
|
||||
<text style="font-weight:600">{{ c.name }}</text> <text class="tag">{{ c.tags }}</text>
|
||||
<view class="hint" style="margin:6px 0">{{ (c.persona || '').slice(0, 60) }}</view>
|
||||
<button class="btn small primary" @click="clone(c)">领养</button>
|
||||
</view>
|
||||
<view class="hint" style="margin-top:10px">有分享码?</view>
|
||||
<input v-model="code" placeholder="输入分享码导入" @confirm="importCode" />
|
||||
</view>
|
||||
</template>
|
||||
<script setup>
|
||||
import { ref } from "vue";
|
||||
import { api, toast } from "../../utils/api";
|
||||
const chars = ref([]), q = ref(""), code = ref("");
|
||||
async function load() { chars.value = (await api("/plaza?q=" + encodeURIComponent(q.value))).characters; }
|
||||
load();
|
||||
async function clone(c) { await api(`/characters/${c.id}/clone`, { method: "POST" }); toast("已领养"); }
|
||||
async function importCode() {
|
||||
try { await api("/characters/import", { method: "POST", body: { share_code: code.value } });
|
||||
toast("导入成功"); } catch (e) { toast(e.message); }
|
||||
}
|
||||
</script>
|
||||
@@ -0,0 +1,69 @@
|
||||
<template>
|
||||
<view style="padding:14px">
|
||||
<view class="row spread" style="margin-bottom:10px">
|
||||
<button class="btn primary" @click="newChat">+ 新对话</button>
|
||||
<button class="btn" @click="go('/pages/novels/index')">📖 小说</button>
|
||||
<button class="btn" @click="go('/pages/moments/index')">🌟 朋友圈</button>
|
||||
<button class="btn" @click="go('/pages/plaza/index')">🏪</button>
|
||||
<button class="btn" @click="go('/pages/channels/index')">🔌</button>
|
||||
<button v-if="me.is_admin" class="btn" @click="go('/pages/admin/index')">⚙️</button>
|
||||
</view>
|
||||
<input placeholder="🔍 搜索所有会话内容" v-model="q" @confirm="search" />
|
||||
<view v-for="r in results" :key="'r'+r.session_id" class="glass" @click="openSession(r.session_id, r.mode)">
|
||||
<text class="hint">{{ r.speaker || '' }}: {{ r.snippet }}</text>
|
||||
</view>
|
||||
<view v-for="s in sessions" :key="s.id" class="glass" @click="openSession(s.id, s.mode)">
|
||||
<view class="row spread">
|
||||
<text>{{ s.pinned ? '📌 ' : '' }}{{ s.title }}</text>
|
||||
<text class="tag">{{ { roleplay:'角色扮演', novel:'动态小说', group:'群聊' }[s.mode] || s.mode }}</text>
|
||||
</view>
|
||||
<view class="row" style="margin-top:6px">
|
||||
<button class="btn small" @click.stop="rename(s)">✏️</button>
|
||||
<button class="btn small" @click.stop="archive(s)">📦</button>
|
||||
</view>
|
||||
</view>
|
||||
<view v-if="!sessions.length" class="hint">还没有会话,点「新对话」开一个。</view>
|
||||
</view>
|
||||
</template>
|
||||
<script setup>
|
||||
import { ref } from "vue";
|
||||
import { api, toast, go } from "../../utils/api";
|
||||
const sessions = ref([]), me = ref({}), q = ref(""), results = ref([]);
|
||||
async function load() {
|
||||
me.value = await api("/auth/me");
|
||||
const d = await api("/sessions");
|
||||
sessions.value = d.sessions.filter(s => !s.archived)
|
||||
.sort((a, b) => (b.pinned - a.pinned) || (b.id - a.id));
|
||||
}
|
||||
async function search() {
|
||||
if (!q.value) return;
|
||||
const d = await api("/search?q=" + encodeURIComponent(q.value));
|
||||
results.value = d.results.slice(0, 10);
|
||||
}
|
||||
function openSession(id, mode) {
|
||||
uni.setStorageSync("curSession", id);
|
||||
uni.navigateTo({ url: `/pages/chat/index?sid=${id}&mode=${mode}` });
|
||||
}
|
||||
async function newChat() {
|
||||
const d = await api("/characters");
|
||||
uni.showActionSheet({
|
||||
itemList: d.characters.slice(0, 6).map(c => c.name),
|
||||
success: async r => {
|
||||
const s = await api("/sessions", { method: "POST", body: {
|
||||
mode: "roleplay", character_id: d.characters[r.tapIndex].id } });
|
||||
openSession(s.id, "roleplay");
|
||||
},
|
||||
});
|
||||
}
|
||||
async function rename(s) {
|
||||
uni.showModal({ editable: true, placeholderText: "新标题", content: s.title,
|
||||
success: async m => { if (m.content) {
|
||||
await api(`/sessions/${s.id}/settings`, { method: "PATCH", body: { title: m.content } });
|
||||
load(); } } });
|
||||
}
|
||||
async function archive(s) {
|
||||
await api(`/sessions/${s.id}/settings`, { method: "PATCH", body: { archived: !s.archived } });
|
||||
load();
|
||||
}
|
||||
load();
|
||||
</script>
|
||||
@@ -0,0 +1,14 @@
|
||||
const BASE = "/api";
|
||||
export const token = () => uni.getStorageSync("token") || "";
|
||||
export async function api(path, opts = {}) {
|
||||
const r = await uni.request({
|
||||
url: BASE + path,
|
||||
method: opts.method || "GET",
|
||||
data: opts.body,
|
||||
header: { "Content-Type": "application/json", Authorization: "Bearer " + token() },
|
||||
});
|
||||
if (r.statusCode >= 400) throw new Error((r.data && r.data.detail) || r.statusCode);
|
||||
return r.data;
|
||||
}
|
||||
export function toast(t) { uni.showToast({ title: String(t).slice(0, 40), icon: "none" }); }
|
||||
export function go(url) { uni.navigateTo({ url }); }
|
||||
@@ -0,0 +1,3 @@
|
||||
import { defineConfig } from "vite";
|
||||
import uni from "@dcloudio/vite-plugin-uni";
|
||||
export default defineConfig({ plugins: [uni()] });
|
||||
+1
-1
@@ -6,7 +6,7 @@ requires-python = ">=3.12"
|
||||
dependencies = [
|
||||
"fastapi>=0.115",
|
||||
"uvicorn[standard]>=0.34",
|
||||
"sqlalchemy>=2.0",
|
||||
"sqlalchemy[asyncio]>=2.0",
|
||||
"alembic>=1.14",
|
||||
"pydantic>=2.10",
|
||||
"pydantic-settings>=2.7",
|
||||
|
||||
@@ -167,3 +167,36 @@ textarea { min-height: 90px; resize: vertical; }
|
||||
.card-grid { grid-template-columns: repeat(2, 1fr); }
|
||||
.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; }
|
||||
/* 第二批 */
|
||||
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; }
|
||||
|
||||
+47
-8
@@ -4,7 +4,7 @@
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover, user-scalable=no">
|
||||
<title>Open Maopaoya · 冒泡鸭开源复刻</title>
|
||||
<link rel="stylesheet" href="/css/glass.css">
|
||||
<link rel="stylesheet" href="/css/glass.css?v=2">
|
||||
</head>
|
||||
<body>
|
||||
<div class="bg-blobs"><i></i><i></i><i></i></div>
|
||||
@@ -28,6 +28,8 @@
|
||||
<button data-page="shelf" class="nav-btn active">📚 书架</button>
|
||||
<button data-page="chars" 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="admin" class="nav-btn admin-only">⚙️ 后台</button>
|
||||
<span class="spacer"></span>
|
||||
@@ -39,7 +41,16 @@
|
||||
<!-- 书架 -->
|
||||
<section id="page-shelf" class="page">
|
||||
<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="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="🔍 搜索所有会话内容"
|
||||
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>
|
||||
</section>
|
||||
|
||||
@@ -58,9 +69,35 @@
|
||||
<div id="novel-list" class="card-grid"></div>
|
||||
</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">
|
||||
<div class="row spread"><h2>模型渠道</h2>
|
||||
<section id="page-channels" class="page hidden"> <div class="row spread"><h2>模型渠道</h2>
|
||||
<button class="btn primary" onclick="editChannel(null)">+ 添加渠道</button></div>
|
||||
<div id="channel-list" class="card-grid"></div>
|
||||
</section>
|
||||
@@ -85,9 +122,11 @@
|
||||
<button class="nav-btn" onclick="backToShelf()">←</button>
|
||||
<b id="chat-title">会话</b>
|
||||
<span class="spacer"></span>
|
||||
<button class="nav-btn" onclick="openDrawer('memory')">🧠 记忆</button>
|
||||
<button class="nav-btn" onclick="openDrawer('worldbook')">🌍 世界书</button>
|
||||
<button class="nav-btn" onclick="openDrawer('card')">🎭 角色</button>
|
||||
<button class="nav-btn" onclick="openDrawer('memory')">🧠</button>
|
||||
<button class="nav-btn" onclick="openDrawer('worldbook')">🌍</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>
|
||||
<div id="chat-log"></div>
|
||||
<div class="glass-inputbar">
|
||||
@@ -121,6 +160,6 @@
|
||||
</div>
|
||||
|
||||
<div id="toast" class="toast hidden"></div>
|
||||
<script src="/js/app.js"></script>
|
||||
<script src="/js/app.js?v=2"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
+350
-11
@@ -50,21 +50,45 @@ 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 =>
|
||||
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>';
|
||||
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;
|
||||
@@ -93,6 +117,7 @@ async function loadCharacters() {
|
||||
<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>';
|
||||
}
|
||||
@@ -161,18 +186,42 @@ function backToShelf() {
|
||||
}
|
||||
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>
|
||||
${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>`;
|
||||
}
|
||||
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;
|
||||
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>`);
|
||||
@@ -181,13 +230,15 @@ async function sendMsg() {
|
||||
$("#chat-log").appendChild(thinking);
|
||||
$("#chat-log").scrollTop = 1e9;
|
||||
try {
|
||||
const d = await api(`/sessions/${CUR.sessionId}/send`, { method: "POST", body: { content: text } });
|
||||
thinking.innerHTML = renderBubble({ id: d.message_id, role: "assistant", content: d.reply });
|
||||
const url = CUR.mode === "group" ? `/sessions/${CUR.sessionId}/send_group` : `/sessions/${CUR.sessionId}/send`;
|
||||
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) {
|
||||
@@ -350,7 +401,9 @@ async function loadAdmin() {
|
||||
<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 =>
|
||||
$("#admin-users").innerHTML = `<div class="row" style="margin-bottom:8px">
|
||||
<button class="btn small primary" onclick="adminCreateUser()">+ 新建用户</button>
|
||||
<button class="btn small primary" onclick="adminGrantChannel()">🔌 渠道分配</button></div>` + 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">
|
||||
@@ -447,6 +500,292 @@ async function revokeGrant(cid, uid) {
|
||||
adminGrantChannel();
|
||||
}
|
||||
|
||||
async function adminCreateUser() {
|
||||
openModal(`<h3>新建用户</h3>
|
||||
<input id="nu-name" placeholder="用户名">
|
||||
<input id="nu-pass" placeholder="初始密码(至少6位)">
|
||||
<div class="row" style="margin-top:12px">
|
||||
<button class="btn primary" onclick="doCreateUser()">创建</button>
|
||||
<button class="btn" onclick="closeModal()">取消</button></div>`);
|
||||
}
|
||||
async function doCreateUser() {
|
||||
try {
|
||||
await api("/admin/users", { method: "POST", body: {
|
||||
username: $("#nu-name").value, password: $("#nu-pass").value } });
|
||||
closeModal(); loadAdmin(); toast("用户已创建");
|
||||
} catch (e) { toast(e.message); }
|
||||
}
|
||||
|
||||
/* ================= 第二批小功能 ================= */
|
||||
|
||||
/* 复制消息 */
|
||||
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() {
|
||||
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"); }
|
||||
@@ -457,6 +796,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"); }
|
||||
})();
|
||||
|
||||
Reference in New Issue
Block a user