fix: galerie sans retéléchargement, ZIP par parties, suppression de photo, miniatures, liens admin et slugs non devinables
- Galerie fête : ne remplace plus l'URL signée d'une image déjà affichée (egress ~10 Go/h par écran) - ZIP découpé en parties (300 photos / 100 Mo), liens directs sans blob en mémoire - Suppression d'une photo par l'admin (original + miniature), POST authentifié par admin_token - Miniatures 480 px générées côté client, ZIP et téléchargement gardent l'original - Token admin dans le fragment (#token=), nginx sans access_log sur /admin/, logs Docker bornés - Slug avec suffixe aléatoire de 6 hex pour les nouveaux événements Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -2,6 +2,12 @@ services:
|
||||
photobooth-front:
|
||||
image: nginx:alpine
|
||||
restart: always
|
||||
# Journaux bornés (~30 Mo max) : contiennent des IP d'invités.
|
||||
logging:
|
||||
driver: json-file
|
||||
options:
|
||||
max-size: "10m"
|
||||
max-file: "3"
|
||||
labels:
|
||||
- traefik.enable=true
|
||||
- traefik.http.routers.photobooth.rule=Host(`photobooth.assistantaikev.eu`)
|
||||
|
||||
@@ -25,6 +25,8 @@ server {
|
||||
# /admin/qrcode/ reste servi tel quel (fichier réel, try_files le trouve
|
||||
# avant de tomber sur le fallback ci-dessous).
|
||||
location /admin/ {
|
||||
# Les anciens liens portent encore ?token=… : ne jamais les journaliser.
|
||||
access_log off;
|
||||
try_files $uri $uri/ /admin/gallery/index.html;
|
||||
}
|
||||
|
||||
|
||||
+177
-65
@@ -13,10 +13,18 @@
|
||||
// GET {SUPABASE_URL}/functions/v1/admin-gallery?slug=<slug>&token=<token>
|
||||
// -> 200 { event: { nom, date_evenement, statut, photo_count },
|
||||
// photos: [ { id, nom_invite, message, uploaded_at,
|
||||
// signed_url, expires_in } ] }
|
||||
// signed_url, thumb_url, expires_in } ] }
|
||||
// (thumb_url : miniature ~480 px pour la grille, null si absente ;
|
||||
// signed_url : original, pour le lien Télécharger et le repli)
|
||||
// -> 403/404 générique si slug/token invalide (pas de distinction)
|
||||
// GET {...}&action=zip
|
||||
// -> 200 application/zip (binaire, toutes les photos de l'événement)
|
||||
// + zip_parts : nombre de parties du ZIP
|
||||
// GET {...}&action=zip&part=N
|
||||
// -> 200 application/zip (partie N), ouvert par un lien direct : le
|
||||
// navigateur télécharge en flux, rien n'est gardé en mémoire ici.
|
||||
// Exige verify_jwt=false sur la fonction (un lien n'envoie pas de
|
||||
// header). Erreur -> texte lisible (text/plain) dans l'onglet ouvert.
|
||||
// POST {...}&action=delete&photo_id=<uuid>
|
||||
// -> 200 { deleted, photo_count, zip_parts } | 404 photo_not_found
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Éléments DOM
|
||||
@@ -31,7 +39,7 @@ const retryBtn = document.getElementById("retry-btn");
|
||||
const contentBlock = document.getElementById("gallery-content");
|
||||
const statusBanner = document.getElementById("status-banner");
|
||||
const refreshBtn = document.getElementById("refresh-btn");
|
||||
const zipBtn = document.getElementById("download-zip-btn");
|
||||
const zipPartsEl = document.getElementById("zip-parts");
|
||||
const zipStatusEl = document.getElementById("zip-status");
|
||||
const emptyStateEl = document.getElementById("empty-state");
|
||||
const photoGridEl = document.getElementById("photo-grid");
|
||||
@@ -47,7 +55,7 @@ const state = {
|
||||
photos: [],
|
||||
loadedAt: 0, // Date.now() au moment de la dernière réponse reçue
|
||||
lastRetryAction: null,
|
||||
isZipping: false,
|
||||
zipParts: 0,
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -64,6 +72,7 @@ const ERROR_MESSAGES = {
|
||||
"server-error":
|
||||
"Le service est momentanément indisponible. Réessaie dans quelques instants.",
|
||||
unknown: "Une erreur inattendue est survenue. Réessaie, ou reviens un peu plus tard.",
|
||||
"photo-gone": "Cette photo a déjà été retirée. Clique sur Actualiser.",
|
||||
};
|
||||
|
||||
const RETRYABLE_CODES = new Set(["network", "server-error", "unknown"]);
|
||||
@@ -102,8 +111,20 @@ function getSlugFromPath() {
|
||||
return match ? decodeURIComponent(match[1]) : null;
|
||||
}
|
||||
|
||||
// Token lu dans le fragment (#token=…, jamais envoyé au serveur). Les anciens
|
||||
// liens en ?token=… restent acceptés, puis le token est déplacé dans le
|
||||
// fragment pour qu'il ne reparte plus vers le serveur au rechargement.
|
||||
function getTokenFromQuery() {
|
||||
return new URLSearchParams(window.location.search).get("token");
|
||||
const fromHash = new URLSearchParams(window.location.hash.slice(1)).get("token");
|
||||
if (fromHash) return fromHash;
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
const fromQuery = params.get("token");
|
||||
if (fromQuery) {
|
||||
params.delete("token");
|
||||
const query = params.toString();
|
||||
history.replaceState(null, "", `${window.location.pathname}${query ? `?${query}` : ""}#token=${encodeURIComponent(fromQuery)}`);
|
||||
}
|
||||
return fromQuery;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -226,8 +247,15 @@ function renderPhotoGrid() {
|
||||
img.alt = photo.nom_invite
|
||||
? `Photo envoyée par ${photo.nom_invite}`
|
||||
: "Photo envoyée par un invité";
|
||||
img.src = photo.signed_url;
|
||||
// Miniature d'abord ; repli unique sur l'original si elle est absente
|
||||
// ou ne charge pas.
|
||||
img.src = photo.thumb_url || photo.signed_url;
|
||||
img.onerror = () => {
|
||||
if (photo.thumb_url && photo.signed_url && img.src === photo.thumb_url) {
|
||||
console.warn(`[admin] miniature indisponible pour ${photo.id}, repli sur l'original`);
|
||||
img.src = photo.signed_url;
|
||||
return;
|
||||
}
|
||||
li.classList.add("photo-card--broken");
|
||||
};
|
||||
|
||||
@@ -287,14 +315,122 @@ function renderPhotoGrid() {
|
||||
}
|
||||
});
|
||||
|
||||
li.append(thumbWrap, meta, downloadLink);
|
||||
li.append(thumbWrap, meta, downloadLink, buildDeleteControl(photo, li));
|
||||
photoGridEl.appendChild(li);
|
||||
}
|
||||
}
|
||||
|
||||
function renderContent(event, photos) {
|
||||
// Bouton "Retirer" discret + confirmation en ligne (pas de window.confirm :
|
||||
// bloquant et mal rendu sur mobile).
|
||||
function buildDeleteControl(photo, li) {
|
||||
const box = document.createElement("div");
|
||||
box.className = "photo-card__delete";
|
||||
|
||||
const askBtn = document.createElement("button");
|
||||
askBtn.type = "button";
|
||||
askBtn.className = "photo-card__delete-btn";
|
||||
askBtn.textContent = "Retirer";
|
||||
|
||||
const confirmBox = document.createElement("div");
|
||||
confirmBox.className = "photo-card__confirm";
|
||||
confirmBox.hidden = true;
|
||||
const question = document.createElement("p");
|
||||
question.textContent = "Retirer définitivement cette photo pour tout le monde ?";
|
||||
const yesBtn = document.createElement("button");
|
||||
yesBtn.type = "button";
|
||||
yesBtn.className = "photo-card__delete-btn photo-card__delete-btn--danger";
|
||||
yesBtn.textContent = "Oui, retirer";
|
||||
const noBtn = document.createElement("button");
|
||||
noBtn.type = "button";
|
||||
noBtn.className = "photo-card__delete-btn";
|
||||
noBtn.textContent = "Annuler";
|
||||
const msg = document.createElement("p");
|
||||
msg.className = "photo-card__delete-msg";
|
||||
msg.setAttribute("role", "status");
|
||||
confirmBox.append(question, yesBtn, noBtn);
|
||||
|
||||
askBtn.addEventListener("click", () => {
|
||||
askBtn.hidden = true;
|
||||
confirmBox.hidden = false;
|
||||
msg.textContent = "";
|
||||
noBtn.focus();
|
||||
});
|
||||
noBtn.addEventListener("click", () => {
|
||||
confirmBox.hidden = true;
|
||||
askBtn.hidden = false;
|
||||
askBtn.focus();
|
||||
});
|
||||
yesBtn.addEventListener("click", async () => {
|
||||
yesBtn.disabled = true;
|
||||
noBtn.disabled = true;
|
||||
msg.textContent = "Suppression…";
|
||||
try {
|
||||
const data = await deletePhoto(photo.id);
|
||||
state.photos = state.photos.filter((p) => p.id !== photo.id);
|
||||
state.event.photo_count = data.photo_count;
|
||||
li.remove();
|
||||
renderHeader(state.event);
|
||||
renderEmptyState(state.event);
|
||||
renderZipParts(data.zip_parts);
|
||||
// Une suppression décale les photos suivantes d'une partie à l'autre.
|
||||
if (state.zipParts > 1) {
|
||||
showZipStatus(
|
||||
"Photo retirée. Les photos suivantes ont pu changer de partie : si tu avais déjà téléchargé des parties, retélécharge celles qui venaient après.",
|
||||
false
|
||||
);
|
||||
}
|
||||
} catch (err) {
|
||||
const normalized = normalizeError(err);
|
||||
msg.textContent = ERROR_MESSAGES[normalized.code] || ERROR_MESSAGES.unknown;
|
||||
if (normalized.cause) console.error(`[gallery:delete:${normalized.code}]`, normalized.cause);
|
||||
yesBtn.disabled = false;
|
||||
noBtn.disabled = false;
|
||||
}
|
||||
});
|
||||
|
||||
box.append(askBtn, confirmBox, msg);
|
||||
return box;
|
||||
}
|
||||
|
||||
function showZipStatus(text, isError) {
|
||||
zipStatusEl.hidden = false;
|
||||
zipStatusEl.className = isError ? "zip-status zip-status--error" : "zip-status";
|
||||
zipStatusEl.textContent = text;
|
||||
}
|
||||
|
||||
// Un lien par partie. Lien direct (pas fetch + blob) : le navigateur écrit
|
||||
// le ZIP sur le disque au fil de l'eau, même sur téléphone. target=_blank :
|
||||
// en cas d'erreur, le message texte s'ouvre dans un autre onglet sans
|
||||
// quitter la galerie.
|
||||
function renderZipParts(count) {
|
||||
state.zipParts = Number.isInteger(count) && count > 0 ? count : 0;
|
||||
zipPartsEl.textContent = "";
|
||||
for (let part = 1; part <= state.zipParts; part++) {
|
||||
const link = document.createElement("a");
|
||||
link.className = "btn";
|
||||
link.href = buildFunctionUrl("zip", { part: String(part) });
|
||||
link.target = "_blank";
|
||||
link.rel = "noopener noreferrer";
|
||||
link.download = "";
|
||||
const label =
|
||||
state.zipParts === 1 ? "Télécharger tout (ZIP)" : `Partie ${part}/${state.zipParts}`;
|
||||
link.innerHTML =
|
||||
'<svg class="btn-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><path d="M12 4v11"/><path d="M7 10.5 12 15.5 17 10.5"/><path d="M5 19.5h14"/></svg>';
|
||||
const span = document.createElement("span");
|
||||
span.textContent = label;
|
||||
link.appendChild(span);
|
||||
link.addEventListener("click", () => {
|
||||
link.classList.add("btn--done");
|
||||
span.textContent = `${label} (lancée)`;
|
||||
});
|
||||
zipPartsEl.appendChild(link);
|
||||
}
|
||||
}
|
||||
|
||||
function renderContent(data) {
|
||||
const event = data.event;
|
||||
state.event = event;
|
||||
state.photos = Array.isArray(photos) ? photos : [];
|
||||
state.photos = Array.isArray(data.photos) ? data.photos : [];
|
||||
|
||||
loadingBlock.hidden = true;
|
||||
errorBlock.hidden = true;
|
||||
@@ -304,22 +440,29 @@ function renderContent(event, photos) {
|
||||
renderStatusBanner(event);
|
||||
renderEmptyState(event);
|
||||
renderPhotoGrid();
|
||||
renderZipParts(data.zip_parts);
|
||||
|
||||
const hasPhotos = state.photos.length > 0;
|
||||
zipBtn.disabled = !hasPhotos;
|
||||
zipBtn.title = hasPhotos ? "" : "Aucune photo à télécharger";
|
||||
if (state.zipParts > 1) {
|
||||
showZipStatus(
|
||||
`Tes ${state.photos.length} photos sont réparties en ${state.zipParts} fichiers ZIP : télécharge chaque partie. Si un téléchargement échoue, ou si une partie contient un fichier PHOTOS-MANQUANTES.txt, relance seulement cette partie.`,
|
||||
false
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Appels réseau
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function buildFunctionUrl(action) {
|
||||
function buildFunctionUrl(action, extraParams) {
|
||||
const { SUPABASE_URL } = getConfig();
|
||||
const url = new URL(`${SUPABASE_URL.replace(/\/+$/, "")}/functions/v1/admin-gallery`);
|
||||
url.searchParams.set("slug", state.slug);
|
||||
url.searchParams.set("token", state.token);
|
||||
if (action) url.searchParams.set("action", action);
|
||||
for (const [key, value] of Object.entries(extraParams || {})) {
|
||||
url.searchParams.set(key, value);
|
||||
}
|
||||
return url.toString();
|
||||
}
|
||||
|
||||
@@ -370,62 +513,35 @@ async function loadGallery() {
|
||||
try {
|
||||
const data = await fetchGallery();
|
||||
state.loadedAt = Date.now();
|
||||
renderContent(data.event, data.photos);
|
||||
renderContent(data);
|
||||
} catch (err) {
|
||||
showError(err, () => loadGallery());
|
||||
}
|
||||
}
|
||||
|
||||
function parseZipFilename(res, fallback) {
|
||||
const header = res.headers.get("Content-Disposition") || "";
|
||||
const match = header.match(/filename\*?=(?:UTF-8'')?"?([^";\n]+)"?/i);
|
||||
return match ? decodeURIComponent(match[1]) : fallback;
|
||||
}
|
||||
async function deletePhoto(photoId) {
|
||||
let res;
|
||||
try {
|
||||
res = await fetch(buildFunctionUrl("delete", { photo_id: photoId }), {
|
||||
method: "POST",
|
||||
headers: buildAuthHeaders(),
|
||||
});
|
||||
} catch (err) {
|
||||
throw appError("network", err);
|
||||
}
|
||||
|
||||
function triggerBlobDownload(blob, filename) {
|
||||
const url = URL.createObjectURL(blob);
|
||||
const link = document.createElement("a");
|
||||
link.href = url;
|
||||
link.download = filename;
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
document.body.removeChild(link);
|
||||
setTimeout(() => URL.revokeObjectURL(url), 1000);
|
||||
}
|
||||
|
||||
async function downloadZip() {
|
||||
if (state.isZipping) return;
|
||||
state.isZipping = true;
|
||||
zipBtn.disabled = true;
|
||||
zipStatusEl.hidden = false;
|
||||
zipStatusEl.className = "zip-status";
|
||||
zipStatusEl.textContent = "Préparation du ZIP…";
|
||||
const body = await safeReadText(res);
|
||||
if (res.status === 404 && body && body.includes("photo_not_found")) {
|
||||
throw appError("photo-gone", body);
|
||||
}
|
||||
if (res.status === 403 || res.status === 404) throw appError("link-invalid", body);
|
||||
if (res.status >= 500) throw appError("server-error", body);
|
||||
if (!res.ok) throw appError("unknown", body);
|
||||
|
||||
try {
|
||||
let res;
|
||||
try {
|
||||
res = await fetch(buildFunctionUrl("zip"), { headers: buildAuthHeaders() });
|
||||
} catch (err) {
|
||||
throw appError("network", err);
|
||||
}
|
||||
|
||||
if (res.status === 403 || res.status === 404) throw appError("link-invalid");
|
||||
if (res.status >= 500) throw appError("server-error", await safeReadText(res));
|
||||
if (!res.ok) throw appError("unknown", await safeReadText(res));
|
||||
|
||||
const blob = await res.blob();
|
||||
const filename = parseZipFilename(res, `photos-${state.slug}.zip`);
|
||||
triggerBlobDownload(blob, filename);
|
||||
|
||||
zipStatusEl.textContent = "Téléchargement lancé.";
|
||||
return JSON.parse(body);
|
||||
} catch (err) {
|
||||
const normalized = normalizeError(err);
|
||||
zipStatusEl.className = "zip-status zip-status--error";
|
||||
zipStatusEl.textContent = ERROR_MESSAGES[normalized.code] || ERROR_MESSAGES.unknown;
|
||||
if (normalized.cause) console.error(`[gallery:zip:${normalized.code}]`, normalized.cause);
|
||||
} finally {
|
||||
state.isZipping = false;
|
||||
zipBtn.disabled = state.photos.length === 0;
|
||||
throw appError("unknown", err);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -442,10 +558,6 @@ refreshBtn.addEventListener("click", () => {
|
||||
loadGallery();
|
||||
});
|
||||
|
||||
zipBtn.addEventListener("click", () => {
|
||||
downloadZip();
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Démarrage
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
+31
-4
@@ -27,6 +27,24 @@ const COMPRESSION_OPTIONS = {
|
||||
preserveExif: false, // on ne conserve pas les métadonnées (GPS, etc.) — minimisation RGPD
|
||||
};
|
||||
|
||||
// Miniature pour les grilles (galerie « fête », admin) : générée depuis la
|
||||
// photo déjà compressée (orientation déjà appliquée, EXIF déjà retiré).
|
||||
const THUMB_OPTIONS = {
|
||||
maxSizeMB: 0.075,
|
||||
maxWidthOrHeight: 480,
|
||||
useWebWorker: true,
|
||||
fileType: "image/jpeg",
|
||||
initialQuality: 0.7,
|
||||
preserveExif: false,
|
||||
};
|
||||
|
||||
// Convention partagée avec les Edge Functions public-gallery/admin-gallery
|
||||
// (thumbPathOf) : même dossier que l'original, donc purgée à J+7 avec lui
|
||||
// (expire-events liste {event_id}/ sans récursion).
|
||||
function thumbPathOf(path) {
|
||||
return path.replace(/\.jpg$/, "_thumb.jpg");
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Éléments DOM
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -498,9 +516,8 @@ async function normalizeAndCompress(file) {
|
||||
// Envoi vers Supabase (Storage + table photos)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
async function uploadToStorage(eventId, blob) {
|
||||
async function uploadToStorage(path, blob) {
|
||||
const { SUPABASE_URL, SUPABASE_ANON_KEY, SUPABASE_STORAGE_BUCKET } = getConfig();
|
||||
const path = `${eventId}/${generateId()}.jpg`;
|
||||
|
||||
let res;
|
||||
try {
|
||||
@@ -523,8 +540,16 @@ async function uploadToStorage(eventId, blob) {
|
||||
|
||||
if (res.status >= 500) throw appError("server-overloaded", await safeReadText(res));
|
||||
if (!res.ok) throw appError("storage-upload-failed", await safeReadText(res));
|
||||
}
|
||||
|
||||
return path;
|
||||
// Non bloquant : sans miniature, les galeries affichent l'original.
|
||||
async function uploadThumbnail(path, blob) {
|
||||
try {
|
||||
const thumb = await imageCompression(blob, THUMB_OPTIONS);
|
||||
await uploadToStorage(thumbPathOf(path), thumb);
|
||||
} catch (err) {
|
||||
console.warn("[upload:thumbnail-failed] la galerie affichera l'original", err);
|
||||
}
|
||||
}
|
||||
|
||||
async function insertPhotoRow(eventId, path, nom, message) {
|
||||
@@ -638,7 +663,9 @@ async function submitPhoto() {
|
||||
}
|
||||
|
||||
setProgress("Envoi de la photo…");
|
||||
const path = await uploadToStorage(state.event.id, blob);
|
||||
const path = `${state.event.id}/${generateId()}.jpg`;
|
||||
await uploadToStorage(path, blob);
|
||||
await uploadThumbnail(path, blob);
|
||||
|
||||
setProgress("Dernière étape…");
|
||||
await insertPhotoRow(state.event.id, path, nomInput.value.trim(), messageInput.value.trim());
|
||||
|
||||
+41
-4
@@ -16,6 +16,10 @@
|
||||
// événements à très fort trafic simultané.
|
||||
|
||||
const POLL_INTERVAL_MS = 25_000;
|
||||
// Les URLs signées durent 10 min (GALLERY_SIGNED_URL_TTL_SECONDS dans
|
||||
// public-gallery) : marge de 2 min pour qu'une image lazy démarre son
|
||||
// chargement avant expiration.
|
||||
const URL_REFRESH_AFTER_MS = 8 * 60_000;
|
||||
|
||||
const eventNameEl = document.getElementById("event-name");
|
||||
const eventMetaEl = document.getElementById("event-meta");
|
||||
@@ -78,6 +82,29 @@ function buildCaption(photo) {
|
||||
return parts;
|
||||
}
|
||||
|
||||
function setPhotoSrc(img, url) {
|
||||
img.src = url;
|
||||
img.dataset.signedAt = String(Date.now());
|
||||
}
|
||||
|
||||
// Miniature (thumb_url) par défaut ; original si pas de miniature (photo
|
||||
// d'avant les miniatures) ou si elle échoue à charger (repli unique, cf.
|
||||
// onerror dans renderPolaroid).
|
||||
function showPhoto(img, photo) {
|
||||
img.dataset.original = photo.signed_url || "";
|
||||
if (!photo.thumb_url) img.dataset.fallback = "1";
|
||||
const url = img.dataset.fallback ? photo.signed_url : photo.thumb_url;
|
||||
if (url) setPhotoSrc(img, url);
|
||||
}
|
||||
|
||||
// Un nouveau src = nouveau token = nouveau téléchargement complet : on ne
|
||||
// le change que si l'image n'est pas déjà affichée.
|
||||
function needsFreshUrl(img, now) {
|
||||
if (img.complete && img.naturalWidth > 0) return false; // chargée : le navigateur garde l'image
|
||||
if (img.complete) return true; // pas de src, ou chargement en échec (URL expirée, réseau)
|
||||
return now - Number(img.dataset.signedAt) > URL_REFRESH_AFTER_MS; // lazy pas encore chargée
|
||||
}
|
||||
|
||||
function renderPolaroid(photo, { animate = false } = {}) {
|
||||
const li = document.createElement("li");
|
||||
li.className = "polaroid" + (animate ? " polaroid--dropping" : "");
|
||||
@@ -86,7 +113,13 @@ function renderPolaroid(photo, { animate = false } = {}) {
|
||||
|
||||
const img = document.createElement("img");
|
||||
img.className = "polaroid__photo";
|
||||
img.src = photo.signed_url || "";
|
||||
img.onerror = () => {
|
||||
if (img.dataset.fallback || !img.dataset.original) return;
|
||||
console.warn(`[galerie] miniature indisponible pour ${photo.id}, repli sur l'original`);
|
||||
img.dataset.fallback = "1";
|
||||
setPhotoSrc(img, img.dataset.original);
|
||||
};
|
||||
showPhoto(img, photo);
|
||||
img.alt = photo.nom_invite
|
||||
? `Photo envoyée par ${photo.nom_invite}`
|
||||
: "Photo envoyée par un invité";
|
||||
@@ -190,10 +223,14 @@ function renderGallery(data) {
|
||||
|
||||
photosDesc.forEach((photo, index) => {
|
||||
if (renderedIds.has(photo.id)) {
|
||||
// Déjà affichée : on rafraîchit juste l'URL signée (elle expire au
|
||||
// bout de 10 min), sans toucher au reste du DOM de la carte.
|
||||
// Déjà rendue : URL fraîche seulement si l'image n'est pas affichée
|
||||
// (sinon chaque poll retéléchargerait toute la galerie).
|
||||
const existing = gridEl.querySelector(`[data-photo-id="${photo.id}"] .polaroid__photo`);
|
||||
if (existing && photo.signed_url) existing.src = photo.signed_url;
|
||||
if (existing && photo.signed_url && needsFreshUrl(existing, Date.now())) {
|
||||
showPhoto(existing, photo);
|
||||
} else if (existing) {
|
||||
existing.dataset.original = photo.signed_url || ""; // repli éventuel avec un jeton frais
|
||||
}
|
||||
return;
|
||||
}
|
||||
const card = renderPolaroid(photo, { animate: true });
|
||||
|
||||
@@ -42,3 +42,10 @@ export function getSupabaseAdmin(): SupabaseClient {
|
||||
export function getStorageBucket(): string {
|
||||
return Deno.env.get("SUPABASE_STORAGE_BUCKET") ?? "event-photos";
|
||||
}
|
||||
|
||||
/** Chemin de la miniature d'une photo (convention fixée par src/e/upload.js,
|
||||
* thumbPathOf) : même dossier que l'original, suffixe `_thumb.jpg`. Les
|
||||
* miniatures n'ont pas de ligne photobooth.photos (jamais dans le ZIP). */
|
||||
export function thumbPathOf(path: string): string {
|
||||
return path.replace(/\.jpg$/, "_thumb.jpg");
|
||||
}
|
||||
|
||||
@@ -1,7 +1,15 @@
|
||||
// Edge Function `admin-gallery`
|
||||
//
|
||||
// Contrat (fixé par le chef de projet, à ne pas renommer) :
|
||||
// GET {SUPABASE_URL}/functions/v1/admin-gallery?slug=<slug>&token=<admin_token>[&action=zip]
|
||||
// GET {SUPABASE_URL}/functions/v1/admin-gallery?slug=<slug>&token=<admin_token>
|
||||
// -> JSON galerie (+ zip_parts : nombre de parties du ZIP)
|
||||
// GET ...&action=zip&part=<1..zip_parts> -> ZIP d'une partie (flux)
|
||||
// POST ...&action=delete&photo_id=<uuid> -> supprime une photo (B1)
|
||||
//
|
||||
// ⚠️ Déploiement : verify_jwt = false requis. Les parties du ZIP sont des
|
||||
// liens directs (<a href>) que le navigateur télécharge en flux, sans header
|
||||
// Authorization possible. La clé publishable n'apportait aucune sécurité
|
||||
// (publique) : l'accès repose sur admin_token, vérifié ci-dessous.
|
||||
//
|
||||
// Tourne avec la service_role key (cf. _shared/supabase-admin.ts).
|
||||
//
|
||||
@@ -25,10 +33,10 @@
|
||||
// (cf. plus bas, section `action=zip`). Non testée en exécution dans cet
|
||||
// environnement (pas d'accès réseau/deploy) — à valider avec
|
||||
// `supabase functions serve` avant premier déploiement réel.
|
||||
import { getSupabaseAdmin, getStorageBucket } from "../_shared/supabase-admin.ts";
|
||||
import { getSupabaseAdmin, getStorageBucket, thumbPathOf } from "../_shared/supabase-admin.ts";
|
||||
import { corsHeaders, handleCorsPreflight } from "../_shared/cors.ts";
|
||||
import { timingSafeEqual } from "../_shared/timing-safe.ts";
|
||||
import { HttpReader, ZipWriter } from "jsr:@zip-js/zip-js";
|
||||
import { TextReader, Uint8ArrayReader, ZipWriter } from "jsr:@zip-js/zip-js";
|
||||
|
||||
// URL signées affichées dans la galerie admin : courte durée, c'est pour un
|
||||
// affichage/téléchargement immédiat dans le navigateur de l'admin, pas pour
|
||||
@@ -41,11 +49,16 @@ const GALLERY_SIGNED_URL_TTL_SECONDS = 10 * 60; // 10 minutes
|
||||
// du ZIP en cas de gros volume.
|
||||
const ZIP_INTERNAL_SIGNED_URL_TTL_SECONDS = 30 * 60; // 30 minutes
|
||||
|
||||
// Garde-fou volume ZIP (placeholder, non validé empiriquement — cf. rapport
|
||||
// de tâche) : au-delà, on refuse `action=zip` plutôt que de risquer un
|
||||
// timeout Edge Function (~150s) ou un flux qui traîne indéfiniment. À
|
||||
// ajuster une fois testé avec un volume réel de photos.
|
||||
const MAX_ZIP_PHOTOS = 400;
|
||||
// Découpage du ZIP en parties (audit B3). Limite Supabase (doc "Edge
|
||||
// Functions > Limits", lue le 2026-10-15) : 150 s de durée max par worker en
|
||||
// plan Free (400 s en payant), 256 Mo de RAM, 2 s de CPU. Une partie doit
|
||||
// donc être téléchargée en entier en < 150 s par le client : 100 Mo
|
||||
// demandent ~5,5 Mbit/s soutenus. Plafond en nombre aussi (1 requête
|
||||
// Storage par photo). Plan payant : on peut monter à ~250 Mo.
|
||||
const MAX_ZIP_PART_BYTES = 100 * 1024 * 1024;
|
||||
const MAX_ZIP_PART_PHOTOS = 300;
|
||||
|
||||
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
||||
|
||||
function jsonResponse(status: number, body: unknown): Response {
|
||||
return new Response(JSON.stringify(body), {
|
||||
@@ -97,8 +110,33 @@ type PhotoRow = {
|
||||
message: string | null;
|
||||
uploaded_at: string;
|
||||
url_storage: string;
|
||||
size_bytes: number;
|
||||
};
|
||||
|
||||
// Découpage glouton dans l'ordre stable (uploaded_at, id) : renvoie l'index
|
||||
// de début de chaque partie. Un ajout de photo ne change que la dernière
|
||||
// partie ; une suppression décale les parties suivantes (le front le dit).
|
||||
function zipPartStarts(photos: PhotoRow[]): number[] {
|
||||
const starts: number[] = [];
|
||||
let bytes = 0;
|
||||
let count = 0;
|
||||
for (let i = 0; i < photos.length; i++) {
|
||||
const size = Number(photos[i].size_bytes) || 0;
|
||||
if (
|
||||
starts.length === 0 ||
|
||||
count >= MAX_ZIP_PART_PHOTOS ||
|
||||
(count > 0 && bytes + size > MAX_ZIP_PART_BYTES)
|
||||
) {
|
||||
starts.push(i);
|
||||
bytes = 0;
|
||||
count = 0;
|
||||
}
|
||||
bytes += size;
|
||||
count++;
|
||||
}
|
||||
return starts;
|
||||
}
|
||||
|
||||
type AdminEventRow = {
|
||||
id: string;
|
||||
nom: string;
|
||||
@@ -120,15 +158,18 @@ Deno.serve(async (req) => {
|
||||
const preflight = handleCorsPreflight(req);
|
||||
if (preflight) return preflight;
|
||||
|
||||
if (req.method !== "GET") {
|
||||
return jsonResponse(405, { error: "method_not_allowed" });
|
||||
}
|
||||
|
||||
const url = new URL(req.url);
|
||||
const slug = url.searchParams.get("slug");
|
||||
const token = url.searchParams.get("token");
|
||||
const action = url.searchParams.get("action");
|
||||
|
||||
// Suppression = POST uniquement (jamais un GET qu'un préchargement ou un
|
||||
// robot pourrait déclencher) ; tout le reste = GET.
|
||||
const expectedMethod = action === "delete" ? "POST" : "GET";
|
||||
if (req.method !== expectedMethod) {
|
||||
return jsonResponse(405, { error: "method_not_allowed" });
|
||||
}
|
||||
|
||||
if (!slug || !token) {
|
||||
return jsonResponse(400, { error: "missing_parameters" });
|
||||
}
|
||||
@@ -174,7 +215,22 @@ Deno.serve(async (req) => {
|
||||
// 20260916090400_create_public_functions.sql), on réutilise donc
|
||||
// directement celui de la query string plutôt que de modifier la RPC
|
||||
// pour ça.
|
||||
return await handleZipExport(supabaseAdmin, bucket, typedEvent, slug);
|
||||
return await handleZipExport(
|
||||
supabaseAdmin,
|
||||
bucket,
|
||||
typedEvent,
|
||||
slug,
|
||||
url.searchParams.get("part")
|
||||
);
|
||||
}
|
||||
|
||||
if (action === "delete") {
|
||||
return await handleDeletePhoto(
|
||||
supabaseAdmin,
|
||||
bucket,
|
||||
typedEvent,
|
||||
url.searchParams.get("photo_id")
|
||||
);
|
||||
}
|
||||
|
||||
return await handleJsonGallery(supabaseAdmin, typedEvent);
|
||||
@@ -185,11 +241,12 @@ async function fetchEventPhotos(
|
||||
supabaseAdmin: any,
|
||||
eventId: string
|
||||
): Promise<PhotoRow[]> {
|
||||
// public.get_event_photos (service_role uniquement) renvoie les photos
|
||||
// triées par uploaded_at ASC (ordre chronologique), cf.
|
||||
// 20260916090400_create_public_functions.sql.
|
||||
const { data, error } = await supabaseAdmin.rpc("get_event_photos", {
|
||||
// public.get_event_photos_admin (service_role uniquement) : photos triées
|
||||
// par uploaded_at ASC puis id, avec la taille du fichier, cf.
|
||||
// 20261015120000_admin_delete_photo_and_zip_sizes.sql.
|
||||
const { data, error } = await supabaseAdmin.rpc("get_event_photos_admin", {
|
||||
p_event_id: eventId,
|
||||
p_bucket: getStorageBucket(),
|
||||
});
|
||||
|
||||
if (error) {
|
||||
@@ -215,7 +272,7 @@ async function handleJsonGallery(
|
||||
// Galerie admin : plus récent en premier. get_event_photos renvoie déjà
|
||||
// un tableau trié ASC (chronologique) ; on l'inverse ici plutôt que
|
||||
// d'ajouter un paramètre d'ordre à la RPC (le volume par événement reste
|
||||
// modeste, cf. MAX_ZIP_PHOTOS = 400, donc un `.reverse()` en mémoire est
|
||||
// modeste, quelques milliers au plus, donc un `.reverse()` en mémoire est
|
||||
// largement suffisant).
|
||||
const photosDesc = [...photosAsc].reverse();
|
||||
|
||||
@@ -223,12 +280,16 @@ async function handleJsonGallery(
|
||||
// plutôt qu'un appel par photo : moins de requêtes réseau, cohérent avec
|
||||
// le principe d'écoconception du projet (CLAUDE.md).
|
||||
const signedUrlBypath = new Map<string, string>();
|
||||
const thumbUrlByPath = new Map<string, string>();
|
||||
if (photosDesc.length > 0) {
|
||||
const paths = photosDesc.map((p) => p.url_storage);
|
||||
const bucket = getStorageBucket();
|
||||
const { data: signedUrls, error: signError } = await supabaseAdmin.storage
|
||||
.from(bucket)
|
||||
.createSignedUrls(paths, GALLERY_SIGNED_URL_TTL_SECONDS);
|
||||
// Originaux + miniatures en une seule requête. Miniature absente
|
||||
// (photo d'avant les miniatures, échec côté invité) : entrée en erreur,
|
||||
// thumb_url null, le front affiche l'original.
|
||||
.createSignedUrls([...paths, ...paths.map(thumbPathOf)], GALLERY_SIGNED_URL_TTL_SECONDS);
|
||||
|
||||
if (signError) {
|
||||
console.error("[admin-gallery] createSignedUrls failed", signError);
|
||||
@@ -236,6 +297,8 @@ async function handleJsonGallery(
|
||||
}
|
||||
|
||||
for (let i = 0; i < paths.length; i++) {
|
||||
const thumbUrl = signedUrls?.[paths.length + i]?.signedUrl;
|
||||
if (thumbUrl) thumbUrlByPath.set(paths[i], thumbUrl);
|
||||
const entry = signedUrls?.[i];
|
||||
if (entry?.signedUrl) {
|
||||
signedUrlBypath.set(paths[i], entry.signedUrl);
|
||||
@@ -259,12 +322,14 @@ async function handleJsonGallery(
|
||||
statut: event.statut,
|
||||
photo_count: photosDesc.length,
|
||||
},
|
||||
zip_parts: zipPartStarts(photosAsc).length,
|
||||
photos: photosDesc.map((p) => ({
|
||||
id: p.id,
|
||||
nom_invite: p.nom_invite,
|
||||
message: p.message,
|
||||
uploaded_at: p.uploaded_at,
|
||||
signed_url: signedUrlBypath.get(p.url_storage) ?? null,
|
||||
thumb_url: thumbUrlByPath.get(p.url_storage) ?? null,
|
||||
expires_in: GALLERY_SIGNED_URL_TTL_SECONDS,
|
||||
})),
|
||||
});
|
||||
@@ -275,31 +340,31 @@ async function handleZipExport(
|
||||
supabaseAdmin: any,
|
||||
bucket: string,
|
||||
event: AdminEventRow,
|
||||
slug: string
|
||||
slug: string,
|
||||
partParam: string | null
|
||||
): Promise<Response> {
|
||||
let photos: PhotoRow[];
|
||||
let allPhotos: PhotoRow[];
|
||||
try {
|
||||
photos = await fetchEventPhotos(supabaseAdmin, event.id);
|
||||
allPhotos = await fetchEventPhotos(supabaseAdmin, event.id);
|
||||
} catch (err) {
|
||||
console.error("[admin-gallery] zip: get_event_photos failed", err);
|
||||
return jsonResponse(500, { error: "internal_error" });
|
||||
console.error("[admin-gallery] zip: get_event_photos_admin failed", err);
|
||||
return textResponse(500, "Le service est momentanément indisponible. Réessaie dans quelques instants.");
|
||||
}
|
||||
|
||||
if (photos.length === 0) {
|
||||
return jsonResponse(404, { error: "no_photos" });
|
||||
if (allPhotos.length === 0) {
|
||||
return textResponse(404, "Il n'y a aucune photo à télécharger pour cet événement.");
|
||||
}
|
||||
|
||||
// Garde-fou volume (cf. MAX_ZIP_PHOTOS ci-dessus) : évite de partir sur un
|
||||
// ZIP qui a de bonnes chances de timeout côté Edge Function pour un très
|
||||
// gros événement. Valeur provisoire, à valider avec un test réel — cf.
|
||||
// rapport de tâche.
|
||||
if (photos.length > MAX_ZIP_PHOTOS) {
|
||||
return jsonResponse(413, {
|
||||
error: "too_many_photos_for_zip",
|
||||
photo_count: photos.length,
|
||||
max_zip_photos: MAX_ZIP_PHOTOS,
|
||||
});
|
||||
const starts = zipPartStarts(allPhotos);
|
||||
const part = partParam === null ? 1 : Number(partParam);
|
||||
if (!Number.isInteger(part) || part < 1 || part > starts.length) {
|
||||
return textResponse(
|
||||
404,
|
||||
`Cette partie du ZIP n'existe plus (l'export compte ${starts.length} partie(s)). Retourne sur la galerie et clique sur "Actualiser".`
|
||||
);
|
||||
}
|
||||
const offset = starts[part - 1];
|
||||
const photos = allPhotos.slice(offset, starts[part] ?? allPhotos.length);
|
||||
|
||||
const paths = photos.map((p) => p.url_storage);
|
||||
const { data: signedUrls, error: signError } = await supabaseAdmin.storage
|
||||
@@ -308,18 +373,23 @@ async function handleZipExport(
|
||||
|
||||
if (signError) {
|
||||
console.error("[admin-gallery] zip: createSignedUrls failed", signError);
|
||||
return jsonResponse(500, { error: "internal_error" });
|
||||
return textResponse(500, "Le service est momentanément indisponible. Réessaie dans quelques instants.");
|
||||
}
|
||||
|
||||
// Construction du ZIP en FLUX (pas de Blob/Uint8Array accumulé en mémoire
|
||||
// pour l'ensemble des photos) : on écrit dans un TransformStream, et on
|
||||
// renvoie sa moitié "readable" comme corps de la Response immédiatement,
|
||||
// pendant que la moitié "writable" continue de recevoir les fichiers
|
||||
// (téléchargés directement depuis Storage via HttpReader). `level: 0`
|
||||
// (lus un par un depuis Storage, cf. fetchPhotoBytes). `level: 0`
|
||||
// (STORE, pas de compression) : les photos sont déjà des JPEG compressés
|
||||
// côté client (cf. src/e/upload.js), les recompresser dans le ZIP
|
||||
// coûterait du CPU pour un gain quasi nul.
|
||||
const { readable, writable } = new TransformStream<Uint8Array, Uint8Array>();
|
||||
let streamController!: TransformStreamDefaultController<Uint8Array>;
|
||||
const { readable, writable } = new TransformStream<Uint8Array, Uint8Array>({
|
||||
start(controller) {
|
||||
streamController = controller;
|
||||
},
|
||||
});
|
||||
const zipWriter = new ZipWriter(writable);
|
||||
|
||||
const usedNames = new Set<string>();
|
||||
@@ -328,49 +398,63 @@ async function handleZipExport(
|
||||
// `return new Response(readable, ...)`, sinon on perdrait l'intérêt du
|
||||
// streaming. La fonction Edge reste vivante tant que la réponse en
|
||||
// streaming n'est pas entièrement consommée par le client.
|
||||
// Photo illisible (Storage en erreur, fichier disparu) : on la saute et on
|
||||
// la liste dans PHOTOS-MANQUANTES.txt à la fin du ZIP. Une fois le 200
|
||||
// envoyé, on ne peut plus signaler d'erreur HTTP, et faire échouer le flux
|
||||
// ne coupe pas la connexion (testé en local : téléchargement suspendu
|
||||
// jusqu'au kill du worker à 150 s). Chaque photo est lue en entier
|
||||
// (<= 6 Mo, cf. src/e/upload.js) AVANT d'être ajoutée : un échec de
|
||||
// lecture ne peut donc pas laisser une entrée à moitié écrite.
|
||||
const missing: string[] = [];
|
||||
|
||||
(async () => {
|
||||
try {
|
||||
for (let i = 0; i < photos.length; i++) {
|
||||
const photo = photos[i];
|
||||
const signed = signedUrls?.[i];
|
||||
if (!signed?.signedUrl) {
|
||||
console.warn(
|
||||
`[admin-gallery] zip: skipping ${photo.url_storage} (no signed url)`
|
||||
);
|
||||
const bytes = signed?.signedUrl ? await fetchPhotoBytes(signed.signedUrl) : null;
|
||||
if (!bytes) {
|
||||
console.warn(`[admin-gallery] zip: missing ${photo.url_storage}`);
|
||||
missing.push(`${photo.nom_invite ?? "invité anonyme"}, ${photo.uploaded_at} (id ${photo.id})`);
|
||||
continue;
|
||||
}
|
||||
|
||||
const ext = extensionFromPath(photo.url_storage);
|
||||
let entryName = buildZipEntryName(photo, i, ext);
|
||||
// Index global (offset + i) : noms uniques d'une partie à l'autre.
|
||||
let entryName = buildZipEntryName(photo, offset + i, ext);
|
||||
// Garantit l'unicité même en cas de collision improbable.
|
||||
let suffix = 1;
|
||||
while (usedNames.has(entryName)) {
|
||||
entryName = `${buildZipEntryName(photo, i, ext).replace(`.${ext}`, "")}-${suffix}.${ext}`;
|
||||
entryName = `${buildZipEntryName(photo, offset + i, ext).replace(`.${ext}`, "")}-${suffix}.${ext}`;
|
||||
suffix++;
|
||||
}
|
||||
usedNames.add(entryName);
|
||||
|
||||
await zipWriter.add(entryName, new HttpReader(signed.signedUrl), {
|
||||
await zipWriter.add(entryName, new Uint8ArrayReader(bytes), {
|
||||
level: 0,
|
||||
});
|
||||
}
|
||||
} catch (err) {
|
||||
// ⚠️ Limite connue : si une erreur survient APRÈS que les premiers
|
||||
// octets de la réponse ont déjà été envoyés (statut 200 déjà commis),
|
||||
// il est impossible de renvoyer un statut d'erreur HTTP à ce stade.
|
||||
// Le client reçoit un ZIP tronqué/corrompu plutôt qu'un message
|
||||
// d'erreur propre — limite inhérente au streaming HTTP.
|
||||
console.error("[admin-gallery] zip: stream build failed", err);
|
||||
} finally {
|
||||
try {
|
||||
await zipWriter.close();
|
||||
} catch (closeErr) {
|
||||
console.error("[admin-gallery] zip: writer close failed", closeErr);
|
||||
if (missing.length > 0) {
|
||||
await zipWriter.add(
|
||||
"PHOTOS-MANQUANTES.txt",
|
||||
new TextReader(
|
||||
`${missing.length} photo(s) n'ont pas pu être ajoutées à cette partie.\n` +
|
||||
`Retélécharge cette partie depuis la galerie admin.\n\n${missing.join("\n")}\n`
|
||||
)
|
||||
);
|
||||
}
|
||||
await zipWriter.close();
|
||||
} catch (err) {
|
||||
// Écriture du ZIP elle-même en échec (client parti, le plus souvent) :
|
||||
// pas de close() qui livrerait un ZIP tronqué d'apparence complète.
|
||||
console.error("[admin-gallery] zip: stream build failed", err);
|
||||
streamController.error(err);
|
||||
}
|
||||
})();
|
||||
|
||||
const zipFilename = `${sanitizeFilenamePart(slug || event.nom, "export")}.zip`;
|
||||
const baseName = sanitizeFilenamePart(slug || event.nom, "export");
|
||||
const zipFilename =
|
||||
starts.length === 1 ? `${baseName}.zip` : `${baseName}-partie-${part}-sur-${starts.length}.zip`;
|
||||
|
||||
return new Response(readable, {
|
||||
status: 200,
|
||||
@@ -381,3 +465,92 @@ async function handleZipExport(
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// Lit une photo en entier, 1 nouvel essai si Storage échoue. null = échec
|
||||
// (journalisé), à l'appelant de la déclarer manquante.
|
||||
async function fetchPhotoBytes(signedUrl: string): Promise<Uint8Array | null> {
|
||||
for (let attempt = 1; attempt <= 2; attempt++) {
|
||||
try {
|
||||
const res = await fetch(signedUrl);
|
||||
if (res.ok) return new Uint8Array(await res.arrayBuffer());
|
||||
console.warn(`[admin-gallery] zip: storage HTTP ${res.status} (essai ${attempt})`);
|
||||
await res.body?.cancel();
|
||||
} catch (err) {
|
||||
console.warn(`[admin-gallery] zip: storage fetch failed (essai ${attempt})`, err);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// Réponses d'erreur du ZIP en texte lisible : la partie est ouverte par un
|
||||
// lien direct (pas un fetch), c'est donc ce texte que l'organisateur voit.
|
||||
function textResponse(status: number, message: string): Response {
|
||||
return new Response(message, {
|
||||
status,
|
||||
headers: { ...corsHeaders(), "Content-Type": "text/plain; charset=utf-8" },
|
||||
});
|
||||
}
|
||||
|
||||
// B1 : suppression d'une photo (original + miniature). Ordre : fichiers
|
||||
// Storage PUIS ligne DB.
|
||||
// - Storage échoue -> rien n'a bougé, 500, l'admin réessaie.
|
||||
// - Ligne échoue après le fichier -> photo listée mais sans image (vignette
|
||||
// cassée, absente du ZIP) ; réessayer termine le travail (remove() d'un
|
||||
// fichier déjà absent ne renvoie pas d'erreur). L'ordre inverse laisserait
|
||||
// un fichier invisible mais toujours présent : pire pour le droit à
|
||||
// l'effacement, et seul le cas à éviter absolument ici.
|
||||
async function handleDeletePhoto(
|
||||
// deno-lint-ignore no-explicit-any
|
||||
supabaseAdmin: any,
|
||||
bucket: string,
|
||||
event: AdminEventRow,
|
||||
photoId: string | null
|
||||
): Promise<Response> {
|
||||
if (!photoId || !UUID_RE.test(photoId)) {
|
||||
return jsonResponse(400, { error: "invalid_photo_id" });
|
||||
}
|
||||
|
||||
let photos: PhotoRow[];
|
||||
try {
|
||||
photos = await fetchEventPhotos(supabaseAdmin, event.id);
|
||||
} catch (err) {
|
||||
console.error("[admin-gallery] delete: get_event_photos_admin failed", err);
|
||||
return jsonResponse(500, { error: "internal_error" });
|
||||
}
|
||||
|
||||
// Appartenance à l'event du token : une photo d'un autre event est
|
||||
// indiscernable d'une photo inexistante.
|
||||
const photo = photos.find((p) => p.id === photoId.toLowerCase());
|
||||
if (!photo) {
|
||||
return jsonResponse(404, { error: "photo_not_found" });
|
||||
}
|
||||
|
||||
const { error: removeError } = await supabaseAdmin.storage
|
||||
.from(bucket)
|
||||
.remove([photo.url_storage, thumbPathOf(photo.url_storage)]);
|
||||
if (removeError) {
|
||||
console.error("[admin-gallery] delete: storage remove failed", removeError);
|
||||
return jsonResponse(500, { error: "storage_delete_failed" });
|
||||
}
|
||||
|
||||
const { data: deleted, error: deleteError } = await supabaseAdmin.rpc(
|
||||
"delete_event_photo",
|
||||
{ p_event_id: event.id, p_photo_id: photo.id }
|
||||
);
|
||||
if (deleteError) {
|
||||
console.error("[admin-gallery] delete: delete_event_photo failed", deleteError);
|
||||
return jsonResponse(500, { error: "db_delete_failed" });
|
||||
}
|
||||
if (deleted !== true) {
|
||||
// Supprimée entre-temps (double clic, autre onglet) : le résultat voulu
|
||||
// est atteint, mais on le signale tel quel.
|
||||
return jsonResponse(404, { error: "photo_not_found" });
|
||||
}
|
||||
|
||||
const remaining = photos.filter((p) => p.id !== photo.id);
|
||||
return jsonResponse(200, {
|
||||
deleted: true,
|
||||
photo_count: remaining.length,
|
||||
zip_parts: zipPartStarts(remaining).length,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -180,7 +180,9 @@ Deno.serve(async (req) => {
|
||||
},
|
||||
links: {
|
||||
invite: `${cleanBaseUrl}/e/${encodeURIComponent(typedEvent.slug)}`,
|
||||
admin: `${cleanBaseUrl}/admin/${encodeURIComponent(typedEvent.slug)}?token=${encodeURIComponent(
|
||||
// Token dans le fragment (#) : jamais envoyé au serveur, donc jamais
|
||||
// dans les logs nginx ni dans un Referer (décision 2026-10-15).
|
||||
admin: `${cleanBaseUrl}/admin/${encodeURIComponent(typedEvent.slug)}#token=${encodeURIComponent(
|
||||
typedEvent.admin_token
|
||||
)}`,
|
||||
// src/admin/qrcode/index.html lit désormais `?slug=` ET `?baseUrl=`
|
||||
|
||||
@@ -33,7 +33,7 @@
|
||||
// le front peut décider d'afficher un message adapté à partir de
|
||||
// `event.statut`, cohérent avec le comportement déjà choisi pour
|
||||
// `get_public_event` côté page d'upload.
|
||||
import { getSupabaseAdmin, getStorageBucket } from "../_shared/supabase-admin.ts";
|
||||
import { getSupabaseAdmin, getStorageBucket, thumbPathOf } from "../_shared/supabase-admin.ts";
|
||||
import { corsHeaders, handleCorsPreflight } from "../_shared/cors.ts";
|
||||
|
||||
// URLs signées affichées dans la galerie invité : courte durée, c'est pour
|
||||
@@ -130,12 +130,16 @@ Deno.serve(async (req) => {
|
||||
// demandée "générer un ZIP" ; ici il n'y a pas d'action, juste un état
|
||||
// d'affichage à rendre).
|
||||
const signedUrlByPath = new Map<string, string>();
|
||||
const thumbUrlByPath = new Map<string, string>();
|
||||
if (photos.length > 0) {
|
||||
const paths = photos.map((p) => p.url_storage);
|
||||
const bucket = getStorageBucket();
|
||||
const { data: signedUrls, error: signError } = await supabaseAdmin.storage
|
||||
.from(bucket)
|
||||
.createSignedUrls(paths, GALLERY_SIGNED_URL_TTL_SECONDS);
|
||||
// Originaux + miniatures en une seule requête. Miniature absente
|
||||
// (photo d'avant les miniatures, échec côté invité) : entrée en erreur,
|
||||
// thumb_url null, le front affiche l'original.
|
||||
.createSignedUrls([...paths, ...paths.map(thumbPathOf)], GALLERY_SIGNED_URL_TTL_SECONDS);
|
||||
|
||||
if (signError) {
|
||||
console.error("[public-gallery] createSignedUrls failed", signError);
|
||||
@@ -143,6 +147,8 @@ Deno.serve(async (req) => {
|
||||
}
|
||||
|
||||
for (let i = 0; i < paths.length; i++) {
|
||||
const thumbUrl = signedUrls?.[paths.length + i]?.signedUrl;
|
||||
if (thumbUrl) thumbUrlByPath.set(paths[i], thumbUrl);
|
||||
const entry = signedUrls?.[i];
|
||||
if (entry?.signedUrl) {
|
||||
signedUrlByPath.set(paths[i], entry.signedUrl);
|
||||
@@ -172,6 +178,7 @@ Deno.serve(async (req) => {
|
||||
message: p.message,
|
||||
uploaded_at: p.uploaded_at,
|
||||
signed_url: signedUrlByPath.get(p.url_storage) ?? null,
|
||||
thumb_url: thumbUrlByPath.get(p.url_storage) ?? null,
|
||||
})),
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
-- Migration : suppression d'une photo par l'admin (audit B1) + taille des
|
||||
-- fichiers pour découper le ZIP en parties (audit B3).
|
||||
--
|
||||
-- Aucune table modifiée : deux fonctions SECURITY DEFINER réservées à
|
||||
-- service_role (Edge Function admin-gallery), sur le même modèle que
|
||||
-- get_event_photos (cf. 20260916090400_create_public_functions.sql). Le
|
||||
-- contrôle d'admin_token reste côté Edge Function (timingSafeEqual).
|
||||
--
|
||||
|
||||
-- =============================================================================
|
||||
-- 1. get_event_photos_admin — service_role UNIQUEMENT
|
||||
-- =============================================================================
|
||||
-- Même chose que get_event_photos + la taille du fichier (storage.objects),
|
||||
-- utilisée pour découper l'export ZIP en parties de taille bornée. Ordre
|
||||
-- stable : uploaded_at puis id (départage les ex-aequo), pour que la
|
||||
-- "partie N" désigne toujours les mêmes photos d'une requête à l'autre.
|
||||
-- size_bytes = 0 si l'objet Storage est introuvable (le ZIP le sautera).
|
||||
create or replace function public.get_event_photos_admin(p_event_id uuid, p_bucket text)
|
||||
returns table (
|
||||
id uuid,
|
||||
url_storage text,
|
||||
nom_invite text,
|
||||
message text,
|
||||
uploaded_at timestamptz,
|
||||
size_bytes bigint
|
||||
)
|
||||
language sql
|
||||
stable
|
||||
security definer
|
||||
set search_path = public, photobooth, storage, pg_temp
|
||||
as $$
|
||||
select p.id, p.url_storage, p.nom_invite, p.message, p.uploaded_at,
|
||||
coalesce((o.metadata->>'size')::bigint, 0)
|
||||
from photobooth.photos p
|
||||
left join storage.objects o
|
||||
on o.bucket_id = p_bucket and o.name = p.url_storage
|
||||
where p.event_id = p_event_id
|
||||
order by p.uploaded_at asc, p.id asc;
|
||||
$$;
|
||||
|
||||
comment on function public.get_event_photos_admin(uuid, text) is
|
||||
'Photos d''un événement + taille du fichier Storage (octets), triées par uploaded_at puis id. Réservée à service_role (Edge Function admin-gallery) : ne JAMAIS accorder EXECUTE à anon/authenticated.';
|
||||
|
||||
revoke all on function public.get_event_photos_admin(uuid, text) from public, anon, authenticated;
|
||||
grant execute on function public.get_event_photos_admin(uuid, text) to service_role;
|
||||
|
||||
-- =============================================================================
|
||||
-- 2. delete_event_photo — service_role UNIQUEMENT
|
||||
-- =============================================================================
|
||||
-- Supprime la ligne photobooth.photos SEULEMENT si elle appartient à
|
||||
-- p_event_id (défense en profondeur : l'Edge Function l'a déjà vérifié).
|
||||
-- Renvoie true si une ligne a été supprimée. Le fichier Storage est supprimé
|
||||
-- AVANT par l'Edge Function (cf. admin-gallery, action=delete).
|
||||
create or replace function public.delete_event_photo(p_event_id uuid, p_photo_id uuid)
|
||||
returns boolean
|
||||
language sql
|
||||
volatile
|
||||
security definer
|
||||
set search_path = public, photobooth, pg_temp
|
||||
as $$
|
||||
with deleted as (
|
||||
delete from photobooth.photos
|
||||
where id = p_photo_id and event_id = p_event_id
|
||||
returning 1
|
||||
)
|
||||
select exists (select 1 from deleted);
|
||||
$$;
|
||||
|
||||
comment on function public.delete_event_photo(uuid, uuid) is
|
||||
'Supprime une photo (photobooth.photos) si elle appartient à l''événement donné. Réservée à service_role (Edge Function admin-gallery, après contrôle admin_token) : ne JAMAIS accorder EXECUTE à anon/authenticated.';
|
||||
|
||||
revoke all on function public.delete_event_photo(uuid, uuid) from public, anon, authenticated;
|
||||
grant execute on function public.delete_event_photo(uuid, uuid) to service_role;
|
||||
@@ -0,0 +1,43 @@
|
||||
-- Rend les slugs non devinables (validé par Kévin le 2026-10-15) : la
|
||||
-- galerie publique /galerie/<slug> n'est protégée que par le slug, et un
|
||||
-- slug dérivé du seul nom ("mariage-clara-mehdi") se devine à partir des
|
||||
-- prénoms. On ajoute toujours un suffixe aléatoire de 6 caractères hex
|
||||
-- (~16 millions de combinaisons par nom). Les events existants gardent
|
||||
-- leur slug (seuls les nouveaux sont concernés).
|
||||
create or replace function photobooth.generate_unique_slug(p_source text)
|
||||
returns text
|
||||
language plpgsql
|
||||
set search_path = photobooth, extensions, pg_temp
|
||||
as $$
|
||||
declare
|
||||
v_base_slug text;
|
||||
v_candidate text;
|
||||
v_attempts integer := 0;
|
||||
v_max_attempts constant integer := 20;
|
||||
begin
|
||||
v_base_slug := lower(trim(both '-' from
|
||||
regexp_replace(extensions.unaccent(coalesce(p_source, '')), '[^a-zA-Z0-9]+', '-', 'g')
|
||||
));
|
||||
|
||||
if v_base_slug = '' then
|
||||
v_base_slug := 'evenement';
|
||||
end if;
|
||||
|
||||
loop
|
||||
v_attempts := v_attempts + 1;
|
||||
v_candidate := v_base_slug || '-' || encode(extensions.gen_random_bytes(3), 'hex');
|
||||
exit when not exists (select 1 from photobooth.events where slug = v_candidate);
|
||||
|
||||
if v_attempts >= v_max_attempts then
|
||||
raise exception 'slug_generation_failed'
|
||||
using errcode = 'P0001',
|
||||
detail = format('Impossible de générer un slug unique pour "%s" après %s tentatives.', p_source, v_max_attempts);
|
||||
end if;
|
||||
end loop;
|
||||
|
||||
return v_candidate;
|
||||
end;
|
||||
$$;
|
||||
|
||||
comment on function photobooth.generate_unique_slug(text) is
|
||||
'Dérive un slug lisible et non devinable (photobooth.events.slug) à partir d''un texte libre (typiquement events.nom) : normalise via unaccent, remplace tout ce qui n''est pas [a-zA-Z0-9] par un tiret, ajoute toujours un suffixe aléatoire de 6 caractères hex. Fonction interne, appelée uniquement par public.create_event.';
|
||||
Reference in New Issue
Block a user