"""The review photo or video of the printed sheet (Fase 2, front 2). In Revisão the card gets "Revisar": the Revisor takes a photo or a short video (up to 30 s) of the sheet with the computer's or the phone's camera in the browser, or sends one already recorded. It is attached to the order as DTF--revisao-., with when and who (dtf_local.order_reviews), and the computers with the order folders turned on copy it to Kanban/Revisões/. An order above 1 m cannot reach Finalizado without a photo; a smaller one may. Once the order is in Finalizado, the customer's order page shows the photos (the "ready" notice links to it). Videos stay on the card. Kept for REVIEW_KEEP_DAYS, longer than artwork: it is the evidence when a customer says the sheet came out wrong. """ from decimal import Decimal from fastapi import HTTPException from . import grade_check from .proof import billed_metres PHOTO_MIN_PX = 1600 # the longer side; enough to read the footer VIDEO_MAX_SECONDS = 30 # enforced by the recorder and the file check in the browser PHOTO_MAX_BYTES = 30 * 1048576 VIDEO_MAX_BYTES = 150 * 1048576 REQUIRED_ABOVE_METRES = Decimal('1') REVIEW_KEEP_DAYS = 180 FOLDER = 'Revisões' # Extension -> (kind, MIME). HEIC is left out: browsers cannot show it. FORMATS = {'jpg': ('photo', 'image/jpeg'), 'jpeg': ('photo', 'image/jpeg'), 'png': ('photo', 'image/png'), 'webp': ('photo', 'image/webp'), 'mp4': ('video', 'video/mp4'), 'webm': ('video', 'video/webm'), 'mov': ('video', 'video/quicktime')} def file_name(number, seq, ext): """DTF-13-revisao-1.jpg: the name in the folder and on the card.""" return f'DTF-{number}-revisao-{seq}.{ext}' FORMAT_MESSAGE = ('Use foto JPG, PNG ou WebP de até 30 MB, ou vídeo MP4, WebM ou MOV de até 150 MB.') # What each extension must start with. MP4 and MOV share the ISO container: # the "ftyp" box sits at byte 4. SIGNATURES = {'jpg': (b'\xff\xd8\xff', 0), 'jpeg': (b'\xff\xd8\xff', 0), 'png': (b'\x89PNG\r\n\x1a\n', 0), 'webp': (b'WEBP', 8), 'mp4': (b'ftyp', 4), 'mov': (b'ftyp', 4), 'webm': (b'\x1a\x45\xdf\xa3', 0)} def kind_of(name, size): """('photo' | 'video', mime, ext) for an accepted file, or HTTPException 422 with a Portuguese message naming the accepted formats and size limits.""" ext = name.rsplit('.', 1)[-1].lower() if '.' in name else '' if ext not in FORMATS: raise HTTPException(422, FORMAT_MESSAGE) kind, mime = FORMATS[ext] limit = PHOTO_MAX_BYTES if kind == 'photo' else VIDEO_MAX_BYTES if size > limit: raise HTTPException(422, FORMAT_MESSAGE) return kind, mime, ext def check(storage, upload): """Read the start of the stored file (a Range read, as grade_check.Files.head) and confirm its signature matches the extension. For a photo, return its (width, height) and refuse (422) when the longer side is below PHOTO_MIN_PX; for a video, return (None, None). Returns (kind, ext, width, height).""" kind, mime, ext = kind_of(upload['name'], upload['size']) head = storage.client.get_object(Bucket=storage.bucket, Key=upload['object_key'], Range=f'bytes=0-{grade_check.HEAD_BYTES - 1}')['Body'].read() # WebP is a RIFF container with its own form type, like the scanner's check. if ext == 'webp': matches = head[:4] == b'RIFF' and head[8:12] == b'WEBP' else: signature, offset = SIGNATURES[ext] matches = head[offset:].startswith(signature) if not matches: raise HTTPException(422, 'O conteúdo do arquivo não corresponde à extensão.') if kind == 'video': return kind, ext, None, None size = grade_check.image_size(head) if not size or not all(size): raise HTTPException(422, 'Não foi possível ler a foto.') width, height = size if max(width, height) < PHOTO_MIN_PX: raise HTTPException(422, f'A foto precisa ter pelo menos {PHOTO_MIN_PX} px no lado maior para ler o rodapé.') return kind, ext, width, height def required(snapshot): """Whether finishing this order needs a review photo: billed metres above REQUIRED_ABOVE_METRES (proof.billed_metres).""" return billed_metres(snapshot) > REQUIRED_ABOVE_METRES def has_photo(c, order_id): return c.execute("SELECT 1 FROM dtf_local.order_reviews WHERE order_id=%s AND kind='photo' LIMIT 1", (order_id,)).fetchone() is not None def attach(c, order, upload, kind, ext, width, height, user): """Record the review: the next seq for the order, the upload renamed to file_name(...) and kept REVIEW_KEEP_DAYS from now. Returns the new row.""" # The order's row is the lock: two reviewers adding at once take one seq # each, never the same one. c.execute('SELECT id FROM dtf_local.orders WHERE id=%s FOR UPDATE', (order['id'],)) seq = c.execute('SELECT COALESCE(max(seq),0)+1 AS seq FROM dtf_local.order_reviews WHERE order_id=%s', (order['id'],)).fetchone()['seq'] name = file_name(order['number'], seq, ext) c.execute("UPDATE dtf_local.uploads SET name=%s, expires_at=now()+make_interval(days => %s) WHERE id=%s", (name, REVIEW_KEEP_DAYS, upload['id'])) row = c.execute('''INSERT INTO dtf_local.order_reviews(order_id,seq,upload_id,kind,width,height,created_by) VALUES(%s,%s,%s,%s,%s,%s,%s) RETURNING *''', (order['id'], seq, upload['id'], kind, width, height, user)).fetchone() return {**row, 'name': name} def by_order(c, order_ids): """{order_id (str): [ {id, seq, kind, name, width, height, created_by, created_at}, ... ]} in seq order, for the board.""" if not order_ids: return {} rows = c.execute('''SELECT r.id,r.order_id,r.seq,r.kind,r.width,r.height,r.created_by,r.created_at,u.name FROM dtf_local.order_reviews r JOIN dtf_local.uploads u ON u.id=r.upload_id WHERE r.order_id=ANY(%s) ORDER BY r.order_id,r.seq''', (order_ids,)).fetchall() out = {} for row in rows: out.setdefault(str(row['order_id']), []).append( {key: row[key] for key in ('id', 'seq', 'kind', 'name', 'width', 'height', 'created_by', 'created_at')}) return out