import fs from 'node:fs'; import fsp from 'node:fs/promises'; import path from 'node:path'; import { DATA_DIR } from './config.mjs'; import { kv } from './db.mjs'; /** * Where image files live. The database always stays in DATA_DIR; only the * originals/previews/thumbs folders move when an admin picks another location. */ const SETTINGS_KEY = 'storageRoot'; const SUBDIRS = ['originals', 'previews', 'thumbs', 'proofs', 'proofThumbs', 'denoised']; const SAFE = /^[A-Za-z0-9_-]{1,80}$/; let cachedRoot = null; export function defaultRoot() { return DATA_DIR; } export function storageRoot() { if (cachedRoot) return cachedRoot; const saved = kv.get(SETTINGS_KEY); cachedRoot = typeof saved === 'string' && saved.trim() ? path.resolve(saved) : DATA_DIR; return cachedRoot; } export function isCustomRoot() { return path.resolve(storageRoot()) !== path.resolve(DATA_DIR); } export function dirs(root = storageRoot()) { return { originals: path.join(root, 'originals'), previews: path.join(root, 'previews'), thumbs: path.join(root, 'thumbs'), denoised: path.join(root, 'denoised'), proofs: path.join(root, 'proofs'), proofThumbs: path.join(root, 'proofThumbs'), }; } export function ensureDirs(root = storageRoot()) { for (const dir of Object.values(dirs(root))) fs.mkdirSync(dir, { recursive: true }); } ensureDirs(); function safeId(id) { if (!SAFE.test(id)) throw new Error('Invalid asset id'); return id; } /** * Reads are lookups: a malformed id simply has no file, so it must not throw a * 500 out of the request handler. Writers keep the strict check. */ function lookupId(id) { return typeof id === 'string' && SAFE.test(id) ? id : null; } function listFiles(dir) { try { return fs.readdirSync(dir); } catch { return []; } } /** Original files keep their real extension so a raw can be recovered later. */ function originalPath(id, ext = 'bin') { ensureDirs(); return path.join( storageRoot(), 'originals', `${safeId(id)}.${ext.replace(/[^a-z0-9]/gi, '') || 'bin'}`, ); } export async function writeOriginal(id, ext, data) { const target = originalPath(id, ext); await fsp.writeFile(target, data); return target; } /** Final path for a streamed upload; the caller writes it without buffering. */ export function originalTarget(id, ext = 'bin') { return originalPath(id, ext); } export function findOriginals(id) { const safe = lookupId(id); if (!safe) return []; const { originals } = dirs(); const prefix = `${safe}.`; return listFiles(originals) // An interrupted upload leaves `..part-xxxx` behind; it is not a // usable original, and returning it would serve a truncated image. .filter((name) => name.startsWith(prefix) && !name.includes('.part-')) .map((name) => path.join(originals, name)); } export function findOriginal(id) { return findOriginals(id)[0] ?? null; } export async function writePreview(id, data, ext = 'jpg') { ensureDirs(); const target = path.join(storageRoot(), 'previews', `${safeId(id)}.${ext}`); await fsp.writeFile(target, data); return target; } export function findPreview(id) { const safe = lookupId(id); if (!safe) return null; const { previews } = dirs(); for (const ext of ['jpg', 'png']) { const p = path.join(previews, `${safe}.${ext}`); if (fs.existsSync(p)) return p; } return null; } /** * The 16-bit sidecar for a raw proxy: the samples LibRaw decoded, before the * JPEG quantised them. Its name keeps a second extension so `findPreview` keeps * returning the JPEG for browsers and for photos imported before this existed. */ export async function writePreview16(id, data) { ensureDirs(); const target = path.join(storageRoot(), 'previews', `${safeId(id)}.p16.png`); await fsp.writeFile(target, data); return target; } export function findPreview16(id) { const safe = lookupId(id); if (!safe) return null; const p = path.join(dirs().previews, `${safe}.p16.png`); return fs.existsSync(p) ? p : null; } export async function removePreview16(id) { const found = findPreview16(id); if (found) await fsp.rm(found, { force: true }); } /** * Camera-native grid thumbnail: the sidecar's samples at the JPEG thumbnail's * size, so the grid can honour a per-photo camera profile without downloading * the full sidecar. Lives beside the sidecar and is regenerated on demand. */ export async function writeThumb16(id, data) { ensureDirs(); const target = path.join(storageRoot(), 'previews', `${safeId(id)}.t16.png`); await fsp.writeFile(target, data); return target; } export function findThumb16(id) { const safe = lookupId(id); if (!safe) return null; const p = path.join(dirs().previews, `${safe}.t16.png`); return fs.existsSync(p) ? p : null; } export async function removeThumb16(id) { const found = findThumb16(id); if (found) await fsp.rm(found, { force: true }); } /** * Denoised proxies, keyed by the hash of the parameters that produced them, so * switching Amount back to a previous value reuses the file instead of spending * another few seconds of CPU on an identical result. */ export function denoisedPath(id, key) { ensureDirs(); const safeKey = String(key).replace(/[^a-z0-9]/gi, ''); return path.join(storageRoot(), 'denoised', `${safeId(id)}.${safeKey}.jpg`); } /** With no key, the most recently written result wins. */ export function findDenoised(id, key) { const safe = lookupId(id); if (!safe) return null; const dir = path.join(storageRoot(), 'denoised'); if (key) { const exact = denoisedPath(safe, key); return fs.existsSync(exact) ? exact : null; } const names = listFiles(dir).filter((name) => name.startsWith(`${safe}.`)); if (names.length === 0) return null; names.sort( (a, b) => fs.statSync(path.join(dir, b)).mtimeMs - fs.statSync(path.join(dir, a)).mtimeMs, ); return path.join(dir, names[0]); } /** * Remove denoised renders for a photo, sparing the keys named in `keepKeys`. * A single key is accepted too; with none, every render for the photo goes. */ export function removeDenoised(id, keepKeys) { const safe = lookupId(id); if (!safe) return 0; const dir = path.join(storageRoot(), 'denoised'); const keys = (Array.isArray(keepKeys) ? keepKeys : keepKeys ? [keepKeys] : []) .map((key) => String(key).replace(/[^a-z0-9]/gi, '')) .filter(Boolean); const keep = new Set(keys.map((key) => `${safe}.${key}.jpg`)); let removed = 0; for (const name of listFiles(dir)) { if (!name.startsWith(`${safe}.`) || keep.has(name)) continue; fs.rmSync(path.join(dir, name), { force: true }); removed += 1; } return removed; } export async function writeThumb(id, data) { ensureDirs(); const target = path.join(storageRoot(), 'thumbs', `${safeId(id)}.jpg`); await fsp.writeFile(target, data); return target; } export function findThumb(id) { const safe = lookupId(id); if (!safe) return null; const p = path.join(storageRoot(), 'thumbs', `${safe}.jpg`); return fs.existsSync(p) ? p : null; } /** Rendered proof used by client galleries; separate from the editable proxy. */ export async function writeProof(id, data) { ensureDirs(); const target = path.join(storageRoot(), 'proofs', `${safeId(id)}.jpg`); await fsp.writeFile(target, data); return target; } export function findProof(id) { const safe = lookupId(id); if (!safe) return null; const p = path.join(storageRoot(), 'proofs', `${safe}.jpg`); return fs.existsSync(p) ? p : null; } export async function writeProofThumb(id, data) { ensureDirs(); const target = path.join(storageRoot(), 'proofThumbs', `${safeId(id)}.jpg`); await fsp.writeFile(target, data); return target; } export function findProofThumb(id) { const safe = lookupId(id); if (!safe) return null; const p = path.join(storageRoot(), 'proofThumbs', `${safe}.jpg`); return fs.existsSync(p) ? p : null; } export async function removeAsset(id) { const files = [ findOriginal(id), findPreview(id), findPreview16(id), findThumb16(id), findThumb(id), findProof(id), findProofThumb(id), ]; await Promise.all(files.map((f) => (f ? fsp.rm(f, { force: true }) : Promise.resolve()))); } export function storageBytes(root = storageRoot()) { let total = 0; for (const dir of Object.values(dirs(root))) { for (const name of listFiles(dir)) { try { total += fs.statSync(path.join(dir, name)).size; } catch { /* file vanished mid-scan */ } } } return total; } /** * Validates a destination and proves it is writable before anything moves. * Returns the resolved absolute path. */ export async function checkRoot(input) { if (typeof input !== 'string' || !input.trim()) throw new Error('Enter a folder path'); const raw = input.trim(); if (raw.includes('\0')) throw new Error('That path is not valid'); if (!path.isAbsolute(raw)) throw new Error('Use an absolute path, for example /srv/luminary-photos'); const root = path.resolve(raw); if (root === path.parse(root).root) throw new Error('Pick a folder below the filesystem root'); const existing = await fsp.stat(root).catch(() => null); if (existing && !existing.isDirectory()) throw new Error('That path is a file, not a folder'); await fsp.mkdir(root, { recursive: true }); const probe = path.join(root, `.luminary-write-test-${process.pid}-${Date.now()}`); try { await fsp.writeFile(probe, 'ok'); await fsp.rm(probe, { force: true }); } catch { throw new Error('That folder is not writable by the Luminary server'); } return root; } async function moveTree(from, to, moved) { let files = 0; let bytes = 0; await fsp.mkdir(to, { recursive: true }); for (const name of listFiles(from)) { const src = path.join(from, name); const dst = path.join(to, name); const stat = await fsp.stat(src).catch(() => null); if (!stat || !stat.isFile()) continue; try { await fsp.rename(src, dst); } catch { // Different filesystem (EXDEV) or an existing target: copy over, then drop. await fsp.copyFile(src, dst); await fsp.rm(src, { force: true }); } moved.push([src, dst]); files += 1; bytes += stat.size; } return { files, bytes }; } /** Puts files back where they came from if a relocation fails partway. */ async function rollback(moved) { for (const [src, dst] of [...moved].reverse()) { try { await fsp.rename(dst, src); } catch { try { await fsp.copyFile(dst, src); await fsp.rm(dst, { force: true }); } catch { /* leave the copy in place rather than lose the file */ } } } } /** * Points storage at a new folder, moving every existing image across so the * library keeps working. Returns what moved and what was skipped. */ export async function setStorageRoot(input) { const next = await checkRoot(input); const current = storageRoot(); if (path.resolve(next) === path.resolve(current)) { return { root: current, previous: current, files: 0, bytes: 0, moved: false }; } const from = dirs(current); const to = dirs(next); const moved = []; let files = 0; let bytes = 0; try { for (const kind of SUBDIRS) { const result = await moveTree(from[kind], to[kind], moved); files += result.files; bytes += result.bytes; } } catch { await rollback(moved); throw new Error('Could not move the existing images; the storage folder was left unchanged'); } kv.set(SETTINGS_KEY, next); cachedRoot = next; ensureDirs(); return { root: next, previous: current, files, bytes, moved: true }; }