75 行
2.9 KiB
Python
75 行
2.9 KiB
Python
"""会话 API:学科窗口(列表/创建/继承/历史)。"""
|
|
from __future__ import annotations
|
|
|
|
from fastapi import APIRouter, Depends, Header, HTTPException
|
|
from pydantic import BaseModel
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.core.db import get_session
|
|
from app.repositories.conversation_repo import ConversationRepo
|
|
from app.repositories.message_repo import MessageRepo
|
|
from app.services.auth_service import AuthService
|
|
|
|
router = APIRouter(prefix="/conversations", tags=["conversations"])
|
|
|
|
|
|
def _user(authorization: str | None, session: Session) -> dict:
|
|
if not authorization or not authorization.lower().startswith("bearer "):
|
|
raise HTTPException(401, "未登录")
|
|
try:
|
|
return AuthService(session).me(authorization[7:].strip())
|
|
except Exception as e:
|
|
raise HTTPException(401, str(e))
|
|
|
|
|
|
class ConvBody(BaseModel):
|
|
course: str = "ap-csa"
|
|
title: str = ""
|
|
inherit_from: int = 0
|
|
|
|
|
|
@router.get("")
|
|
async def list_conversations(authorization: str | None = Header(None), session: Session = Depends(get_session)):
|
|
"""当前用户全部会话(学科窗口,按活跃倒序)。"""
|
|
u = _user(authorization, session)
|
|
convs = ConversationRepo(session).list_by_user(u["id"])
|
|
out = []
|
|
for c in convs:
|
|
d = c.to_dict()
|
|
d["msg_count"] = len(MessageRepo(session).list_by_user(u["id"], limit=500, conversation_id=c.id))
|
|
out.append(d)
|
|
return out
|
|
|
|
|
|
@router.post("")
|
|
async def create_conversation(body: ConvBody, authorization: str | None = Header(None),
|
|
session: Session = Depends(get_session)):
|
|
"""新建会话(学科窗口)。inherit_from>0 时继承源会话学科与标题。"""
|
|
u = _user(authorization, session)
|
|
repo = ConversationRepo(session)
|
|
course, title, inherit = body.course, body.title, body.inherit_from
|
|
if inherit > 0:
|
|
src = repo.get(inherit)
|
|
if src and src.user_id == u["id"]:
|
|
course = src.course
|
|
if not title:
|
|
title = src.title or "续接 · " + course
|
|
if not title:
|
|
title = course
|
|
c = repo.create(u["id"], course=course, title=title, inherit_from=inherit)
|
|
return c.to_dict()
|
|
|
|
|
|
@router.get("/{conv_id}/messages")
|
|
async def conversation_messages(conv_id: int, limit: int = 300,
|
|
authorization: str | None = Header(None),
|
|
session: Session = Depends(get_session)):
|
|
"""某会话的完整消息流(含分界符/公告,上翻复盘)。"""
|
|
u = _user(authorization, session)
|
|
repo = ConversationRepo(session)
|
|
c = repo.get(conv_id)
|
|
if not c or c.user_id != u["id"]:
|
|
raise HTTPException(404, "会话不存在")
|
|
msgs = MessageRepo(session).list_by_user(u["id"], limit=min(limit, 500), conversation_id=conv_id)
|
|
return {"conversation": c.to_dict(), "messages": [m.to_dict() for m in msgs]}
|