Files
mtusi2026lab2-fork/api/routes/chats.py
T
2026-11-14 04:50:02 +03:00

112 lines
3.4 KiB
Python

import uuid
from fastapi import APIRouter, Request, status
from ..models import CreateChatRequest
from ..utils import authenticate_user, validate_uuid, format_iso, get_utc_now
from ..exceptions import ApiException
from ..db import get_pool
router = APIRouter(tags=["chats"])
@router.post("/chats", status_code=status.HTTP_201_CREATED)
async def create_chat(body: CreateChatRequest, request: Request):
caller_id = await authenticate_user(request)
if not body.title.strip() or len(body.title) > 128:
raise ApiException(400, "invalid_request", "Invalid title")
if len(body.member_ids) != len(set(body.member_ids)):
raise ApiException(400, "invalid_request", "Duplicate member_ids")
if caller_id not in body.member_ids:
raise ApiException(400, "invalid_request", "Caller must be included in member_ids")
pool = get_pool()
member_uuids = []
for mid in body.member_ids:
validate_uuid(mid)
u = uuid.UUID(mid)
exists = await pool.fetchval("SELECT id FROM users WHERE id = $1", u)
if not exists:
raise ApiException(400, "invalid_request", f"Member {mid} not found")
member_uuids.append(u)
cid = uuid.uuid4()
now = get_utc_now()
async with pool.acquire() as conn:
async with conn.transaction():
await conn.execute("INSERT INTO chats (id, title, created_at) VALUES ($1, $2, $3)", cid, body.title, now)
for m in member_uuids:
await conn.execute("INSERT INTO chat_members (chat_id, user_id) VALUES ($1, $2)", cid, m)
return {
"id": str(cid),
"title": body.title,
"member_ids": body.member_ids,
"created_at": format_iso(now)
}
@router.get("/chats")
async def list_chats(request: Request, limit: int = 50):
caller_id = await authenticate_user(request)
if limit < 1 or limit > 100:
raise ApiException(400, "invalid_request", "Limit must be between 1 and 100")
pool = get_pool()
rows = await pool.fetch("""
SELECT c.id, c.title, c.created_at, array_agg(cm.user_id::text) as member_ids
FROM chats c
JOIN chat_members cm ON c.id = cm.chat_id
WHERE c.id IN (SELECT chat_id FROM chat_members WHERE user_id = $1)
GROUP BY c.id, c.title, c.created_at
ORDER BY c.created_at ASC, c.id ASC
LIMIT $2
""", uuid.UUID(caller_id), limit)
items = [
{
"id": str(r["id"]),
"title": r["title"],
"member_ids": list(r["member_ids"]),
"created_at": format_iso(r["created_at"])
}
for r in rows
]
result = {
"items": items,
"next_cursor": None
}
print("API RESPONSE:", result)
return result
@router.get("/chats/{chat_id}")
async def get_chat(chat_id: str, request: Request):
caller_id = await authenticate_user(request)
validate_uuid(chat_id)
pool = get_pool()
row = await pool.fetchrow("""
SELECT c.id, c.title, c.created_at, array_agg(cm.user_id::text) as member_ids
FROM chats c
JOIN chat_members cm ON c.id = cm.chat_id
WHERE c.id = $1
GROUP BY c.id, c.title, c.created_at
""", uuid.UUID(chat_id))
if not row or caller_id not in row["member_ids"]:
raise ApiException(404, "not_found", "Chat not found")
return {
"id": str(row["id"]),
"title": row["title"],
"member_ids": list(row["member_ids"]),
"created_at": format_iso(row["created_at"])
}