Implement lab4 S3 attachments and reliability checks
This commit is contained in:
@@ -0,0 +1,90 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
from fastapi import APIRouter, Request
|
||||
|
||||
from app.dependencies import accessible_chat, current_user
|
||||
from app.errors import invalid
|
||||
from app.idempotency import create_message_once
|
||||
from app.pagination import page_response, pagination
|
||||
from app.responses import json_response
|
||||
from app.store import store
|
||||
from app.validation import parse_uuid, read_payload
|
||||
|
||||
|
||||
router = APIRouter()
|
||||
KEY_RE = re.compile(r"[A-Za-z0-9._:-]{1,128}", re.ASCII)
|
||||
|
||||
|
||||
@router.post("/api/v1/chats/{chat_id}/messages")
|
||||
async def create_message(chat_id: str, request: Request):
|
||||
user, _ = await current_user(request)
|
||||
|
||||
chat_uuid, _ = await accessible_chat(
|
||||
chat_id,
|
||||
user["id"],
|
||||
)
|
||||
|
||||
keys = request.headers.getlist("idempotency-key")
|
||||
if len(keys) != 1 or KEY_RE.fullmatch(keys[0]) is None:
|
||||
raise invalid("Требуется корректный Idempotency-Key")
|
||||
|
||||
payload = await read_payload(
|
||||
request,
|
||||
{"text"},
|
||||
optional_fields={"attachment_ids"},
|
||||
)
|
||||
|
||||
text = payload["text"]
|
||||
if not isinstance(text, str) or len(text) > 4000:
|
||||
raise invalid("Некорректный текст сообщения")
|
||||
|
||||
raw_attachment_ids = payload.get("attachment_ids", [])
|
||||
if (
|
||||
not isinstance(raw_attachment_ids, list)
|
||||
or len(raw_attachment_ids) > 10
|
||||
):
|
||||
raise invalid("Допускается список максимум из 10 вложений")
|
||||
|
||||
attachment_ids = [
|
||||
parse_uuid(value)
|
||||
for value in raw_attachment_ids
|
||||
]
|
||||
|
||||
if len(set(attachment_ids)) != len(attachment_ids):
|
||||
raise invalid("Вложения не должны повторяться")
|
||||
|
||||
if not text.strip() and not attachment_ids:
|
||||
raise invalid("Сообщение должно содержать текст или вложение")
|
||||
|
||||
message = await create_message_once(
|
||||
chat_uuid,
|
||||
user["id"],
|
||||
text,
|
||||
keys[0],
|
||||
attachment_ids=attachment_ids,
|
||||
)
|
||||
|
||||
return json_response(message, 201)
|
||||
|
||||
|
||||
@router.get("/api/v1/chats/{chat_id}/messages")
|
||||
async def list_messages(chat_id: str, request: Request):
|
||||
user, _ = await current_user(request)
|
||||
|
||||
chat_uuid, _ = await accessible_chat(
|
||||
chat_id,
|
||||
user["id"],
|
||||
)
|
||||
|
||||
scope = f"messages:{chat_uuid}"
|
||||
limit, after = pagination(request, scope)
|
||||
|
||||
rows = await store.list_messages(
|
||||
chat_uuid,
|
||||
limit,
|
||||
after,
|
||||
)
|
||||
|
||||
return page_response(rows, limit, scope)
|
||||
Reference in New Issue
Block a user