forked from mtusi2026/mtusi2026lab2
+ скопировала все файлы проекта из л.р. 1
This commit is contained in:
@@ -0,0 +1,91 @@
|
||||
import base64
|
||||
import json
|
||||
from uuid import UUID
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, Security
|
||||
from ..models.schemas import Chat, ChatPage, CreateChat
|
||||
from ..storage.memory import storage
|
||||
from .security import dev_user
|
||||
|
||||
|
||||
router = APIRouter(prefix="/api/v1/chats", tags=["chats"])
|
||||
|
||||
|
||||
def _current_user_id(x_user_id: str | None = Security(dev_user)) -> UUID:
|
||||
if not x_user_id:
|
||||
raise HTTPException(status_code=401, detail="unauthorized")
|
||||
try:
|
||||
return UUID(x_user_id)
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=401, detail="unauthorized")
|
||||
|
||||
|
||||
def _encode_cursor(user_id: UUID, chat: Chat) -> str:
|
||||
"""Простой курсор: user_id + id + created_at, base64."""
|
||||
data = {"user_id": str(user_id), "id": str(chat.id), "created_at": chat.created_at.isoformat()}
|
||||
return base64.urlsafe_b64encode(json.dumps(data).encode()).decode()
|
||||
|
||||
|
||||
def _decode_cursor(user_id: UUID, cursor: str) -> tuple:
|
||||
try:
|
||||
data = json.loads(base64.urlsafe_b64decode(cursor.encode()).decode())
|
||||
if data.get("user_id") != str(user_id):
|
||||
raise ValueError("cursor_user_mismatch")
|
||||
return UUID(data["id"]), data["created_at"]
|
||||
except Exception:
|
||||
raise HTTPException(status_code=400, detail="invalid_request")
|
||||
|
||||
|
||||
@router.post(
|
||||
path="",
|
||||
summary="Создать чат",
|
||||
response_model=Chat,
|
||||
status_code=201,
|
||||
)
|
||||
def create_chat(
|
||||
payload: CreateChat,
|
||||
user_id: UUID = Depends(_current_user_id),
|
||||
) -> Chat:
|
||||
"""Вызывающий должен входить в member_ids"""
|
||||
|
||||
if user_id not in payload.member_ids:
|
||||
raise HTTPException(status_code=400, detail="invalid_request")
|
||||
if len(set(payload.member_ids)) != len(payload.member_ids):
|
||||
raise HTTPException(status_code=400, detail="invalid_request")
|
||||
try:
|
||||
return storage.create_chat(payload.title, list(payload.member_ids))
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=400, detail="invalid_request")
|
||||
|
||||
|
||||
@router.get(
|
||||
path="",
|
||||
summary="Получить список чатов текущего пользователя",
|
||||
response_model=ChatPage,
|
||||
)
|
||||
def list_chats(
|
||||
user_id: UUID = Depends(_current_user_id),
|
||||
limit: int = Query(50, ge=1, le=100),
|
||||
cursor: str | None = None,
|
||||
) -> ChatPage:
|
||||
chats = storage.list_chats_for_user(user_id)
|
||||
if cursor:
|
||||
cid, ccreated = _decode_cursor(user_id, cursor)
|
||||
chats = [c for c in chats if (c.created_at.isoformat(), str(c.id)) > (ccreated, str(cid))]
|
||||
page = chats[:limit]
|
||||
next_cursor = _encode_cursor(user_id, page[-1]) if len(chats) > limit else None
|
||||
return ChatPage(items=page, next_cursor=next_cursor)
|
||||
|
||||
|
||||
@router.get(
|
||||
path="/{chat_id}",
|
||||
summary="Получить доступный чат по идентификатору",
|
||||
response_model=Chat,
|
||||
)
|
||||
def get_chat(
|
||||
chat_id: UUID,
|
||||
user_id: UUID = Depends(_current_user_id),
|
||||
) -> Chat:
|
||||
chat = storage.get_chat(chat_id)
|
||||
if chat is None or user_id not in chat.member_ids:
|
||||
raise HTTPException(status_code=404, detail="not_found")
|
||||
return chat
|
||||
Reference in New Issue
Block a user