67 lines
2.5 KiB
Python
67 lines
2.5 KiB
Python
import hashlib
|
|
import io
|
|
import json
|
|
import sys
|
|
import tempfile
|
|
|
|
from PIL import Image, ImageOps
|
|
|
|
from .attachments import validate_image
|
|
from .errors import ApiError
|
|
from .objects import Objects
|
|
|
|
|
|
def process(job):
|
|
objects = Objects()
|
|
try:
|
|
with tempfile.TemporaryFile(mode='w+b') as original:
|
|
body = objects.content(job['staging_key'])
|
|
checksum, size = hashlib.sha256(), 0
|
|
try:
|
|
while chunk := body.read(65536):
|
|
size += len(chunk)
|
|
if size > 10485760:
|
|
raise ValueError('size')
|
|
checksum.update(chunk)
|
|
original.write(chunk)
|
|
finally:
|
|
body.close()
|
|
if size != job['size_bytes'] or checksum.hexdigest() != job['sha256']:
|
|
raise ValueError('checksum')
|
|
validate_image(original, job['content_type'])
|
|
original.seek(0)
|
|
with Image.open(original) as image:
|
|
ImageOps.exif_transpose(image, in_place=True)
|
|
scale = min(1, 256 / image.width, 256 / image.height)
|
|
width, height = max(1, int(image.width * scale)), max(1, int(image.height * scale))
|
|
with image.resize((width, height), Image.Resampling.LANCZOS) as small:
|
|
rgba = small.convert('RGBA')
|
|
rgb = Image.new('RGB', small.size, 'white')
|
|
try:
|
|
rgb.paste(rgba, mask=rgba.getchannel('A'))
|
|
output = io.BytesIO()
|
|
rgb.save(output, format='JPEG', quality=85)
|
|
finally:
|
|
rgba.close()
|
|
rgb.close()
|
|
thumb = output.getvalue()
|
|
key = 'variants/' + job['attachment_id'] + '/v1/thumbnail.jpg'
|
|
objects.put(job['object_key'], original, size, job['content_type'])
|
|
objects.put(key, io.BytesIO(thumb), len(thumb), 'image/jpeg')
|
|
return {'name': 'thumbnail', 'content_type': 'image/jpeg', 'width': width, 'height': height,
|
|
'size_bytes': len(thumb), 'sha256': hashlib.sha256(thumb).hexdigest(), 'object_key': key}
|
|
finally:
|
|
objects.close()
|
|
|
|
|
|
if __name__ == '__main__':
|
|
try:
|
|
result = process(json.load(sys.stdin))
|
|
print(json.dumps(result), flush=True)
|
|
except (ValueError, OSError):
|
|
sys.exit(43)
|
|
except ApiError as error:
|
|
sys.exit(43 if error.status in (400, 413, 415) else 1)
|
|
except Exception:
|
|
sys.exit(1)
|