"""Small, bounded header check for the final file FlexiPRINT receives. The original upload may be PNG or PDF. A *final* file is a transparent, 8-bit RGBA PNG tagged 300 DPI. Read only header chunks before IDAT, so even a multi-gigabyte sheet is checked without decoding or downloading the film. """ import struct PNG = b'\x89PNG\r\n\x1a\n' HEADER_BYTES = 1 << 20 def final_png_issue(data): if not data.startswith(PNG): return 'O arquivo final precisa ser PNG transparente a 300 DPI. Converta PDF/TIFF antes de enviar.' at = len(PNG) rgba = False dpi = None image_data = False while at + 12 <= len(data): size = struct.unpack('>I', data[at:at + 4])[0] kind = data[at + 4:at + 8] end = at + 12 + size if kind == b'IDAT': image_data = True break if end > len(data): return 'O cabeçalho do PNG final está incompleto ou inválido.' body = data[at + 8:at + 8 + size] if kind == b'IHDR': if at != 8 or size != 13: return 'O cabeçalho do PNG final está inválido.' width, height, depth, color, compression, filtering, interlace = struct.unpack('>IIBBBBB', body) rgba = bool(width and height and depth == 8 and color == 6 and compression == 0 and filtering == 0 and interlace == 0) elif kind == b'pHYs' and size == 9: x, y, unit = struct.unpack('>IIB', body) if unit == 1 and x and y: dpi = (x * .0254, y * .0254) at = end if not rgba: return 'O PNG final precisa ter transparência (canal alfa RGBA de 8 bits).' if not dpi or any(abs(axis - 300) > 1 for axis in dpi): return 'O PNG final precisa estar marcado como 300 DPI nos dois eixos.' if not image_data: return 'O PNG final está incompleto: faltam os dados da imagem.' return None def final_png_problem(storage, upload): """Why this upload cannot be a final file, or None: its name and the header chunks of the stored file.""" if not upload['name'].lower().endswith('.png'): return 'O arquivo final precisa ser PNG transparente a 300 DPI. Converta PDF/TIFF antes de enviar.' response = storage.client.get_object(Bucket=storage.bucket, Key=upload['object_key'], Range=f'bytes=0-{HEADER_BYTES - 1}') return final_png_issue(response['Body'].read()) def require_final_png(storage, upload): from fastapi import HTTPException issue = final_png_problem(storage, upload) if issue: raise HTTPException(422, issue)