Clients who need smaller files no longer make the photographer re-export. Two capabilities, both off by default. STANDARD RESOLUTION — the size a gallery hands out for every ordinary download (single, selected, download-all). Global default in Settings, overridable per gallery with the NULL=inherit tri-state. The pre-built download-all zip is built AT the standard resolution, so changing it invalidates those archives, including a fan-out to inheriting galleries. RESOLUTION PICKER — opt-in modal letting guests choose a different size. Custom archives are built as a DB-backed job the client polls, never cached. The picker never offers a size above the standard, and Original reappears only when the admin explicitly allows it. Resize is fit:'inside' + withoutEnlargement — aspect preserved, never upscaled — applied before the watermark, since the mark is sized relative to its input. Three rounds of external review hardened this: job archives are bound to the requester's visibility scope and re-validated at delivery, the streamed download-all path applies the cap, queue admission is bounded, and rejected resolutions no longer inflate download stats. Closes #858.
This commit is contained in:
@@ -0,0 +1,140 @@
|
||||
// Per-event download resolution overrides (#858). Same sub-router shape as
|
||||
// ./slideshow.js — see ./index.js for the registration-order contract.
|
||||
//
|
||||
// All three fields are tri-state: explicit null = inherit the global
|
||||
// (Settings → Downloads), matching show_watermark / show_qr. Changing the
|
||||
// standard resolution invalidates this event's cached download-all zip,
|
||||
// because that archive is built AT the standard resolution.
|
||||
|
||||
const { body, validationResult } = require('express-validator');
|
||||
const { db, logActivity } = require('../../database/db');
|
||||
const { formatBoolean } = require('../../utils/dbCompat');
|
||||
const { adminAuth } = require('../../middleware/auth');
|
||||
const { requirePermission } = require('../../middleware/permissions');
|
||||
const { errorResponse } = require('../../utils/routeHelpers');
|
||||
const { parseBooleanInput } = require('../../utils/parsers');
|
||||
const { requireEventOwnership } = require('../../middleware/ownership');
|
||||
const {
|
||||
getDownloadGlobals,
|
||||
resolveEventDownloadPolicy,
|
||||
ORIGINAL,
|
||||
} = require('../../utils/downloadResolutions');
|
||||
const downloadZipService = require('../../services/downloadZipService');
|
||||
|
||||
async function loadOwnedEvent(req) {
|
||||
let q = db('events').where('id', req.params.id);
|
||||
if (req.admin.roleName === 'editor') {
|
||||
q = q.where('created_by', req.admin.id);
|
||||
}
|
||||
return q.first();
|
||||
}
|
||||
|
||||
module.exports = (router) => {
|
||||
// Read the event's effective policy plus the raw overrides, so the admin UI
|
||||
// can show "inheriting 1500x1000" vs "overridden to Original".
|
||||
router.get('/:id/download-resolutions', adminAuth, requirePermission('events.view'), requireEventOwnership, async (req, res) => {
|
||||
try {
|
||||
const event = await loadOwnedEvent(req);
|
||||
if (!event) return res.status(404).json({ error: 'Event not found' });
|
||||
|
||||
const globals = await getDownloadGlobals();
|
||||
const policy = await resolveEventDownloadPolicy(event);
|
||||
res.json({
|
||||
overrides: {
|
||||
download_standard_resolution: event.download_standard_resolution ?? null,
|
||||
download_resolution_picker_enabled: event.download_resolution_picker_enabled ?? null,
|
||||
download_allow_original: event.download_allow_original ?? null,
|
||||
},
|
||||
globals,
|
||||
effective: {
|
||||
standard: policy.standard,
|
||||
picker_enabled: policy.pickerEnabled,
|
||||
allow_original: policy.allowOriginal,
|
||||
choices: policy.choices,
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
errorResponse(res, error, 500, 'Failed to load download resolution settings');
|
||||
}
|
||||
});
|
||||
|
||||
router.patch('/:id/download-resolutions', adminAuth, requirePermission('events.edit'), requireEventOwnership, [
|
||||
body('download_standard_resolution').optional({ nullable: true }),
|
||||
body('download_resolution_picker_enabled').optional({ nullable: true }),
|
||||
body('download_allow_original').optional({ nullable: true }),
|
||||
], async (req, res) => {
|
||||
try {
|
||||
const errors = validationResult(req);
|
||||
if (!errors.isEmpty()) {
|
||||
return res.status(400).json({ error: 'Invalid download settings', details: errors.array() });
|
||||
}
|
||||
|
||||
const event = await loadOwnedEvent(req);
|
||||
if (!event) return res.status(404).json({ error: 'Event not found' });
|
||||
|
||||
const globals = await getDownloadGlobals();
|
||||
const updates = {};
|
||||
let standardChanged = false;
|
||||
|
||||
if (req.body.download_standard_resolution !== undefined) {
|
||||
const raw = req.body.download_standard_resolution;
|
||||
if (raw === null) {
|
||||
updates.download_standard_resolution = null;
|
||||
} else {
|
||||
const v = String(raw);
|
||||
if (v !== ORIGINAL && !globals.resolutions.some((r) => r.id === v)) {
|
||||
return res.status(400).json({ error: `Unknown resolution "${v}"` });
|
||||
}
|
||||
updates.download_standard_resolution = v;
|
||||
}
|
||||
standardChanged = (event.download_standard_resolution ?? null)
|
||||
!== (updates.download_standard_resolution ?? null);
|
||||
}
|
||||
|
||||
// events has no updated_at column — don't set it.
|
||||
if (req.body.download_resolution_picker_enabled !== undefined) {
|
||||
updates.download_resolution_picker_enabled = req.body.download_resolution_picker_enabled === null
|
||||
? null
|
||||
: formatBoolean(parseBooleanInput(req.body.download_resolution_picker_enabled, false));
|
||||
}
|
||||
if (req.body.download_allow_original !== undefined) {
|
||||
updates.download_allow_original = req.body.download_allow_original === null
|
||||
? null
|
||||
: formatBoolean(parseBooleanInput(req.body.download_allow_original, false));
|
||||
}
|
||||
|
||||
if (Object.keys(updates).length === 0) {
|
||||
return res.status(400).json({ error: 'No settings supplied' });
|
||||
}
|
||||
|
||||
await db('events').where('id', event.id).update(updates);
|
||||
|
||||
// Only the standard resolution changes what the cached archive contains.
|
||||
// Toggling the picker or the original allowance doesn't, so don't throw
|
||||
// away a valid zip for those.
|
||||
if (standardChanged) {
|
||||
downloadZipService.invalidate(event.id);
|
||||
}
|
||||
|
||||
const fresh = await db('events').where('id', event.id).first();
|
||||
const policy = await resolveEventDownloadPolicy(fresh);
|
||||
|
||||
await logActivity('event_download_resolutions_updated', {
|
||||
event_id: event.id, ...updates,
|
||||
}, null, { type: 'admin', id: req.admin.id, name: req.admin.username });
|
||||
|
||||
res.json({
|
||||
message: 'Download resolution settings updated',
|
||||
zip_invalidated: standardChanged,
|
||||
effective: {
|
||||
standard: policy.standard,
|
||||
picker_enabled: policy.pickerEnabled,
|
||||
allow_original: policy.allowOriginal,
|
||||
choices: policy.choices,
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
errorResponse(res, error, 500, 'Failed to save download resolution settings');
|
||||
}
|
||||
});
|
||||
};
|
||||
@@ -10,6 +10,7 @@ const router = express.Router();
|
||||
|
||||
require('./crud')(router);
|
||||
require('./slideshow')(router);
|
||||
require('./downloadResolutions')(router);
|
||||
require('./resets')(router);
|
||||
require('./archiveBulk')(router);
|
||||
require('./logo')(router);
|
||||
|
||||
@@ -51,7 +51,13 @@ const RESERVED_SETTING_KEYS = [
|
||||
// clobbered with plaintext, and the policy/mapping keys carry invariants
|
||||
// (role targets exist, break-glass account present) that only the dedicated
|
||||
// PUT /sso validates — a generic upsert would bypass all of them.
|
||||
const isReservedSettingKey = (key) => RESERVED_SETTING_KEYS.includes(key) || key.startsWith('oidc_');
|
||||
// Every download_* key is reserved too (#858): the cached download-all zip is
|
||||
// built AT the standard resolution, so changing it has to invalidate those
|
||||
// zips and re-validate the value against the preset list. A generic upsert
|
||||
// would do neither, leaving galleries handing out archives at the old size.
|
||||
const isReservedSettingKey = (key) => RESERVED_SETTING_KEYS.includes(key)
|
||||
|| key.startsWith('oidc_')
|
||||
|| key.startsWith('download_');
|
||||
const stripReservedSettingKeys = (settings) => {
|
||||
for (const key of Object.keys(settings)) {
|
||||
if (isReservedSettingKey(key)) delete settings[key];
|
||||
@@ -443,6 +449,126 @@ router.put('/slideshow', adminAuth, requirePermission('settings.edit'), async (r
|
||||
}
|
||||
});
|
||||
|
||||
// ──────────────────────────────────────────────────────────────────────────
|
||||
// Download resolutions (#858). The standard resolution is what every ordinary
|
||||
// download hands out; the picker is an opt-in modal letting guests choose a
|
||||
// different size. Dedicated endpoints because a change here has to invalidate
|
||||
// the pre-built download-all zips, which are built AT the standard resolution.
|
||||
// ──────────────────────────────────────────────────────────────────────────
|
||||
|
||||
router.get('/downloads', adminAuth, requirePermission('settings.view'), async (req, res) => {
|
||||
try {
|
||||
const { getDownloadGlobals } = require('../utils/downloadResolutions');
|
||||
res.json(await getDownloadGlobals());
|
||||
} catch (error) {
|
||||
errorResponse(res, error, 500, 'Failed to load download settings');
|
||||
}
|
||||
});
|
||||
|
||||
router.put('/downloads', adminAuth, requirePermission('settings.edit'), async (req, res) => {
|
||||
try {
|
||||
const {
|
||||
invalidateDownloadGlobals, getDownloadGlobals, ORIGINAL,
|
||||
} = require('../utils/downloadResolutions');
|
||||
const has = (k) => Object.prototype.hasOwnProperty.call(req.body, k);
|
||||
const updates = [];
|
||||
const push = (key, value) => updates.push({
|
||||
setting_key: key, setting_value: JSON.stringify(value), setting_type: 'download',
|
||||
});
|
||||
|
||||
// Presets first — the standard is validated against the resulting list,
|
||||
// so a single request can add a size and select it in one go.
|
||||
const before = await getDownloadGlobals();
|
||||
const previousStandard = before.standard_resolution;
|
||||
let presets = before.resolutions;
|
||||
if (has('download_resolutions')) {
|
||||
const raw = Array.isArray(req.body.download_resolutions) ? req.body.download_resolutions : [];
|
||||
const cleaned = [];
|
||||
const seen = new Set();
|
||||
for (const p of raw) {
|
||||
const width = Math.round(Number(p?.width));
|
||||
const height = Math.round(Number(p?.height));
|
||||
// 20000px ceiling keeps a typo ("30000000") from asking sharp for a
|
||||
// multi-terabyte canvas on every subsequent download.
|
||||
if (!width || !height || width < 1 || height < 1 || width > 20000 || height > 20000) continue;
|
||||
const id = `${width}x${height}`;
|
||||
if (seen.has(id)) continue;
|
||||
seen.add(id);
|
||||
cleaned.push({ label: String(p.label || id).slice(0, 40), width, height });
|
||||
}
|
||||
if (cleaned.length === 0) {
|
||||
return res.status(400).json({ error: 'At least one valid resolution is required' });
|
||||
}
|
||||
push('download_resolutions', cleaned);
|
||||
presets = cleaned.map((p) => ({ ...p, id: `${p.width}x${p.height}` }));
|
||||
}
|
||||
|
||||
if (has('download_standard_resolution')) {
|
||||
const v = String(req.body.download_standard_resolution || ORIGINAL);
|
||||
if (v !== ORIGINAL && !presets.some((p) => p.id === v)) {
|
||||
return res.status(400).json({ error: `Unknown resolution "${v}"` });
|
||||
}
|
||||
push('download_standard_resolution', v);
|
||||
} else if (has('download_resolutions')) {
|
||||
// Replacing the preset list without naming a standard can orphan the
|
||||
// CURRENT standard — galleries would keep handing out a size the picker
|
||||
// no longer offers, breaking the "standard is always a preset" invariant.
|
||||
if (previousStandard !== ORIGINAL && !presets.some((p) => p.id === previousStandard)) {
|
||||
return res.status(400).json({
|
||||
error: `The current standard resolution "${previousStandard}" is not in the new list — set download_standard_resolution in the same request`,
|
||||
});
|
||||
}
|
||||
}
|
||||
if (has('download_resolution_picker_enabled')) {
|
||||
push('download_resolution_picker_enabled', !!req.body.download_resolution_picker_enabled);
|
||||
}
|
||||
if (has('download_allow_original')) {
|
||||
push('download_allow_original', !!req.body.download_allow_original);
|
||||
}
|
||||
|
||||
for (const u of updates) {
|
||||
await upsertAppSetting(u.setting_key, u.setting_value, u.setting_type);
|
||||
}
|
||||
invalidateDownloadGlobals();
|
||||
|
||||
// The cached download-all zip is built at the standard resolution, so a
|
||||
// change to the GLOBAL standard makes every INHERITING gallery's zip
|
||||
// stale. Events with their own override are unaffected and keep theirs.
|
||||
// Only a REAL change to the standard invalidates. The settings form
|
||||
// submits every field on every save, so keying off "was it present" would
|
||||
// schedule a rebuild of every inheriting gallery each time an admin
|
||||
// renamed a preset — a stampede on installs with many galleries.
|
||||
const standardUpdate = updates.find((u) => u.setting_key === 'download_standard_resolution');
|
||||
const standardChanged = standardUpdate
|
||||
&& JSON.parse(standardUpdate.setting_value) !== previousStandard;
|
||||
|
||||
let invalidatedZips = 0;
|
||||
if (standardChanged) {
|
||||
// Every inheriting event, whether or not it currently HAS a cached zip:
|
||||
// one may be mid-build against the old standard right now. Going through
|
||||
// downloadZipService.invalidate bumps its generation counter, which
|
||||
// aborts that build — a raw UPDATE would let it finish and re-publish a
|
||||
// permanently stale archive.
|
||||
const downloadZipService = require('../services/downloadZipService');
|
||||
const inheriting = await db('events')
|
||||
.whereNull('download_standard_resolution')
|
||||
.select('id');
|
||||
for (const ev of inheriting) {
|
||||
downloadZipService.invalidate(ev.id);
|
||||
}
|
||||
invalidatedZips = inheriting.length;
|
||||
}
|
||||
|
||||
res.json({
|
||||
message: 'Download settings updated',
|
||||
updated: updates.map((u) => u.setting_key),
|
||||
invalidated_zips: invalidatedZips,
|
||||
});
|
||||
} catch (error) {
|
||||
errorResponse(res, error, 500, 'Failed to save download settings');
|
||||
}
|
||||
});
|
||||
|
||||
// Get settings by type
|
||||
// ──────────────────────────────────────────────────────────────────────────
|
||||
// OIDC SSO settings (#798). Dedicated endpoints — NOT the generic upsert —
|
||||
|
||||
+247
-32
@@ -35,8 +35,17 @@ const { handleAsync, errorResponse } = require('../utils/routeHelpers');
|
||||
const { isGalleryHidden, guestBlockedByReveal, blockHiddenGallery } = require('../utils/revealMode');
|
||||
const { toIso } = require('../utils/dateNormalize');
|
||||
const { NotFoundError } = require('../utils/errors');
|
||||
const { ensureThumbnail, ensureHeroImage, ensurePreviewImage, withLocalCopy } = require('../services/imageProcessor');
|
||||
const { ensureThumbnail, ensureHeroImage, ensurePreviewImage, withLocalCopy, resizeToBox } = require('../services/imageProcessor');
|
||||
const downloadZipService = require('../services/downloadZipService');
|
||||
const { renderPhotoForDownload } = require('../services/downloadRendition');
|
||||
const downloadJobService = require('../services/downloadJobService');
|
||||
// Download resolutions (#858) — the standard size a gallery hands out, plus
|
||||
// validation of any guest-picked override.
|
||||
const {
|
||||
resolveEventDownloadPolicy,
|
||||
pickRequestedResolution,
|
||||
parseResolution,
|
||||
} = require('../utils/downloadResolutions');
|
||||
const { applyPhotoVisibilityFilter, canSeeHiddenPhotos } = require('../utils/photoVisibility');
|
||||
const {
|
||||
getUseOriginalFilenames,
|
||||
@@ -885,6 +894,7 @@ router.get('/:slug/photos', verifyGalleryAccess, resolveGuest, async (req, res)
|
||||
const useOriginalFilenames = await getUseOriginalFilenames();
|
||||
const globalHeroLogoVisible = await getAppSetting('branding_logo_display_hero', true);
|
||||
const globalLogoSize = await getAppSetting('branding_logo_size', 'medium');
|
||||
const downloadPolicy = await resolveEventDownloadPolicy(req.event);
|
||||
|
||||
res.json({
|
||||
event: {
|
||||
@@ -898,6 +908,14 @@ router.get('/:slug/photos', verifyGalleryAccess, resolveGuest, async (req, res)
|
||||
hero_photo_id: req.event.hero_photo_id,
|
||||
allow_downloads: req.event.allow_downloads !== false,
|
||||
allow_user_uploads: req.event.allow_user_uploads === true,
|
||||
// Download resolutions (#858). `choices` drives the picker modal and is
|
||||
// empty when the picker is off, so the UI can never offer a size the
|
||||
// server would reject.
|
||||
download_resolution: {
|
||||
standard: downloadPolicy.standard,
|
||||
picker_enabled: downloadPolicy.pickerEnabled,
|
||||
choices: downloadPolicy.pickerEnabled ? downloadPolicy.choices : [],
|
||||
},
|
||||
// Reveal mode (#838): armed flag lets an open VISIBLE gallery keep
|
||||
// polling so a re-hide propagates without a manual reload.
|
||||
reveal_armed: req.event.reveal_mode === true || req.event.reveal_mode === 1 || req.event.reveal_mode === '1',
|
||||
@@ -1121,6 +1139,18 @@ router.get('/:slug/download/:photoId', verifyGalleryAccess, denySlideshowToken,
|
||||
}
|
||||
}
|
||||
|
||||
// Download resolution (#858). Resolved BEFORE the counters below: a
|
||||
// rejected resolution must not inflate download stats, which a guest
|
||||
// could otherwise do by replaying ?resolution=bogus.
|
||||
const isVideo = photo.media_type === 'video'
|
||||
|| (photo.mime_type && photo.mime_type.startsWith('video/'));
|
||||
const policy = await resolveEventDownloadPolicy(req.event);
|
||||
const requested = pickRequestedResolution(policy, req.query.resolution);
|
||||
if (requested === null) {
|
||||
return res.status(400).json({ error: 'Resolution not available for this gallery' });
|
||||
}
|
||||
const box = isVideo ? null : parseResolution(requested);
|
||||
|
||||
// Admin preview (#868) downloads are excluded from the download count +
|
||||
// guest analytics — kept out of client-facing stats.
|
||||
if (!req.isAdminPreview) {
|
||||
@@ -1169,23 +1199,42 @@ router.get('/:slug/download/:photoId', verifyGalleryAccess, denySlideshowToken,
|
||||
const downloadName = pickRawDownloadName(photo, useOriginal);
|
||||
const contentDisposition = buildContentDisposition(downloadName);
|
||||
|
||||
if (shouldApplyWatermark) {
|
||||
// Apply watermark and send
|
||||
// Use event watermark text if available, otherwise fall back to global settings
|
||||
const effectiveSettings = {
|
||||
// The gallery's standard applies to EVERY ordinary download, single photos
|
||||
// included — otherwise a lowered standard is trivially bypassed by
|
||||
// downloading photos one at a time. `box` was resolved above, before the
|
||||
// counters. Videos have no resize path and always ship as-is.
|
||||
if (shouldApplyWatermark || box) {
|
||||
// Resize BEFORE watermarking: applyWatermark sizes the mark relative to
|
||||
// its input's width, so watermarking the original and then shrinking
|
||||
// would resample the mark and waste work on discarded pixels.
|
||||
//
|
||||
// With no resize (the default 'original' standard) hand applyWatermark
|
||||
// the PATH, not a buffer: buffer inputs deliberately skip its cache, so
|
||||
// buffering here would re-run sharp over the full-size original on every
|
||||
// download and regress the pre-#858 watermark performance.
|
||||
const effectiveSettings = shouldApplyWatermark ? {
|
||||
...watermarkSettings,
|
||||
enabled: true,
|
||||
text: req.event.watermark_text || watermarkSettings?.text || 'Protected'
|
||||
};
|
||||
const watermarkedBuffer = await watermarkService.applyWatermark(filePath, effectiveSettings);
|
||||
} : null;
|
||||
|
||||
let buffer;
|
||||
if (!box) {
|
||||
buffer = await watermarkService.applyWatermark(filePath, effectiveSettings);
|
||||
} else {
|
||||
buffer = await resizeToBox(await fs.promises.readFile(filePath), box);
|
||||
if (shouldApplyWatermark) {
|
||||
buffer = await watermarkService.applyWatermark(buffer, effectiveSettings);
|
||||
}
|
||||
}
|
||||
|
||||
res.set({
|
||||
'Content-Type': photo.mime_type || 'image/jpeg',
|
||||
'Content-Disposition': contentDisposition,
|
||||
'Content-Length': watermarkedBuffer.length
|
||||
'Content-Length': buffer.length
|
||||
});
|
||||
|
||||
res.send(watermarkedBuffer);
|
||||
res.send(buffer);
|
||||
} else {
|
||||
// res.download() builds Content-Disposition itself but doesn't emit the
|
||||
// RFC 5987 filename* parameter, so unicode camera filenames would lose
|
||||
@@ -1368,6 +1417,10 @@ router.get('/:slug/download-all', verifyGalleryAccess, denySlideshowToken, block
|
||||
text: req.event.watermark_text || watermarkSettings?.text || 'Protected'
|
||||
} : null;
|
||||
|
||||
// The gallery's standard resolution applies to the streamed archive too,
|
||||
// not only the cached one (#858).
|
||||
const { standardBox: bulkBox } = await resolveEventDownloadPolicy(req.event);
|
||||
|
||||
// Add photos to archive — managed photos via storage backend, external via local path.
|
||||
const { resolvePhotoStorageKey } = require('../services/photoResolver');
|
||||
const storage = getStorage();
|
||||
@@ -1408,21 +1461,14 @@ router.get('/:slug/download-all', verifyGalleryAccess, denySlideshowToken, block
|
||||
throw new Error('Photo file missing on disk');
|
||||
}
|
||||
|
||||
if (shouldApplyWatermark && effectiveSettings) {
|
||||
// Watermark service operates on a local path. For managed photos in
|
||||
// S3 mode, materialize a tmp local copy first.
|
||||
const { withLocalCopy } = require('../services/imageProcessor');
|
||||
const sourceForWatermark = storageKey
|
||||
? null
|
||||
: resolvePhotoFilePath(req.event, photo);
|
||||
|
||||
const watermarkedBuffer = storageKey
|
||||
? await withLocalCopy(storageKey, (localPath) =>
|
||||
watermarkService.applyWatermark(localPath, effectiveSettings)
|
||||
)
|
||||
: await watermarkService.applyWatermark(sourceForWatermark, effectiveSettings);
|
||||
|
||||
archive.append(watermarkedBuffer, { name: archiveName });
|
||||
// Resize to the gallery's standard resolution (#858) and/or watermark.
|
||||
// This branch runs whenever the cached zip isn't usable — the first
|
||||
// download after an invalidation, PIN clients, and galleries with
|
||||
// hidden photos all land here, so skipping the cap would leak
|
||||
// full-resolution files for exactly those cases.
|
||||
const rendered = await renderPhotoForDownload(req.event, photo, bulkBox, effectiveSettings);
|
||||
if (rendered) {
|
||||
archive.append(rendered, { name: archiveName });
|
||||
} else if (storageKey) {
|
||||
const stream = await storage.get(storageKey);
|
||||
archive.append(stream, { name: archiveName });
|
||||
@@ -1515,6 +1561,15 @@ router.post('/:slug/download-selected', verifyGalleryAccess, denySlideshowToken,
|
||||
return res.status(404).json({ error: 'No photos found for selected IDs' });
|
||||
}
|
||||
|
||||
// Download resolution (#858). Resolve BEFORE any header goes out — once
|
||||
// the archive starts streaming we can no longer return a JSON error.
|
||||
const selectedPolicy = await resolveEventDownloadPolicy(req.event);
|
||||
const selectedResolution = pickRequestedResolution(selectedPolicy, req.body?.resolution);
|
||||
if (selectedResolution === null) {
|
||||
return res.status(400).json({ error: 'Resolution not available for this gallery' });
|
||||
}
|
||||
const selectedBox = parseResolution(selectedResolution);
|
||||
|
||||
const archiveName = `${req.event.slug}-selected.zip`;
|
||||
res.setHeader('Content-Type', 'application/zip');
|
||||
res.setHeader('Content-Disposition', `attachment; filename="${archiveName}"`);
|
||||
@@ -1545,7 +1600,6 @@ router.post('/:slug/download-selected', verifyGalleryAccess, denySlideshowToken,
|
||||
} : null;
|
||||
|
||||
const { resolvePhotoStorageKey: resolveSelectedKey } = require('../services/photoResolver');
|
||||
const { withLocalCopy: withSelectedLocalCopy } = require('../services/imageProcessor');
|
||||
const selectedStorage = getStorage();
|
||||
// #493: same display-name resolution as bulk download, with dedup.
|
||||
const useOriginalSelected = await getUseOriginalFilenames();
|
||||
@@ -1570,13 +1624,12 @@ router.post('/:slug/download-selected', verifyGalleryAccess, denySlideshowToken,
|
||||
throw new Error('Photo file missing on disk');
|
||||
}
|
||||
|
||||
if (shouldApplyWatermark && effectiveSettings) {
|
||||
const buf = storageKey
|
||||
? await withSelectedLocalCopy(storageKey, (lp) =>
|
||||
watermarkService.applyWatermark(lp, effectiveSettings)
|
||||
)
|
||||
: await watermarkService.applyWatermark(resolvePhotoFilePath(req.event, photo), effectiveSettings);
|
||||
archive.append(buf, { name });
|
||||
// Resize (#858) and/or watermark. renderPhotoForDownload returns null
|
||||
// when neither applies, so the untransformed case still streams from
|
||||
// storage rather than buffering the whole photo.
|
||||
const rendered = await renderPhotoForDownload(req.event, photo, selectedBox, effectiveSettings);
|
||||
if (rendered) {
|
||||
archive.append(rendered, { name });
|
||||
} else if (storageKey) {
|
||||
const stream = await selectedStorage.get(storageKey);
|
||||
archive.append(stream, { name });
|
||||
@@ -1623,6 +1676,168 @@ router.post('/:slug/download-selected', verifyGalleryAccess, denySlideshowToken,
|
||||
});
|
||||
|
||||
|
||||
// ──────────────────────────────────────────────────────────────────────────
|
||||
// Custom-resolution download jobs (#858).
|
||||
//
|
||||
// The plain download-all is served from the pre-built cache at the gallery's
|
||||
// STANDARD resolution. Picking a different size has nothing to cache against,
|
||||
// and resizing a whole gallery inside one request would sit far past any
|
||||
// reverse-proxy timeout — so those archives are built as a job the client
|
||||
// polls. Same access rules as the download routes above.
|
||||
// ──────────────────────────────────────────────────────────────────────────
|
||||
|
||||
// Kick off (or join) a build. Returns the polling token.
|
||||
router.post('/:slug/download-jobs', verifyGalleryAccess, denySlideshowToken, blockHiddenGallery, async (req, res) => {
|
||||
try {
|
||||
if (req.event.allow_downloads === false) {
|
||||
return res.status(403).json({ error: 'Downloads are disabled for this gallery' });
|
||||
}
|
||||
|
||||
const policy = await resolveEventDownloadPolicy(req.event);
|
||||
if (!policy.pickerEnabled) {
|
||||
return res.status(403).json({ error: 'Resolution choice is not enabled for this gallery' });
|
||||
}
|
||||
const resolution = pickRequestedResolution(policy, req.body?.resolution);
|
||||
if (resolution === null) {
|
||||
return res.status(400).json({ error: 'Resolution not available for this gallery' });
|
||||
}
|
||||
|
||||
// Optional subset. Absent = the whole visible gallery.
|
||||
let photoIds = null;
|
||||
if (Array.isArray(req.body?.photo_ids) && req.body.photo_ids.length) {
|
||||
photoIds = req.body.photo_ids
|
||||
.map((v) => parseInt(v, 10))
|
||||
.filter((v) => Number.isInteger(v))
|
||||
.slice(0, 500);
|
||||
if (photoIds.length === 0) {
|
||||
return res.status(400).json({ error: 'No valid photo IDs provided' });
|
||||
}
|
||||
}
|
||||
|
||||
let job;
|
||||
try {
|
||||
job = await downloadJobService.createJob({
|
||||
event: req.event,
|
||||
resolution,
|
||||
photoIds,
|
||||
accessLevel: req.accessLevel,
|
||||
});
|
||||
} catch (err) {
|
||||
if (err.code === 'NO_PHOTOS') {
|
||||
return res.status(404).json({ error: 'No photos available for this selection' });
|
||||
}
|
||||
if (err.code === 'BUSY') {
|
||||
return res.status(429).json({ error: 'Too many downloads are being prepared right now — please try again shortly' });
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
|
||||
res.status(202).json({
|
||||
token: job.token,
|
||||
status: job.status,
|
||||
resolution: job.resolution,
|
||||
});
|
||||
} catch (error) {
|
||||
errorResponse(res, error, 500, 'Failed to start download preparation');
|
||||
}
|
||||
});
|
||||
|
||||
// Poll. The token is unguessable, but it is never sufficient on its own —
|
||||
// verifyGalleryAccess still runs and the job must belong to THIS event.
|
||||
router.get('/:slug/download-jobs/:token', verifyGalleryAccess, denySlideshowToken, blockHiddenGallery, async (req, res) => {
|
||||
try {
|
||||
const job = await downloadJobService.getStatus(req.params.token);
|
||||
if (!job || job.event_id !== req.event.id) {
|
||||
return res.status(404).json({ error: 'Download job not found' });
|
||||
}
|
||||
res.json({
|
||||
status: job.status,
|
||||
resolution: job.resolution,
|
||||
photo_count: job.photo_count || 0,
|
||||
size_bytes: job.size_bytes || null,
|
||||
error: job.status === 'failed' ? (job.error || 'Preparation failed') : undefined,
|
||||
});
|
||||
} catch (error) {
|
||||
errorResponse(res, error, 500, 'Failed to read download job');
|
||||
}
|
||||
});
|
||||
|
||||
// Deliver the finished archive.
|
||||
router.get('/:slug/download-jobs/:token/file', verifyGalleryAccess, denySlideshowToken, blockHiddenGallery, async (req, res) => {
|
||||
try {
|
||||
// Downloads can be switched off after a job was created — every other
|
||||
// download route re-checks this per request, so this one must too.
|
||||
if (req.event.allow_downloads === false) {
|
||||
return res.status(403).json({ error: 'Downloads are disabled for this gallery' });
|
||||
}
|
||||
|
||||
const job = await downloadJobService.getStatus(req.params.token);
|
||||
if (!job || job.event_id !== req.event.id) {
|
||||
return res.status(404).json({ error: 'Download job not found' });
|
||||
}
|
||||
// The token alone never grants access: the archive was built under one
|
||||
// visibility scope, and only a requester still in that scope may take it.
|
||||
// Without this, a leaked client token would hand hidden photos to a guest.
|
||||
if (job.visibility_scope !== downloadJobService.visibilityScopeFor(req.accessLevel)) {
|
||||
return res.status(404).json({ error: 'Download job not found' });
|
||||
}
|
||||
if (job.status !== 'ready' || !job.zip_path) {
|
||||
return res.status(409).json({ error: 'Download is not ready yet', status: job.status });
|
||||
}
|
||||
if (new Date(job.expires_at).getTime() <= Date.now()) {
|
||||
return res.status(410).json({ error: 'This download has expired — please request it again' });
|
||||
}
|
||||
// A photo hidden AFTER this archive was built is still inside it, and the
|
||||
// scope check above can't see that — both sides remain 'public'. Re-run
|
||||
// the visibility query over the packaged set before handing it over.
|
||||
if (!(await downloadJobService.isStillDeliverable(job, req.event, req.accessLevel))) {
|
||||
return res.status(409).json({
|
||||
error: 'This gallery changed since the download was prepared — please request it again',
|
||||
status: 'stale',
|
||||
});
|
||||
}
|
||||
|
||||
const storage = getStorage();
|
||||
const stat = await storage.stat(job.zip_path);
|
||||
if (!stat) {
|
||||
return res.status(410).json({ error: 'This download is no longer available' });
|
||||
}
|
||||
|
||||
// Stats parity with the other bulk paths (#895): only count once the
|
||||
// response actually completed, and keep admin previews out of guest stats.
|
||||
res.on('finish', () => {
|
||||
if (res.statusCode >= 400 || req.isAdminPreview) return;
|
||||
// The DELIVERED set, not the requested one: a photo whose source was
|
||||
// missing at build time isn't in the zip and must not be counted.
|
||||
let ids = [];
|
||||
try {
|
||||
ids = JSON.parse(job.delivered_photo_ids || job.photo_ids || '[]');
|
||||
} catch (_) { /* malformed row — skip counting rather than fail */ }
|
||||
if (ids.length > 0) {
|
||||
db('photos').whereIn('id', ids).increment('download_count', 1).catch(() => {});
|
||||
}
|
||||
db('access_logs').insert({
|
||||
event_id: req.event.id,
|
||||
ip_address: req.ip,
|
||||
user_agent: req.headers['user-agent'],
|
||||
action: 'download',
|
||||
photo_id: null,
|
||||
}).catch(() => {});
|
||||
logActivity('gallery_downloaded', { scope: 'all', resolution: job.resolution },
|
||||
req.event.id, galleryActor(req));
|
||||
});
|
||||
|
||||
const suffix = job.resolution === 'original' ? 'original' : job.resolution;
|
||||
res.setHeader('Content-Type', 'application/zip');
|
||||
res.setHeader('Content-Length', stat.size);
|
||||
res.setHeader('Content-Disposition', `attachment; filename="${req.event.slug}-${suffix}.zip"`);
|
||||
const stream = await storage.get(job.zip_path);
|
||||
stream.pipe(res);
|
||||
} catch (error) {
|
||||
errorResponse(res, error, 500, 'Failed to serve prepared download');
|
||||
}
|
||||
});
|
||||
|
||||
// Explicit per-photo view beacon (#895). Counting views on the image-
|
||||
// serving routes is wrong in both directions: the lightbox preloads the
|
||||
// prev/next neighbours (three fetches per open), while a preloaded
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
/**
|
||||
* downloadJobCleanupService — TTL sweep for custom-resolution download jobs
|
||||
* (#858).
|
||||
*
|
||||
* Job archives are one-off renditions of a gallery at a size nothing else
|
||||
* caches against, so they are pure disposable bytes: once the TTL passes the
|
||||
* row and its zip go away. Without this sweep, every guest who ever picked a
|
||||
* non-standard resolution would leave a full gallery-sized archive behind in
|
||||
* `.download-cache` forever.
|
||||
*
|
||||
* Runs every 20 minutes, offset from the hourly jobs so the three cleanup
|
||||
* schedulers don't all wake at once.
|
||||
*/
|
||||
|
||||
const cron = require('node-cron');
|
||||
const logger = require('../utils/logger');
|
||||
const downloadJobService = require('./downloadJobService');
|
||||
|
||||
function startDownloadJobCleanup() {
|
||||
// A restart leaves any in-flight build with no worker. Fail those rows once
|
||||
// at startup so their owners get a clear error instead of polling forever.
|
||||
downloadJobService.recoverOrphanedJobs().catch((err) =>
|
||||
logger.error('Download job recovery failed', { error: err.message }));
|
||||
|
||||
cron.schedule('7,27,47 * * * *', async () => {
|
||||
await runDownloadJobCleanup();
|
||||
});
|
||||
logger.info('Download job cleanup scheduler started');
|
||||
}
|
||||
|
||||
async function runDownloadJobCleanup() {
|
||||
try {
|
||||
await downloadJobService.sweepExpired();
|
||||
} catch (err) {
|
||||
logger.error('Download job cleanup failed', { error: err.message });
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
startDownloadJobCleanup,
|
||||
// exported for tests / manual invocation
|
||||
runDownloadJobCleanup,
|
||||
};
|
||||
@@ -0,0 +1,418 @@
|
||||
/**
|
||||
* Custom-resolution download jobs (#858).
|
||||
*
|
||||
* The plain download-all is served from the pre-built cache, which is built at
|
||||
* the gallery's STANDARD resolution. When a guest picks a different size there
|
||||
* is nothing to cache against — so instead of holding an HTTP connection open
|
||||
* while sharp chews through a whole gallery (a reverse proxy would time it out
|
||||
* long before it finished), the archive is built as a job:
|
||||
*
|
||||
* POST .../download-jobs → { token, status: 'pending' }
|
||||
* GET .../download-jobs/:token → poll { status, progress }
|
||||
* GET .../download-jobs/:token/file → the finished zip
|
||||
*
|
||||
* State lives in the `download_jobs` table rather than in memory: an in-memory
|
||||
* map loses every "ready" job on restart and is simply wrong the moment the
|
||||
* backend runs more than one replica.
|
||||
*
|
||||
* Artifacts land in the same `.download-cache` directory as the pre-built zip.
|
||||
* That directory is a dotfile, and s3AutoImporter skips dotfiles, so job zips
|
||||
* can never be mistaken for gallery photos and re-imported.
|
||||
*/
|
||||
|
||||
const path = require('path');
|
||||
const os = require('os');
|
||||
const fs = require('fs');
|
||||
const fsp = require('fs').promises;
|
||||
const crypto = require('crypto');
|
||||
const archiver = require('archiver');
|
||||
const { db } = require('../database/db');
|
||||
const { getStorage } = require('./storage');
|
||||
const { getUseOriginalFilenames, getZipEntryNames } = require('./downloadFilenameService');
|
||||
const { renderPhotoForDownload, resolveWatermarkSettings } = require('./downloadRendition');
|
||||
const { resolvePhotoStorageKey, resolvePhotoFilePath } = require('./photoResolver');
|
||||
const { parseResolution } = require('../utils/downloadResolutions');
|
||||
const { applyPhotoVisibilityFilter, canSeeHiddenPhotos } = require('../utils/photoVisibility');
|
||||
const logger = require('../utils/logger');
|
||||
|
||||
// How long a finished archive stays downloadable before the sweep deletes it.
|
||||
const JOB_TTL_MS = 60 * 60 * 1000; // 1 hour
|
||||
// Guards against a handful of guests each kicking off a whole-gallery resize.
|
||||
const MAX_CONCURRENT_BUILDS = 2;
|
||||
// Hard ceiling on queued+running builds. Gallery routes are not behind the
|
||||
// general rate limiter, so without this a token holder could vary the photo
|
||||
// subset to enqueue unbounded 500-photo resizes — each one parking a promise
|
||||
// and eventually a full gallery's worth of CPU and disk.
|
||||
const MAX_QUEUED_BUILDS = 8;
|
||||
// A build heartbeats while it works. A row whose heartbeat is older than this
|
||||
// has no live worker (crashed or restarted) and may be failed by recovery.
|
||||
const LEASE_TIMEOUT_MS = 5 * 60 * 1000;
|
||||
|
||||
/**
|
||||
* Collapse an access level to the visibility scope that decides WHICH photos a
|
||||
* requester may receive. Anything that can see hidden photos is one scope;
|
||||
* ordinary guests are another. Part of the job dedup identity so archives are
|
||||
* never shared across the boundary.
|
||||
*/
|
||||
function visibilityScope(accessLevel) {
|
||||
return canSeeHiddenPhotos(accessLevel) ? 'hidden' : 'public';
|
||||
}
|
||||
|
||||
class DownloadJobService {
|
||||
constructor() {
|
||||
this.running = 0;
|
||||
// jobId -> in-flight build promise. Only jobs present here are safe to
|
||||
// rejoin; rows left 'pending'/'building' by a previous process are not.
|
||||
this.liveBuilds = new Map();
|
||||
// Slots claimed between the admission check and the liveBuilds entry.
|
||||
// Without it, concurrent requests all pass the check before any registers.
|
||||
this.reserved = 0;
|
||||
}
|
||||
|
||||
cacheDir(slug) {
|
||||
return path.posix.join('events/active', slug, '.download-cache');
|
||||
}
|
||||
|
||||
jobKey(slug, token) {
|
||||
return path.posix.join(this.cacheDir(slug), `job-${token}.zip`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Stable identity for "the same archive".
|
||||
*
|
||||
* SECURITY: `visibilityScope` and the RESOLVED photo id list are part of the
|
||||
* identity, not just the requested one. A PIN client sees hidden photos that
|
||||
* an ordinary guest must not; without the scope in the key, a guest asking
|
||||
* for the same size would be handed the client's job token and could
|
||||
* download hidden photos, because the delivery route only checks the event
|
||||
* id. Hashing the resolved id set also stops a stale archive being reused
|
||||
* after photos are added, removed or hidden.
|
||||
*/
|
||||
dedupKey(eventId, resolution, resolvedPhotoIds, watermark, visibilityScope) {
|
||||
const ids = [...resolvedPhotoIds].map(Number).sort((a, b) => a - b).join(',');
|
||||
// The full watermark SETTINGS, not just the on/off flag: an admin who
|
||||
// edits the watermark text or logo while it stays enabled would otherwise
|
||||
// have the old mark served from a ready job for the rest of its TTL.
|
||||
const wm = watermark
|
||||
? crypto.createHash('sha256').update(JSON.stringify(watermark)).digest('hex').slice(0, 16)
|
||||
: 'raw';
|
||||
return crypto.createHash('sha256')
|
||||
.update(`${eventId}|${resolution}|${visibilityScope}|${ids}|${wm}`)
|
||||
.digest('hex')
|
||||
.slice(0, 64);
|
||||
}
|
||||
|
||||
/**
|
||||
* The photos a given requester would actually receive. Used both to build
|
||||
* the dedup identity and to build the archive, so the two can never drift.
|
||||
*/
|
||||
photoQuery(eventId, photoIds, accessLevel) {
|
||||
let query = db('photos')
|
||||
.leftJoin('photo_categories', 'photos.category_id', 'photo_categories.id')
|
||||
.where('photos.event_id', eventId)
|
||||
.where(function () {
|
||||
this.whereNull('photos.category_id')
|
||||
.orWhere('photo_categories.allow_downloads', true)
|
||||
.orWhereNull('photo_categories.allow_downloads');
|
||||
});
|
||||
if (photoIds && photoIds.length) {
|
||||
query = query.whereIn('photos.id', photoIds);
|
||||
}
|
||||
return applyPhotoVisibilityFilter(query, accessLevel);
|
||||
}
|
||||
|
||||
/**
|
||||
* Find a job that already satisfies this request — either still building or
|
||||
* finished and not yet expired. Failed jobs are ignored so a transient error
|
||||
* doesn't poison every later attempt.
|
||||
*
|
||||
* `pending`/`building` rows are only reusable while THIS process is actually
|
||||
* building them: after a restart those rows have no live worker, so rejoining
|
||||
* one would leave the client polling until the TTL expires.
|
||||
*/
|
||||
async findReusable(eventId, dedupKey) {
|
||||
const rows = await db('download_jobs')
|
||||
.where({ event_id: eventId, dedup_key: dedupKey })
|
||||
.whereIn('status', ['pending', 'building', 'ready'])
|
||||
.where('expires_at', '>', new Date().toISOString())
|
||||
.orderBy('id', 'desc');
|
||||
return rows.find((r) => r.status === 'ready' || this.liveBuilds.has(r.id)) || null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create (or join) a job. Returns the job row. Building continues in the
|
||||
* background — callers poll getStatus().
|
||||
*/
|
||||
async createJob({ event, resolution, photoIds, accessLevel }) {
|
||||
const watermark = await resolveWatermarkSettings(event);
|
||||
|
||||
// Resolve the photo set up front, under THIS requester's visibility, so
|
||||
// the dedup identity reflects what they may actually receive.
|
||||
const resolved = await this.photoQuery(event.id, photoIds, accessLevel).select('photos.id');
|
||||
const resolvedIds = resolved.map((r) => r.id);
|
||||
if (resolvedIds.length === 0) {
|
||||
const err = new Error('No photos available for this selection');
|
||||
err.code = 'NO_PHOTOS';
|
||||
throw err;
|
||||
}
|
||||
|
||||
const scope = visibilityScope(accessLevel);
|
||||
const dedupKey = this.dedupKey(event.id, resolution, resolvedIds, watermark, scope);
|
||||
|
||||
const existing = await this.findReusable(event.id, dedupKey);
|
||||
if (existing) return existing;
|
||||
|
||||
// Refuse rather than queue without bound. The client shows this as a
|
||||
// retryable error, which is far better than accepting work the box can't
|
||||
// absorb and timing the user out anyway.
|
||||
//
|
||||
// The slot is reserved SYNCHRONOUSLY here — checking liveBuilds.size and
|
||||
// only populating it after the awaited insert let a burst of concurrent
|
||||
// requests all pass the check before any of them registered.
|
||||
if (this.reserved + this.liveBuilds.size >= MAX_QUEUED_BUILDS) {
|
||||
const err = new Error('Too many downloads are being prepared right now');
|
||||
err.code = 'BUSY';
|
||||
throw err;
|
||||
}
|
||||
this.reserved += 1;
|
||||
|
||||
try {
|
||||
const token = crypto.randomBytes(32).toString('hex');
|
||||
const expiresAt = new Date(Date.now() + JOB_TTL_MS).toISOString();
|
||||
|
||||
const inserted = await db('download_jobs').insert({
|
||||
token,
|
||||
event_id: event.id,
|
||||
resolution,
|
||||
photo_ids: JSON.stringify(resolvedIds),
|
||||
dedup_key: dedupKey,
|
||||
visibility_scope: scope,
|
||||
status: 'pending',
|
||||
heartbeat_at: new Date().toISOString(),
|
||||
created_at: new Date().toISOString(),
|
||||
expires_at: expiresAt,
|
||||
}).returning('id');
|
||||
const id = inserted[0]?.id ?? inserted[0];
|
||||
|
||||
// Fire and forget — the row is the source of truth for progress. The
|
||||
// liveBuilds entry is what makes a pending/building row reusable; a row
|
||||
// without one is an orphan from a previous process.
|
||||
const promise = this._build(id, event, resolution, resolvedIds, watermark, accessLevel)
|
||||
.catch((err) => logger.error('Download job build failed', { jobId: id, error: err.message }))
|
||||
.finally(() => this.liveBuilds.delete(id));
|
||||
this.liveBuilds.set(id, promise);
|
||||
|
||||
return await db('download_jobs').where({ id }).first();
|
||||
} finally {
|
||||
// The slot is now accounted for by liveBuilds (or the insert failed).
|
||||
this.reserved -= 1;
|
||||
}
|
||||
}
|
||||
|
||||
async getStatus(token) {
|
||||
return db('download_jobs').where({ token }).first();
|
||||
}
|
||||
|
||||
/** Exposed so the delivery route can re-check the requester's scope. */
|
||||
visibilityScopeFor(accessLevel) {
|
||||
return visibilityScope(accessLevel);
|
||||
}
|
||||
|
||||
/**
|
||||
* Is every photo in this finished archive STILL visible to the requester?
|
||||
*
|
||||
* The scope check alone isn't enough: a photo hidden after a public job went
|
||||
* ready stays inside that zip, and both job and requester are still
|
||||
* 'public', so the archive would keep serving it for the rest of its TTL.
|
||||
* Re-running the visibility query at delivery closes that window.
|
||||
*/
|
||||
async isStillDeliverable(job, event, accessLevel) {
|
||||
let ids;
|
||||
try {
|
||||
ids = JSON.parse(job.photo_ids || '[]');
|
||||
} catch (_) {
|
||||
return false;
|
||||
}
|
||||
if (!Array.isArray(ids) || ids.length === 0) return false;
|
||||
|
||||
// Every packaged photo must still be visible to this requester.
|
||||
const visible = await this.photoQuery(job.event_id, ids, accessLevel).select('photos.id');
|
||||
if (visible.length !== ids.length) return false;
|
||||
|
||||
// …and the archive must still match the CURRENT rendition policy. Turning
|
||||
// a watermark on, editing it, or revoking a resolution after the job went
|
||||
// ready would otherwise keep serving the old bytes for the rest of the
|
||||
// TTL. Recomputing the identity is the cheapest way to notice: any input
|
||||
// that changes the archive changes the key.
|
||||
const watermark = await resolveWatermarkSettings(event);
|
||||
const expected = this.dedupKey(
|
||||
job.event_id, job.resolution, ids, watermark, visibilityScope(accessLevel)
|
||||
);
|
||||
return expected === job.dedup_key;
|
||||
}
|
||||
|
||||
async _fail(id, message) {
|
||||
await db('download_jobs').where({ id }).update({
|
||||
status: 'failed',
|
||||
error: String(message).slice(0, 500),
|
||||
completed_at: new Date().toISOString(),
|
||||
});
|
||||
}
|
||||
|
||||
async _build(id, event, resolution, photoIds, watermarkSettings, accessLevel) {
|
||||
// Back-pressure: a queued job stays 'pending' (which the UI shows as
|
||||
// "preparing") rather than piling more sharp pipelines onto a box that is
|
||||
// already saturated.
|
||||
while (this.running >= MAX_CONCURRENT_BUILDS) {
|
||||
await new Promise((r) => setTimeout(r, 500));
|
||||
}
|
||||
this.running += 1;
|
||||
|
||||
let tmpDir;
|
||||
try {
|
||||
await db('download_jobs').where({ id }).update({ status: 'building', heartbeat_at: new Date().toISOString() });
|
||||
|
||||
// Same query that produced the dedup identity, so the archive can never
|
||||
// contain photos the requester wasn't entitled to at creation time.
|
||||
const photos = await this.photoQuery(event.id, photoIds, accessLevel)
|
||||
.select('photos.*')
|
||||
.orderBy('photos.uploaded_at', 'desc');
|
||||
|
||||
if (photos.length === 0) {
|
||||
await this._fail(id, 'No photos available for this selection');
|
||||
return;
|
||||
}
|
||||
|
||||
const box = parseResolution(resolution);
|
||||
const storage = getStorage();
|
||||
const useOriginal = await getUseOriginalFilenames();
|
||||
const entryNames = getZipEntryNames(photos, useOriginal);
|
||||
|
||||
tmpDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'picpeak-dljob-'));
|
||||
const tmpPath = path.join(tmpDir, `${crypto.randomBytes(4).toString('hex')}.zip`);
|
||||
|
||||
let appended = 0;
|
||||
const appendedIds = [];
|
||||
await new Promise((resolve, reject) => {
|
||||
const output = fs.createWriteStream(tmpPath);
|
||||
// level 0 — photos are already compressed, so deflate only burns CPU.
|
||||
const archive = archiver('zip', { zlib: { level: 0 } });
|
||||
output.on('close', resolve);
|
||||
archive.on('error', reject);
|
||||
archive.pipe(output);
|
||||
|
||||
(async () => {
|
||||
for (let i = 0; i < photos.length; i += 1) {
|
||||
const photo = photos[i];
|
||||
const name = entryNames[i] || `photo-${photo.id}.jpg`;
|
||||
try {
|
||||
const rendered = await renderPhotoForDownload(event, photo, box, watermarkSettings);
|
||||
if (rendered) {
|
||||
archive.append(rendered, { name });
|
||||
} else {
|
||||
const key = resolvePhotoStorageKey(event, photo);
|
||||
if (key) {
|
||||
archive.append(await storage.get(key), { name });
|
||||
} else {
|
||||
archive.file(resolvePhotoFilePath(event, photo), { name });
|
||||
}
|
||||
}
|
||||
appended += 1;
|
||||
appendedIds.push(photo.id);
|
||||
// Progress is coarse (photo count, not bytes) but it is what the
|
||||
// modal needs to show movement on a long build.
|
||||
if (appended % 10 === 0 || appended === photos.length) {
|
||||
// Doubles as the lease heartbeat — see LEASE_TIMEOUT_MS.
|
||||
await db('download_jobs').where({ id })
|
||||
.update({ photo_count: appended, heartbeat_at: new Date().toISOString() });
|
||||
}
|
||||
} catch (err) {
|
||||
logger.warn('Skipping photo in download job', { jobId: id, photoId: photo.id, error: err.message });
|
||||
}
|
||||
}
|
||||
archive.finalize();
|
||||
})().catch(reject);
|
||||
});
|
||||
|
||||
if (appended === 0) {
|
||||
await this._fail(id, 'No photos could be packaged');
|
||||
return;
|
||||
}
|
||||
|
||||
const stat = await fsp.stat(tmpPath);
|
||||
const key = this.jobKey(event.slug, (await db('download_jobs').where({ id }).first()).token);
|
||||
await storage.putFromFile(key, tmpPath);
|
||||
|
||||
await db('download_jobs').where({ id }).update({
|
||||
status: 'ready',
|
||||
zip_path: key,
|
||||
size_bytes: stat.size,
|
||||
photo_count: appended,
|
||||
// Only what actually landed in the zip: a missing/corrupt source is
|
||||
// skipped, and counting it as downloaded would inflate that photo's
|
||||
// stats for a file the guest never received. Kept SEPARATE from
|
||||
// photo_ids, which is the requested set the dedup fingerprint was
|
||||
// computed from — overwriting it would make every job with a skipped
|
||||
// photo fail the delivery fingerprint check.
|
||||
delivered_photo_ids: JSON.stringify(appendedIds),
|
||||
completed_at: new Date().toISOString(),
|
||||
});
|
||||
logger.info('Download job ready', { jobId: id, photos: appended, bytes: stat.size });
|
||||
} catch (err) {
|
||||
logger.error('Download job error', { jobId: id, error: err.message });
|
||||
await this._fail(id, err.message).catch(() => {});
|
||||
} finally {
|
||||
this.running -= 1;
|
||||
if (tmpDir) await fsp.rm(tmpDir, { recursive: true, force: true }).catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fail rows left mid-build by a previous process. Without this they linger
|
||||
* as 'pending'/'building' until the TTL, and although findReusable now skips
|
||||
* them, the client that owns such a token would poll a job that can never
|
||||
* finish. Called once at startup.
|
||||
*/
|
||||
async recoverOrphanedJobs() {
|
||||
// Only rows whose LEASE has expired. A live worker heartbeats while it
|
||||
// builds, so in a multi-replica deployment a rolling restart can't have
|
||||
// one replica fail jobs another is still working on — which a blanket
|
||||
// "fail everything pending" would do.
|
||||
const staleBefore = new Date(Date.now() - LEASE_TIMEOUT_MS).toISOString();
|
||||
const orphaned = await db('download_jobs')
|
||||
.whereIn('status', ['pending', 'building'])
|
||||
.where(function () {
|
||||
this.whereNull('heartbeat_at').orWhere('heartbeat_at', '<', staleBefore);
|
||||
})
|
||||
.update({
|
||||
status: 'failed',
|
||||
error: 'Interrupted by a server restart — please request the download again',
|
||||
completed_at: new Date().toISOString(),
|
||||
});
|
||||
if (orphaned > 0) {
|
||||
logger.info(`Failed ${orphaned} download job(s) orphaned by a restart`);
|
||||
}
|
||||
return orphaned;
|
||||
}
|
||||
|
||||
/** Delete expired jobs and their artifacts. Returns how many were removed. */
|
||||
async sweepExpired() {
|
||||
const now = new Date().toISOString();
|
||||
const expired = await db('download_jobs').where('expires_at', '<=', now);
|
||||
if (expired.length === 0) return 0;
|
||||
|
||||
const storage = getStorage();
|
||||
for (const job of expired) {
|
||||
if (job.zip_path) {
|
||||
await storage.delete(job.zip_path).catch((e) =>
|
||||
logger.warn('Failed deleting download job artifact', { jobId: job.id, error: e.message }));
|
||||
}
|
||||
}
|
||||
await db('download_jobs').whereIn('id', expired.map((j) => j.id)).del();
|
||||
logger.info(`Download job sweep removed ${expired.length} expired job(s)`);
|
||||
return expired.length;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = new DownloadJobService();
|
||||
module.exports.JOB_TTL_MS = JOB_TTL_MS;
|
||||
@@ -0,0 +1,85 @@
|
||||
/**
|
||||
* Download renditions (#858).
|
||||
*
|
||||
* One place that answers "what bytes does this photo ship as for this
|
||||
* download?" — used by the single-photo route, the selected-photos archive,
|
||||
* the cached download-all build, and the custom-resolution job builder.
|
||||
*
|
||||
* The ordering matters and is the whole reason this is centralised: the
|
||||
* watermark is sized relative to its input's width, so it MUST be applied
|
||||
* after the resize. Watermarking the original and then downscaling would
|
||||
* resample the mark and burn CPU on pixels that get thrown away.
|
||||
*
|
||||
* Returns null when the photo needs no transformation at all, which lets
|
||||
* callers stream the original straight from storage instead of buffering it.
|
||||
*/
|
||||
|
||||
const { resolvePhotoStorageKey, resolvePhotoFilePath } = require('./photoResolver');
|
||||
const { withLocalCopy, resizeToBox } = require('./imageProcessor');
|
||||
const watermarkService = require('./watermarkService');
|
||||
const { getStorage } = require('./storage');
|
||||
const fs = require('fs');
|
||||
|
||||
/** Videos have no resize path — they always ship as stored. */
|
||||
function isVideo(photo) {
|
||||
return photo.media_type === 'video'
|
||||
|| (photo.mime_type && String(photo.mime_type).startsWith('video/'));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {object} event
|
||||
* @param {object} photo
|
||||
* @param {object?} box {width,height} or null for original size
|
||||
* @param {object?} watermarkSettings effective settings, or null to skip
|
||||
* @returns {Promise<Buffer|null>} null = serve the stored bytes unchanged
|
||||
*/
|
||||
async function renderPhotoForDownload(event, photo, box, watermarkSettings) {
|
||||
const wantsResize = !!box && !isVideo(photo);
|
||||
const wantsWatermark = !!(watermarkSettings && watermarkSettings.enabled);
|
||||
if (!wantsResize && !wantsWatermark) return null;
|
||||
|
||||
const storageKey = resolvePhotoStorageKey(event, photo);
|
||||
|
||||
const transform = async (localPath) => {
|
||||
// No resize → hand applyWatermark the PATH. Buffer inputs intentionally
|
||||
// bypass its cache, so buffering here would re-run sharp over the
|
||||
// full-size original for every download of an unresized gallery.
|
||||
if (!wantsResize) {
|
||||
return watermarkService.applyWatermark(localPath, watermarkSettings);
|
||||
}
|
||||
const buffer = await resizeToBox(await fs.promises.readFile(localPath), box);
|
||||
return wantsWatermark
|
||||
? watermarkService.applyWatermark(buffer, watermarkSettings)
|
||||
: buffer;
|
||||
};
|
||||
|
||||
// Managed photos live behind the storage abstraction (possibly S3); external
|
||||
// / reference photos are already on a local mount.
|
||||
return storageKey
|
||||
? withLocalCopy(storageKey, transform)
|
||||
: transform(resolvePhotoFilePath(event, photo));
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the effective watermark settings for an event, or null when no
|
||||
* watermark applies. Same global-OR-event rule the download routes already
|
||||
* used, lifted here so the job builder can't drift from it.
|
||||
*/
|
||||
async function resolveWatermarkSettings(event) {
|
||||
const settings = await watermarkService.getWatermarkSettings();
|
||||
const eventEnabled = event.watermark_downloads === true || event.watermark_downloads === 1;
|
||||
const shouldApply = (settings && settings.enabled) || eventEnabled;
|
||||
if (!shouldApply) return null;
|
||||
return {
|
||||
...settings,
|
||||
enabled: true,
|
||||
text: event.watermark_text || settings?.text || 'Protected',
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
renderPhotoForDownload,
|
||||
resolveWatermarkSettings,
|
||||
isVideo,
|
||||
getStorage,
|
||||
};
|
||||
@@ -24,6 +24,8 @@ const watermarkService = require('./watermarkService');
|
||||
const { resolvePhotoStorageKey, resolvePhotoFilePath } = require('./photoResolver');
|
||||
const { getStorage } = require('./storage');
|
||||
const { getUseOriginalFilenames, getZipEntryNames } = require('./downloadFilenameService');
|
||||
const { renderPhotoForDownload } = require('./downloadRendition');
|
||||
const { resolveEventDownloadPolicy } = require('../utils/downloadResolutions');
|
||||
const logger = require('../utils/logger');
|
||||
|
||||
const DEBOUNCE_MS = 5000;
|
||||
@@ -137,6 +139,12 @@ class DownloadZipService {
|
||||
text: event.watermark_text || watermarkSettings?.text || 'Protected',
|
||||
} : null;
|
||||
|
||||
// The cached archive is built AT the gallery's standard resolution
|
||||
// (#858) — 'original' keeps the historical behaviour. Any change to the
|
||||
// standard invalidates this zip via the settings write paths, so a
|
||||
// cached archive always matches the currently configured size.
|
||||
const { standardBox } = await resolveEventDownloadPolicy(event);
|
||||
|
||||
const finalKey = this.getCacheKey(event.slug);
|
||||
|
||||
tmpDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'picpeak-zipbuild-'));
|
||||
@@ -182,26 +190,20 @@ class DownloadZipService {
|
||||
// for external, in which case fall back to resolvePhotoFilePath.
|
||||
const storageKey = resolvePhotoStorageKey(event, photo);
|
||||
|
||||
if (shouldApplyWatermark && effectiveSettings) {
|
||||
try {
|
||||
let sourcePath;
|
||||
if (storageKey) {
|
||||
// Stream the original to a tmp file just long enough for sharp
|
||||
// (watermarkService) to operate on it. Avoids buffering the
|
||||
// entire image in memory for huge originals.
|
||||
sourcePath = path.join(tmpDir, `wm-${crypto.randomBytes(4).toString('hex')}`);
|
||||
await storage.getToFile(storageKey, sourcePath);
|
||||
} else {
|
||||
sourcePath = resolvePhotoFilePath(event, photo);
|
||||
}
|
||||
const buf = await watermarkService.applyWatermark(sourcePath, effectiveSettings);
|
||||
archive.append(buf, { name: archiveName });
|
||||
if (storageKey) {
|
||||
await fsp.unlink(sourcePath).catch(() => {});
|
||||
}
|
||||
} catch (err) {
|
||||
logger.warn('Skipping watermark in pre-zip', { photoId: photo.id, error: err.message });
|
||||
}
|
||||
// Resize to the gallery's standard resolution (#858) and/or
|
||||
// watermark. Returns null when neither applies, so an
|
||||
// original-size unwatermarked gallery still streams straight
|
||||
// from storage with nothing buffered.
|
||||
let rendered = null;
|
||||
try {
|
||||
rendered = await renderPhotoForDownload(event, photo, standardBox, effectiveSettings);
|
||||
} catch (err) {
|
||||
logger.warn('Skipping photo in pre-zip', { photoId: photo.id, error: err.message });
|
||||
continue;
|
||||
}
|
||||
|
||||
if (rendered) {
|
||||
archive.append(rendered, { name: archiveName });
|
||||
} else if (storageKey) {
|
||||
const stream = await storage.get(storageKey);
|
||||
archive.append(stream, { name: archiveName });
|
||||
|
||||
@@ -736,7 +736,75 @@ async function extractCaptureDate(imagePath) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Downscale to fit inside a box, for the download-resolution feature (#858).
|
||||
*
|
||||
* `fit: 'inside'` + `withoutEnlargement` is exactly the "up to" semantic the
|
||||
* requester asked for on #858: the box is a maximum, aspect ratio is kept
|
||||
* (so a 3:2 box leaves a 4:3 photo slightly smaller than the box on one
|
||||
* edge), and an image already smaller than the box is returned untouched
|
||||
* rather than upscaled into mush.
|
||||
*
|
||||
* Takes and returns a Buffer so callers can chain resize → watermark without
|
||||
* a tmp file. Returns the input unchanged when `box` is null ('original').
|
||||
* Never throws: on a corrupt/undecodable source it logs and returns the input,
|
||||
* because failing a download outright is worse than serving the full size.
|
||||
*/
|
||||
async function resizeToBox(inputBuffer, box, options = {}) {
|
||||
if (!box || !box.width || !box.height) return inputBuffer;
|
||||
try {
|
||||
const probe = sharp(inputBuffer, { limitInputPixels: 268402689, failOn: 'none' });
|
||||
const metadata = await probe.metadata();
|
||||
// Already inside the box — hand back the original bytes rather than
|
||||
// re-encoding, which would only cost quality and CPU.
|
||||
if (metadata.width && metadata.height
|
||||
&& metadata.width <= box.width && metadata.height <= box.height) {
|
||||
return inputBuffer;
|
||||
}
|
||||
|
||||
const format = (metadata.format || '').toLowerCase();
|
||||
// Animated sources must be re-opened with `animated: true`, otherwise
|
||||
// sharp keeps only the first frame and the download silently loses its
|
||||
// animation. `.rotate()` would flatten an animated source, so it is
|
||||
// applied only to stills (where EXIF orientation actually exists).
|
||||
const animated = (metadata.pages || 1) > 1;
|
||||
const image = animated
|
||||
? sharp(inputBuffer, { limitInputPixels: 268402689, failOn: 'none', animated: true })
|
||||
: probe.rotate();
|
||||
|
||||
let pipeline = image
|
||||
.resize(box.width, box.height, { fit: 'inside', withoutEnlargement: true });
|
||||
|
||||
// Re-encode in the SOURCE format. The download routes keep the original
|
||||
// filename and mime type, so emitting JPEG for a .gif would ship
|
||||
// mislabelled bytes. GIF is an accepted upload format (multerConfig.photos).
|
||||
//
|
||||
// HEIC/HEIF is the exception: sharp builds generally cannot ENCODE it, and
|
||||
// the browser can't display the original anyway (see originalNeedsPreview
|
||||
// in gallery.js). Rather than emit JPEG bytes under a .heic name, leave
|
||||
// those downloads at original size — correct-but-larger beats
|
||||
// mislabelled-and-broken.
|
||||
if (format === 'heif' || format === 'heic') {
|
||||
return inputBuffer;
|
||||
}
|
||||
if (format === 'png') {
|
||||
pipeline = pipeline.png({ compressionLevel: 6 });
|
||||
} else if (format === 'webp') {
|
||||
pipeline = pipeline.webp({ quality: options.quality || 90 });
|
||||
} else if (format === 'gif') {
|
||||
pipeline = pipeline.gif();
|
||||
} else {
|
||||
pipeline = pipeline.jpeg({ quality: options.quality || 90, mozjpeg: true });
|
||||
}
|
||||
return await pipeline.toBuffer();
|
||||
} catch (e) {
|
||||
logger.warn(`resizeToBox failed (${box.width}x${box.height}), serving original: ${e.message}`);
|
||||
return inputBuffer;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
resizeToBox,
|
||||
generateThumbnail,
|
||||
isThumbnailValid,
|
||||
ensureThumbnail,
|
||||
|
||||
@@ -90,18 +90,29 @@ class WatermarkService {
|
||||
/**
|
||||
* Apply watermark to an image
|
||||
*/
|
||||
/**
|
||||
* `imagePath` may be a path OR an in-memory Buffer (#858). Buffers let the
|
||||
* download paths resize first and watermark second without a second tmp
|
||||
* file — which matters because the mark is sized relative to the input's
|
||||
* own width, so it has to be applied at the OUTPUT size to come out right.
|
||||
*/
|
||||
async applyWatermark(imagePath, settings) {
|
||||
const isBuffer = Buffer.isBuffer(imagePath);
|
||||
try {
|
||||
if (!settings || !settings.enabled) {
|
||||
// Return original image if watermarking is disabled
|
||||
return await fs.readFile(imagePath);
|
||||
return isBuffer ? imagePath : await fs.readFile(imagePath);
|
||||
}
|
||||
|
||||
// Check cache first
|
||||
const cacheKey = `${imagePath}_${JSON.stringify(settings)}`;
|
||||
const cached = this.cache.get(cacheKey);
|
||||
if (cached && Date.now() - cached.timestamp < this.cacheMaxAge) {
|
||||
return cached.buffer;
|
||||
// Check cache first. Buffer inputs are already-resized intermediates:
|
||||
// they have no stable key (hashing megabytes per photo would cost more
|
||||
// than the watermark) and no reuse across requests, so skip the cache.
|
||||
const cacheKey = isBuffer ? null : `${imagePath}_${JSON.stringify(settings)}`;
|
||||
if (cacheKey) {
|
||||
const cached = this.cache.get(cacheKey);
|
||||
if (cached && Date.now() - cached.timestamp < this.cacheMaxAge) {
|
||||
return cached.buffer;
|
||||
}
|
||||
}
|
||||
|
||||
// Load the main image
|
||||
@@ -199,20 +210,24 @@ class WatermarkService {
|
||||
watermarkedBuffer = await watermarkedImage.jpeg({ quality: 100, mozjpeg: true }).toBuffer();
|
||||
}
|
||||
|
||||
// Cache the result
|
||||
this.cache.set(cacheKey, {
|
||||
buffer: watermarkedBuffer,
|
||||
timestamp: Date.now()
|
||||
});
|
||||
// Cache the result (path inputs only — see cacheKey above)
|
||||
if (cacheKey) {
|
||||
this.cache.set(cacheKey, {
|
||||
buffer: watermarkedBuffer,
|
||||
timestamp: Date.now()
|
||||
});
|
||||
|
||||
// Clean old cache entries
|
||||
this.cleanCache();
|
||||
// Clean old cache entries
|
||||
this.cleanCache();
|
||||
}
|
||||
|
||||
return watermarkedBuffer;
|
||||
} catch (error) {
|
||||
logger.error('Error applying watermark:', error);
|
||||
// Return original image on error
|
||||
return await fs.readFile(imagePath);
|
||||
// Return the un-watermarked input on error. Buffer inputs are already
|
||||
// in memory — readFile() would treat the Buffer as a path and throw,
|
||||
// turning a cosmetic watermark failure into a failed download.
|
||||
return isBuffer ? imagePath : await fs.readFile(imagePath);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,176 @@
|
||||
/**
|
||||
* Download resolutions (#858) — global defaults + per-event cascade.
|
||||
*
|
||||
* Two things live here:
|
||||
*
|
||||
* getDownloadGlobals() Cached read of the download_* app_settings.
|
||||
* resolveEventDownloadPolicy() Folds an event row over those globals into
|
||||
* the policy the download routes actually act
|
||||
* on: which size is handed out by default, and
|
||||
* which sizes (if any) a guest may pick from.
|
||||
*
|
||||
* Cascade rule: the per-event columns are NULLABLE and NULL means inherit,
|
||||
* matching the tri-state `show_watermark` / `show_qr` convention. Same TTL +
|
||||
* invalidate-on-write shape as slideshowGlobals — the gallery photo list and
|
||||
* every download hit this, so it must not fan out into N settings reads.
|
||||
*/
|
||||
|
||||
const { getAppSetting } = require('./appSettings');
|
||||
|
||||
const TTL_MS = 5000;
|
||||
let cache = null; // { at, val }
|
||||
|
||||
const ORIGINAL = 'original';
|
||||
|
||||
// Mirrors migration 173's seed. Used when the setting row is missing entirely
|
||||
// (fresh install mid-migration, or an admin who deleted the row).
|
||||
const FALLBACK_PRESETS = [
|
||||
{ label: 'Large', width: 3000, height: 2000 },
|
||||
{ label: 'Medium', width: 1500, height: 1000 },
|
||||
{ label: 'Small', width: 800, height: 600 },
|
||||
];
|
||||
|
||||
/** `{width, height}` → the canonical `'3000x2000'` id used on the wire. */
|
||||
function resolutionId(preset) {
|
||||
return `${preset.width}x${preset.height}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a resolution id back into dimensions. Returns null for 'original',
|
||||
* anything malformed, or non-positive/absurd values — callers treat null as
|
||||
* "serve the original bytes", which is the safe direction: a bad id can only
|
||||
* ever cost fidelity, never leak a larger image than intended.
|
||||
*/
|
||||
function parseResolution(id) {
|
||||
if (!id || id === ORIGINAL) return null;
|
||||
const m = /^(\d{1,5})x(\d{1,5})$/.exec(String(id));
|
||||
if (!m) return null;
|
||||
const width = parseInt(m[1], 10);
|
||||
const height = parseInt(m[2], 10);
|
||||
if (!width || !height) return null;
|
||||
return { width, height };
|
||||
}
|
||||
|
||||
function normalisePresets(raw) {
|
||||
const list = Array.isArray(raw) ? raw : FALLBACK_PRESETS;
|
||||
const seen = new Set();
|
||||
const out = [];
|
||||
for (const p of list) {
|
||||
const width = parseInt(p?.width, 10);
|
||||
const height = parseInt(p?.height, 10);
|
||||
if (!width || !height || width < 1 || height < 1) continue;
|
||||
const id = `${width}x${height}`;
|
||||
if (seen.has(id)) continue;
|
||||
seen.add(id);
|
||||
out.push({ id, label: String(p.label || id), width, height });
|
||||
}
|
||||
// Largest first — the picker reads top-down from best quality.
|
||||
out.sort((a, b) => (b.width * b.height) - (a.width * a.height));
|
||||
return out;
|
||||
}
|
||||
|
||||
async function getDownloadGlobals() {
|
||||
const now = Date.now();
|
||||
if (cache && now - cache.at < TTL_MS) return cache.val;
|
||||
|
||||
const [standard, pickerEnabled, allowOriginal, presets] = await Promise.all([
|
||||
getAppSetting('download_standard_resolution', ORIGINAL),
|
||||
getAppSetting('download_resolution_picker_enabled', false),
|
||||
getAppSetting('download_allow_original', false),
|
||||
getAppSetting('download_resolutions', FALLBACK_PRESETS),
|
||||
]);
|
||||
|
||||
const val = {
|
||||
standard_resolution: typeof standard === 'string' && standard ? standard : ORIGINAL,
|
||||
picker_enabled: pickerEnabled === true,
|
||||
allow_original: allowOriginal === true,
|
||||
resolutions: normalisePresets(presets),
|
||||
};
|
||||
cache = { at: now, val };
|
||||
return val;
|
||||
}
|
||||
|
||||
/** Clear the cache — call after any write to a download_* global. */
|
||||
function invalidateDownloadGlobals() {
|
||||
cache = null;
|
||||
}
|
||||
|
||||
/** NULL/undefined = inherit the global; an explicit value wins. */
|
||||
function inherit(eventValue, globalValue) {
|
||||
if (eventValue === null || eventValue === undefined) return globalValue;
|
||||
return eventValue === true || eventValue === 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* The effective download policy for one event.
|
||||
*
|
||||
* Returns:
|
||||
* standard resolution id handed out by every ordinary download
|
||||
* standardBox {width,height} or null when standard is 'original'
|
||||
* pickerEnabled whether the guest-facing modal is offered at all
|
||||
* choices what the modal may offer, largest first
|
||||
*
|
||||
* `choices` is capped at the standard: a photographer who sets the standard to
|
||||
* 1500x1000 is saying "this gallery hands out 1500px", so the picker must not
|
||||
* quietly hand back something larger. 'Original' re-enters only when the admin
|
||||
* explicitly allows it.
|
||||
*/
|
||||
async function resolveEventDownloadPolicy(event) {
|
||||
const globals = await getDownloadGlobals();
|
||||
|
||||
const standard = (event && event.download_standard_resolution)
|
||||
|| globals.standard_resolution
|
||||
|| ORIGINAL;
|
||||
const standardBox = parseResolution(standard);
|
||||
|
||||
const pickerEnabled = inherit(
|
||||
event ? event.download_resolution_picker_enabled : null,
|
||||
globals.picker_enabled
|
||||
);
|
||||
const allowOriginal = inherit(
|
||||
event ? event.download_allow_original : null,
|
||||
globals.allow_original
|
||||
);
|
||||
|
||||
// Never offer a size above the standard, bounding EACH dimension rather
|
||||
// than the pixel area: with mixed aspect ratios an area comparison lets
|
||||
// e.g. 2000x700 (1.4MP) through under a 1500x1000 (1.5MP) standard, and the
|
||||
// guest then gets a 2000px-wide rendition despite the stated 1500px cap.
|
||||
// When the standard IS original, every preset qualifies.
|
||||
const choices = globals.resolutions.filter((r) => !standardBox
|
||||
|| (r.width <= standardBox.width && r.height <= standardBox.height));
|
||||
|
||||
if (allowOriginal && standardBox) {
|
||||
// The standard is capped but the admin opted into full-res downloads.
|
||||
choices.unshift({ id: ORIGINAL, label: 'Original', width: null, height: null });
|
||||
} else if (!standardBox) {
|
||||
// Standard is already original — it heads the list regardless, otherwise
|
||||
// the picker couldn't offer what the plain download button already gives.
|
||||
choices.unshift({ id: ORIGINAL, label: 'Original', width: null, height: null });
|
||||
}
|
||||
|
||||
return { standard, standardBox, pickerEnabled, allowOriginal, choices };
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate a guest-supplied resolution id against the event's policy.
|
||||
* Returns the resolution id to actually use, or null when the request is not
|
||||
* permitted — routes turn null into a 400 rather than silently downgrading,
|
||||
* so a broken client is visible instead of quietly serving the wrong size.
|
||||
*/
|
||||
function pickRequestedResolution(policy, requested) {
|
||||
if (!requested) return policy.standard;
|
||||
if (!policy.pickerEnabled) return null;
|
||||
const match = policy.choices.find((c) => c.id === requested);
|
||||
return match ? match.id : null;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
ORIGINAL,
|
||||
getDownloadGlobals,
|
||||
invalidateDownloadGlobals,
|
||||
resolveEventDownloadPolicy,
|
||||
pickRequestedResolution,
|
||||
parseResolution,
|
||||
resolutionId,
|
||||
};
|
||||
Reference in New Issue
Block a user