Implement lab5 asynchronous image processing
This commit is contained in:
@@ -0,0 +1,108 @@
|
||||
|
||||
import io
|
||||
import re
|
||||
import uuid
|
||||
import hashlib
|
||||
|
||||
from PIL import Image, UnidentifiedImageError
|
||||
|
||||
|
||||
MAX_BYTES = 10 * 1024 * 1024
|
||||
MAX_PIXELS = 40_000_000
|
||||
|
||||
|
||||
def valid_filename(filename):
|
||||
if not isinstance(filename, str):
|
||||
return False
|
||||
|
||||
if not 1 <= len(filename) <= 255:
|
||||
return False
|
||||
|
||||
if filename.strip() == "":
|
||||
return False
|
||||
|
||||
if "/" in filename or "\\" in filename:
|
||||
return False
|
||||
|
||||
if any(ord(ch) < 32 or ord(ch) == 127 for ch in filename):
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
|
||||
def inspect_image(data, declared_mime):
|
||||
if len(data) > MAX_BYTES:
|
||||
raise ValueError("too_large")
|
||||
|
||||
if not data:
|
||||
raise ValueError("invalid_image")
|
||||
|
||||
if declared_mime not in ("image/png", "image/jpeg"):
|
||||
raise ValueError("invalid_image")
|
||||
|
||||
try:
|
||||
with Image.open(io.BytesIO(data)) as image:
|
||||
image_format = image.format
|
||||
|
||||
width, height = image.size
|
||||
|
||||
if width * height > MAX_PIXELS:
|
||||
raise ValueError("too_many_pixels")
|
||||
|
||||
if image_format not in ("PNG", "JPEG"):
|
||||
raise ValueError("invalid_image")
|
||||
|
||||
actual_mime = (
|
||||
"image/png"
|
||||
if image_format == "PNG"
|
||||
else "image/jpeg"
|
||||
)
|
||||
|
||||
if declared_mime != actual_mime:
|
||||
raise ValueError("invalid_image")
|
||||
|
||||
image.verify()
|
||||
|
||||
except Image.DecompressionBombError:
|
||||
raise ValueError("too_many_pixels")
|
||||
except (
|
||||
UnidentifiedImageError,
|
||||
OSError,
|
||||
SyntaxError,
|
||||
EOFError,
|
||||
):
|
||||
raise ValueError("invalid_image")
|
||||
|
||||
return {
|
||||
"content_type": actual_mime,
|
||||
"width": width,
|
||||
"height": height,
|
||||
"size_bytes": len(data),
|
||||
"sha256": hashlib.sha256(data).hexdigest(),
|
||||
}
|
||||
|
||||
def attachment_json(row, variants=None):
|
||||
from datetime import timezone
|
||||
|
||||
def timestamp(value):
|
||||
return value.astimezone(timezone.utc).isoformat(
|
||||
timespec="microseconds"
|
||||
).replace("+00:00", "Z")
|
||||
|
||||
return {
|
||||
"id": str(row["id"]),
|
||||
"chat_id": str(row["chat_id"]),
|
||||
"owner_id": str(row["uploader_id"]),
|
||||
"filename": row["filename"],
|
||||
"content_type": row["content_type"],
|
||||
"size_bytes": row["size_bytes"],
|
||||
"sha256": row["sha256"],
|
||||
"status": row["status"],
|
||||
"variants": variants if variants is not None else [],
|
||||
"error_code": row["error_code"],
|
||||
"created_at": timestamp(row["created_at"]),
|
||||
"updated_at": timestamp(row["updated_at"]),
|
||||
}
|
||||
|
||||
def object_key():
|
||||
return f"originals/{uuid.uuid4()}"
|
||||
Reference in New Issue
Block a user