diff --git a/app.py b/app.py index 1d3bd0f..c823f4b 100644 --- a/app.py +++ b/app.py @@ -1,9 +1,12 @@ +import logging +import subprocess from enum import Enum from pathlib import Path -from fastapi import FastAPI, File, Form, UploadFile +from fastapi import FastAPI, File, Form, UploadFile, HTTPException from fastapi.responses import FileResponse from fastapi.staticfiles import StaticFiles +from PIL import UnidentifiedImageError from imaging.process import to_1bit from printer.cups import spool_raw @@ -34,6 +37,8 @@ class Lang(str, Enum): static_dir = Path(__file__).parent / "static" app.mount("/static", StaticFiles(directory=static_dir), name="static") +logger = logging.getLogger(__name__) + @app.get("/") async def index() -> FileResponse: @@ -46,12 +51,22 @@ async def print_image( media: Media = Form(...), lang: Lang = Form(...), ) -> dict: - img_bytes = await file.read() - width = MEDIA_WIDTHS[media] - img = to_1bit(img_bytes, width) - if lang == Lang.EPL: - payload = img_to_epl_gw(img) - else: - payload = img_to_zpl_gf(img) - spool_raw(PRINTER_NAME, payload) + try: + img_bytes = await file.read() + width = MEDIA_WIDTHS[media] + img = to_1bit(img_bytes, width) + if lang == Lang.EPL: + payload = img_to_epl_gw(img) + else: + payload = img_to_zpl_gf(img) + spool_raw(PRINTER_NAME, payload) + except UnidentifiedImageError: + logger.exception("Failed to process uploaded image") + raise HTTPException(status_code=400, detail="Invalid image file") + except subprocess.CalledProcessError: + logger.exception("Printing failed") + raise HTTPException(status_code=500, detail="Failed to spool print job") + except Exception: + logger.exception("Unexpected error during printing") + raise HTTPException(status_code=500, detail="Internal server error") return {"status": "ok"}