import hashlib import io import json import os import warnings from contextlib import contextmanager from datetime import datetime, timezone from pathlib import Path import boto3 from botocore.config import Config import psycopg from psycopg.rows import dict_row from psycopg.types.json import Jsonb from PIL import Image, ImageOps, UnidentifiedImageError def config(name, default=None): filename = os.getenv(name+'_FILE') return Path(filename).read_text().strip() if filename else os.getenv(name, default) def now(): return datetime.now(timezone.utc).isoformat(timespec='microseconds').replace('+00:00', 'Z') @contextmanager def db(): with psycopg.connect(config('DATABASE_URL'), row_factory=dict_row, connect_timeout=3, options='-c statement_timeout=10000') as conn: yield conn def get(conn, kind, oid, lock=False): row = conn.execute('SELECT data FROM objects WHERE kind=%s AND id=%s'+(' FOR UPDATE' if lock else ''), (kind, oid)).fetchone() return row['data'] if row else None def put(conn, kind, value): conn.execute('INSERT INTO objects(kind,id,data) VALUES(%s,%s,%s) ON CONFLICT(kind,id) DO UPDATE SET data=excluded.data', (kind, value['id'], Jsonb(value))) def sha(data): return hashlib.sha256(data).hexdigest() def s3(): return boto3.client('s3', endpoint_url=config('S3_ENDPOINT', 'https://s3:9443'), aws_access_key_id=config('S3_ACCESS_KEY_ID'), aws_secret_access_key=config('S3_SECRET_ACCESS_KEY'), verify=config('LAB_CA'), region_name=config('S3_REGION', 'us-east-1'), config=Config( connect_timeout=3, read_timeout=10, retries={'max_attempts': 2}, request_checksum_calculation='when_required', response_checksum_validation='when_required', s3={'addressing_style': 'path'})) def bucket(): return config('S3_BUCKET', 'messenger-attachments') class InvalidImage(Exception): pass class ImageTooLarge(Exception): pass def inspect_image(data, content_type=None): try: with warnings.catch_warnings(): warnings.simplefilter('error', Image.DecompressionBombWarning) with Image.open(io.BytesIO(data)) as image: if image.width * image.height > int(config('MAX_IMAGE_PIXELS', '40000000')): raise ImageTooLarge() mime = {'PNG': 'image/png', 'JPEG': 'image/jpeg'}.get(image.format) if not mime or (content_type and mime != content_type): raise InvalidImage() image.verify() with Image.open(io.BytesIO(data)) as image: image.load() return mime except (Image.DecompressionBombError, Image.DecompressionBombWarning): raise ImageTooLarge() from None except (UnidentifiedImageError, OSError, ValueError, SyntaxError): raise InvalidImage() from None def thumbnail(data): with Image.open(io.BytesIO(data)) as image: image = ImageOps.exif_transpose(image).convert('RGBA') scale = min(1, 256/image.width, 256/image.height) size = (max(1, int(image.width*scale)), max(1, int(image.height*scale))) image = image.resize(size, Image.Resampling.LANCZOS) canvas = Image.new('RGB', size, 'white') canvas.paste(image, mask=image.getchannel('A')) output = io.BytesIO() canvas.save(output, format='JPEG', quality=85) result = output.getvalue() return result, {'name': 'thumbnail', 'content_type': 'image/jpeg', 'width': size[0], 'height': size[1], 'size_bytes': len(result), 'sha256': sha(result)}