File size: 7,432 Bytes
0d7bef5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
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",
    )