add level 3
This commit is contained in:
+29
-9
@@ -1,4 +1,5 @@
|
||||
import asyncio
|
||||
from datetime import datetime, timezone
|
||||
from hashlib import sha256
|
||||
import os
|
||||
from tempfile import TemporaryFile
|
||||
@@ -15,6 +16,7 @@ from .errors import ApiError
|
||||
from .models import Attachment
|
||||
from .routes import get_current_user, get_store
|
||||
from .storage.postgres import PostgresStore
|
||||
from .broker import publish
|
||||
|
||||
router = APIRouter()
|
||||
Image.MAX_IMAGE_PIXELS = 40000000
|
||||
@@ -42,7 +44,7 @@ def inspect_image(file, content_type, max_pixels):
|
||||
file.seek(0)
|
||||
|
||||
|
||||
@router.post("/api/v1/chats/{chat_id}/attachments", response_model=Attachment, status_code=201)
|
||||
@router.post("/api/v1/chats/{chat_id}/attachments", response_model=Attachment, status_code=202)
|
||||
async def upload(chat_id: UUID, request: Request, filename: str = Query(...),
|
||||
user: dict = Depends(get_current_user), store: PostgresStore = Depends(get_store)):
|
||||
await store.get_chat_for_member(chat_id, user["id"])
|
||||
@@ -80,8 +82,8 @@ async def upload(chat_id: UUID, request: Request, filename: str = Query(...),
|
||||
digest.update(chunk)
|
||||
await run_in_threadpool(file.write, chunk)
|
||||
await run_in_threadpool(inspect_image, file, content_type, s3.settings.max_pixels)
|
||||
attachment_id = uuid4()
|
||||
key = f"originals/{attachment_id}"
|
||||
attachment_id, job_id = uuid4(), uuid4()
|
||||
key = f"staging/{attachment_id}/original"
|
||||
async with store.attachment_transaction() as connection:
|
||||
await s3.put(key, file, size, content_type)
|
||||
# Disabled by default; models a crash after PUT, before INSERT.
|
||||
@@ -89,9 +91,15 @@ async def upload(chat_id: UUID, request: Request, filename: str = Query(...),
|
||||
raise ApiError(503, "unavailable", "Инъецирован отказ после S3 PUT")
|
||||
attachment = await store.create_attachment(
|
||||
attachment_id, chat_id, user["id"], filename, content_type,
|
||||
size, digest.hexdigest(), key, connection=connection,
|
||||
size, digest.hexdigest(), key, job_id, connection=connection,
|
||||
)
|
||||
return attachment # Transaction has committed before 201.
|
||||
await publish({
|
||||
"schema_version": 1, "job_id": str(job_id), "type": "attachment.process.v1",
|
||||
"attachment_id": str(attachment_id), "pipeline_version": 1, "attempt": 1,
|
||||
"created_at": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"),
|
||||
})
|
||||
attachment["variants"] = []
|
||||
return attachment
|
||||
except ClientDisconnect:
|
||||
raise ApiError(400, "invalid_request", "Загрузка прервана") from None
|
||||
except TimeoutError:
|
||||
@@ -109,8 +117,20 @@ async def download(attachment_id: UUID, request: Request,
|
||||
variant: str = Query("original", pattern="^(original|thumbnail|crop|optimized)$"),
|
||||
user: dict = Depends(get_current_user), store: PostgresStore = Depends(get_store)):
|
||||
attachment = await store.attachment_for_member(attachment_id, user["id"])
|
||||
if variant != "original":
|
||||
raise ApiError(404, "not_found", "Вариант не найден")
|
||||
data = await request.app.state.s3.download(attachment)
|
||||
return Response(data, media_type=attachment["content_type"],
|
||||
if attachment["status"] != "ready":
|
||||
raise ApiError(409, "conflict", "Вложение ещё не готово")
|
||||
if variant == "original":
|
||||
data = await request.app.state.s3.download(attachment)
|
||||
content_type = attachment["content_type"]
|
||||
else:
|
||||
matching = [item for item in attachment["variants"] if item["name"] == variant]
|
||||
if not matching:
|
||||
raise ApiError(404, "not_found", "Вариант не найден")
|
||||
item = matching[0]
|
||||
suffix = {"thumbnail": "thumbnail.jpg", "crop": "crop.jpg", "optimized": "optimized.webp"}[variant]
|
||||
data = await request.app.state.s3.download_key(
|
||||
f"variants/{attachment_id}/{suffix}", item["size_bytes"], item["sha256"]
|
||||
)
|
||||
content_type = item["content_type"]
|
||||
return Response(data, media_type=content_type,
|
||||
headers={"X-Content-Type-Options": "nosniff", "Cache-Control": "private, no-store"})
|
||||
|
||||
Reference in New Issue
Block a user