affection.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. """
  2. 好感度API
  3. """
  4. from fastapi import APIRouter, Depends, HTTPException
  5. from sqlalchemy.ext.asyncio import AsyncSession
  6. from sqlalchemy import select
  7. from app.core.database import get_db
  8. from app.models.user import User
  9. from app.models.affection import AffectionScore, AffectionLog
  10. from app.schemas.affection import AffectionScoreResponse, AffectionDetailResponse, AffectionLogResponse
  11. from app.api.auth import get_current_user
  12. from app.services.affection_service import get_next_level_score
  13. from typing import List
  14. router = APIRouter()
  15. @router.get("/{character_id}", response_model=AffectionDetailResponse)
  16. async def get_affection(
  17. character_id: int,
  18. current_user: User = Depends(get_current_user),
  19. db: AsyncSession = Depends(get_db)
  20. ):
  21. """获取与某个AI角色的好感度"""
  22. result = await db.execute(
  23. select(AffectionScore).where(
  24. AffectionScore.user_id == current_user.id,
  25. AffectionScore.character_id == character_id
  26. )
  27. )
  28. affection = result.scalar_one_or_none()
  29. if not affection:
  30. raise HTTPException(status_code=404, detail="好感度记录不存在")
  31. # 获取最近的好感度变化记录
  32. logs_result = await db.execute(
  33. select(AffectionLog)
  34. .where(AffectionLog.affection_score_id == affection.id)
  35. .order_by(AffectionLog.created_at.desc())
  36. .limit(10)
  37. )
  38. recent_logs = logs_result.scalars().all()
  39. # 构建响应
  40. response = AffectionDetailResponse(
  41. character_id=character_id,
  42. current_score=affection.current_score,
  43. level=affection.level,
  44. next_level_score=get_next_level_score(affection.current_score),
  45. total_interactions=affection.total_interactions,
  46. last_interaction=affection.last_interaction,
  47. recent_changes=[AffectionLogResponse.from_orm(log) for log in recent_logs]
  48. )
  49. return response