feat-(routes updating)

This commit is contained in:
2026-11-05 21:56:37 +03:00
parent 273519109e
commit d1a8c0394b
15 changed files with 345 additions and 63 deletions
+47 -35
View File
@@ -1,10 +1,12 @@
import base64
from fastapi import HTTPException, APIRouter, Query
from fastapi import HTTPException, APIRouter, Query, status
from typing import Optional
from uuid import UUID
from src.pydantic_valid.message import Message, CreateMessage
from src.pydantic_valid.page_response import PageResponse
from src.api.dependencies import Repo, CurrentUser, generate_id, get_now_iso
from src.api.dependencies import DbSession, CurrentUser, generate_id, get_now_iso
from src.api.repositories.main_repo import Repository
import datetime
router = APIRouter()
@@ -33,46 +35,56 @@ def _decode_msg_cursor(scope_chat_id: str, cursor: str) -> tuple[str, str]:
@router.post("/v1/chats/{chat_id}/messages", response_model=Message, status_code=201)
async def send_message(chat_id: UUID, msg_in: CreateMessage, repo: Repo, crnt_usr_id: CurrentUser):
chat = repo.chats.chats_db.get(str(chat_id))
if not chat:
raise HTTPException(status_code=404, detail="Chat not found")
if crnt_usr_id not in chat["member_ids"]:
raise HTTPException(status_code=404, detail="Not found")
msg_data = Message(
id = generate_id(),
chat_id = str(chat_id),
sender_id = crnt_usr_id,
text = msg_in.text,
created_at = get_now_iso()
async def send_message(chat_id: UUID, msg_in: CreateMessage, session: DbSession, current_user: CurrentUser):
repo = Repository(session)
if not await repo.chats.is_user_member(chat_id, current_user.id):
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,
detail="chat not found")
message = await repo.messages.create(chat_id=chat_id,
sender_id=current_user.id,
text=msg_in.text)
return Message(
id=str(message.id),
chat_id=str(message.chat_id),
sender_id=str(message.sender_id),
text=message.text,
created_at=message.created_at.strftime("%Y-%m-%dT%H:%M:%SZ")
)
if await repo.create_message(msg_data):
return msg_data
else:
raise HTTPException(status_code=404, detail="Chat not found")
@router.get("/v1/chats/{chat_id}/messages", response_model=PageResponse, status_code=200)
async def list_messages(repo: Repo, crnt_usr_id: CurrentUser, chat_id: UUID, limit: int = Query(default=50, ge=1, le=100), cursor: Optional[str] = Query(default=None, min_length=1)):
chat = repo.chats.chats_db.get(str(chat_id))
async def list_messages(session: DbSession, current_user: CurrentUser, chat_id: UUID, limit: int = Query(default=50, ge=1, le=100), cursor: Optional[str] = Query(default=None, min_length=1)):
repo = Repository(session)
chat = await repo.chats.get_by_id_with_members(chat_id)
if not chat:
raise HTTPException(status_code=404, detail="Chat not found")
if crnt_usr_id not in chat["member_ids"]:
raise HTTPException(status_code=404, detail="Not found")
# all_msgs = repo.messages.message_db.get(str(chat_id), [])
# all_msgs.sort(key=lambda x: (x["created_at"], x["id"]))
all_msgs = repo.messages.get_sorted_messages(str(chat_id))
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,
detail="chat not found")
member_ids = {str(m.user_id) for m in chat.members}
if str(current_user.id) not in member_ids:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,
detail="chat not found")
cursor_created_at = None
cursor_msg_id = None
if cursor:
cursor_created_at, cursor_message_id = _decode_msg_cursor(str(chat_id), cursor)
all_msgs = [m for m in all_msgs if (m["created_at"], m["id"]) > (cursor_created_at, cursor_message_id)]
created_at_str, msg_id_str = _decode_msg_cursor(str(chat_id), cursor)
cursor_created_at = datetime.fromisoformat(created_at_str.replace("Z", "+00:00"))
cursor_msg_id = UUID(msg_id_str)
page_items = all_msgs[:limit]
messages, has_more = await repo.messages.get_chat_messages(chat_id=chat_id, limit=limit, cursor_created_at=cursor_created_at, cursor_msg_id=cursor_msg_id)
next_cursor = None
if len(all_msgs) > limit and page_items:
last = page_items[-1]
next_cursor = _encode_msg_cursor(str(chat_id), last["created_at"], last["id"])
return PageResponse(items=page_items, next_cursor=next_cursor)
if has_more and messages:
last = messages[-1]
next_cursor = _encode_msg_cursor(chat_id=str(chat_id), created_at=last.created_at.strftime("%Y-%m-%dT%H:%M:%SZ"), msg_id=str(last.id))
return PageResponse(
items=[Message(id=str(msg.id), chat_id=str(msg.chat_id), sender_id=str(msg.sender_id), text=msg.text, created_at=msg.created_at.strftime("%Y-%m-%dT%H:%M:%SZ"))
for msg in messages],
next_cursor=next_cursor,
)