from __future__ import annotations import shutil import time from pathlib import Path from threading import RLock from typing import Any from uuid import uuid4 from fastapi import BackgroundTasks, FastAPI, File, Form, HTTPException, Request, UploadFile from fastapi.responses import FileResponse from fastapi.staticfiles import StaticFiles try: from .processor import ( DEFAULT_BG_COLOR, DEFAULT_FOLDER_NAME, DEFAULT_OUTPUT_MODE, DEFAULT_QUALITY_PROFILE, parse_bg_color, process_zip, sanitize_folder_name, validate_output_mode, validate_quality_profile, ) except ImportError: # Allows `uvicorn main:app` from inside the app directory. from processor import ( DEFAULT_BG_COLOR, DEFAULT_FOLDER_NAME, DEFAULT_OUTPUT_MODE, DEFAULT_QUALITY_PROFILE, parse_bg_color, process_zip, sanitize_folder_name, validate_output_mode, validate_quality_profile, ) APP_NAME = "BackDropStudio" MAX_UPLOAD_BYTES = 500 * 1024 * 1024 RETENTION_SECONDS = 60 * 60 BASE_DIR = Path(__file__).resolve().parent STATIC_DIR = BASE_DIR / "static" TEMP_DIR = BASE_DIR / "temp" app = FastAPI(title=APP_NAME) app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static") jobs: dict[str, dict[str, Any]] = {} jobs_lock = RLock() def _now() -> float: return time.time() def _public_job(record: dict[str, Any]) -> dict[str, Any]: return { "status": record["status"], "total": record["total"], "completed": record["completed"], "failed_files": record["failed_files"], } def _update_job(job_id: str, **changes: Any) -> None: with jobs_lock: if job_id not in jobs: return jobs[job_id].update(changes) jobs[job_id]["updated_at"] = _now() def _cleanup_stale_jobs() -> None: cutoff = _now() - RETENTION_SECONDS expired: list[dict[str, Any]] = [] with jobs_lock: for job_id, record in list(jobs.items()): if record["status"] in {"done", "failed"} and record["updated_at"] < cutoff: expired.append(jobs.pop(job_id)) for record in expired: shutil.rmtree(record["job_dir"], ignore_errors=True) async def _save_upload(upload: UploadFile, destination: Path) -> None: destination.parent.mkdir(parents=True, exist_ok=True) size = 0 with destination.open("wb") as target: while chunk := await upload.read(1024 * 1024): size += len(chunk) if size > MAX_UPLOAD_BYTES: raise HTTPException( status_code=413, detail="Upload is too large. Maximum ZIP size is 500MB.", ) target.write(chunk) def _run_processing_job( job_id: str, zip_path: Path, output_zip_path: Path, folder_name: str, bg_rgb: tuple[int, int, int], quality_profile: str, output_mode: str, ) -> None: def report_progress(total: int, completed: int, failed_files: list[str]) -> None: _update_job(job_id, total=total, completed=completed, failed_files=failed_files) try: result = process_zip( zip_path, output_zip_path, folder_name, bg_rgb, quality_profile=quality_profile, output_mode=output_mode, progress_callback=report_progress, ) _update_job( job_id, status="done", total=result.total, completed=result.completed, failed_files=result.failed_files, output_zip_path=result.output_zip_path, ) except Exception as exc: _update_job(job_id, status="failed", error=str(exc)) finally: zip_path.unlink(missing_ok=True) @app.get("/", include_in_schema=False) async def index() -> FileResponse: return FileResponse(STATIC_DIR / "index.html") @app.post("/api/process") async def process_upload( request: Request, background_tasks: BackgroundTasks, file: UploadFile = File(...), bg_color: str = Form(DEFAULT_BG_COLOR), folder_name: str = Form(DEFAULT_FOLDER_NAME), quality_profile: str = Form(DEFAULT_QUALITY_PROFILE), output_mode: str = Form(DEFAULT_OUTPUT_MODE), ) -> dict[str, str]: _cleanup_stale_jobs() filename = file.filename or "" if Path(filename).suffix.lower() != ".zip": raise HTTPException(status_code=400, detail="Please upload a .zip file.") content_length = request.headers.get("content-length") if content_length and content_length.isdigit() and int(content_length) > MAX_UPLOAD_BYTES + 1024 * 1024: raise HTTPException( status_code=413, detail="Upload is too large. Maximum ZIP size is 500MB.", ) try: bg_rgb = parse_bg_color(bg_color) safe_folder_name = sanitize_folder_name(folder_name) safe_quality_profile = validate_quality_profile(quality_profile) safe_output_mode = validate_output_mode(output_mode) except ValueError as exc: raise HTTPException(status_code=400, detail=str(exc)) from exc job_id = str(uuid4()) job_dir = TEMP_DIR / job_id zip_path = job_dir / "upload.zip" output_zip_path = job_dir / "backdropstudio-output.zip" try: await _save_upload(file, zip_path) except Exception: shutil.rmtree(job_dir, ignore_errors=True) raise finally: await file.close() with jobs_lock: jobs[job_id] = { "status": "processing", "total": 0, "completed": 0, "failed_files": [], "error": None, "output_zip_path": None, "folder_name": safe_folder_name, "quality_profile": safe_quality_profile, "output_mode": safe_output_mode, "job_dir": job_dir, "created_at": _now(), "updated_at": _now(), } background_tasks.add_task( _run_processing_job, job_id, zip_path, output_zip_path, safe_folder_name, bg_rgb, safe_quality_profile, safe_output_mode, ) return {"job_id": job_id} @app.get("/api/status/{job_id}") async def get_status(job_id: str) -> dict[str, Any]: _cleanup_stale_jobs() with jobs_lock: record = jobs.get(job_id) if not record: raise HTTPException(status_code=404, detail="Job not found.") response = _public_job(record) if record.get("error"): response["error"] = record["error"] return response @app.get("/api/download/{job_id}") async def download(job_id: str) -> FileResponse: _cleanup_stale_jobs() with jobs_lock: record = jobs.get(job_id) if not record: raise HTTPException(status_code=404, detail="Job not found.") if record["status"] != "done": raise HTTPException(status_code=409, detail="Output ZIP is not ready yet.") output_zip_path = record["output_zip_path"] folder_name = record["folder_name"] if not output_zip_path or not Path(output_zip_path).exists(): raise HTTPException(status_code=404, detail="Output ZIP has expired.") return FileResponse( output_zip_path, media_type="application/zip", filename=f"{folder_name}.zip", )