feat: organizer Android app and token-gated upload API
CI / lint-and-test (push) Failing after 1m18s

Replace Syncthing as the product upload path with a share-target app
and POST /api/jobs. Web UI live-polls job progress.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Frank Schwenk
2026-08-27 21:38:50 +02:00
parent 5dcc3717c7
commit c03f17488c
58 changed files with 3134 additions and 186 deletions
+143
View File
@@ -0,0 +1,143 @@
"""JSON API for the organizer Android app (upload + job status)."""
from __future__ import annotations
import hashlib
import hmac
import logging
import uuid
from pathlib import Path
from fastapi import APIRouter, File, Header, HTTPException, Request, UploadFile
from fastapi.responses import JSONResponse
from . import config, jobs, pipeline
logger = logging.getLogger("livef12.api")
router = APIRouter(prefix="/api")
_CHUNK = 1024 * 1024
_JSON_HEADERS = {"Cache-Control": "no-store"}
def _provided_token(
authorization: str | None,
x_upload_token: str | None,
) -> str:
if x_upload_token and x_upload_token.strip():
return x_upload_token.strip()
if authorization:
scheme, _, rest = authorization.partition(" ")
if scheme.lower() == "bearer" and rest.strip():
return rest.strip()
return ""
def _token_ok(provided: str) -> bool:
expected = config.UPLOAD_TOKEN
if not expected or not provided:
return False
# Hash first so compare_digest never sees unequal lengths.
left = hashlib.sha256(provided.encode("utf-8")).digest()
right = hashlib.sha256(expected.encode("utf-8")).digest()
return hmac.compare_digest(left, right)
def require_upload_token(
authorization: str | None,
x_upload_token: str | None,
) -> None:
if not config.UPLOAD_TOKEN:
raise HTTPException(status_code=503, detail="Upload ist nicht konfiguriert")
if not _token_ok(_provided_token(authorization, x_upload_token)):
raise HTTPException(status_code=401, detail="Ungültiger Upload-Token")
@router.get("/health")
def health() -> JSONResponse:
return JSONResponse(
{"ok": True, "upload": bool(config.UPLOAD_TOKEN)},
headers=_JSON_HEADERS,
)
@router.get("/jobs")
def api_list_jobs() -> JSONResponse:
items = jobs.list_jobs()
return JSONResponse(
{
"jobs": items,
"active": any(j["status"] in jobs.ACTIVE_STATUSES for j in items),
},
headers=_JSON_HEADERS,
)
@router.get("/jobs/{job_id}")
def api_job_detail(job_id: str) -> JSONResponse:
return JSONResponse(jobs.job_detail_payload(job_id), headers=_JSON_HEADERS)
@router.post("/jobs", status_code=202)
async def api_upload_job(
request: Request,
file: UploadFile = File(...),
authorization: str | None = Header(default=None),
x_upload_token: str | None = Header(default=None),
) -> JSONResponse:
require_upload_token(authorization, x_upload_token)
original_name = file.filename or "photo.jpg"
dest_name = jobs.make_inbox_filename(original_name)
suffix = Path(dest_name).suffix.lower()
if suffix not in config.SUPPORTED_EXTENSIONS:
raise HTTPException(status_code=400, detail="Dateityp nicht unterstützt")
config.INBOX_DIR.mkdir(parents=True, exist_ok=True)
config.META_DIR.mkdir(parents=True, exist_ok=True)
tmp = config.INBOX_DIR / f".upload_{uuid.uuid4().hex}"
dest = config.INBOX_DIR / dest_name
written = 0
try:
with tmp.open("wb") as out:
while True:
chunk = await file.read(_CHUNK)
if not chunk:
break
written += len(chunk)
if written > config.MAX_UPLOAD_BYTES:
raise HTTPException(
status_code=413,
detail=f"Datei zu groß (max {config.MAX_UPLOAD_BYTES // (1024 * 1024)} MB)",
)
out.write(chunk)
if written == 0:
raise HTTPException(status_code=400, detail="Leere Datei")
tmp.replace(dest)
except HTTPException:
tmp.unlink(missing_ok=True)
raise
except OSError as exc:
tmp.unlink(missing_ok=True)
logger.exception("upload write failed")
raise HTTPException(status_code=500, detail="Upload konnte nicht gespeichert werden") from exc
finally:
await file.close()
stem = pipeline.sanitize_stem(dest.stem)
paths = pipeline.job_paths(stem, suffix)
pipeline.write_status(
paths,
"queued",
source_file=dest.name,
source_stem=stem,
stage="queued",
progress={"current": 0, "total": config.OUTPUT_COUNT},
error=None,
uploaded_from=request.client.host if request.client else None,
)
logger.info("queued upload %s -> job %s (%d bytes)", dest.name, stem, written)
payload = jobs.summarize_job(stem)
payload["status"] = "queued"
return JSONResponse(payload, status_code=202, headers=_JSON_HEADERS)
+4
View File
@@ -107,3 +107,7 @@ STABLE_WAIT_SECONDS = _float_env("STABLE_WAIT_SECONDS", 2)
# --- Web ---------------------------------------------------------------
SITE_TITLE = os.environ.get("SITE_TITLE", "live.f12.rocks")
# Shared secret for POST /api/jobs. Empty = upload API disabled (fail closed).
UPLOAD_TOKEN = os.environ.get("UPLOAD_TOKEN", "")
# Hard cap after client-side 2000px JPEG; 25 MB is generous for a bad encode.
MAX_UPLOAD_BYTES = _int_env("MAX_UPLOAD_BYTES", 25 * 1024 * 1024)
+1 -3
View File
@@ -76,9 +76,7 @@ def _write_resized(source: Path, dest: Path, width: int) -> None:
img = img.resize((width, new_h), Image.Resampling.LANCZOS)
dest.parent.mkdir(parents=True, exist_ok=True)
with tempfile.NamedTemporaryFile(
dir=dest.parent, suffix=".webp", delete=False
) as tmp:
with tempfile.NamedTemporaryFile(dir=dest.parent, suffix=".webp", delete=False) as tmp:
tmp_path = Path(tmp.name)
try:
img.save(tmp_path, format="WEBP", quality=78, method=4)
+180
View File
@@ -0,0 +1,180 @@
"""Job listing, labels, and JSON payloads shared by the HTML UI and /api."""
from __future__ import annotations
import re
import uuid
from datetime import UTC, datetime
from pathlib import Path
from typing import Any
from fastapi import HTTPException
from . import config, images, pipeline
_JOB_ID_RE = re.compile(r"^[A-Za-z0-9._-]+$")
STATUS_LABELS: dict[str, str] = {
"queued": "Warteschlange",
"processing": "Läuft",
"done": "Fertig",
"error": "Fehler",
"unknown": "unbekannt",
}
ACTIVE_STATUSES = frozenset({"queued", "processing", "pending"})
class JobIdError(ValueError):
"""Invalid or missing job id."""
def validate_job_id(job_id: str) -> str:
raw = job_id or ""
if not raw.strip() or "/" in raw or "\\" in raw or ".." in raw:
raise JobIdError("Ungültige Job-ID")
stem = pipeline.sanitize_stem(raw)
if not _JOB_ID_RE.match(stem):
raise JobIdError("Ungültige Job-ID")
return stem
def require_job_id(job_id: str) -> str:
try:
stem = validate_job_id(job_id)
except JobIdError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
if pipeline.read_status(stem) is None and not pipeline.job_paths(stem).original.exists():
raise HTTPException(status_code=404, detail="Job nicht gefunden")
return stem
def status_label(status: str | None) -> str:
key = (status or "unknown").strip() or "unknown"
return STATUS_LABELS.get(key, key)
def stage_label(status: str | None, stage: str | None, progress: dict[str, Any] | None) -> str:
if status == "queued":
return "Wartet auf Worker"
if status == "done":
return "Fertig"
if status == "error":
return "Fehler"
if stage == "preprocess":
return "Vorverarbeitung"
if stage == "rembg":
return "Freistellen"
if stage == "variant":
current = (progress or {}).get("current")
total = (progress or {}).get("total")
if current and total:
return f"Variante {current}/{total}"
return "Varianten"
if status == "processing":
return "Läuft"
return status_label(status)
def file_url(job_id: str, filename: str | None) -> str | None:
if not filename:
return None
return images.file_url(job_id, filename)
def list_intermediates(stem: str) -> list[str]:
paths = pipeline.job_paths(stem)
if not paths.intermediates.exists():
return []
return sorted(p.name for p in paths.intermediates.glob(f"{stem}_*.png") if p.is_file())
def _progress(data: dict[str, Any]) -> dict[str, int] | None:
raw = data.get("progress")
if not isinstance(raw, dict):
return None
try:
current = int(raw.get("current", 0))
total = int(raw.get("total", 0))
except (TypeError, ValueError):
return None
if total <= 0:
return None
return {"current": current, "total": total}
def _file_entry(job_id: str, filename: str | None) -> dict[str, str] | None:
if not filename:
return None
return {"file": filename, "url": images.file_url(job_id, filename)}
def summarize_job(job_id: str, data: dict[str, Any] | None = None) -> dict[str, Any]:
meta = data if data is not None else (pipeline.read_meta(job_id) or {})
variants = meta.get("variants") or []
status = meta.get("status", "unknown")
progress = _progress(meta)
stage = meta.get("stage")
thumb = variants[-1].get("file") if variants else None
return {
"job_id": job_id,
"status": status,
"status_label": status_label(status),
"stage": stage,
"stage_label": stage_label(status, stage if isinstance(stage, str) else None, progress),
"progress": progress,
"created_at": meta.get("created_at") or "",
"updated_at": meta.get("updated_at") or "",
"variant_count": len(variants),
"thumbnail": thumb,
"thumbnail_url": file_url(job_id, thumb),
"error": meta.get("error"),
}
def list_jobs() -> list[dict[str, Any]]:
jobs = [summarize_job(job_id) for job_id in pipeline.list_job_ids()]
jobs.sort(key=lambda j: j["created_at"] or j["job_id"], reverse=True)
return jobs
def job_detail_payload(job_id: str) -> dict[str, Any]:
stem = require_job_id(job_id)
meta = pipeline.read_meta(stem) or {}
paths = pipeline.job_paths(stem)
summary = summarize_job(stem, meta)
variants = []
for item in meta.get("variants") or []:
if not isinstance(item, dict) or not item.get("file"):
continue
entry = dict(item)
entry["url"] = images.file_url(stem, item["file"])
variants.append(entry)
intermediates = [_file_entry(stem, name) for name in list_intermediates(stem)]
original_name = paths.original.name if paths.original.exists() else meta.get("original_file")
rembg_name = paths.rembg.name if paths.rembg.exists() else meta.get("rembg_file")
summary.update(
{
"original": _file_entry(stem, original_name if original_name else None),
"rembg": _file_entry(stem, rembg_name if rembg_name else None),
"has_rembg": paths.rembg.exists(),
"variants": variants,
"intermediates": [item for item in intermediates if item],
"variant_errors": meta.get("variant_errors") or [],
"source_file": meta.get("source_file"),
}
)
return summary
def make_inbox_filename(original_name: str) -> str:
"""Unique inbox name so two party.jpg uploads don't clobber each other."""
stem = pipeline.sanitize_stem(original_name)
suffix = Path(original_name).suffix.lower()
if suffix not in config.SUPPORTED_EXTENSIONS:
suffix = ".jpg"
if suffix == ".jpeg":
suffix = ".jpg"
stamp = datetime.now(UTC).strftime("%Y%m%d_%H%M%S")
short = uuid.uuid4().hex[:6]
return f"{stamp}_{short}_{stem}{suffix}"
+25 -45
View File
@@ -3,9 +3,7 @@
from __future__ import annotations
import logging
import re
from pathlib import Path
from typing import Any
from urllib.parse import quote
from fastapi import FastAPI, Form, HTTPException, Query, Request
@@ -13,40 +11,35 @@ from fastapi.responses import FileResponse, HTMLResponse, RedirectResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from . import config, images, pipeline, remix
from . import api, config, images, jobs, pipeline, remix
from .logging_config import configure_logging
configure_logging()
logger = logging.getLogger("livef12.web")
app = FastAPI(title=config.SITE_TITLE)
app.include_router(api.router)
BASE_DIR = Path(__file__).resolve().parent
templates = Jinja2Templates(directory=str(BASE_DIR / "templates"))
templates.env.globals["img_attrs"] = images.img_attrs
templates.env.globals["PAIR_SIZES"] = images.PAIR_SIZES
templates.env.globals["GRID_SIZES"] = images.GRID_SIZES
templates.env.globals["status_label"] = jobs.status_label
templates.env.globals["stage_label"] = jobs.stage_label
templates.env.globals["ACTIVE_STATUSES"] = jobs.ACTIVE_STATUSES
app.mount("/static", StaticFiles(directory=str(BASE_DIR / "static")), name="static")
# Job id = sanitized source stem (may include dots).
_JOB_ID_RE = re.compile(r"^[A-Za-z0-9._-]+$")
def _validate_job_id(job_id: str) -> str:
raw = job_id or ""
if not raw.strip() or "/" in raw or "\\" in raw or ".." in raw:
raise HTTPException(status_code=400, detail="Ungueltige Job-ID")
stem = pipeline.sanitize_stem(raw)
if not _JOB_ID_RE.match(stem):
raise HTTPException(status_code=400, detail="Ungueltige Job-ID")
return stem
try:
return jobs.validate_job_id(job_id)
except jobs.JobIdError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
def _job_exists(job_id: str) -> str:
stem = _validate_job_id(job_id)
if pipeline.read_status(stem) is None and not pipeline.job_paths(stem).original.exists():
raise HTTPException(status_code=404, detail="Job nicht gefunden")
return stem
return jobs.require_job_id(job_id)
def _safe_job_file(job_id: str, filename: str) -> Path:
@@ -54,9 +47,9 @@ def _safe_job_file(job_id: str, filename: str) -> Path:
stem = _validate_job_id(job_id)
name = Path(filename).name
if name != filename or "/" in filename or "\\" in filename or name.startswith("."):
raise HTTPException(status_code=400, detail="Ungueltiger Pfad")
raise HTTPException(status_code=400, detail="Ungültiger Pfad")
if not name.startswith(f"{stem}_"):
raise HTTPException(status_code=400, detail="Ungueltiger Pfad")
raise HTTPException(status_code=400, detail="Ungültiger Pfad")
for directory in (config.VARIANTS_DIR, config.INTERMEDIATES_DIR):
candidate = (directory / name).resolve()
@@ -67,30 +60,17 @@ def _safe_job_file(job_id: str, filename: str) -> Path:
raise HTTPException(status_code=404, detail="Datei nicht gefunden")
def list_jobs() -> list[dict[str, Any]]:
jobs = []
for job_id in pipeline.list_job_ids():
data = pipeline.read_meta(job_id) or {}
variants = data.get("variants") or []
jobs.append(
{
"job_id": job_id,
"status": data.get("status", "unknown"),
"created_at": data.get("created_at") or "",
"variant_count": len(variants),
"thumbnail": variants[-1].get("file") if variants else None,
}
)
jobs.sort(key=lambda j: j["created_at"] or j["job_id"], reverse=True)
return jobs
@app.get("/", response_class=HTMLResponse)
def index(request: Request) -> HTMLResponse:
job_list = jobs.list_jobs()
return templates.TemplateResponse(
request,
"index.html",
{"jobs": list_jobs(), "site_title": config.SITE_TITLE},
{
"jobs": job_list,
"site_title": config.SITE_TITLE,
"has_active": any(j["status"] in jobs.ACTIVE_STATUSES for j in job_list),
},
)
@@ -100,11 +80,7 @@ def job_detail(request: Request, job_id: str) -> HTMLResponse:
paths = pipeline.job_paths(stem)
status = pipeline.read_status(stem) or {}
manifest = pipeline.read_manifest(stem) or {"variants": []}
intermediates = (
sorted(p.name for p in paths.intermediates.glob(f"{stem}_*.png") if p.is_file())
if paths.intermediates.exists()
else []
)
intermediates = jobs.list_intermediates(stem)
return templates.TemplateResponse(
request,
@@ -118,6 +94,7 @@ def job_detail(request: Request, job_id: str) -> HTMLResponse:
"rembg_name": paths.rembg.name if paths.rembg.exists() else None,
"has_rembg": paths.rembg.exists(),
"intermediates": intermediates,
"live": (status.get("status") or "") in jobs.ACTIVE_STATUSES,
},
)
@@ -134,7 +111,7 @@ def job_file(
if w not in images.SRCSET_WIDTHS:
raise HTTPException(
status_code=400,
detail=f"Ungueltige Breite (erlaubt: {', '.join(map(str, images.SRCSET_WIDTHS))})",
detail=f"Ungültige Breite (erlaubt: {', '.join(map(str, images.SRCSET_WIDTHS))})",
)
try:
cached = images.get_or_create_resized(path, w)
@@ -154,7 +131,10 @@ def remix_form(
stem = _job_exists(job_id)
paths = pipeline.job_paths(stem)
if not paths.rembg.exists():
raise HTTPException(status_code=409, detail="Job hat noch kein Rembg-Ergebnis, Remix noch nicht moeglich.")
raise HTTPException(
status_code=409,
detail="Job hat noch kein Rembg-Ergebnis, Remix noch nicht möglich.",
)
assets = pipeline.load_assets()
options = remix.build_remix_options(assets)
+33 -4
View File
@@ -396,6 +396,8 @@ def read_status(job_id: str) -> dict[str, Any] | None:
return None
return {
"status": data.get("status", "unknown"),
"stage": data.get("stage"),
"progress": data.get("progress"),
"created_at": data.get("created_at"),
"updated_at": data.get("updated_at"),
"error": data.get("error"),
@@ -628,7 +630,15 @@ def process_job(
paths.intermediates.mkdir(parents=True, exist_ok=True)
paths.meta.parent.mkdir(parents=True, exist_ok=True)
write_status(paths, "processing", source_file=str(source_path.name), source_stem=stem)
write_status(
paths,
"processing",
source_file=str(source_path.name),
source_stem=stem,
stage="preprocess",
progress={"current": 0, "total": config.OUTPUT_COUNT},
error=None,
)
try:
paths = preprocess_original(paths)
@@ -643,6 +653,12 @@ def process_job(
}
write_manifest(paths, manifest)
write_status(
paths,
"processing",
stage="rembg",
progress={"current": 0, "total": config.OUTPUT_COUNT},
)
ok, err = run_rembg(paths.original, paths.rembg)
if not ok:
raise PipelineError(f"rembg fehlgeschlagen: {err}")
@@ -654,6 +670,12 @@ def process_job(
for i in range(1, config.OUTPUT_COUNT + 1):
variant_id = f"v{i}"
write_status(
paths,
"processing",
stage="variant",
progress={"current": i, "total": config.OUTPUT_COUNT},
)
try:
entry = compose_variant(
paths,
@@ -700,10 +722,17 @@ def process_job(
if not manifest["variants"]:
raise PipelineError("Keine Variante erfolgreich erzeugt: " + "; ".join(variant_errors))
write_status(paths, "done", variant_errors=variant_errors)
done_count = len(manifest["variants"])
write_status(
paths,
"done",
stage="done",
progress={"current": done_count, "total": config.OUTPUT_COUNT},
variant_errors=variant_errors,
)
except PipelineError as exc:
logger.error("[%s] job failed: %s", stem, exc)
write_status(paths, "error", error=str(exc))
write_status(paths, "error", stage="error", error=str(exc))
except Exception as exc: # noqa: BLE001 - keep the worker loop alive
logger.exception("[%s] unexpected error", stem)
write_status(paths, "error", error=f"Unerwarteter Fehler: {exc}")
write_status(paths, "error", stage="error", error=f"Unerwarteter Fehler: {exc}")
+160
View File
@@ -0,0 +1,160 @@
/* live.f12.rocks — live poll + lightbox gallery. No framework. */
(function () {
"use strict";
var POLL_MS = 4000;
function $(id) {
return document.getElementById(id);
}
/* --- live reload while jobs run --- */
function fingerprint(payload) {
if (!payload) return "";
if (payload.job_id) {
return [
payload.status,
payload.stage,
payload.updated_at,
payload.variant_count,
(payload.intermediates || []).length,
payload.error || "",
].join("|");
}
var jobs = payload.jobs || [];
return jobs
.map(function (j) {
return [j.job_id, j.status, j.updated_at, j.variant_count, j.stage].join(":");
})
.join(",");
}
function startLivePoll() {
if (!document.body.hasAttribute("data-live")) return;
var jobId = document.body.getAttribute("data-job-id");
var url = jobId ? "/api/jobs/" + encodeURIComponent(jobId) : "/api/jobs";
var last = "";
var first = true;
function tick() {
fetch(url, { headers: { Accept: "application/json" } })
.then(function (r) {
if (!r.ok) throw new Error("poll " + r.status);
return r.json();
})
.then(function (data) {
var next = fingerprint(data);
if (first) {
last = next;
first = false;
return;
}
if (next !== last) {
window.location.reload();
}
})
.catch(function () {
/* venue wifi: try again next tick */
});
}
tick();
setInterval(tick, POLL_MS);
}
/* --- lightbox with prev/next --- */
function startLightbox() {
var box = $("lightbox");
var img = $("lightbox-img");
var caption = $("lightbox-caption");
if (!box || !img) return;
var items = [];
var index = 0;
function collect() {
items = Array.prototype.slice
.call(document.querySelectorAll("img.lightboxable"))
.map(function (el) {
return {
src: el.getAttribute("data-full-src") || el.currentSrc || el.src,
alt: el.alt || "",
};
});
}
function show(i) {
if (!items.length) return;
index = (i + items.length) % items.length;
img.src = items[index].src;
img.alt = items[index].alt;
if (caption) caption.textContent = items[index].alt;
box.hidden = false;
document.body.classList.add("lightbox-open");
}
function close() {
box.hidden = true;
img.removeAttribute("src");
document.body.classList.remove("lightbox-open");
}
document.addEventListener("click", function (e) {
var target = e.target;
if (!(target instanceof HTMLImageElement)) return;
if (!target.classList.contains("lightboxable")) return;
e.preventDefault();
e.stopPropagation();
collect();
var full = target.getAttribute("data-full-src") || target.currentSrc || target.src;
var found = items.findIndex(function (it) {
return it.src === full;
});
show(found >= 0 ? found : 0);
});
box.addEventListener("click", function (e) {
if (e.target === box || (e.target && e.target.classList.contains("lightbox-close"))) {
close();
return;
}
if (e.target && e.target.classList.contains("lightbox-next")) {
show(index + 1);
}
if (e.target && e.target.classList.contains("lightbox-prev")) {
show(index - 1);
}
});
document.addEventListener("keydown", function (e) {
if (box.hidden) return;
if (e.key === "Escape") close();
if (e.key === "ArrowRight") show(index + 1);
if (e.key === "ArrowLeft") show(index - 1);
});
var startX = 0;
box.addEventListener(
"touchstart",
function (e) {
if (e.changedTouches && e.changedTouches[0]) startX = e.changedTouches[0].screenX;
},
{ passive: true }
);
box.addEventListener(
"touchend",
function (e) {
if (!e.changedTouches || !e.changedTouches[0]) return;
var dx = e.changedTouches[0].screenX - startX;
if (Math.abs(dx) < 40) return;
show(index + (dx < 0 ? 1 : -1));
},
{ passive: true }
);
}
startLivePoll();
startLightbox();
})();
+6
View File
@@ -0,0 +1,6 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
<rect width="64" height="64" rx="12" fill="#14161a"/>
<rect x="10" y="14" width="44" height="36" rx="4" fill="#1d2025" stroke="#ff5a1f" stroke-width="3"/>
<circle cx="24" cy="28" r="5" fill="#ff5a1f"/>
<path d="M14 44l12-12 8 8 8-6 8 10H14z" fill="#ff5a1f"/>
</svg>

After

Width:  |  Height:  |  Size: 335 B

+94
View File
@@ -52,6 +52,17 @@ a:focus-visible {
.site-header {
padding: 1rem var(--gap);
border-bottom: 1px solid var(--border);
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 0.75rem;
}
.header-note {
color: var(--text-dim);
font-size: 0.8rem;
letter-spacing: 0.04em;
text-transform: uppercase;
}
.brand {
@@ -147,6 +158,33 @@ h2 {
}
}
.job-heading {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 0.5rem 0.75rem;
margin: 0.5rem 0 1rem;
}
.job-heading h1 {
margin: 0;
}
.progress {
height: 4px;
background: var(--border);
border-radius: 999px;
overflow: hidden;
margin: -0.5rem 0 1rem;
}
.progress span {
display: block;
height: 100%;
background: var(--accent);
min-width: 0;
}
.job-card {
background: var(--bg-elevated);
border: 1px solid var(--border);
@@ -154,6 +192,27 @@ h2 {
overflow: hidden;
}
.job-card.is-live {
border-color: var(--pending);
animation: live-pulse 1.8s ease-in-out infinite;
}
@keyframes live-pulse {
0%,
100% {
box-shadow: 0 0 0 0 rgba(217, 164, 65, 0);
}
50% {
box-shadow: 0 0 0 3px rgba(217, 164, 65, 0.35);
}
}
@media (prefers-reduced-motion: reduce) {
.job-card.is-live {
animation: none;
}
}
.job-card a {
color: var(--text);
display: block;
@@ -390,4 +449,39 @@ body.lightbox-open {
padding: 0.25rem 0.5rem;
min-height: 2.75rem;
min-width: 2.75rem;
z-index: 1;
}
.lightbox-nav {
position: absolute;
top: 50%;
transform: translateY(-50%);
border: 0;
background: transparent;
color: var(--text);
font-size: 2.4rem;
line-height: 1;
cursor: pointer;
padding: 0.5rem 0.75rem;
min-height: 2.75rem;
min-width: 2.75rem;
}
.lightbox-prev {
left: 0.25rem;
}
.lightbox-next {
right: 0.25rem;
}
.lightbox-caption {
position: absolute;
bottom: 0.75rem;
left: 1rem;
right: 1rem;
margin: 0;
text-align: center;
color: var(--text-dim);
font-size: 0.85rem;
}
+11 -42
View File
@@ -3,61 +3,30 @@
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="theme-color" content="#14161a">
<meta name="color-scheme" content="dark">
<title>{% block title %}{{ site_title }}{% endblock %}</title>
<link rel="icon" href="/static/favicon.svg" type="image/svg+xml">
<link rel="apple-touch-icon" href="/static/favicon.svg">
<link rel="stylesheet" href="/static/style.css">
</head>
<body>
<body{% if live is defined and live %} data-live="1"{% endif %}{% if job_id is defined %} data-job-id="{{ job_id }}"{% endif %}{% if has_active is defined and has_active %} data-live="1"{% endif %}>
<header class="site-header">
<a class="brand" href="/">{{ site_title }}</a>
<span class="header-note">Event-Pep</span>
</header>
<main>
{% block content %}{% endblock %}
</main>
<div id="lightbox" class="lightbox" hidden>
<button type="button" class="lightbox-close" aria-label="Schliessen">&times;</button>
<button type="button" class="lightbox-close" aria-label="Schließen">&times;</button>
<button type="button" class="lightbox-nav lightbox-prev" aria-label="Vorheriges Bild">‹</button>
<img id="lightbox-img" alt="">
<button type="button" class="lightbox-nav lightbox-next" aria-label="Nächstes Bild">›</button>
<p id="lightbox-caption" class="lightbox-caption"></p>
</div>
<script>
(function () {
var box = document.getElementById("lightbox");
var img = document.getElementById("lightbox-img");
if (!box || !img) return;
function openLightbox(src, alt) {
img.src = src;
img.alt = alt || "";
box.hidden = false;
document.body.classList.add("lightbox-open");
}
function closeLightbox() {
box.hidden = true;
img.removeAttribute("src");
document.body.classList.remove("lightbox-open");
}
document.addEventListener("click", function (e) {
var target = e.target;
if (!(target instanceof HTMLImageElement)) return;
if (!target.classList.contains("lightboxable")) return;
e.preventDefault();
e.stopPropagation();
var full = target.getAttribute("data-full-src");
openLightbox(full || target.currentSrc || target.src, target.alt);
});
box.addEventListener("click", function (e) {
if (e.target === box || (e.target && e.target.classList.contains("lightbox-close"))) {
closeLightbox();
}
});
document.addEventListener("keydown", function (e) {
if (e.key === "Escape" && !box.hidden) closeLightbox();
});
})();
</script>
<script src="/static/app.js" defer></script>
</body>
</html>
+12 -6
View File
@@ -2,28 +2,34 @@
{% block title %}{{ site_title }}{% endblock %}
{% block content %}
{% if not jobs %}
<p class="empty-state">Noch keine Jobs. Bild in den Sync-Ordner legen, dann kurz warten.</p>
<p class="empty-state">Noch keine Jobs. Foto in der App teilen, dann kurz warten.</p>
{% else %}
<ul class="job-grid">
{% for job in jobs %}
<li class="job-card">
<li class="job-card{% if job.status in ACTIVE_STATUSES %} is-live{% endif %}">
<a href="/jobs/{{ job.job_id }}">
{% if job.thumbnail %}
{% set img = img_attrs(job.job_id, job.thumbnail) %}
<img class="thumb lightboxable"
<img class="thumb"
src="{{ img.src }}"
srcset="{{ img.srcset }}"
sizes="{{ img.sizes }}"
data-full-src="{{ img.full_src }}"
alt="Variante von Job {{ job.job_id }}"
loading="lazy"
decoding="async">
{% else %}
<span class="thumb thumb-placeholder status-{{ job.status }}">{{ job.status }}</span>
<span class="thumb thumb-placeholder status-{{ job.status }}">{{ job.status_label }}</span>
{% endif %}
<span class="job-meta">
<span class="job-id">{{ job.job_id }}</span>
<span class="job-status status-{{ job.status }}">{{ job.status }} &middot; {{ job.variant_count }} Varianten</span>
<span class="job-status status-{{ job.status }}">
{{ job.status_label }}
{% if job.stage_label and job.status in ACTIVE_STATUSES %}
&middot; {{ job.stage_label }}
{% else %}
&middot; {{ job.variant_count }} Varianten
{% endif %}
</span>
</span>
</a>
</li>
+16 -2
View File
@@ -3,8 +3,20 @@
{% block content %}
<p class="back-link"><a href="/">&larr; Alle Jobs</a></p>
<h1>Job {{ job_id }}</h1>
<p class="job-status status-{{ status.status }}">Status: {{ status.status or "unbekannt" }}</p>
<div class="job-heading">
<h1>Job {{ job_id }}</h1>
<p class="job-status status-{{ status.status }}">
{{ status_label(status.status) }}
{% if status.status in ACTIVE_STATUSES %}
&middot; {{ stage_label(status.status, status.stage, status.progress) }}
{% endif %}
</p>
</div>
{% if status.status in ACTIVE_STATUSES and status.progress and status.progress.total %}
<div class="progress" aria-hidden="true">
<span style="width: {{ (status.progress.current / status.progress.total * 100) | int }}%"></span>
</div>
{% endif %}
{% if status.error %}
<p class="error-box">Fehler: {{ status.error }}</p>
{% endif %}
@@ -28,6 +40,8 @@
<a href="/jobs/{{ job_id }}/files/{{ original_name }}" download>Download</a>
</figcaption>
</figure>
{% else %}
<p class="empty-state">Original kommt, sobald der Worker greift.</p>
{% endif %}
{% if has_rembg and rembg_name %}
{% set img = img_attrs(job_id, rembg_name, sizes=PAIR_SIZES) %}
+1 -1
View File
@@ -1,7 +1,7 @@
{% extends "base.html" %}
{% block title %}Remix {{ job_id }} — {{ site_title }}{% endblock %}
{% block content %}
<p class="back-link"><a href="/jobs/{{ job_id }}">&larr; Zurueck zum Job</a></p>
<p class="back-link"><a href="/jobs/{{ job_id }}">&larr; Zurück zum Job</a></p>
<h1>Remix &middot; Job {{ job_id }}</h1>
{% if from_variant %}