"""Export related API routes.""" from pathlib import Path from typing import Any, Dict, Optional from fastapi import APIRouter, Depends, HTTPException, status from fastapi.responses import FileResponse from pydantic import BaseModel from chatfast.db import MessageContent from chatfast.services.auth import UserInfo, get_current_user from chatfast.services.chat import ( export_message_to_blog, get_export_record, list_exports_for_user, record_export_entry, ) class ExportRequest(BaseModel): content: MessageContent session_id: Optional[int] = None router = APIRouter(prefix="/api", tags=["exports"]) @router.post("/export") async def api_export_message(payload: ExportRequest, current_user: UserInfo = Depends(get_current_user)) -> Dict[str, Any]: path = await export_message_to_blog(payload.content) record = await record_export_entry(current_user.id, payload.session_id, path, payload.content) return {"status": "ok", "path": path, "export": record} @router.get("/exports/me") async def api_my_exports(current_user: UserInfo = Depends(get_current_user)) -> Dict[str, Any]: items = await list_exports_for_user(current_user.id) return {"items": items} @router.get("/exports/{export_id}/download") async def api_download_export(export_id: int, current_user: UserInfo = Depends(get_current_user)) -> FileResponse: record = await get_export_record(export_id) if not record: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="导出记录不存在") if record["user_id"] != current_user.id and current_user.role != "admin": raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="无权下载该内容") file_path = Path(record["file_path"]) if not file_path.exists(): raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="导出文件不存在") return FileResponse(file_path, filename=record["filename"])