feat-(move2lab2, postgres settings, repo base and other)
This commit is contained in:
@@ -0,0 +1,78 @@
|
||||
import base64
|
||||
from fastapi import HTTPException, APIRouter, Query
|
||||
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
|
||||
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
def _encode_msg_cursor(chat_id: str, created_at: str, msg_id: str) -> str:
|
||||
raw = f"m|{chat_id}|{created_at}|{msg_id}"
|
||||
return base64.urlsafe_b64encode(raw.encode("utf-8")).decode("ascii").rstrip("=")
|
||||
|
||||
|
||||
def _decode_msg_cursor(scope_chat_id: str, cursor: str) -> tuple[str, str]:
|
||||
try:
|
||||
padded = cursor + "=" * (-len(cursor) % 4)
|
||||
raw = base64.urlsafe_b64decode(padded).decode("utf-8")
|
||||
parts = raw.split("|", 3)
|
||||
if len(parts) != 4 or parts[0] != "m":
|
||||
raise ValueError("bad cursor structure")
|
||||
chat_id, created_at, msg_id = parts[1], parts[2], parts[3]
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=400, detail="invalid cursor") from e
|
||||
|
||||
if scope_chat_id != chat_id:
|
||||
raise HTTPException(status_code=400, detail="cursor from another chat")
|
||||
|
||||
return created_at, msg_id
|
||||
|
||||
|
||||
@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()
|
||||
)
|
||||
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))
|
||||
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))
|
||||
|
||||
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)]
|
||||
|
||||
page_items = all_msgs[:limit]
|
||||
|
||||
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)
|
||||
Reference in New Issue
Block a user