273 lines
7.8 KiB
Python
273 lines
7.8 KiB
Python
from __future__ import annotations
|
|
|
|
import asyncio
|
|
import hashlib
|
|
from contextlib import asynccontextmanager
|
|
from uuid import UUID, uuid4
|
|
|
|
from fastapi import APIRouter, Request
|
|
from fastapi.responses import Response
|
|
from starlette.concurrency import run_in_threadpool
|
|
from starlette.requests import ClientDisconnect
|
|
|
|
from app.db import pool
|
|
from app.dependencies import accessible_chat, current_user
|
|
from app.errors import ApiError, invalid, not_found
|
|
from app.images import MAX_BYTES, inspect_image, validate_filename
|
|
from app.object_locks import object_lock_id
|
|
from app.responses import json_response
|
|
from app.storage import bucket_name, get_object, put_object
|
|
from app.validation import parse_uuid
|
|
|
|
|
|
router = APIRouter()
|
|
binary_slot = asyncio.Semaphore(1)
|
|
|
|
PUBLIC_FIELDS = (
|
|
"id",
|
|
"chat_id",
|
|
"owner_id",
|
|
"filename",
|
|
"content_type",
|
|
"size_bytes",
|
|
"sha256",
|
|
"status",
|
|
"created_at",
|
|
"updated_at",
|
|
)
|
|
|
|
|
|
@asynccontextmanager
|
|
async def binary_operation():
|
|
try:
|
|
await asyncio.wait_for(binary_slot.acquire(), timeout=3)
|
|
except TimeoutError:
|
|
raise ApiError(
|
|
503,
|
|
"unavailable",
|
|
"Обработка файлов временно занята",
|
|
) from None
|
|
|
|
try:
|
|
yield
|
|
finally:
|
|
binary_slot.release()
|
|
|
|
|
|
def public_attachment(row: dict) -> dict:
|
|
result = {field: row[field] for field in PUBLIC_FIELDS}
|
|
result["variants"] = []
|
|
result["error_code"] = None
|
|
return result
|
|
|
|
|
|
async def read_image_body(request: Request) -> bytes:
|
|
lengths = request.headers.getlist("content-length")
|
|
|
|
if len(lengths) > 1:
|
|
raise invalid("Некорректный Content-Length")
|
|
|
|
expected = None
|
|
if lengths:
|
|
value = lengths[0]
|
|
if not value.isascii() or not value.isdecimal():
|
|
raise invalid("Некорректный Content-Length")
|
|
|
|
if len(value) > 20:
|
|
raise ApiError(
|
|
413, "payload_too_large", "Файл превышает 10 MiB"
|
|
)
|
|
|
|
expected = int(value)
|
|
if expected > MAX_BYTES:
|
|
raise ApiError(
|
|
413, "payload_too_large", "Файл превышает 10 MiB"
|
|
)
|
|
|
|
data = bytearray()
|
|
|
|
async for chunk in request.stream():
|
|
if len(data) + len(chunk) > MAX_BYTES:
|
|
raise ApiError(
|
|
413, "payload_too_large", "Файл превышает 10 MiB"
|
|
)
|
|
data.extend(chunk)
|
|
|
|
if expected is not None and len(data) != expected:
|
|
raise invalid("Размер тела не соответствует Content-Length")
|
|
|
|
return bytes(data)
|
|
|
|
|
|
async def accessible_attachment(
|
|
attachment_id: UUID,
|
|
user_id: UUID,
|
|
) -> dict:
|
|
async with pool.connection() as conn:
|
|
cursor = await conn.execute(
|
|
"""
|
|
SELECT a.id, a.chat_id, a.owner_id,
|
|
a.filename, a.content_type, a.size_bytes,
|
|
a.sha256, a.object_key, a.status,
|
|
a.created_at, a.updated_at
|
|
FROM attachments AS a
|
|
WHERE a.id = %s
|
|
AND EXISTS (
|
|
SELECT 1
|
|
FROM chat_members AS cm
|
|
WHERE cm.chat_id = a.chat_id
|
|
AND cm.user_id = %s
|
|
)
|
|
""",
|
|
(attachment_id, user_id),
|
|
)
|
|
row = await cursor.fetchone()
|
|
|
|
if row is None:
|
|
raise not_found()
|
|
|
|
return row
|
|
|
|
|
|
@router.post("/api/v1/chats/{chat_id}/attachments")
|
|
async def upload_attachment(chat_id: str, request: Request):
|
|
user, _ = await current_user(request)
|
|
chat_uuid, _ = await accessible_chat(chat_id, user["id"])
|
|
|
|
filenames = request.query_params.getlist("filename")
|
|
if len(filenames) != 1:
|
|
raise invalid("Требуется одно имя файла")
|
|
|
|
filename = validate_filename(filenames[0])
|
|
|
|
content_types = request.headers.getlist("content-type")
|
|
if len(content_types) != 1:
|
|
raise ApiError(
|
|
415,
|
|
"unsupported_media_type",
|
|
"Требуется Content-Type изображения",
|
|
)
|
|
|
|
declared_type = content_types[0].split(";", 1)[0].strip().lower()
|
|
if declared_type not in ("image/png", "image/jpeg"):
|
|
raise ApiError(
|
|
415,
|
|
"unsupported_media_type",
|
|
"Допустимы только image/png и image/jpeg",
|
|
)
|
|
|
|
async with binary_operation():
|
|
try:
|
|
data = await asyncio.wait_for(
|
|
read_image_body(request),
|
|
timeout=60,
|
|
)
|
|
except ClientDisconnect:
|
|
raise invalid("Загрузка файла прервана") from None
|
|
except TimeoutError:
|
|
raise invalid("Превышено время загрузки файла") from None
|
|
|
|
content_type = await run_in_threadpool(
|
|
inspect_image,
|
|
data,
|
|
declared_type,
|
|
)
|
|
|
|
attachment_id = uuid4()
|
|
object_key = f"originals/{attachment_id}"
|
|
digest = hashlib.sha256(data).hexdigest()
|
|
|
|
async with pool.connection() as conn:
|
|
await conn.execute(
|
|
"SET LOCAL idle_in_transaction_session_timeout = '60s'"
|
|
)
|
|
await conn.execute(
|
|
"SELECT pg_advisory_xact_lock(%s)",
|
|
(object_lock_id(bucket_name(), object_key),),
|
|
)
|
|
|
|
await put_object(object_key, data, content_type)
|
|
|
|
cursor = await conn.execute(
|
|
"""
|
|
INSERT INTO attachments (
|
|
id, chat_id, owner_id, filename,
|
|
content_type, size_bytes, sha256, object_key
|
|
)
|
|
VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
|
|
RETURNING id, chat_id, owner_id, filename,
|
|
content_type, size_bytes, sha256,
|
|
status, created_at, updated_at
|
|
""",
|
|
(
|
|
attachment_id,
|
|
chat_uuid,
|
|
user["id"],
|
|
filename,
|
|
content_type,
|
|
len(data),
|
|
digest,
|
|
object_key,
|
|
),
|
|
)
|
|
row = await cursor.fetchone()
|
|
|
|
return json_response(public_attachment(row), 201)
|
|
|
|
|
|
@router.get("/api/v1/attachments/{attachment_id}")
|
|
async def get_attachment(attachment_id: str, request: Request):
|
|
user, _ = await current_user(request)
|
|
|
|
row = await accessible_attachment(
|
|
parse_uuid(attachment_id),
|
|
user["id"],
|
|
)
|
|
|
|
return json_response(public_attachment(row))
|
|
|
|
|
|
@router.get("/api/v1/attachments/{attachment_id}/content")
|
|
async def download_attachment(attachment_id: str, request: Request):
|
|
user, _ = await current_user(request)
|
|
|
|
row = await accessible_attachment(
|
|
parse_uuid(attachment_id),
|
|
user["id"],
|
|
)
|
|
|
|
variants = request.query_params.getlist("variant")
|
|
if len(variants) > 1:
|
|
raise invalid("Допускается один вариант изображения")
|
|
if variants and variants[0] != "original":
|
|
raise not_found()
|
|
|
|
if row["status"] != "ready":
|
|
raise ApiError(
|
|
409,
|
|
"conflict",
|
|
"Вложение ещё не готово",
|
|
)
|
|
|
|
async with binary_operation():
|
|
data = await get_object(row["object_key"])
|
|
|
|
if (
|
|
len(data) != row["size_bytes"]
|
|
or hashlib.sha256(data).hexdigest() != row["sha256"]
|
|
):
|
|
raise ApiError(
|
|
503,
|
|
"unavailable",
|
|
"Оригинал временно недоступен",
|
|
)
|
|
|
|
return Response(
|
|
content=data,
|
|
media_type=row["content_type"],
|
|
headers={
|
|
"X-Content-Type-Options": "nosniff",
|
|
"Cache-Control": "private, no-store",
|
|
},
|
|
)
|