fix: UUID→fichier via API photobooth (created_at/processed), photo_id dans print_queue
This commit is contained in:
@@ -1,8 +1,9 @@
|
||||
"""API galerie admin — impression et suppression de photos."""
|
||||
|
||||
import logging
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import APIRouter, Request, Query
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
@@ -21,49 +22,6 @@ def _get_id(item: dict) -> str:
|
||||
return str(item.get("id", item.get("filename", item.get("uid", ""))))
|
||||
|
||||
|
||||
def _find_file(media_dir: str, photo_id: str) -> Path | None:
|
||||
"""Cherche un fichier image correspondant à l'identifiant.
|
||||
|
||||
Cherche dans media_dir, processed_full/ et les chemins photobooth standard.
|
||||
"""
|
||||
base = Path(media_dir)
|
||||
candidates = [
|
||||
base,
|
||||
base / "processed_full",
|
||||
Path("/home/pi/photobooth-data/media/processed_full"),
|
||||
Path("/home/pi/photobooth-data/media"),
|
||||
]
|
||||
for d in candidates:
|
||||
if not d.exists():
|
||||
continue
|
||||
for ext in (".jpg", ".jpeg", ".png"):
|
||||
f = d / f"{photo_id}{ext}"
|
||||
if f.exists():
|
||||
return f
|
||||
return None
|
||||
|
||||
|
||||
def _build_mtime_index(media_dir: Path) -> dict[str, float]:
|
||||
"""Construit un index {stem: mtime, name: mtime} en cherchant dans les dossiers connus."""
|
||||
index: dict[str, float] = {}
|
||||
checked: set[Path] = set()
|
||||
candidates = [
|
||||
media_dir,
|
||||
media_dir / "processed_full",
|
||||
Path("/home/pi/photobooth-data/media/processed_full"),
|
||||
Path("/home/pi/photobooth-data/media"),
|
||||
]
|
||||
for d in candidates:
|
||||
if not d.exists() or d in checked:
|
||||
continue
|
||||
checked.add(d)
|
||||
for f in d.iterdir():
|
||||
if f.is_file() and f.suffix.lower() in (".jpg", ".jpeg", ".png"):
|
||||
mt = f.stat().st_mtime
|
||||
index[f.name] = mt
|
||||
index[f.stem] = mt
|
||||
return index
|
||||
|
||||
|
||||
def _require_auth(request: Request):
|
||||
return request.session.get("authenticated") is True
|
||||
@@ -88,21 +46,25 @@ async def admin_get_photos(
|
||||
printer_svc = request.app.state.printer_service
|
||||
cfg = request.app.state.config
|
||||
event_svc = getattr(request.app.state, "event_service", None)
|
||||
media_dir = Path(cfg.photobooth.media_dir)
|
||||
|
||||
# Récupère toutes les photos
|
||||
all_photos = await pb.get_media_collection(limit=500)
|
||||
photos = [p for p in all_photos if _is_image(p)]
|
||||
|
||||
# Enrichit chaque photo avec mtime depuis le disque
|
||||
mtime_index = _build_mtime_index(media_dir)
|
||||
|
||||
# Enrichit chaque photo avec son timestamp de création
|
||||
# photobooth-app retourne 'created_at' en UTC (ex: "2026-07-17T14:15:52")
|
||||
for p in photos:
|
||||
pid = _get_id(p)
|
||||
p["photo_id"] = pid
|
||||
stem = pid.rsplit(".", 1)[0] if "." in pid else pid
|
||||
mt = mtime_index.get(pid) or mtime_index.get(stem) or 0.0
|
||||
created_str = p.get("created_at", "")
|
||||
try:
|
||||
# Interprète created_at comme UTC → timestamp Unix correct
|
||||
dt = datetime.fromisoformat(created_str).replace(tzinfo=timezone.utc)
|
||||
mt = dt.timestamp()
|
||||
except (ValueError, TypeError):
|
||||
mt = 0.0
|
||||
p["mtime"] = mt
|
||||
# Date pour affichage : convertit UTC → heure locale
|
||||
p["date_iso"] = datetime.fromtimestamp(mt).strftime("%Y-%m-%d") if mt else ""
|
||||
p["date_label"] = datetime.fromtimestamp(mt).strftime("%d/%m/%Y %H:%M") if mt else ""
|
||||
|
||||
@@ -178,12 +140,24 @@ async def admin_print_photo(
|
||||
ws = request.app.state.ws_manager
|
||||
cfg = request.app.state.config
|
||||
|
||||
filename = _find_file(cfg.photobooth.media_dir, photo_id)
|
||||
if not filename:
|
||||
return JSONResponse({"error": f"Fichier introuvable pour {photo_id}"}, status_code=404)
|
||||
# Récupère les détails de la photo via l'API photobooth-app
|
||||
# (le champ 'processed' donne le chemin relatif réel : media/processed_full/YYYYMMDD-xxx.jpg)
|
||||
item = await pb.get_media_item(photo_id)
|
||||
if not item:
|
||||
return JSONResponse({"error": f"Photo introuvable: {photo_id}"}, status_code=404)
|
||||
|
||||
file_path = pb.media_file_path(item)
|
||||
if not file_path or not file_path.exists():
|
||||
logger.error("Fichier manquant pour %s: %s", photo_id, file_path)
|
||||
return JSONResponse(
|
||||
{"error": f"Fichier manquant sur le disque: {file_path}"}, status_code=404
|
||||
)
|
||||
|
||||
filename = file_path
|
||||
logger.info("Fichier pour impression: %s → %s", photo_id, filename)
|
||||
|
||||
thumb_url = pb.thumbnail_url(photo_id)
|
||||
entry = await printer_svc.add_request(str(filename), thumb_url, copies)
|
||||
entry = await printer_svc.add_request(str(filename), thumb_url, copies, photo_id=photo_id)
|
||||
|
||||
should_print_now = (cfg.print.mode == "direct") or immediate
|
||||
|
||||
|
||||
Reference in New Issue
Block a user