Files
mtusi2026lab7-Leskovskiy/src/routers/messages.py
T

147 lines
4.2 KiB
Python

import uuid
import json
import hashlib
import base64
from datetime import datetime
from fastapi import APIRouter, Depends, Request
from sqlalchemy.orm import Session
from ..db import get_db
from ..models import (
User,
ChatMember,
Message,
MessageAttachment,
IdempotencyKey,
Attachment,
)
from ..schemas import CreateMessageIn, MessageOut, MessagePage
from ..errors import ApiError
from ..auth import current_user
router = APIRouter(prefix="/api/v1/chats/{chat_id}/messages", tags=["messages"])
def _msg_out(db: Session, m: Message) -> MessageOut:
atts = [
a.attachment_id
for a in db.query(MessageAttachment)
.filter(MessageAttachment.message_id == m.id)
.order_by(MessageAttachment.position)
.all()
]
return MessageOut(
id=m.id,
chat_id=m.chat_id,
sender_id=m.sender_id,
text=m.text,
created_at=m.created_at,
attachment_ids=atts,
)
def _require_member(db: Session, chat_id: uuid.UUID, user_id: uuid.UUID) -> None:
if not db.get(ChatMember, (chat_id, user_id)):
raise ApiError(404, "not_found", "chat not found")
@router.post("", status_code=201, response_model=MessageOut)
def send(
chat_id: uuid.UUID,
body: CreateMessageIn,
request: Request,
db: Session = Depends(get_db),
user: User = Depends(current_user),
):
_require_member(db, chat_id, user.id)
key = request.headers.get("idempotency-key", "")
if not key or len(key) > 128:
raise ApiError(400, "invalid_request", "Idempotency-Key required")
if not body.text.strip() and not body.attachment_ids:
raise ApiError(400, "invalid_request", "empty message")
for aid in body.attachment_ids:
a = db.get(Attachment, aid)
if not a or a.chat_id != chat_id:
raise ApiError(404, "not_found", "attachment not found")
path = f"/api/v1/chats/{chat_id}/messages"
body_hash = hashlib.sha256(
json.dumps(body.model_dump(), sort_keys=True, default=str).encode()
).hexdigest()
existing = db.get(IdempotencyKey, (user.id, "POST", path, key))
if existing:
if existing.request_hash != body_hash:
raise ApiError(409, "conflict", "idempotency key reused with different body")
return json.loads(existing.response_json)
m = Message(chat_id=chat_id, sender_id=user.id, text=body.text)
db.add(m)
db.flush() # чтобы появился m.id
for i, aid in enumerate(body.attachment_ids):
db.add(MessageAttachment(message_id=m.id, attachment_id=aid, position=i))
db.flush() # чтобы _msg_out увидел MessageAttachment
out = _msg_out(db, m)
db.add(
IdempotencyKey(
user_id=user.id,
method="POST",
path=path,
key=key,
request_hash=body_hash,
response_json=json.dumps(out.model_dump(), default=str),
)
)
db.commit()
return out
@router.get("", response_model=MessagePage)
def list_messages(
chat_id: uuid.UUID,
limit: int = 50,
cursor: str | None = None,
db: Session = Depends(get_db),
user: User = Depends(current_user),
):
_require_member(db, chat_id, user.id)
if limit < 1 or limit > 100:
raise ApiError(400, "invalid_request", "bad limit")
q = (
db.query(Message)
.filter(Message.chat_id == chat_id)
.order_by(Message.created_at, Message.id)
)
if cursor:
try:
c = json.loads(base64.urlsafe_b64decode(cursor.encode()).decode())
ts = datetime.fromisoformat(c["t"])
mid = uuid.UUID(c["i"])
q = q.filter(
(Message.created_at > ts)
| ((Message.created_at == ts) & (Message.id > mid))
)
except Exception:
raise ApiError(400, "invalid_request", "bad cursor")
rows = q.limit(limit + 1).all()
has_more = len(rows) > limit
rows = rows[:limit]
next_cursor = None
if has_more:
last = rows[-1]
payload = json.dumps({"t": last.created_at.isoformat(), "i": str(last.id)}).encode()
next_cursor = base64.urlsafe_b64encode(payload).decode()
return MessagePage(items=[_msg_out(db, m) for m in rows], next_cursor=next_cursor)