75 lines
2.0 KiB
Python
75 lines
2.0 KiB
Python
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 read_payload, valid_text
|
|
|
|
|
|
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"},
|
|
)
|
|
|
|
if not valid_text(payload["text"], 4000):
|
|
raise invalid("Некорректный текст сообщения")
|
|
|
|
attachments = payload.get("attachment_ids", [])
|
|
if not isinstance(attachments, list) or attachments:
|
|
raise invalid("В ЛР 3 поддерживаются сообщения без вложений")
|
|
|
|
message = await create_message_once(
|
|
chat_uuid,
|
|
user["id"],
|
|
payload["text"],
|
|
keys[0],
|
|
)
|
|
|
|
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)
|