forked from mtusi2026/mtusi2026lab3
101 lines
3.6 KiB
Python
101 lines
3.6 KiB
Python
import base64
|
|
import json
|
|
import uuid
|
|
from datetime import datetime
|
|
|
|
from fastapi import APIRouter, Depends, Query, Security
|
|
from sqlalchemy import select
|
|
from sqlalchemy.orm import Session
|
|
|
|
from ..deps import current_user, get_db, parse_uuid
|
|
from ..errors import ApiError
|
|
from ..models import Chat, ChatMember, User
|
|
from ..schemas import ChatOut, ChatPage, CreateChat
|
|
|
|
router = APIRouter()
|
|
|
|
|
|
def _chat_out(chat: Chat, member_ids) -> ChatOut:
|
|
return ChatOut(id=chat.id, title=chat.title, member_ids=list(member_ids), created_at=chat.created_at)
|
|
|
|
|
|
def _member_ids(db: Session, chat_id) -> list:
|
|
return list(db.scalars(select(ChatMember.user_id).where(ChatMember.chat_id == chat_id)))
|
|
|
|
|
|
def _require_member(db: Session, chat_id, user_id) -> Chat:
|
|
chat = db.get(Chat, chat_id)
|
|
if chat is None:
|
|
raise ApiError(404, "not_found", "Чат не найден")
|
|
if db.get(ChatMember, (chat_id, user_id)) is None:
|
|
raise ApiError(404, "not_found", "Чат не найден")
|
|
return chat
|
|
|
|
|
|
def _encode_cursor(created_at: datetime, id_: uuid.UUID) -> str:
|
|
payload = json.dumps({"t": created_at.isoformat(), "i": str(id_)}).encode()
|
|
return base64.urlsafe_b64encode(payload).decode().rstrip("=")
|
|
|
|
|
|
def _decode_cursor(cursor: str):
|
|
try:
|
|
pad = "=" * (-len(cursor) % 4)
|
|
data = json.loads(base64.urlsafe_b64decode(cursor + pad))
|
|
return datetime.fromisoformat(data["t"]), uuid.UUID(data["i"])
|
|
except Exception:
|
|
raise ApiError(400, "invalid_request", "Некорректный cursor")
|
|
|
|
|
|
@router.post("/api/v1/chats", response_model=ChatOut, status_code=201)
|
|
def create_chat(body: CreateChat, user: User = Security(current_user), db: Session = Depends(get_db)):
|
|
if not body.title.strip():
|
|
raise ApiError(400, "invalid_request", "title не может быть пустым")
|
|
ids = list(dict.fromkeys(body.member_ids))
|
|
if user.id not in ids:
|
|
raise ApiError(400, "invalid_request", "Вызывающий должен быть участником")
|
|
found = set(db.scalars(select(User.id).where(User.id.in_(ids))))
|
|
if found != set(ids):
|
|
raise ApiError(400, "invalid_request", "Неизвестный участник")
|
|
chat = Chat(title=body.title)
|
|
db.add(chat)
|
|
db.flush()
|
|
for uid in ids:
|
|
db.add(ChatMember(chat_id=chat.id, user_id=uid))
|
|
db.commit()
|
|
db.refresh(chat)
|
|
return _chat_out(chat, ids)
|
|
|
|
|
|
@router.get("/api/v1/chats", response_model=ChatPage)
|
|
def list_chats(
|
|
limit: int = Query(50, ge=1, le=100),
|
|
cursor: str | None = Query(None),
|
|
user: User = Security(current_user),
|
|
db: Session = Depends(get_db),
|
|
):
|
|
stmt = (
|
|
select(Chat)
|
|
.join(ChatMember, ChatMember.chat_id == Chat.id)
|
|
.where(ChatMember.user_id == user.id)
|
|
.order_by(Chat.created_at.asc(), Chat.id.asc())
|
|
.limit(limit + 1)
|
|
)
|
|
if cursor:
|
|
t, i = _decode_cursor(cursor)
|
|
stmt = stmt.where((Chat.created_at > t) | ((Chat.created_at == t) & (Chat.id > i)))
|
|
rows = list(db.scalars(stmt))
|
|
next_cursor = None
|
|
if len(rows) > limit:
|
|
rows = rows[:limit]
|
|
last = rows[-1]
|
|
next_cursor = _encode_cursor(last.created_at, last.id)
|
|
items = [_chat_out(c, _member_ids(db, c.id)) for c in rows]
|
|
return ChatPage(items=items, next_cursor=next_cursor)
|
|
|
|
|
|
@router.get("/api/v1/chats/{chat_id}", response_model=ChatOut)
|
|
def get_chat(chat_id: str, user: User = Security(current_user), db: Session = Depends(get_db)):
|
|
cid = parse_uuid(chat_id)
|
|
chat = _require_member(db, cid, user.id)
|
|
return _chat_out(chat, _member_ids(db, cid))
|