diff --git a/app/image_utils.py b/app/image_utils.py new file mode 100644 index 0000000..e212a62 --- /dev/null +++ b/app/image_utils.py @@ -0,0 +1,25 @@ +import io +from PIL import Image +from fastapi import HTTPException + +MAX_SIZE = 10 * 1024 * 1024 # 10 мбайт +MAX_PIXELS = 40_000_000 + +def validate_image(content: bytes) -> str: + if len(content) > MAX_SIZE: + raise HTTPException(413, "File too large") + try: + img = Image.open(io.BytesIO(content)) + img.verify() + img = Image.open(io.BytesIO(content)) + except Exception: + raise HTTPException(415, "Invalid image format") + + if img.format not in ("PNG", "JPEG"): + raise HTTPException(415, "Unsupported media type") + + width, height = img.size + if width * height > MAX_PIXELS: + raise HTTPException(413, "Image too large in pixels") + + return "image/png" if img.format == "PNG" else "image/jpeg" \ No newline at end of file diff --git a/app/s3_client.py b/app/s3_client.py new file mode 100644 index 0000000..07a1059 --- /dev/null +++ b/app/s3_client.py @@ -0,0 +1,20 @@ +import boto3 +from botocore.client import Config +import os + +s3 = boto3.client( + "s3", + endpoint_url=os.getenv("S3_ENDPOINT", "http://minio:9000"), + aws_access_key_id=os.getenv("S3_ACCESS_KEY", "minioadmin"), + aws_secret_access_key=os.getenv("S3_SECRET_KEY", "minioadmin"), + config=Config(signature_version="s3v4"), + region_name="us-east-1", +) + +BUCKET = os.getenv("S3_BUCKET", "attachments") + +def ensure_bucket(): + try: + s3.head_bucket(Bucket=BUCKET) + except Exception: + s3.create_bucket(Bucket=BUCKET) \ No newline at end of file