diff --git a/.gitea/workflows/deploy.yml b/.gitea/workflows/deploy.yml index 6e955f4..6f17c7a 100644 --- a/.gitea/workflows/deploy.yml +++ b/.gitea/workflows/deploy.yml @@ -73,7 +73,7 @@ jobs: # one a developer exercises on localhost. - name: API and workflow regressions run: | - for suite in smoke_test workflow_test security_test scanning_test payment_test quote_pagination_test kanban_test reconcile_test order_actions_test print_file_test launch_reset_test; do + for suite in smoke_test workflow_test security_test scanning_test payment_test quote_pagination_test kanban_test reconcile_test order_actions_test print_file_test thumbnail_backfill_test launch_reset_test; do echo "--- $suite" $COMPOSE exec -T \ -e SITE_BASE_URL=http://site \ diff --git a/ops/backfill_thumbnails.py b/ops/backfill_thumbnails.py new file mode 100644 index 0000000..cbd6c30 --- /dev/null +++ b/ops/backfill_thumbnails.py @@ -0,0 +1,99 @@ +"""Make the Kanban's artwork pictures for orders and quotes from before them. + +The customer's browser makes each picture while uploading; older uploads have +none, so their cards show "sem prévia". Run once from the worker's console: + + python -m ops.backfill_thumbnails makes the missing pictures + python -m ops.backfill_thumbnails --limite 20 at most 20 this run + +Only PNG, JPEG and WebP: a PDF, CDR, AI or PSD needs a renderer the server +does not have, and keeps showing the layout drawing. Files are read from +storage one at a time, and very large images are skipped, so the worker is +never asked for more memory than a normal sheet takes. Safe to run again: it +only looks at uploads that still have no picture. +""" +import argparse +import io +import os +import sys +import tempfile + +from app.core import db + +# The Site's own picture size (site-upload.js: miniatura(..., 480, 720)). +BOX = (480, 720) +# Decoding a PNG takes about 4 bytes a pixel: 100 million pixels is ~400 MB. +MAX_PIXELS = 100_000_000 +MAX_BYTES = 300 * 1024 * 1024 +IMAGES = ('.png', '.jpg', '.jpeg', '.webp') + + +def missing(c, limit): + """Uploads an order or a live quote refers to, still readable, without a picture.""" + return c.execute('''WITH used AS ( + SELECT (jsonb_array_elements_text(i->'uploads'))::uuid AS id + FROM dtf_local.orders o, jsonb_array_elements(o.snapshot->'items') i + UNION + SELECT (jsonb_array_elements_text(i->'uploads'))::uuid + FROM dtf_local.quotes q, jsonb_array_elements(q.draft->'items') i + WHERE q.discarded_at IS NULL AND q.created_at > now() - interval '3 days') + SELECT u.id, u.name, u.size, u.object_key FROM dtf_local.uploads u JOIN used ON used.id=u.id + LEFT JOIN dtf_local.upload_thumbnails t ON t.upload_id=u.id + WHERE t.upload_id IS NULL AND u.complete AND u.purged_at IS NULL AND u.expires_at>now() + AND u.scan_state='clean' + ORDER BY u.created_at DESC LIMIT %s''', (limit,)).fetchall() + + +def picture(path): + """A WebP no larger than BOX, or None when the image is too large to decode.""" + from PIL import Image + Image.MAX_IMAGE_PIXELS = None # the size is checked here, before decoding + with Image.open(path) as image: + width, height = image.size + if width * height > MAX_PIXELS: + return None + image.draft('RGB', BOX) # JPEG decodes at a reduced size + image.thumbnail(BOX) + out = io.BytesIO() + image.convert('RGBA' if 'A' in image.getbands() or image.mode == 'P' else 'RGB').save( + out, 'WEBP', quality=80) + return out.getvalue() + + +def main(argv=None, out=print, storage=None, connect=db.connect): + parser = argparse.ArgumentParser(prog='python -m ops.backfill_thumbnails') + parser.add_argument('--limite', type=int, default=500) + args = parser.parse_args(argv) + if storage is None: + from app.runtime import storage + with connect() as c: + rows = missing(c, args.limite) + made = skipped = 0 + for row in rows: + if not row['name'].lower().endswith(IMAGES) or (row['size'] or 0) > MAX_BYTES: + skipped += 1 + continue + handle, path = tempfile.mkstemp(prefix='thumb-') + os.close(handle) + try: + storage.fetch(row['object_key'], path) + data = picture(path) + except Exception as exc: # one unreadable file must not stop the others + out(f"{row['name']}: não deu para ler ({type(exc).__name__})") + skipped += 1 + continue + finally: + os.unlink(path) + if data is None: + skipped += 1 + continue + with connect() as c: + c.execute('''INSERT INTO dtf_local.upload_thumbnails(upload_id,mime,data) VALUES(%s,'image/webp',%s) + ON CONFLICT (upload_id) DO NOTHING''', (row['id'], data)) + made += 1 + out(f'{made} miniatura(s) criada(s); {skipped} arquivo(s) sem miniatura possível (PDF, CDR, muito grande).') + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tests/thumbnail_backfill_test.py b/tests/thumbnail_backfill_test.py new file mode 100644 index 0000000..e810cfe --- /dev/null +++ b/tests/thumbnail_backfill_test.py @@ -0,0 +1,71 @@ +"""Old orders get their artwork picture from the stored image, once. + +Run inside the API container: python -m tests.thumbnail_backfill_test +""" +import io +from uuid import uuid4 + +from PIL import Image +from psycopg.types.json import Jsonb + +from app.core import db +from ops import backfill_thumbnails + + +def png(width, height): + out = io.BytesIO() + Image.new('RGBA', (width, height), (255, 0, 0, 128)).save(out, 'PNG') + return out.getvalue() + + +class Storage: + """Objects by key, written where the worker asks.""" + def __init__(self, objects): + self.objects, self.fetched = objects, [] + + def fetch(self, key, path): + """Other uploads in a shared database are not this test's: they fail like unreadable files.""" + self.fetched.append(key) + with open(path, 'wb') as handle: + handle.write(self.objects[key]) + + +def run(): + owner, quote, order = uuid4(), uuid4(), uuid4() + image, drawing = uuid4(), uuid4() + files = {image: ('folha.png', png(1200, 3000)), drawing: ('arte.cdr', b'CDR')} + storage = Storage({f'backfill/{uid}': content for uid, (_, content) in files.items()}) + try: + with db.connect() as c: + for uid, (name, content) in files.items(): + c.execute('''INSERT INTO dtf_local.uploads(id,owner,name,size,object_key,multipart_id,complete, + expires_at,scan_state) VALUES(%s,%s,%s,%s,%s,'m',true,now()+interval '1 day','clean')''', + (uid, owner, name, len(content), f'backfill/{uid}')) + items = [{'mode': 'file', 'uploads': [str(image), str(drawing)]}] + c.execute('''INSERT INTO dtf_local.quotes(id,owner,request_key,request_hash,draft) + VALUES(%s,%s,%s,'backfill-fixture',%s)''', (quote, owner, uuid4(), Jsonb({'items': items}))) + c.execute('INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment) VALUES(%s,%s,%s,%s,%s)', + (order, quote, owner, Jsonb({'items': items, 'total_cents': 1490}), Jsonb({'provider': 'teste'}))) + lines = [] + assert backfill_thumbnails.main([], out=lines.append, storage=storage) == 0 + with db.connect() as c: + made = c.execute('SELECT mime,data FROM dtf_local.upload_thumbnails WHERE upload_id=%s', (image,)).fetchone() + assert made and made['mime'] == 'image/webp' + with Image.open(io.BytesIO(bytes(made['data']))) as picture: + assert picture.format == 'WEBP' and picture.size[0] <= 480 and picture.size[1] <= 720, picture.size + assert not c.execute('SELECT 1 FROM dtf_local.upload_thumbnails WHERE upload_id=%s', (drawing,)).fetchone() + # The CDR is never fetched; a second run does not fetch the image again. + assert storage.fetched.count(f'backfill/{image}') == 1 and f'backfill/{drawing}' not in storage.fetched + backfill_thumbnails.main([], out=lines.append, storage=storage) + assert storage.fetched.count(f'backfill/{image}') == 1 + print('PASS: old orders get a WebP picture from a stored PNG; drawings are skipped; a rerun repeats nothing') + finally: + with db.connect() as c: + c.execute('DELETE FROM dtf_local.upload_thumbnails WHERE upload_id=ANY(%s)', (list(files),)) + c.execute('DELETE FROM dtf_local.orders WHERE id=%s', (order,)) + c.execute('DELETE FROM dtf_local.quotes WHERE id=%s', (quote,)) + c.execute('DELETE FROM dtf_local.uploads WHERE id=ANY(%s)', (list(files),)) + + +if __name__ == '__main__': + run()