cd52a2f82f
Browser-based photo catalog with an optional team server (SQLite + LibRaw). Local database, uploaded photos, build output and dependencies are gitignored. 🤖 Generated with Codebuff Co-Authored-By: Codebuff <noreply@codebuff.com>
326 lines
9.3 KiB
JavaScript
326 lines
9.3 KiB
JavaScript
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;
|
|
}
|
|
|
|
export function findOriginal(id) {
|
|
const safe = lookupId(id);
|
|
if (!safe) return null;
|
|
const { originals } = dirs();
|
|
const prefix = `${safe}.`;
|
|
for (const name of listFiles(originals)) {
|
|
if (name.startsWith(prefix)) return path.join(originals, name);
|
|
}
|
|
return 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;
|
|
}
|
|
|
|
/**
|
|
* 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 every denoised render for a photo, sparing `keepKey` if given. */
|
|
export function removeDenoised(id, keepKey) {
|
|
const safe = lookupId(id);
|
|
if (!safe) return 0;
|
|
const dir = path.join(storageRoot(), 'denoised');
|
|
const key = keepKey ? String(keepKey).replace(/[^a-z0-9]/gi, '') : null;
|
|
const keep = key ? `${safe}.${key}.jpg` : null;
|
|
let removed = 0;
|
|
for (const name of listFiles(dir)) {
|
|
if (!name.startsWith(`${safe}.`) || name === keep) 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),
|
|
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 };
|
|
}
|