Files
MCM/api/routes/conversations.py

80 lines
2.9 KiB
Python

from fastapi import APIRouter, Depends, HTTPException, Query, status
from sqlalchemy.orm import Session
from api.auth import require_api_key
from db.database import get_db
from schemas import ConversationResponse, MessageResponse
from services import conversation_service
router = APIRouter(prefix="/conversations", tags=["conversations"])
@router.get("/", response_model=list[ConversationResponse])
def list_conversations(
channel: str | None = Query(None),
archived: bool = Query(False),
db: Session = Depends(get_db),
_: str = Depends(require_api_key),
):
convs = conversation_service.get_all(db, channel=channel, archived=archived)
result = []
for conv in convs:
last_msg = conv.messages[-1] if conv.messages else None
contact_id = conv.participants[0].id if conv.participants else None
result.append(
ConversationResponse(
**{c.key: getattr(conv, c.key) for c in conv.__table__.columns},
last_message=MessageResponse.model_validate(last_msg) if last_msg else None,
unread_count=conversation_service.unread_count(db, conv.id),
contact_id=contact_id,
)
)
return result
@router.get("/{conv_id}", response_model=ConversationResponse)
def get_conversation(
conv_id: str,
db: Session = Depends(get_db),
_: str = Depends(require_api_key),
):
conv = conversation_service.get_by_id(db, conv_id)
if not conv:
raise HTTPException(status_code=404, detail="Conversation not found")
last_msg = conv.messages[-1] if conv.messages else None
contact_id = conv.participants[0].id if conv.participants else None
return ConversationResponse(
**{c.key: getattr(conv, c.key) for c in conv.__table__.columns},
last_message=MessageResponse.model_validate(last_msg) if last_msg else None,
unread_count=conversation_service.unread_count(db, conv.id),
contact_id=contact_id,
)
@router.get("/{conv_id}/messages", response_model=list[MessageResponse])
def get_messages(
conv_id: str,
limit: int = Query(50, ge=1, le=200),
offset: int = Query(0, ge=0),
db: Session = Depends(get_db),
_: str = Depends(require_api_key),
):
conv = conversation_service.get_by_id(db, conv_id)
if not conv:
raise HTTPException(status_code=404, detail="Conversation not found")
msgs = conversation_service.get_messages(db, conv_id, limit=limit, offset=offset)
conversation_service.mark_all_read(db, conv_id)
return [MessageResponse.model_validate(m) for m in msgs]
@router.delete("/{conv_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_conversation(
conv_id: str,
db: Session = Depends(get_db),
_: str = Depends(require_api_key),
):
conv = conversation_service.get_by_id(db, conv_id)
if not conv:
raise HTTPException(status_code=404, detail="Conversation not found")
conversation_service.delete(db, conv)