Initial commit: Luminary photo catalog and RAW editor
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>
This commit is contained in:
@@ -0,0 +1,60 @@
|
||||
import crypto from 'node:crypto';
|
||||
import { SESSION_DAYS } from './config.mjs';
|
||||
import { sessions, users } from './db.mjs';
|
||||
|
||||
const KEYLEN = 64;
|
||||
|
||||
export function hashPassword(password) {
|
||||
const salt = crypto.randomBytes(16);
|
||||
const hash = crypto.scryptSync(password, salt, KEYLEN);
|
||||
return `scrypt$${salt.toString('hex')}$${hash.toString('hex')}`;
|
||||
}
|
||||
|
||||
export function verifyPassword(password, stored) {
|
||||
const [scheme, saltHex, hashHex] = String(stored).split('$');
|
||||
if (scheme !== 'scrypt' || !saltHex || !hashHex) return false;
|
||||
const expected = Buffer.from(hashHex, 'hex');
|
||||
const actual = crypto.scryptSync(password, Buffer.from(saltHex, 'hex'), expected.length);
|
||||
return expected.length === actual.length && crypto.timingSafeEqual(expected, actual);
|
||||
}
|
||||
|
||||
export function createSession(userId) {
|
||||
const token = crypto.randomBytes(32).toString('hex');
|
||||
const expiresAt = Date.now() + SESSION_DAYS * 24 * 60 * 60 * 1000;
|
||||
sessions.purge();
|
||||
sessions.create(token, userId, expiresAt);
|
||||
return token;
|
||||
}
|
||||
|
||||
export function publicUser(row) {
|
||||
if (!row) return null;
|
||||
return {
|
||||
id: row.id,
|
||||
email: row.email,
|
||||
name: row.name ?? '',
|
||||
role: row.role ?? 'member',
|
||||
};
|
||||
}
|
||||
|
||||
export function authenticate(req) {
|
||||
const header = String(req.headers.authorization ?? '');
|
||||
const token = header.startsWith('Bearer ') ? header.slice(7).trim() : '';
|
||||
if (!token) return null;
|
||||
const session = sessions.find(token);
|
||||
if (!session) return null;
|
||||
if (Number(session.expires_at) < Date.now()) {
|
||||
sessions.destroy(token);
|
||||
return null;
|
||||
}
|
||||
const user = users.byId(session.user_id);
|
||||
if (!user || user.disabled) return null;
|
||||
return publicUser(user);
|
||||
}
|
||||
|
||||
export function normalizeEmail(value) {
|
||||
return typeof value === 'string' ? value.trim().toLowerCase() : '';
|
||||
}
|
||||
|
||||
export function validEmail(email) {
|
||||
return /^[^@\s]+@[^@\s]+\.[^@\s]{2,}$/.test(email);
|
||||
}
|
||||
@@ -0,0 +1,265 @@
|
||||
/**
|
||||
* Bridge to the Media Team Hub dashboard.
|
||||
*
|
||||
* The dashboard signs a short-lived token scoped to one event; this module
|
||||
* verifies it, exchanges it for a service token, mirrors the event's photo list
|
||||
* into the local catalog, and proxies bytes/save-backs for as long as the
|
||||
* bridge session lives. Nothing here is reachable without a valid token.
|
||||
*/
|
||||
|
||||
import crypto from 'node:crypto';
|
||||
import { BRIDGE_SECRET, BRIDGE_TTL_HOURS, GLENLOCH_URL } from './config.mjs';
|
||||
import { db, removeEvent, removePhoto, saveEvent, savePhoto } from './db.mjs';
|
||||
import { removeAsset } from './storage.mjs';
|
||||
|
||||
const VERSION = 'g1';
|
||||
|
||||
/* ------------------------------------------------------------------- tokens */
|
||||
|
||||
export function bridgeConfigured() {
|
||||
return Boolean(BRIDGE_SECRET && GLENLOCH_URL);
|
||||
}
|
||||
|
||||
export function verifyBridgeToken(token, now = Date.now()) {
|
||||
if (!BRIDGE_SECRET || typeof token !== 'string') return null;
|
||||
const parts = token.split('.');
|
||||
if (parts.length !== 3 || parts[0] !== VERSION) return null;
|
||||
const [, body, signature] = parts;
|
||||
|
||||
const expected = crypto.createHmac('sha256', BRIDGE_SECRET).update(body).digest();
|
||||
let supplied;
|
||||
try {
|
||||
supplied = Buffer.from(signature.replace(/-/g, '+').replace(/_/g, '/'), 'base64');
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
if (
|
||||
supplied.length !== expected.length ||
|
||||
!crypto.timingSafeEqual(supplied, expected)
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
let payload;
|
||||
try {
|
||||
payload = JSON.parse(Buffer.from(body, 'base64url').toString('utf8'));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
if (
|
||||
!payload ||
|
||||
typeof payload.sid !== 'string' ||
|
||||
typeof payload.eid !== 'string' ||
|
||||
typeof payload.uid !== 'string' ||
|
||||
typeof payload.email !== 'string' ||
|
||||
(payload.kind !== 'login' && payload.kind !== 'service') ||
|
||||
typeof payload.exp !== 'number' ||
|
||||
payload.exp * 1000 <= now
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
return payload;
|
||||
}
|
||||
|
||||
async function dashboardJson(url, token, init = {}) {
|
||||
const res = await fetch(url, {
|
||||
...init,
|
||||
headers: {
|
||||
...(init.headers ?? {}),
|
||||
authorization: `Bearer ${token}`,
|
||||
},
|
||||
});
|
||||
const text = await res.text();
|
||||
let body = null;
|
||||
try {
|
||||
body = text ? JSON.parse(text) : null;
|
||||
} catch {
|
||||
body = null;
|
||||
}
|
||||
if (!res.ok) {
|
||||
throw new Error(body?.error || `Dashboard request failed (${res.status})`);
|
||||
}
|
||||
return body;
|
||||
}
|
||||
|
||||
/** Swap the one browser-hop login token for a longer server-side token. */
|
||||
export async function exchangeBridgeToken(loginToken, sessionId) {
|
||||
return dashboardJson(
|
||||
`${GLENLOCH_URL}/api/bridge/sessions/${encodeURIComponent(sessionId)}/exchange`,
|
||||
loginToken,
|
||||
{ method: 'POST' },
|
||||
);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ storage */
|
||||
|
||||
const bridgeInsert = db.prepare(`
|
||||
INSERT INTO bridge_events (event_id, session_id, token, glenloch_url, source_event_id, return_url, expires_at, created_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(event_id) DO UPDATE SET
|
||||
session_id = excluded.session_id,
|
||||
token = excluded.token,
|
||||
glenloch_url = excluded.glenloch_url,
|
||||
source_event_id = excluded.source_event_id,
|
||||
return_url = excluded.return_url,
|
||||
expires_at = excluded.expires_at,
|
||||
created_at = excluded.created_at
|
||||
`);
|
||||
const bridgeGet = db.prepare('SELECT * FROM bridge_events WHERE event_id = ?');
|
||||
const bridgeExpired = db.prepare('SELECT event_id FROM bridge_events WHERE expires_at < ?');
|
||||
const bridgeDelete = db.prepare('DELETE FROM bridge_events WHERE event_id = ?');
|
||||
const photosForEvent = db.prepare('SELECT id FROM photos WHERE event_id = ?');
|
||||
|
||||
export function bridgeEventId(sourceEventId) {
|
||||
return `br-${sourceEventId}`;
|
||||
}
|
||||
|
||||
export function bridgePhotoId(sourcePhotoId) {
|
||||
return `br-${sourcePhotoId}`;
|
||||
}
|
||||
|
||||
export function bridgeForEvent(eventId) {
|
||||
return bridgeGet.get(eventId) ?? null;
|
||||
}
|
||||
|
||||
/** Deletes an imported event, its rows and any cached previews/thumbnails. */
|
||||
function dropBridgeEvent(eventId) {
|
||||
for (const row of photosForEvent.all(eventId)) {
|
||||
removePhoto(row.id);
|
||||
removeAsset(row.id).catch(() => undefined);
|
||||
}
|
||||
removeEvent(eventId);
|
||||
bridgeDelete.run(eventId);
|
||||
}
|
||||
|
||||
/** Removes events whose bridge session has expired. Safe to call often. */
|
||||
export function purgeExpiredBridges(now = Date.now()) {
|
||||
for (const row of bridgeExpired.all(now)) {
|
||||
dropBridgeEvent(row.event_id);
|
||||
}
|
||||
}
|
||||
|
||||
function eventRecordFrom(listing, eventId, sessionId, returnUrl, expiresAt) {
|
||||
const source = listing.event;
|
||||
return {
|
||||
id: eventId,
|
||||
name: source.title || 'Advanced edit',
|
||||
date: source.startsAt ? Date.parse(source.startsAt) : Date.now(),
|
||||
createdAt: Date.now(),
|
||||
notes: source.description ?? undefined,
|
||||
bridge: {
|
||||
sessionId,
|
||||
sourceEventId: source.id,
|
||||
dashboardUrl: returnUrl ?? `${GLENLOCH_URL}/events/${source.id}`,
|
||||
expiresAt,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function photoRecordFrom(photo, eventId, sessionId, index) {
|
||||
const id = bridgePhotoId(photo.id);
|
||||
const raw = photo.kind === 'raw';
|
||||
return {
|
||||
id,
|
||||
eventId,
|
||||
order: index,
|
||||
name: photo.filename,
|
||||
width: photo.width || 0,
|
||||
height: photo.height || 0,
|
||||
size: photo.sizeBytes || 0,
|
||||
mime: photo.mimeType || 'application/octet-stream',
|
||||
addedAt: Date.now(),
|
||||
takenAt: photo.takenAt ? Date.parse(photo.takenAt) : undefined,
|
||||
meta: {},
|
||||
thumb: '',
|
||||
thumbUrl: `/api/photos/${id}/thumb`,
|
||||
rating: 0,
|
||||
flag: 'none',
|
||||
color: '',
|
||||
keywords: [],
|
||||
edits: {},
|
||||
history: [],
|
||||
raw,
|
||||
previewUrl: raw ? `/api/photos/${id}/preview` : undefined,
|
||||
bridgeSource: { sessionId, sourceId: photo.id },
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Mirrors one event into the local catalog. The photo bytes stay on the
|
||||
* dashboard; only metadata, previews and thumbnails are temporary here.
|
||||
*/
|
||||
export async function importBridgeEvent({ serviceToken, sessionId, ownerId = '' }) {
|
||||
const expiresAt =
|
||||
Date.now() + Math.max(1, BRIDGE_TTL_HOURS) * 60 * 60 * 1000;
|
||||
|
||||
const listing = await dashboardJson(
|
||||
`${GLENLOCH_URL}/api/bridge/sessions/${encodeURIComponent(sessionId)}`,
|
||||
serviceToken,
|
||||
);
|
||||
const eventId = bridgeEventId(listing.event.id);
|
||||
dropBridgeEvent(eventId);
|
||||
|
||||
const returnUrl = listing.editor?.returnUrl ?? null;
|
||||
saveEvent(eventRecordFrom(listing, eventId, sessionId, returnUrl, expiresAt), 0, ownerId);
|
||||
listing.photos.forEach((photo, index) => {
|
||||
savePhoto(photoRecordFrom(photo, eventId, sessionId, index), Date.now(), ownerId);
|
||||
});
|
||||
bridgeInsert.run(
|
||||
eventId,
|
||||
sessionId,
|
||||
serviceToken,
|
||||
GLENLOCH_URL,
|
||||
listing.event.id,
|
||||
returnUrl,
|
||||
expiresAt,
|
||||
Date.now(),
|
||||
);
|
||||
|
||||
return {
|
||||
eventId,
|
||||
photoCount: listing.photos.length,
|
||||
sessionId,
|
||||
expiresAt,
|
||||
};
|
||||
}
|
||||
|
||||
/* ----------------------------------------------------------------- proxying */
|
||||
|
||||
export function bridgeSourceUrl(row, sourcePhotoId, variant) {
|
||||
const params = new URLSearchParams({ variant });
|
||||
return `${row.glenloch_url}/api/bridge/sessions/${encodeURIComponent(
|
||||
row.session_id,
|
||||
)}/photos/${encodeURIComponent(sourcePhotoId)}/source?${params}`;
|
||||
}
|
||||
|
||||
export async function fetchBridgeImage(row, sourcePhotoId, variant) {
|
||||
return fetch(bridgeSourceUrl(row, sourcePhotoId, variant), {
|
||||
headers: { authorization: `Bearer ${row.token}` },
|
||||
});
|
||||
}
|
||||
|
||||
/** Forwards a browser-rendered JPEG and recipe to the dashboard. */
|
||||
export async function forwardBridgeRender(row, sourcePhotoId, payload) {
|
||||
const res = await fetch(
|
||||
`${row.glenloch_url}/api/bridge/sessions/${encodeURIComponent(
|
||||
row.session_id,
|
||||
)}/photos/${encodeURIComponent(sourcePhotoId)}/render`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'content-type': 'application/json',
|
||||
authorization: `Bearer ${row.token}`,
|
||||
},
|
||||
body: JSON.stringify(payload),
|
||||
},
|
||||
);
|
||||
const text = await res.text();
|
||||
let body = null;
|
||||
try {
|
||||
body = text ? JSON.parse(text) : null;
|
||||
} catch {
|
||||
body = null;
|
||||
}
|
||||
return { status: res.status, body };
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const here = path.dirname(fileURLToPath(import.meta.url));
|
||||
|
||||
export const ROOT = path.resolve(here, '..');
|
||||
|
||||
/** Read a Luminary setting, falling back to its pre-rebrand LUMENROOM_ name. */
|
||||
function setting(name, fallback = '') {
|
||||
return process.env[`LUMINARY_${name}`] || process.env[`LUMENROOM_${name}`] || fallback;
|
||||
}
|
||||
|
||||
const dataDir = setting('DATA');
|
||||
export const DATA_DIR = dataDir ? path.resolve(dataDir) : path.join(here, 'data');
|
||||
|
||||
export const ORIGINAL_DIR = path.join(DATA_DIR, 'originals');
|
||||
export const PREVIEW_DIR = path.join(DATA_DIR, 'previews');
|
||||
export const THUMB_DIR = path.join(DATA_DIR, 'thumbs');
|
||||
// Keep the original filename so an existing catalog opens without a migration.
|
||||
export const DB_PATH = path.join(DATA_DIR, 'lumenroom.db');
|
||||
export const DIST_DIR = path.join(ROOT, 'dist');
|
||||
|
||||
export const PORT = Number(process.env.PORT || 8787);
|
||||
export const HOST = process.env.HOST || '0.0.0.0';
|
||||
|
||||
/** Shared invite code required to register after the first account exists. */
|
||||
export const INVITE = setting('INVITE');
|
||||
|
||||
/** Base URL of the dashboard this editor is bridged to, e.g. http://hub:3000. */
|
||||
export const GLENLOCH_URL = (process.env.GLENLOCH_URL || '').replace(/\/+$/, '');
|
||||
|
||||
/** Shared HMAC secret for bridge tokens; must match the dashboard's value. */
|
||||
export const BRIDGE_SECRET = process.env.BRIDGE_SECRET || '';
|
||||
|
||||
/** How long an imported bridge event survives without being reopened. */
|
||||
export const BRIDGE_TTL_HOURS = Number(setting('BRIDGE_TTL_HOURS', '12'));
|
||||
|
||||
/** Upload ceiling in bytes (300 MB default, bigger than any consumer raw). */
|
||||
export const MAX_UPLOAD = Number(setting('MAX_UPLOAD', String(300 * 1024 * 1024)));
|
||||
|
||||
/** Per-account storage allowance. 100 GiB unless the admin changes it. */
|
||||
export const QUOTA_BYTES = Number(setting('QUOTA_BYTES', String(100 * 1024 * 1024 * 1024)));
|
||||
|
||||
/** Fraction of the quota at which the account is warned (0.9 = 90%). */
|
||||
export const QUOTA_WARN_RATIO = Math.min(
|
||||
0.99,
|
||||
Math.max(0.5, Number(setting('QUOTA_WARN_RATIO', '0.9')) || 0.9),
|
||||
);
|
||||
|
||||
/** Scheduled prunes always leave at least this much room below the cap. */
|
||||
export const QUOTA_TARGET_RATIO = Math.min(
|
||||
0.95,
|
||||
Math.max(0.5, Number(setting('QUOTA_TARGET_RATIO', '0.8')) || 0.8),
|
||||
);
|
||||
|
||||
/** Public URL used in notification emails. Empty falls back to localhost. */
|
||||
export const PUBLIC_URL = setting('PUBLIC_URL').replace(/\/+$/, '');
|
||||
|
||||
/** Gmail SMTP defaults; the admin can override these in Administration. */
|
||||
export const SMTP_HOST = setting('SMTP_HOST', 'smtp.gmail.com');
|
||||
export const SMTP_PORT = Number(setting('SMTP_PORT', '465'));
|
||||
export const SMTP_SECURE = setting('SMTP_SECURE', 'true') !== 'false';
|
||||
export const SMTP_USER = setting('SMTP_USER');
|
||||
export const SMTP_APP_PASSWORD = setting('SMTP_APP_PASSWORD');
|
||||
export const SMTP_FROM = setting('SMTP_FROM', SMTP_USER);
|
||||
|
||||
/** Long edge used for the editable proxy of raw files. */
|
||||
export const RAW_PREVIEW_EDGE = Number(setting('RAW_EDGE', '6000'));
|
||||
|
||||
export const SESSION_DAYS = 30;
|
||||
|
||||
/** How many raws decode at once. One core is left for the HTTP server. */
|
||||
export const RAW_WORKERS = Math.max(
|
||||
1,
|
||||
Number(
|
||||
setting(
|
||||
'RAW_WORKERS',
|
||||
String(Math.min(4, Math.max(1, (os.availableParallelism?.() ?? os.cpus().length) - 1))),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
/** Idle decoder workers are disposed after this long to release memory. */
|
||||
export const RAW_IDLE_MS = Number(setting('RAW_IDLE_MS', '90000'));
|
||||
+592
@@ -0,0 +1,592 @@
|
||||
import fs from 'node:fs';
|
||||
import { DatabaseSync } from 'node:sqlite';
|
||||
import { DATA_DIR, DB_PATH } from './config.mjs';
|
||||
|
||||
fs.mkdirSync(DATA_DIR, { recursive: true });
|
||||
|
||||
export const db = new DatabaseSync(DB_PATH);
|
||||
|
||||
db.exec(`
|
||||
PRAGMA journal_mode = WAL;
|
||||
PRAGMA foreign_keys = ON;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id TEXT PRIMARY KEY,
|
||||
email TEXT NOT NULL UNIQUE,
|
||||
name TEXT NOT NULL DEFAULT '',
|
||||
pass_hash TEXT NOT NULL,
|
||||
role TEXT NOT NULL DEFAULT 'member',
|
||||
disabled INTEGER NOT NULL DEFAULT 0,
|
||||
created_at INTEGER NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS sessions (
|
||||
token TEXT PRIMARY KEY,
|
||||
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
created_at INTEGER NOT NULL,
|
||||
expires_at INTEGER NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS events (
|
||||
id TEXT PRIMARY KEY,
|
||||
owner_id TEXT NOT NULL DEFAULT '',
|
||||
sort_index REAL NOT NULL DEFAULT 0,
|
||||
created_at INTEGER NOT NULL,
|
||||
data TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS photos (
|
||||
id TEXT PRIMARY KEY,
|
||||
owner_id TEXT NOT NULL DEFAULT '',
|
||||
event_id TEXT NOT NULL DEFAULT '',
|
||||
sort_index REAL NOT NULL DEFAULT 0,
|
||||
updated_at INTEGER NOT NULL,
|
||||
raw INTEGER NOT NULL DEFAULT 0,
|
||||
data TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS photos_event ON photos(event_id);
|
||||
CREATE INDEX IF NOT EXISTS photos_updated ON photos(updated_at);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS kv (
|
||||
key TEXT PRIMARY KEY,
|
||||
value TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS gallery_picks (
|
||||
token TEXT NOT NULL,
|
||||
photo_id TEXT NOT NULL,
|
||||
client_id TEXT NOT NULL,
|
||||
client_name TEXT NOT NULL DEFAULT '',
|
||||
picked INTEGER NOT NULL DEFAULT 1,
|
||||
updated_at INTEGER NOT NULL,
|
||||
PRIMARY KEY (token, photo_id, client_id)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS gallery_picks_token ON gallery_picks(token);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS gallery_comments (
|
||||
id TEXT PRIMARY KEY,
|
||||
token TEXT NOT NULL,
|
||||
photo_id TEXT NOT NULL,
|
||||
client_id TEXT NOT NULL,
|
||||
client_name TEXT NOT NULL DEFAULT '',
|
||||
body TEXT NOT NULL,
|
||||
created_at INTEGER NOT NULL
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS gallery_comments_token ON gallery_comments(token);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS gallery_reviews (
|
||||
token TEXT NOT NULL,
|
||||
photo_id TEXT NOT NULL,
|
||||
client_id TEXT NOT NULL,
|
||||
client_name TEXT NOT NULL DEFAULT '',
|
||||
status TEXT NOT NULL,
|
||||
updated_at INTEGER NOT NULL,
|
||||
PRIMARY KEY (token, photo_id, client_id)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS gallery_reviews_token ON gallery_reviews(token);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS invites (
|
||||
token TEXT PRIMARY KEY,
|
||||
email TEXT NOT NULL DEFAULT '',
|
||||
role TEXT NOT NULL DEFAULT 'member',
|
||||
created_by TEXT NOT NULL DEFAULT '',
|
||||
created_at INTEGER NOT NULL,
|
||||
expires_at INTEGER NOT NULL,
|
||||
accepted_at INTEGER,
|
||||
accepted_by TEXT,
|
||||
revoked_at INTEGER
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS invites_created ON invites(created_at);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS bridge_events (
|
||||
event_id TEXT PRIMARY KEY,
|
||||
session_id TEXT NOT NULL,
|
||||
token TEXT NOT NULL,
|
||||
glenloch_url TEXT NOT NULL,
|
||||
source_event_id TEXT NOT NULL,
|
||||
return_url TEXT,
|
||||
expires_at INTEGER NOT NULL,
|
||||
created_at INTEGER NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS user_quota (
|
||||
user_id TEXT PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE,
|
||||
bytes_limit INTEGER NOT NULL DEFAULT 100 * 1024 * 1024 * 1024,
|
||||
prune_at INTEGER,
|
||||
prune_plan TEXT,
|
||||
prune_notified_at INTEGER,
|
||||
last_quota_email_at INTEGER
|
||||
);
|
||||
`);
|
||||
|
||||
/* Databases created before account disabling existed get the column in place. */
|
||||
const userColumns = db.prepare('PRAGMA table_info(users)').all().map((c) => c.name);
|
||||
if (!userColumns.includes('disabled')) {
|
||||
db.exec('ALTER TABLE users ADD COLUMN disabled INTEGER NOT NULL DEFAULT 0');
|
||||
}
|
||||
|
||||
/* Quota rows created before scheduled-prune plans were stored need the columns. */
|
||||
const quotaColumns = db.prepare('PRAGMA table_info(user_quota)').all().map((c) => c.name);
|
||||
if (!quotaColumns.includes('prune_plan')) {
|
||||
db.exec('ALTER TABLE user_quota ADD COLUMN prune_plan TEXT');
|
||||
}
|
||||
if (!quotaColumns.includes('prune_notified_at')) {
|
||||
db.exec('ALTER TABLE user_quota ADD COLUMN prune_notified_at INTEGER');
|
||||
}
|
||||
|
||||
/**
|
||||
* Workspaces arrived after the first shared library. Existing events and photos
|
||||
* are handed to the oldest account (the admin who created them) once; new rows
|
||||
* always carry the account that uploaded them.
|
||||
*/
|
||||
for (const table of ['events', 'photos']) {
|
||||
const columns = db.prepare(`PRAGMA table_info(${table})`).all().map((c) => c.name);
|
||||
if (columns.includes('owner_id')) continue;
|
||||
db.exec(`ALTER TABLE ${table} ADD COLUMN owner_id TEXT NOT NULL DEFAULT ''`);
|
||||
db.exec(`CREATE INDEX IF NOT EXISTS ${table}_owner ON ${table}(owner_id)`);
|
||||
db.exec(
|
||||
`UPDATE ${table} SET owner_id = COALESCE((SELECT id FROM users ORDER BY created_at ASC LIMIT 1), '') WHERE owner_id = ''`,
|
||||
);
|
||||
}
|
||||
|
||||
/* Proofing links arrived after the first release: events carry their token,
|
||||
and every client pick is stored against that token. */
|
||||
const eventColumns = db.prepare('PRAGMA table_info(events)').all().map((c) => c.name);
|
||||
if (!eventColumns.includes('share_token')) {
|
||||
db.exec('ALTER TABLE events ADD COLUMN share_token TEXT');
|
||||
}
|
||||
db.exec('CREATE UNIQUE INDEX IF NOT EXISTS events_share_token ON events(share_token)');
|
||||
|
||||
const q = {
|
||||
upsertEvent: db.prepare(`
|
||||
INSERT INTO events (id, owner_id, sort_index, created_at, data) VALUES (?, ?, ?, ?, ?)
|
||||
ON CONFLICT(id) DO UPDATE SET
|
||||
sort_index = excluded.sort_index,
|
||||
data = excluded.data,
|
||||
owner_id = events.owner_id
|
||||
`),
|
||||
deleteEvent: db.prepare('DELETE FROM events WHERE id = ?'),
|
||||
allEvents: db.prepare('SELECT data FROM events ORDER BY sort_index ASC, created_at ASC'),
|
||||
allEventsByOwner: db.prepare(
|
||||
'SELECT data FROM events WHERE owner_id = ? ORDER BY sort_index ASC, created_at ASC',
|
||||
),
|
||||
eventOwner: db.prepare('SELECT owner_id FROM events WHERE id = ?'),
|
||||
eventByShare: db.prepare('SELECT id, owner_id, data FROM events WHERE share_token = ?'),
|
||||
shareTokenFor: db.prepare('SELECT share_token FROM events WHERE id = ?'),
|
||||
setShareToken: db.prepare('UPDATE events SET share_token = ? WHERE id = ?'),
|
||||
clearPicks: db.prepare('DELETE FROM gallery_picks WHERE token = ?'),
|
||||
clearComments: db.prepare('DELETE FROM gallery_comments WHERE token = ?'),
|
||||
clearReviews: db.prepare('DELETE FROM gallery_reviews WHERE token = ?'),
|
||||
commentsByToken: db.prepare(
|
||||
'SELECT id, photo_id, client_id, client_name, body, created_at FROM gallery_comments WHERE token = ? ORDER BY created_at ASC',
|
||||
),
|
||||
commentsByOwner: db.prepare(`
|
||||
SELECT e.id AS event_id, c.photo_id, c.client_name, c.body, c.created_at
|
||||
FROM gallery_comments c JOIN events e ON e.share_token = c.token
|
||||
WHERE e.owner_id = ? ORDER BY c.created_at ASC
|
||||
`),
|
||||
insertComment: db.prepare(`
|
||||
INSERT INTO gallery_comments (id, token, photo_id, client_id, client_name, body, created_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)
|
||||
`),
|
||||
deleteCommentsForPhoto: db.prepare('DELETE FROM gallery_comments WHERE photo_id = ?'),
|
||||
reviewsByToken: db.prepare(
|
||||
'SELECT photo_id, client_id, client_name, status, updated_at FROM gallery_reviews WHERE token = ?',
|
||||
),
|
||||
reviewsByOwner: db.prepare(`
|
||||
SELECT e.id AS event_id, r.photo_id, r.client_name, r.status, r.updated_at
|
||||
FROM gallery_reviews r JOIN events e ON e.share_token = r.token
|
||||
WHERE e.owner_id = ?
|
||||
`),
|
||||
upsertReview: db.prepare(`
|
||||
INSERT INTO gallery_reviews (token, photo_id, client_id, client_name, status, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(token, photo_id, client_id) DO UPDATE SET
|
||||
client_name = excluded.client_name,
|
||||
status = excluded.status,
|
||||
updated_at = excluded.updated_at
|
||||
`),
|
||||
deleteReview: db.prepare('DELETE FROM gallery_reviews WHERE token = ? AND photo_id = ? AND client_id = ?'),
|
||||
deleteReviewsForPhoto: db.prepare('DELETE FROM gallery_reviews WHERE photo_id = ?'),
|
||||
picksByToken: db.prepare(
|
||||
'SELECT photo_id, client_id, client_name, picked, updated_at FROM gallery_picks WHERE token = ?',
|
||||
),
|
||||
picksByOwner: db.prepare(`
|
||||
SELECT e.id AS event_id, p.photo_id, p.client_id, p.client_name, p.picked, p.updated_at
|
||||
FROM gallery_picks p JOIN events e ON e.share_token = p.token
|
||||
WHERE e.owner_id = ?
|
||||
`),
|
||||
upsertPick: db.prepare(`
|
||||
INSERT INTO gallery_picks (token, photo_id, client_id, client_name, picked, updated_at)
|
||||
VALUES (?, ?, ?, ?, 1, ?)
|
||||
ON CONFLICT(token, photo_id, client_id) DO UPDATE SET
|
||||
client_name = excluded.client_name,
|
||||
picked = 1,
|
||||
updated_at = excluded.updated_at
|
||||
`),
|
||||
deletePick: db.prepare('DELETE FROM gallery_picks WHERE token = ? AND photo_id = ? AND client_id = ?'),
|
||||
deletePicksForPhoto: db.prepare('DELETE FROM gallery_picks WHERE photo_id = ?'),
|
||||
|
||||
upsertPhoto: db.prepare(`
|
||||
INSERT INTO photos (id, owner_id, event_id, sort_index, updated_at, raw, data) VALUES (?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(id) DO UPDATE SET
|
||||
event_id = excluded.event_id,
|
||||
sort_index = excluded.sort_index,
|
||||
updated_at = excluded.updated_at,
|
||||
raw = excluded.raw,
|
||||
data = excluded.data,
|
||||
owner_id = photos.owner_id
|
||||
`),
|
||||
deletedPhotoBytes: db.prepare(
|
||||
`SELECT COALESCE(SUM(json_extract(data, '$.size')), 0) AS bytes
|
||||
FROM photos WHERE owner_id = ? AND json_extract(data, '$.deletedAt') IS NOT NULL`,
|
||||
),
|
||||
deletePhoto: db.prepare('DELETE FROM photos WHERE id = ?'),
|
||||
allPhotos: db.prepare('SELECT data FROM photos ORDER BY sort_index ASC, updated_at ASC'),
|
||||
allPhotosByOwner: db.prepare(
|
||||
'SELECT data FROM photos WHERE owner_id = ? ORDER BY sort_index ASC, updated_at ASC',
|
||||
),
|
||||
photoOwner: db.prepare('SELECT owner_id FROM photos WHERE id = ?'),
|
||||
photo: db.prepare('SELECT data FROM photos WHERE id = ?'),
|
||||
photoCount: db.prepare('SELECT COUNT(*) AS n FROM photos'),
|
||||
|
||||
findUserByEmail: db.prepare('SELECT * FROM users WHERE email = ?'),
|
||||
insertUser: db.prepare(
|
||||
'INSERT INTO users (id, email, name, pass_hash, role, created_at) VALUES (?, ?, ?, ?, ?, ?)',
|
||||
),
|
||||
userCount: db.prepare('SELECT COUNT(*) AS n FROM users'),
|
||||
findUserById: db.prepare('SELECT id, email, name, role, disabled, created_at FROM users WHERE id = ?'),
|
||||
allUsers: db.prepare(
|
||||
'SELECT id, email, name, role, disabled, created_at FROM users ORDER BY created_at ASC',
|
||||
),
|
||||
activeAdmins: db.prepare("SELECT COUNT(*) AS n FROM users WHERE role = 'admin' AND disabled = 0"),
|
||||
setUserName: db.prepare('UPDATE users SET name = ? WHERE id = ?'),
|
||||
setUserRole: db.prepare('UPDATE users SET role = ? WHERE id = ?'),
|
||||
setUserDisabled: db.prepare('UPDATE users SET disabled = ? WHERE id = ?'),
|
||||
setUserPassword: db.prepare('UPDATE users SET pass_hash = ? WHERE id = ?'),
|
||||
deleteUser: db.prepare('DELETE FROM users WHERE id = ?'),
|
||||
quotaForUser: db.prepare(
|
||||
'SELECT user_id, bytes_limit, prune_at, prune_plan, prune_notified_at, last_quota_email_at FROM user_quota WHERE user_id = ?',
|
||||
),
|
||||
upsertQuota: db.prepare(`
|
||||
INSERT INTO user_quota (user_id, bytes_limit, prune_at, prune_plan, prune_notified_at, last_quota_email_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(user_id) DO UPDATE SET
|
||||
bytes_limit = excluded.bytes_limit,
|
||||
prune_at = excluded.prune_at,
|
||||
prune_plan = excluded.prune_plan,
|
||||
prune_notified_at = excluded.prune_notified_at,
|
||||
last_quota_email_at = excluded.last_quota_email_at
|
||||
`),
|
||||
photoIdsByEvent: db.prepare('SELECT id FROM photos WHERE event_id = ?'),
|
||||
// Trashed photos are excluded everywhere a library total is shown: a photo in
|
||||
// the trash is no longer part of the shoot, and its bytes are freed when the
|
||||
// trash is emptied.
|
||||
eventTotals: db.prepare(`
|
||||
SELECT event_id, COUNT(*) AS n, COALESCE(SUM(json_extract(data, '$.size')), 0) AS bytes
|
||||
FROM photos
|
||||
WHERE json_extract(data, '$.deletedAt') IS NULL
|
||||
GROUP BY event_id
|
||||
`),
|
||||
livePhotoCount: db.prepare(
|
||||
"SELECT COUNT(*) AS n FROM photos WHERE json_extract(data, '$.deletedAt') IS NULL",
|
||||
),
|
||||
livePhotoBytes: db.prepare(`
|
||||
SELECT COALESCE(SUM(json_extract(data, '$.size')), 0) AS bytes
|
||||
FROM photos WHERE json_extract(data, '$.deletedAt') IS NULL
|
||||
`),
|
||||
livePhotoBytesByOwner: db.prepare(`
|
||||
SELECT COALESCE(SUM(json_extract(data, '$.size')), 0) AS bytes
|
||||
FROM photos WHERE owner_id = ? AND json_extract(data, '$.deletedAt') IS NULL
|
||||
`),
|
||||
allQuotas: db.prepare('SELECT * FROM user_quota'),
|
||||
|
||||
insertSession: db.prepare(
|
||||
'INSERT INTO sessions (token, user_id, created_at, expires_at) VALUES (?, ?, ?, ?)',
|
||||
),
|
||||
findSession: db.prepare('SELECT * FROM sessions WHERE token = ?'),
|
||||
deleteSession: db.prepare('DELETE FROM sessions WHERE token = ?'),
|
||||
deleteUserSessions: db.prepare('DELETE FROM sessions WHERE user_id = ?'),
|
||||
purgeSessions: db.prepare('DELETE FROM sessions WHERE expires_at < ?'),
|
||||
|
||||
insertInvite: db.prepare(`
|
||||
INSERT INTO invites (token, email, role, created_by, created_at, expires_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?)
|
||||
`),
|
||||
findInvite: db.prepare('SELECT * FROM invites WHERE token = ?'),
|
||||
allInvites: db.prepare('SELECT * FROM invites ORDER BY created_at DESC LIMIT 100'),
|
||||
revokeInvite: db.prepare(
|
||||
'UPDATE invites SET revoked_at = ? WHERE token = ? AND accepted_at IS NULL AND revoked_at IS NULL',
|
||||
),
|
||||
acceptInvite: db.prepare(`
|
||||
UPDATE invites SET accepted_at = ?, accepted_by = ?
|
||||
WHERE token = ? AND accepted_at IS NULL AND revoked_at IS NULL AND expires_at > ?
|
||||
`),
|
||||
pendingInvites: db.prepare(
|
||||
'SELECT COUNT(*) AS n FROM invites WHERE accepted_at IS NULL AND revoked_at IS NULL AND expires_at > ?',
|
||||
),
|
||||
|
||||
kvGet: db.prepare('SELECT value FROM kv WHERE key = ?'),
|
||||
kvSet: db.prepare(
|
||||
'INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value',
|
||||
),
|
||||
};
|
||||
|
||||
function parse(json) {
|
||||
if (!json) return null;
|
||||
try {
|
||||
return JSON.parse(json);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function listEvents(ownerId = null) {
|
||||
const rows = ownerId ? q.allEventsByOwner.all(ownerId) : q.allEvents.all();
|
||||
return rows.map((r) => parse(r.data)).filter((r) => r !== null);
|
||||
}
|
||||
|
||||
export function eventOwner(id) {
|
||||
return q.eventOwner.get(id)?.owner_id ?? null;
|
||||
}
|
||||
|
||||
export function saveEvent(record, sortIndex = 0, ownerId = '') {
|
||||
q.upsertEvent.run(record.id, ownerId, sortIndex, record.createdAt ?? Date.now(), JSON.stringify(record));
|
||||
}
|
||||
|
||||
export function removeEvent(id) {
|
||||
q.deleteEvent.run(id);
|
||||
}
|
||||
|
||||
export function shareTokenFor(id) {
|
||||
return q.shareTokenFor.get(id)?.share_token ?? null;
|
||||
}
|
||||
|
||||
export function eventByShareToken(token) {
|
||||
const row = q.eventByShare.get(token);
|
||||
if (!row) return null;
|
||||
const record = parse(row.data);
|
||||
if (!record) return null;
|
||||
return { id: row.id, ownerId: row.owner_id, event: record };
|
||||
}
|
||||
|
||||
/** Sets or clears the event's token; revoking also drops the picks made with it. */
|
||||
export function setShareToken(id, token) {
|
||||
const previous = shareTokenFor(id);
|
||||
q.setShareToken.run(token, id);
|
||||
if (token === null && previous) {
|
||||
q.clearPicks.run(previous);
|
||||
q.clearComments.run(previous);
|
||||
q.clearReviews.run(previous);
|
||||
}
|
||||
return token;
|
||||
}
|
||||
|
||||
export function picksForToken(token) {
|
||||
return q.picksByToken.all(token).map((row) => ({
|
||||
photoId: row.photo_id,
|
||||
clientId: row.client_id,
|
||||
clientName: row.client_name,
|
||||
picked: Boolean(row.picked),
|
||||
updatedAt: row.updated_at,
|
||||
}));
|
||||
}
|
||||
|
||||
export function picksByOwner(ownerId) {
|
||||
return q.picksByOwner.all(ownerId).map((row) => ({
|
||||
eventId: row.event_id,
|
||||
photoId: row.photo_id,
|
||||
clientId: row.client_id,
|
||||
clientName: row.client_name,
|
||||
picked: Boolean(row.picked),
|
||||
updatedAt: row.updated_at,
|
||||
}));
|
||||
}
|
||||
|
||||
export function galleryPick(token, photoId, clientId, clientName, picked) {
|
||||
if (!picked) {
|
||||
q.deletePick.run(token, photoId, clientId);
|
||||
return;
|
||||
}
|
||||
q.upsertPick.run(token, photoId, clientId, clientName, Date.now());
|
||||
}
|
||||
|
||||
export function commentsForToken(token) {
|
||||
return q.commentsByToken.all(token).map((row) => ({
|
||||
id: row.id,
|
||||
photoId: row.photo_id,
|
||||
clientId: row.client_id,
|
||||
clientName: row.client_name,
|
||||
body: row.body,
|
||||
createdAt: row.created_at,
|
||||
}));
|
||||
}
|
||||
|
||||
export function commentsByOwner(ownerId) {
|
||||
return q.commentsByOwner.all(ownerId).map((row) => ({
|
||||
eventId: row.event_id,
|
||||
photoId: row.photo_id,
|
||||
clientName: row.client_name,
|
||||
body: row.body,
|
||||
createdAt: row.created_at,
|
||||
}));
|
||||
}
|
||||
|
||||
export function addGalleryComment({ id, token, photoId, clientId, clientName, body }) {
|
||||
q.insertComment.run(id, token, photoId, clientId, clientName, body, Date.now());
|
||||
}
|
||||
|
||||
export function reviewsForToken(token) {
|
||||
return q.reviewsByToken.all(token).map((row) => ({
|
||||
photoId: row.photo_id,
|
||||
clientId: row.client_id,
|
||||
clientName: row.client_name,
|
||||
status: row.status,
|
||||
updatedAt: row.updated_at,
|
||||
}));
|
||||
}
|
||||
|
||||
export function reviewsByOwner(ownerId) {
|
||||
return q.reviewsByOwner.all(ownerId).map((row) => ({
|
||||
eventId: row.event_id,
|
||||
photoId: row.photo_id,
|
||||
clientName: row.client_name,
|
||||
status: row.status,
|
||||
updatedAt: row.updated_at,
|
||||
}));
|
||||
}
|
||||
|
||||
export function setGalleryReview({ token, photoId, clientId, clientName, status }) {
|
||||
if (!status || status === 'none') {
|
||||
q.deleteReview.run(token, photoId, clientId);
|
||||
return;
|
||||
}
|
||||
q.upsertReview.run(token, photoId, clientId, clientName, status, Date.now());
|
||||
}
|
||||
|
||||
export function listPhotos(ownerId = null) {
|
||||
const rows = ownerId ? q.allPhotosByOwner.all(ownerId) : q.allPhotos.all();
|
||||
return rows.map((r) => parse(r.data)).filter((r) => r !== null);
|
||||
}
|
||||
|
||||
export function getPhoto(id) {
|
||||
const row = q.photo.get(id);
|
||||
return row ? parse(row.data) : null;
|
||||
}
|
||||
|
||||
export function photoOwner(id) {
|
||||
return q.photoOwner.get(id)?.owner_id ?? null;
|
||||
}
|
||||
|
||||
export function savePhoto(record, updatedAt = Date.now(), ownerId = '') {
|
||||
q.upsertPhoto.run(
|
||||
record.id,
|
||||
ownerId,
|
||||
record.eventId ?? '',
|
||||
typeof record.order === 'number' ? record.order : 0,
|
||||
updatedAt,
|
||||
record.raw ? 1 : 0,
|
||||
JSON.stringify(record),
|
||||
);
|
||||
}
|
||||
|
||||
export function removePhoto(id) {
|
||||
q.deletePhoto.run(id);
|
||||
// A permanently deleted photo must not keep client feedback alive anywhere.
|
||||
q.deletePicksForPhoto.run(id);
|
||||
q.deleteCommentsForPhoto.run(id);
|
||||
q.deleteReviewsForPhoto.run(id);
|
||||
}
|
||||
|
||||
export function countPhotos() {
|
||||
return Number(q.livePhotoCount.get()?.n ?? 0);
|
||||
}
|
||||
|
||||
/** Bytes of live photo records, excluding anything sitting in the trash. */
|
||||
export function livePhotoBytes() {
|
||||
return Number(q.livePhotoBytes.get()?.bytes ?? 0);
|
||||
}
|
||||
|
||||
/** Bytes of an account's photos that are sitting in the trash. */
|
||||
export function deletedPhotoBytes(ownerId) {
|
||||
return Number(q.deletedPhotoBytes.get(ownerId)?.bytes ?? 0);
|
||||
}
|
||||
|
||||
export function livePhotoBytesByOwner(ownerId) {
|
||||
const row = q.livePhotoBytesByOwner.get(ownerId);
|
||||
return Number(row?.bytes ?? 0);
|
||||
}
|
||||
|
||||
export function quotaRow(userId) {
|
||||
return q.quotaForUser.get(userId) ?? null;
|
||||
}
|
||||
|
||||
export function saveQuota(userId, patch = {}) {
|
||||
const row = quotaRow(userId);
|
||||
q.upsertQuota.run(
|
||||
userId,
|
||||
patch.bytesLimit ?? row?.bytes_limit ?? 100 * 1024 * 1024 * 1024,
|
||||
patch.pruneAt !== undefined ? patch.pruneAt : (row?.prune_at ?? null),
|
||||
patch.prunePlan !== undefined
|
||||
? (patch.prunePlan === null ? null : JSON.stringify(patch.prunePlan))
|
||||
: (row?.prune_plan ?? null),
|
||||
patch.pruneNotifiedAt !== undefined ? patch.pruneNotifiedAt : (row?.prune_notified_at ?? null),
|
||||
patch.lastQuotaEmailAt !== undefined ? patch.lastQuotaEmailAt : (row?.last_quota_email_at ?? null),
|
||||
);
|
||||
return quotaRow(userId);
|
||||
}
|
||||
|
||||
export function allQuotaRows() {
|
||||
return q.allQuotas.all();
|
||||
}
|
||||
|
||||
export const users = {
|
||||
count: () => Number(q.userCount.get()?.n ?? 0),
|
||||
byEmail: (email) => q.findUserByEmail.get(String(email).toLowerCase()),
|
||||
byId: (id) => q.findUserById.get(id),
|
||||
list: () => q.allUsers.all().map((row) => ({ ...row, disabled: Boolean(row.disabled) })),
|
||||
activeAdmins: () => Number(q.activeAdmins.get()?.n ?? 0),
|
||||
create: (user) =>
|
||||
q.insertUser.run(user.id, user.email.toLowerCase(), user.name, user.passHash, user.role, Date.now()),
|
||||
update: (id, patch) => {
|
||||
if (typeof patch.name === 'string') q.setUserName.run(patch.name, id);
|
||||
if (typeof patch.role === 'string') q.setUserRole.run(patch.role, id);
|
||||
if (typeof patch.disabled === 'boolean') q.setUserDisabled.run(patch.disabled ? 1 : 0, id);
|
||||
if (typeof patch.passHash === 'string') q.setUserPassword.run(patch.passHash, id);
|
||||
return q.findUserById.get(id);
|
||||
},
|
||||
remove: (id) => q.deleteUser.run(id),
|
||||
photoIdsByEvent: (eventId) => q.photoIdsByEvent.all(eventId).map((row) => row.id),
|
||||
eventTotals: () => q.eventTotals.all(),
|
||||
};
|
||||
|
||||
export const invites = {
|
||||
create: ({ token, email, role, createdBy, expiresAt }) =>
|
||||
q.insertInvite.run(token, email, role, createdBy, Date.now(), expiresAt),
|
||||
byToken: (token) => q.findInvite.get(token) ?? null,
|
||||
all: () => q.allInvites.all(),
|
||||
pendingCount: () => Number(q.pendingInvites.get(Date.now())?.n ?? 0),
|
||||
revoke: (token) => q.revokeInvite.run(Date.now(), token).changes > 0,
|
||||
accept: (token, userId) => q.acceptInvite.run(Date.now(), userId, token, Date.now()).changes > 0,
|
||||
};
|
||||
|
||||
export const sessions = {
|
||||
create: (token, userId, expiresAt) => q.insertSession.run(token, userId, Date.now(), expiresAt),
|
||||
find: (token) => q.findSession.get(token),
|
||||
destroy: (token) => q.deleteSession.run(token),
|
||||
destroyForUser: (userId) => q.deleteUserSessions.run(userId),
|
||||
purge: () => q.purgeSessions.run(Date.now()),
|
||||
};
|
||||
|
||||
export const kv = {
|
||||
get: (key) => {
|
||||
const row = q.kvGet.get(key);
|
||||
return row ? parse(row.value) : null;
|
||||
},
|
||||
set: (key, value) => q.kvSet.run(key, JSON.stringify(value)),
|
||||
};
|
||||
@@ -0,0 +1,62 @@
|
||||
/**
|
||||
* Denoise one proxy. Runs in a worker thread: this is seconds of solid CPU and
|
||||
* the request thread is also serving the rest of the library.
|
||||
*
|
||||
* The proxy is decoded rather than the raw file, deliberately -- these are the
|
||||
* exact pixels the editor edits, so the result lines up with the canvas and with
|
||||
* the client's export path.
|
||||
*/
|
||||
import { parentPort, workerData } from 'node:worker_threads';
|
||||
import fs from 'node:fs/promises';
|
||||
import sharp from 'sharp';
|
||||
import { denoiseRgb } from './denoise/rgbPipeline.ts';
|
||||
import { guidedDenoiser } from './denoise/standin.ts';
|
||||
|
||||
try {
|
||||
const { sourcePath, outPath } = workerData;
|
||||
const buffer = await fs.readFile(sourcePath);
|
||||
const { data, info } = await sharp(buffer)
|
||||
.rotate()
|
||||
.toColourspace('srgb')
|
||||
.removeAlpha()
|
||||
.raw()
|
||||
.toBuffer({ resolveWithObject: true });
|
||||
|
||||
const { width, height, channels } = info;
|
||||
const rgb = new Uint8Array(width * height * 3);
|
||||
if (channels === 3) {
|
||||
rgb.set(data);
|
||||
} else {
|
||||
for (let i = 0; i < width * height; i++) {
|
||||
const s = i * channels;
|
||||
rgb[i * 3] = data[s];
|
||||
rgb[i * 3 + 1] = data[Math.min(s + 1, s + channels - 1)];
|
||||
rgb[i * 3 + 2] = data[Math.min(s + 2, s + channels - 1)];
|
||||
}
|
||||
}
|
||||
|
||||
const started = performance.now();
|
||||
// Always full strength: the Amount slider blends on the client, so one render
|
||||
// serves every setting and the cache key does not move with the slider.
|
||||
const out = await denoiseRgb({ rgb, width, height }, { amount: 1 }, guidedDenoiser());
|
||||
// 4:4:4 so the chroma work is not immediately thrown away by the encoder.
|
||||
const jpeg = await sharp(Buffer.from(out.rgb), { raw: { width, height, channels: 3 } })
|
||||
.jpeg({ quality: 95, chromaSubsampling: '4:4:4' })
|
||||
.toBuffer();
|
||||
await fs.writeFile(outPath, jpeg);
|
||||
|
||||
parentPort?.postMessage({
|
||||
type: 'done',
|
||||
ms: Math.round(performance.now() - started),
|
||||
bytes: jpeg.length,
|
||||
stats: {
|
||||
amount: out.stats.amount,
|
||||
autoGate: out.stats.autoGate,
|
||||
gate: out.stats.gateCoverage,
|
||||
noise: out.stats.noise.global,
|
||||
baseWidth: out.stats.baseWidth,
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
parentPort?.postMessage({ type: 'error', error: error?.message ?? String(error) });
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
/**
|
||||
* Job runner for the detail-preserving denoise.
|
||||
*
|
||||
* `server/denoise/` is a verbatim copy of the dependency-free pipeline from the
|
||||
* raw-noise package. It reconstructs from a per-pixel crossfade between the
|
||||
* source and a denoised base, so the result is bounded by the original pixels and
|
||||
* cannot ring or overshoot; flat noise is replaced, structure is given back
|
||||
* verbatim. The GPU's own `noise` sliders are a separate, much simpler path.
|
||||
*
|
||||
* Three things here are deliberate:
|
||||
*
|
||||
* - Amount belongs to the client. The worker always renders the full-strength
|
||||
* denoise and the renderer applies the blend, so the slider is instant, one
|
||||
* file serves every amount, and the amount cannot be applied twice.
|
||||
* - The key carries a pipeline version. A change to `server/denoise/` has to
|
||||
* re-key, or the old renders keep being served as if they were current.
|
||||
* - Each run is seconds of solid CPU, so runs go through a capped queue and a
|
||||
* second request for the same photo joins the run already in progress
|
||||
* instead of starting an identical one.
|
||||
*/
|
||||
import crypto from 'node:crypto';
|
||||
import os from 'node:os';
|
||||
import { Worker } from 'node:worker_threads';
|
||||
import { denoisedPath, findDenoised, removeDenoised } from './storage.mjs';
|
||||
|
||||
/** Lookup used by the download route; storage owns where the files live. */
|
||||
export function findDenoisedFor(photoId, key) {
|
||||
return findDenoised(photoId, key);
|
||||
}
|
||||
|
||||
/** Drop the renders for a photo, e.g. when its edit is cleared. */
|
||||
export function clearDenoised(photoId) {
|
||||
return removeDenoised(photoId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Bump whenever the copied modules under `server/denoise/` change output. The key
|
||||
* is the only thing between a fixed pipeline and a stale cached file.
|
||||
*/
|
||||
const PIPELINE_VERSION = 'guided-5';
|
||||
|
||||
const MAX_JOBS = 40;
|
||||
/**
|
||||
* A burst of clicks must not pin every core: the raw decoders have their own
|
||||
* budget and the request thread still has the rest of the library to serve.
|
||||
*/
|
||||
const MAX_WORKERS = Math.max(
|
||||
1,
|
||||
Math.min(4, Number(process.env.LUMINARY_DENOISE_WORKERS) || (os.cpus().length || 2) - 1),
|
||||
);
|
||||
|
||||
const jobs = new Map();
|
||||
/** key -> job that is queued or running, so a repeat request joins it. */
|
||||
const byKey = new Map();
|
||||
const queue = [];
|
||||
let active = 0;
|
||||
|
||||
export function getDenoiseJob(id) {
|
||||
return jobs.get(id) ?? null;
|
||||
}
|
||||
|
||||
/** Stable for a photo and a pipeline version -- Amount is the client's business. */
|
||||
export function denoiseKey(photoId) {
|
||||
return crypto
|
||||
.createHash('sha1')
|
||||
.update(`${photoId}|${PIPELINE_VERSION}`)
|
||||
.digest('hex')
|
||||
.slice(0, 12);
|
||||
}
|
||||
|
||||
export function startDenoise({ photoId, sourcePath }) {
|
||||
const key = denoiseKey(photoId);
|
||||
|
||||
const joined = byKey.get(key);
|
||||
if (joined) return joined;
|
||||
|
||||
const url = `/api/photos/${encodeURIComponent(photoId)}/denoised?v=${key}`;
|
||||
const job = { id: crypto.randomUUID(), photoId, key, state: 'running', startedAt: Date.now() };
|
||||
|
||||
// Re-running after the edit was cleared, or a second browser, should not pay
|
||||
// for the CPU again. The file is the cache; the job just reports it.
|
||||
if (findDenoised(photoId, key)) {
|
||||
job.state = 'done';
|
||||
job.cached = true;
|
||||
job.url = url;
|
||||
jobs.set(job.id, job);
|
||||
pruneJobs();
|
||||
return job;
|
||||
}
|
||||
|
||||
job.sourcePath = sourcePath;
|
||||
job.url = url;
|
||||
jobs.set(job.id, job);
|
||||
byKey.set(key, job);
|
||||
queue.push(job);
|
||||
pruneJobs();
|
||||
pump();
|
||||
return job;
|
||||
}
|
||||
|
||||
function pump() {
|
||||
while (active < MAX_WORKERS && queue.length > 0) {
|
||||
run(queue.shift());
|
||||
}
|
||||
}
|
||||
|
||||
function run(job) {
|
||||
active += 1;
|
||||
const outPath = denoisedPath(job.photoId, job.key);
|
||||
const worker = new Worker(new URL('./denoise-worker.mjs', import.meta.url), {
|
||||
workerData: { sourcePath: job.sourcePath, outPath },
|
||||
});
|
||||
|
||||
worker.on('message', (message) => {
|
||||
if (message?.type === 'done') {
|
||||
job.state = 'done';
|
||||
job.ms = message.ms;
|
||||
job.bytes = message.bytes;
|
||||
job.stats = message.stats;
|
||||
// A version bump (or an older build) leaves its render behind; keep the
|
||||
// current one and drop the rest so the folder cannot grow without bound.
|
||||
try {
|
||||
removeDenoised(job.photoId, job.key);
|
||||
} catch {
|
||||
/* cleanup is best effort -- never fail a finished job over it */
|
||||
}
|
||||
} else if (message?.type === 'error') {
|
||||
job.state = 'error';
|
||||
job.error = message.error;
|
||||
}
|
||||
});
|
||||
worker.on('error', (error) => {
|
||||
job.state = 'error';
|
||||
job.error = error?.message ?? 'denoise worker failed';
|
||||
});
|
||||
worker.on('exit', () => {
|
||||
// A crash inside the pipeline would otherwise leave the UI polling forever.
|
||||
if (job.state === 'running') {
|
||||
job.state = 'error';
|
||||
job.error = 'denoise worker exited unexpectedly';
|
||||
}
|
||||
active -= 1;
|
||||
byKey.delete(job.key);
|
||||
job.sourcePath = null;
|
||||
pump();
|
||||
});
|
||||
}
|
||||
|
||||
/** Keep the newest finished jobs; never drop one that is queued or running. */
|
||||
function pruneJobs() {
|
||||
if (jobs.size <= MAX_JOBS) return;
|
||||
for (const [id, job] of jobs) {
|
||||
if (jobs.size <= MAX_JOBS) break;
|
||||
if (job.state === 'running') continue;
|
||||
jobs.delete(id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
/**
|
||||
* Interleaved RGB <-> luma/chroma, so luma and chroma can take different
|
||||
* denoise paths.
|
||||
*
|
||||
* Chroma noise is low-frequency and the eye has little chroma acuity, so it is
|
||||
* worth smoothing hard; luma carries all the detail and is the expensive,
|
||||
* gated path. The transform is the standard sRGB-weighted one and round-trips
|
||||
* to within rounding.
|
||||
*/
|
||||
|
||||
export interface RgbImage {
|
||||
/** Interleaved 8-bit RGB, `width * height * 3` bytes. */
|
||||
rgb: Uint8Array;
|
||||
width: number;
|
||||
height: number;
|
||||
}
|
||||
|
||||
export interface YccPlanes {
|
||||
y: Float32Array;
|
||||
cb: Float32Array;
|
||||
cr: Float32Array;
|
||||
}
|
||||
|
||||
export function toYcc(image: RgbImage): YccPlanes {
|
||||
const { rgb, width, height } = image;
|
||||
const n = width * height;
|
||||
const y = new Float32Array(n);
|
||||
const cb = new Float32Array(n);
|
||||
const cr = new Float32Array(n);
|
||||
for (let i = 0, p = 0; i < n; i++, p += 3) {
|
||||
const r = rgb[p];
|
||||
const g = rgb[p + 1];
|
||||
const b = rgb[p + 2];
|
||||
y[i] = 0.299 * r + 0.587 * g + 0.114 * b;
|
||||
cb[i] = 128 - 0.168736 * r - 0.331264 * g + 0.5 * b;
|
||||
cr[i] = 128 + 0.5 * r - 0.418688 * g - 0.081312 * b;
|
||||
}
|
||||
return { y, cb, cr };
|
||||
}
|
||||
|
||||
export function fromYcc(planes: YccPlanes, width: number, height: number): Uint8Array {
|
||||
const n = width * height;
|
||||
const out = new Uint8Array(n * 3);
|
||||
for (let i = 0, p = 0; i < n; i++, p += 3) {
|
||||
const y = planes.y[i];
|
||||
const cb = planes.cb[i] - 128;
|
||||
const cr = planes.cr[i] - 128;
|
||||
const r = y + 1.402 * cr;
|
||||
const g = y - 0.344136 * cb - 0.714136 * cr;
|
||||
const b = y + 1.772 * cb;
|
||||
out[p] = r < 0 ? 0 : r > 255 ? 255 : r + 0.5;
|
||||
out[p + 1] = g < 0 ? 0 : g > 255 ? 255 : g + 0.5;
|
||||
out[p + 2] = b < 0 ? 0 : b > 255 ? 255 : b + 0.5;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -0,0 +1,253 @@
|
||||
/**
|
||||
* Detail / structure separation.
|
||||
*
|
||||
* The whole feature rests on one idea: a denoiser may only remove things that
|
||||
* do *not* look like structure. This module produces the map that decides
|
||||
* that, from three cheap local measurements:
|
||||
*
|
||||
* 1. `detail` -- the high-frequency residual of an edge-preserving filter.
|
||||
* 2. `sigma` -- the noise level expected at this luminance.
|
||||
* 3. `coherence` -- how organised the local gradient is (a curve vs. grain).
|
||||
*
|
||||
* A pixel with detail well above the noise floor, or with a coherent edge
|
||||
* through it, gets `gate -> 1` and its original values are restored verbatim
|
||||
* after denoising. Flat grain gets `gate -> 0` and is replaced wholesale.
|
||||
*/
|
||||
|
||||
import { boxBlur, clamp, clamp01, resample, smoothstep } from './planes.ts';
|
||||
|
||||
/**
|
||||
* Guided filter (He et al.), O(1) per pixel.
|
||||
*
|
||||
* Used instead of a bilateral filter because it needs no per-pixel search:
|
||||
* four box passes, and the edge-preserving behaviour is exactly what the
|
||||
* base/detail split needs. `eps` is a variance, so it is the noise sigma
|
||||
* squared, scaled by how aggressively we want to smooth.
|
||||
*/
|
||||
export function guidedFilter(
|
||||
src: Float32Array,
|
||||
width: number,
|
||||
height: number,
|
||||
radius: number,
|
||||
eps: number,
|
||||
): Float32Array {
|
||||
const a = boxBlur(src, width, height, radius);
|
||||
const b = new Float32Array(src.length);
|
||||
for (let i = 0; i < src.length; i++) b[i] = src[i] * src[i];
|
||||
boxBlur(b, width, height, radius, b);
|
||||
|
||||
// b <- a (the guided-filter gain), a <- mean * (1 - gain).
|
||||
const e = Math.max(eps, 1e-6);
|
||||
for (let i = 0; i < src.length; i++) {
|
||||
const mean = a[i];
|
||||
const variance = b[i] - mean * mean;
|
||||
const gain = variance / (variance + e);
|
||||
b[i] = gain;
|
||||
a[i] = mean * (1 - gain);
|
||||
}
|
||||
|
||||
boxBlur(b, width, height, radius, b);
|
||||
boxBlur(a, width, height, radius, a);
|
||||
|
||||
const out = new Float32Array(src.length);
|
||||
for (let i = 0; i < src.length; i++) out[i] = b[i] * src[i] + a[i];
|
||||
return out;
|
||||
}
|
||||
|
||||
export interface StructureMap {
|
||||
/** 0 = isotropic (grain, flat), 1 = a clean line or edge. */
|
||||
data: Float32Array;
|
||||
width: number;
|
||||
height: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Structure-tensor coherence, computed at reduced resolution.
|
||||
*
|
||||
* Coherence is a geometric property of edges and varies slowly across the
|
||||
* frame, so measuring it at 1/`stride` and interpolating back is visually
|
||||
* identical and ~`stride^2` cheaper in both time and memory.
|
||||
*/
|
||||
export function structureMap(
|
||||
gray: Float32Array,
|
||||
width: number,
|
||||
height: number,
|
||||
radius = 2,
|
||||
stride = 2,
|
||||
sigmaFloor = 1,
|
||||
): StructureMap {
|
||||
const sw = Math.max(2, Math.floor(width / stride));
|
||||
const sh = Math.max(2, Math.floor(height / stride));
|
||||
const small = resample(gray, width, height, sw, sh);
|
||||
|
||||
const gx = new Float32Array(sw * sh);
|
||||
const gy = new Float32Array(sw * sh);
|
||||
for (let y = 0; y < sh; y++) {
|
||||
const y0 = clamp(y - 1, 0, sh - 1) * sw;
|
||||
const y1 = clamp(y + 1, 0, sh - 1) * sw;
|
||||
const row = y * sw;
|
||||
for (let x = 0; x < sw; x++) {
|
||||
const x0 = clamp(x - 1, 0, sw - 1);
|
||||
const x1 = clamp(x + 1, 0, sw - 1);
|
||||
// Scharr kernels: better rotational symmetry than Sobel at this size.
|
||||
gx[row + x] =
|
||||
(3 * (small[y0 + x1] - small[y0 + x0]) + 10 * (small[row + x1] - small[row + x0]) + 3 * (small[y1 + x1] - small[y1 + x0])) / 16;
|
||||
gy[row + x] =
|
||||
(3 * (small[y1 + x0] - small[y0 + x0]) + 10 * (small[y1 + x] - small[y0 + x]) + 3 * (small[y1 + x1] - small[y0 + x1])) / 16;
|
||||
}
|
||||
}
|
||||
|
||||
const jxx = new Float32Array(sw * sh);
|
||||
const jyy = new Float32Array(sw * sh);
|
||||
const jxy = new Float32Array(sw * sh);
|
||||
for (let i = 0; i < gx.length; i++) {
|
||||
jxx[i] = gx[i] * gx[i];
|
||||
jyy[i] = gy[i] * gy[i];
|
||||
jxy[i] = gx[i] * gy[i];
|
||||
}
|
||||
boxBlur(jxx, sw, sh, radius, jxx);
|
||||
boxBlur(jyy, sw, sh, radius, jyy);
|
||||
boxBlur(jxy, sw, sh, radius, jxy);
|
||||
|
||||
const data = new Float32Array(sw * sh);
|
||||
const floor = sigmaFloor * sigmaFloor;
|
||||
for (let i = 0; i < data.length; i++) {
|
||||
const trace = jxx[i] + jyy[i];
|
||||
const disc = Math.sqrt(Math.max(0, (jxx[i] - jyy[i]) * (jxx[i] - jyy[i]) + 4 * jxy[i] * jxy[i]));
|
||||
if (trace <= floor) continue;
|
||||
data[i] = clamp01(disc / trace);
|
||||
}
|
||||
return { data, width: sw, height: sh };
|
||||
}
|
||||
|
||||
/**
|
||||
* Mean |detail| of pure Gaussian noise, relative to sigma.
|
||||
*
|
||||
* The statistic compared against the threshold is a mean absolute value over
|
||||
* the 3x3-smoothed high-pass of a noise field, which measures ~1.0 sigma when
|
||||
* the noise model is correct. Calibrated against a flat ISO 6400 sky, where
|
||||
* |detail|/sigma had median 1.05. Expressing the ramp in these units puts 1.0
|
||||
* at "indistinguishable from grain" instead of at "one sigma", which is not
|
||||
* the same thing at all.
|
||||
*/
|
||||
const NOISE_MAGNITUDE = 1.0;
|
||||
|
||||
export interface GateOptions {
|
||||
/** Below this multiple of the expected noise magnitude, detail is noise. */
|
||||
lo: number;
|
||||
/** Above this multiple, detail is unambiguously signal. */
|
||||
hi: number;
|
||||
/**
|
||||
* How much an organised edge lowers the amplitude needed to open the gate.
|
||||
* 1.0 means a perfectly coherent line needs half the contrast of grain to be
|
||||
* believed; 0 disables the structure term entirely.
|
||||
*/
|
||||
coherenceBoost: number;
|
||||
/**
|
||||
* Isolated points have no coherence, so the structure term cannot save them
|
||||
* and the 3x3 magnitude average below shrinks them toward the noise floor. A
|
||||
* pixel that is the local maximum of |detail| and clears this many noise
|
||||
* magnitudes on its own opens the gate anyway.
|
||||
*/
|
||||
pointLo: number;
|
||||
/** Above this multiple, an isolated point is unambiguously real. */
|
||||
pointHi: number;
|
||||
}
|
||||
|
||||
// 1.0 measured on three D700 frames with synthetic sigma=6: fine-texture
|
||||
// retention 48/52/24% -> 78/79/45% against 0 (no structure term), edge
|
||||
// retention up, global grain unchanged. 1.5 reaches 97-98% but at 14% gate
|
||||
// coverage it starts keeping the grain that sits on the texture, which is not
|
||||
// separable at this scale anyway -- 1.0 is the knee.
|
||||
// pointLo/Hi measured by injecting 1 px sources into a real ISO 6400 sky. The
|
||||
// old gate kept 8% of a 5-sigma point's contrast and 44% of an 8-sigma one.
|
||||
//
|
||||
// The threshold looks high for a reason: the rule is a *local maximum*, and the
|
||||
// max of nine correlated grain samples routinely reaches ~2 sigma, so 2.2 both
|
||||
// protected grain and failed the corpus guard (grain 0.55 -> 1.36). 3.0 is the
|
||||
// lowest value that leaves grain and chroma unchanged across the guarded corpus
|
||||
// while keeping 5-sigma points (~0.9 of their contrast) and 8-sigma points
|
||||
// (~1.0). A 3-sigma point stays smoothed -- at this scale it is not separable
|
||||
// from the brightest grain beside it, and pretending otherwise costs the frame.
|
||||
export const DEFAULT_GATE: GateOptions = {
|
||||
lo: 1.15,
|
||||
hi: 2.1,
|
||||
coherenceBoost: 1.0,
|
||||
pointLo: 3.0,
|
||||
pointHi: 4.0,
|
||||
};
|
||||
|
||||
/**
|
||||
* Per-pixel "how much of this pixel is real" map, 0..1.
|
||||
* *`detail` is the signed residual, `sigma` the expected noise at each pixel.
|
||||
* The detail magnitude is box-smoothed so a single stray pixel cannot open the
|
||||
* gate on its own, and `coherence` scales the amplitude required to open it.
|
||||
* The one exception is an isolated peak large enough to be a point source:
|
||||
* smoothing would erase exactly the detail (stars, specular pinpoints) this
|
||||
* feature exists to keep, so local maxima get their own path.
|
||||
*/
|
||||
export function detailGate(
|
||||
detail: Float32Array,
|
||||
width: number,
|
||||
height: number,
|
||||
sigma: Float32Array,
|
||||
coherence: Float32Array,
|
||||
options: GateOptions = DEFAULT_GATE,
|
||||
): Float32Array {
|
||||
const magnitude = new Float32Array(detail.length);
|
||||
for (let i = 0; i < detail.length; i++) magnitude[i] = detail[i] < 0 ? -detail[i] : detail[i];
|
||||
boxBlur(magnitude, width, height, 1, magnitude);
|
||||
|
||||
const gate = new Float32Array(detail.length);
|
||||
const pointOn = options.pointHi > 0 && options.pointHi > options.pointLo;
|
||||
for (let i = 0; i < detail.length; i++) {
|
||||
const s = sigma[i] < 0.05 ? 0.05 : sigma[i];
|
||||
// 1.0 means "exactly what a flat noisy patch measures", not "one sigma".
|
||||
const ratio = magnitude[i] / (NOISE_MAGNITUDE * s);
|
||||
// Coherence of pure noise measures ~0.49, so it cannot be applied linearly:
|
||||
// that leaks ~0.12 of gate onto every grain pixel. Cubing it keeps ordinary
|
||||
// noise at ~0.12 while a real edge (0.9) still reaches 0.73.
|
||||
const organised = coherence[i] * coherence[i] * coherence[i];
|
||||
// Coherence *lowers the bar*, it does not add to the answer. Adding an
|
||||
// independent term (the previous form) meant an organised line still had to
|
||||
// clear the full amplitude threshold on its own, so low-contrast 2-3 px
|
||||
// texture -- which is exactly what "detail soft" looks like -- got nothing.
|
||||
// Scaling the ratio instead says: a line needs less contrast to be believed,
|
||||
// which is the same claim the threshold makes about grain.
|
||||
const belief = 1 + options.coherenceBoost * organised;
|
||||
let g = smoothstep(options.lo, options.hi, ratio * belief);
|
||||
|
||||
// Isolated-point path. The 3x3 average above shrinks a 1 px source toward
|
||||
// the noise floor, so the crossfade replaced it with the softened base --
|
||||
// measured: a 5-sigma point kept 8%, an 8-sigma point 44%. The threshold sits
|
||||
// above the local maximum grain reaches (see DEFAULT_GATE). Ties pass so a
|
||||
// 2 px highlight is not lost to the comparison.
|
||||
if (pointOn) {
|
||||
const a = detail[i] < 0 ? -detail[i] : detail[i];
|
||||
const own = a / (NOISE_MAGNITUDE * s);
|
||||
if (own > options.pointLo) {
|
||||
const x = i % width;
|
||||
const y = (i - x) / width;
|
||||
if (x > 0 && y > 0 && x < width - 1 && y < height - 1) {
|
||||
let peak = true;
|
||||
for (let dy = -1; dy <= 1 && peak; dy++) {
|
||||
for (let dx = -1; dx <= 1; dx++) {
|
||||
if (dx === 0 && dy === 0) continue;
|
||||
const n = detail[i + dy * width + dx];
|
||||
if ((n < 0 ? -n : n) > a) {
|
||||
peak = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (peak) {
|
||||
const opened = smoothstep(options.pointLo, options.pointHi, own);
|
||||
if (opened > g) g = opened;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
gate[i] = g;
|
||||
}
|
||||
return gate;
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
/**
|
||||
* Noise level estimation from a single finished image.
|
||||
*
|
||||
* The model is the Poisson-Gaussian one the rest of the pipeline assumes:
|
||||
*
|
||||
* var(luma) = shot * luma + read
|
||||
*
|
||||
* but measured in 8-bit sRGB units directly, because the thing we can actually
|
||||
* see and measure is the finished proxy -- after demosaic, tone curve and JPEG.
|
||||
* Fitting a sensor model and then pushing it through LibRaw's tone curve would
|
||||
* be more principled and much less reliable.
|
||||
*
|
||||
* Two details make the estimate usable on real photographs:
|
||||
*
|
||||
* - The high-pass residual is taken over 16x16 blocks, and texture (which
|
||||
* raises the local MAD) is kept out of the answer by a two-step statistic:
|
||||
* a low quantile of the per-block sigmas sets the scale, blocks near it are
|
||||
* kept, and the median of those is the estimate. See the comment at the
|
||||
* computation for why neither statistic works alone.
|
||||
* - A 3x3 box high-pass attenuates white noise by sqrt(8/9); that gain is
|
||||
* divided back out, otherwise every sigma is 6% low.
|
||||
*/
|
||||
|
||||
import { boxBlur, clamp, quantile } from './planes.ts';
|
||||
|
||||
/** White-noise gain of `I - boxBlur(I, 1)`; sqrt(1 - 2/9 + 1/9). */
|
||||
const HP_NOISE_GAIN = Math.sqrt(8 / 9);
|
||||
/** MAD -> sigma for a Gaussian. */
|
||||
const MAD_TO_SIGMA = 1 / 0.6745;
|
||||
/** Below this, an 8-bit sRGB image has no measurable noise. */
|
||||
export const SIGMA_FLOOR = 0.35;
|
||||
|
||||
export type NoiseTrend = 'fit' | 'flat';
|
||||
|
||||
export interface NoiseModel {
|
||||
/** sigma = a + b * luma, 8-bit units. */
|
||||
a: number;
|
||||
b: number;
|
||||
/** Whether the luminance trend was trusted, or a flat floor was used. */
|
||||
trend: NoiseTrend;
|
||||
/** Per-bin measurements that produced the fit (diagnostics). */
|
||||
bins: { luma: number; sigma: number; blocks: number }[];
|
||||
/** Robust global floor, ignoring the luminance trend. */
|
||||
global: number;
|
||||
sigmaAt(luma: number): number;
|
||||
}
|
||||
|
||||
export function createNoiseModel(
|
||||
a: number,
|
||||
b: number,
|
||||
global: number,
|
||||
bins: NoiseModel['bins'],
|
||||
trend: NoiseTrend = 'flat',
|
||||
): NoiseModel {
|
||||
return {
|
||||
a,
|
||||
b,
|
||||
global,
|
||||
trend,
|
||||
bins,
|
||||
sigmaAt(luma: number): number {
|
||||
const s = a + b * clamp(luma, 0, 255);
|
||||
return s < SIGMA_FLOOR ? SIGMA_FLOOR : s;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function estimateNoise(luma: Float32Array, width: number, height: number): NoiseModel {
|
||||
const residual = boxBlur(luma, width, height, 1);
|
||||
for (let i = 0; i < residual.length; i++) residual[i] = luma[i] - residual[i];
|
||||
|
||||
const BLOCK = 16;
|
||||
const BINS = 16;
|
||||
const perBin: number[][] = Array.from({ length: BINS }, () => []);
|
||||
const all: number[] = [];
|
||||
const scratch = new Float32Array(BLOCK * BLOCK);
|
||||
|
||||
for (let by = 0; by + BLOCK <= height; by += BLOCK) {
|
||||
for (let bx = 0; bx + BLOCK <= width; bx += BLOCK) {
|
||||
let sumLuma = 0;
|
||||
let n = 0;
|
||||
for (let y = 0; y < BLOCK; y++) {
|
||||
const row = (by + y) * width + bx;
|
||||
for (let x = 0; x < BLOCK; x++) {
|
||||
sumLuma += luma[row + x];
|
||||
const v = residual[row + x];
|
||||
scratch[n++] = v < 0 ? -v : v;
|
||||
}
|
||||
}
|
||||
const meanLuma = sumLuma / n;
|
||||
// Clipped highlights and crushed blacks have no usable noise statistic.
|
||||
if (meanLuma < 6 || meanLuma > 249) continue;
|
||||
|
||||
const sigma = quantile(scratch.subarray(0, n), 0.5) * MAD_TO_SIGMA / HP_NOISE_GAIN;
|
||||
// A perfectly flat block measures exactly zero and must be *kept*: it is
|
||||
// the strongest evidence of a clean frame. Dropping it left a frame that
|
||||
// was half flat and half texture reported as uniformly noisy.
|
||||
if (!Number.isFinite(sigma)) continue;
|
||||
|
||||
all.push(sigma);
|
||||
const bin = clamp(Math.floor(meanLuma / (256 / BINS)), 0, BINS - 1);
|
||||
perBin[bin].push(sigma);
|
||||
}
|
||||
}
|
||||
|
||||
if (all.length === 0) {
|
||||
return createNoiseModel(SIGMA_FLOOR, 0, SIGMA_FLOOR, []);
|
||||
}
|
||||
|
||||
// Two steps, because either statistic alone fails on a real frame:
|
||||
//
|
||||
// - the *median* is accurate on a homogeneous field but reads texture as
|
||||
// noise when more than half the frame is detailed (a brick wall, a striping
|
||||
// shirt, half a test chart), which can push sigma 30x high;
|
||||
// - a low quantile ignores texture but sits in the low tail of the
|
||||
// estimator's own sampling noise.
|
||||
//
|
||||
// So: a low quantile sets the scale, blocks near it are kept, and the median
|
||||
// of those is the answer. At ~10k blocks the quantile's bias is a few percent
|
||||
// and the median removes it.
|
||||
const floor = Math.max(SIGMA_FLOOR, quantile(all, 0.25));
|
||||
const cutoff = floor * 1.5;
|
||||
const flatBlocks = all.filter((value) => value <= cutoff);
|
||||
const global = Math.max(SIGMA_FLOOR, quantile(flatBlocks.length > 0 ? flatBlocks : all, 0.5));
|
||||
const bins: NoiseModel['bins'] = [];
|
||||
for (let i = 0; i < BINS; i++) {
|
||||
const flat = perBin[i].filter((v) => v <= cutoff);
|
||||
if (flat.length < 5) continue;
|
||||
bins.push({
|
||||
luma: (i + 0.5) * (256 / BINS),
|
||||
sigma: quantile(flat, 0.5),
|
||||
blocks: flat.length,
|
||||
});
|
||||
}
|
||||
|
||||
// A bin that is mostly texture reports texture, not noise: on a frame with a
|
||||
// detailed foreground the low-luma bins can read several times the true
|
||||
// floor. Fit only the bins that sit near the floor, then reject the whole
|
||||
// trend if the resulting line leaves a physically plausible range. A flat
|
||||
// sigma is a worse model than a good trend and a far better one than a bad
|
||||
// trend, and this keeps the bad trend out.
|
||||
const usable = bins.filter((bin) => bin.blocks >= 8 && bin.sigma <= global * 1.6);
|
||||
if (usable.length >= 3) {
|
||||
let sw = 0;
|
||||
let sx = 0;
|
||||
let sy = 0;
|
||||
let sxx = 0;
|
||||
let sxy = 0;
|
||||
for (const bin of usable) {
|
||||
const w = bin.blocks;
|
||||
sw += w;
|
||||
sx += w * bin.luma;
|
||||
sy += w * bin.sigma;
|
||||
sxx += w * bin.luma * bin.luma;
|
||||
sxy += w * bin.luma * bin.sigma;
|
||||
}
|
||||
const det = sw * sxx - sx * sx;
|
||||
if (Math.abs(det) > 1e-6) {
|
||||
const b = (sw * sxy - sx * sy) / det;
|
||||
const a = (sy - b * sx) / sw;
|
||||
const low = a;
|
||||
const high = a + b * 255;
|
||||
const lo = global * 0.5;
|
||||
const hi = global * 2.5;
|
||||
if (
|
||||
Number.isFinite(a) &&
|
||||
Number.isFinite(b) &&
|
||||
low >= lo && low <= hi &&
|
||||
high >= lo && high <= hi
|
||||
) {
|
||||
return createNoiseModel(a, b, global, bins, 'fit');
|
||||
}
|
||||
}
|
||||
}
|
||||
return createNoiseModel(global, 0, global, bins);
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
/**
|
||||
* Scalar float planes plus the resampling and box-filter primitives the
|
||||
* detail-preserving denoise is built from.
|
||||
*
|
||||
* Everything here is plain `Float32Array` arithmetic with no allocation in the
|
||||
* hot loops: the full-resolution stage runs at proxy size (up to 24 MP), and
|
||||
* allocation churn is the difference between two seconds and six per photo.
|
||||
*/
|
||||
|
||||
export interface Plane {
|
||||
data: Float32Array;
|
||||
width: number;
|
||||
height: number;
|
||||
}
|
||||
|
||||
export function createPlane(width: number, height: number): Plane {
|
||||
return { data: new Float32Array(width * height), width, height };
|
||||
}
|
||||
|
||||
export function clamp01(v: number): number {
|
||||
return v < 0 ? 0 : v > 1 ? 1 : v;
|
||||
}
|
||||
|
||||
export function clamp(v: number, lo: number, hi: number): number {
|
||||
return v < lo ? lo : v > hi ? hi : v;
|
||||
}
|
||||
|
||||
/** Hermite ramp: 0 below `lo`, 1 above `hi`. */
|
||||
export function smoothstep(lo: number, hi: number, x: number): number {
|
||||
if (hi <= lo) return x >= hi ? 1 : 0;
|
||||
const t = clamp01((x - lo) / (hi - lo));
|
||||
return t * t * (3 - 2 * t);
|
||||
}
|
||||
|
||||
function edge(i: number, n: number): number {
|
||||
return i < 0 ? 0 : i >= n ? n - 1 : i;
|
||||
}
|
||||
|
||||
/**
|
||||
* Scratch buffer for the separable passes, grown on demand.
|
||||
*
|
||||
* Safe because `boxBlur` is not reentrant: every caller finishes with the
|
||||
* buffer before making another call, and the buffer is never handed out.
|
||||
*/
|
||||
let scratchBuffer: Float32Array | null = null;
|
||||
|
||||
function scratch(length: number): Float32Array {
|
||||
if (!scratchBuffer || scratchBuffer.length < length) scratchBuffer = new Float32Array(length);
|
||||
return scratchBuffer.subarray(0, length);
|
||||
}
|
||||
|
||||
/**
|
||||
* Separable box blur with clamped edges, O(1) per pixel.
|
||||
*
|
||||
* `out` may alias `src`: the horizontal pass goes through the shared scratch
|
||||
* buffer, and only the vertical pass writes `out`, so an in-place call is
|
||||
* safe. That aliasing is what keeps the guided filter allocation-light.
|
||||
*/
|
||||
export function boxBlur(
|
||||
src: Float32Array,
|
||||
width: number,
|
||||
height: number,
|
||||
radius: number,
|
||||
out?: Float32Array,
|
||||
): Float32Array {
|
||||
const dst = out ?? new Float32Array(src.length);
|
||||
if (src.length < width * height) {
|
||||
throw new Error(`plane is ${src.length} values, expected ${width * height}`);
|
||||
}
|
||||
if (radius <= 0) {
|
||||
if (dst !== src) dst.set(src);
|
||||
return dst;
|
||||
}
|
||||
const tmp = scratch(width * height);
|
||||
const norm = 1 / (2 * radius + 1);
|
||||
|
||||
// Horizontal pass: src -> tmp.
|
||||
for (let y = 0; y < height; y++) {
|
||||
const row = y * width;
|
||||
let sum = 0;
|
||||
for (let x = -radius; x <= radius; x++) sum += src[row + edge(x, width)];
|
||||
for (let x = 0; x < width; x++) {
|
||||
tmp[row + x] = sum * norm;
|
||||
sum += src[row + edge(x + radius + 1, width)] - src[row + edge(x - radius, width)];
|
||||
}
|
||||
}
|
||||
|
||||
// Vertical pass: tmp -> dst.
|
||||
for (let x = 0; x < width; x++) {
|
||||
let sum = 0;
|
||||
for (let y = -radius; y <= radius; y++) sum += tmp[edge(y, height) * width + x];
|
||||
for (let y = 0; y < height; y++) {
|
||||
dst[y * width + x] = sum * norm;
|
||||
sum +=
|
||||
tmp[edge(y + radius + 1, height) * width + x] -
|
||||
tmp[edge(y - radius, height) * width + x];
|
||||
}
|
||||
}
|
||||
return dst;
|
||||
}
|
||||
|
||||
/**
|
||||
* Bilinear resample. Used for the two-scale split: luma is reduced to the
|
||||
* inference size, denoised, then brought back up so full-resolution detail can
|
||||
* be re-injected on top.
|
||||
*/
|
||||
export function resample(
|
||||
src: Float32Array,
|
||||
sw: number,
|
||||
sh: number,
|
||||
dw: number,
|
||||
dh: number,
|
||||
): Float32Array {
|
||||
if (sw === dw && sh === dh) return src.slice();
|
||||
const out = new Float32Array(dw * dh);
|
||||
const xRatio = sw / dw;
|
||||
const yRatio = sh / dh;
|
||||
for (let y = 0; y < dh; y++) {
|
||||
// Sample at pixel centres so a downscale is a centred box, not a shifted one.
|
||||
const sy = clamp((y + 0.5) * yRatio - 0.5, 0, sh - 1);
|
||||
const y0 = Math.floor(sy);
|
||||
const y1 = Math.min(y0 + 1, sh - 1);
|
||||
const wy = sy - y0;
|
||||
for (let x = 0; x < dw; x++) {
|
||||
const sx = clamp((x + 0.5) * xRatio - 0.5, 0, sw - 1);
|
||||
const x0 = Math.floor(sx);
|
||||
const x1 = Math.min(x0 + 1, sw - 1);
|
||||
const wx = sx - x0;
|
||||
const top = src[y0 * sw + x0] * (1 - wx) + src[y0 * sw + x1] * wx;
|
||||
const bot = src[y1 * sw + x0] * (1 - wx) + src[y1 * sw + x1] * wx;
|
||||
out[y * dw + x] = top * (1 - wy) + bot * wy;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* O(n) percentile for large non-negative arrays, by histogram.
|
||||
*
|
||||
* `quantile` sorts, which is correct and fine for a 256-value block but ruinous
|
||||
* for an 18 MP plane: two sorts there cost 11.5 s against a 6.6 s denoise. Bins
|
||||
* over [0, max] return a median accurate to ~0.2 on 8-bit data, far inside the
|
||||
* noise being measured.
|
||||
*
|
||||
* `values` must be non-negative (magnitudes, gradients, residuals).
|
||||
*/
|
||||
export function fastPercentile(values: Float32Array, q: number, bins = 1024): number {
|
||||
const n = values.length;
|
||||
if (n === 0) return 0;
|
||||
let max = 0;
|
||||
for (let i = 0; i < n; i++) {
|
||||
const v = values[i];
|
||||
if (v > max) max = v;
|
||||
}
|
||||
if (!(max > 0)) return 0;
|
||||
|
||||
const hist = new Uint32Array(bins);
|
||||
const scale = (bins - 1) / max;
|
||||
for (let i = 0; i < n; i++) hist[(values[i] * scale) | 0]++;
|
||||
|
||||
const target = clamp(q, 0, 1) * (n - 1);
|
||||
let seen = 0;
|
||||
for (let b = 0; b < bins; b++) {
|
||||
seen += hist[b];
|
||||
if (seen > target) return b / scale;
|
||||
}
|
||||
return max;
|
||||
}
|
||||
|
||||
/** Linear-interpolated quantile of a copy of `values`. `q` is 0..1. */
|
||||
export function quantile(values: Float32Array | number[], q: number): number {
|
||||
const n = values.length;
|
||||
if (n === 0) return 0;
|
||||
const sorted = Float32Array.from(values as ArrayLike<number>).sort();
|
||||
const pos = clamp(q, 0, 1) * (n - 1);
|
||||
const lo = Math.floor(pos);
|
||||
const hi = Math.min(lo + 1, n - 1);
|
||||
return sorted[lo] + (sorted[hi] - sorted[lo]) * (pos - lo);
|
||||
}
|
||||
@@ -0,0 +1,349 @@
|
||||
/**
|
||||
* The RGB proxy denoise pipeline: two scales, one gate.
|
||||
*
|
||||
* proxy -> YCbCr
|
||||
* -> base: downscale RGB, run `runBase`, upscale
|
||||
* -> luma: low-pass at the detail scale, gate per pixel
|
||||
* -> reconstruct: crossfade luma to the base where the gate is closed,
|
||||
* and take chroma from the base outright
|
||||
*
|
||||
* `runBase` is the only thing that knows how to denoise. Today it is a guided
|
||||
* filter or NLM; when the ONNX session lands it is a tiled model runner and
|
||||
* nothing else in this file changes. That is the seam the build plan is built
|
||||
* around, and it is RGB so a colour-trained model is fed what it expects.
|
||||
*
|
||||
* The reconstruction invariant: output luma is a per-pixel crossfade between
|
||||
* the untouched input (gate 1) and the denoised base (gate 0). It is bounded by
|
||||
* its two inputs, so it cannot ring or overshoot, and where the gate opens the
|
||||
* pixels are identical to the original.
|
||||
*/
|
||||
|
||||
import { fromYcc, toYcc, type RgbImage } from './color.ts';
|
||||
import {
|
||||
DEFAULT_GATE,
|
||||
detailGate,
|
||||
structureMap,
|
||||
type GateOptions,
|
||||
} from './detail.ts';
|
||||
import { estimateNoise, type NoiseModel } from './noise.ts';
|
||||
import { boxBlur, clamp01, clamp, resample, smoothstep } from './planes.ts';
|
||||
import type { BaseDenoiser, BaseImage } from './standin.ts';
|
||||
|
||||
export type DenoiserName = 'guided' | 'nlm' | 'onnx';
|
||||
|
||||
export interface DenoiseOptions {
|
||||
/** 0..1 blend against the input, applied after reconstruction. */
|
||||
amount: number;
|
||||
/**
|
||||
* Long edge of the plane the base denoiser runs on.
|
||||
*
|
||||
* Raising this on extreme-ISO frames looks like a free win on a detail metric
|
||||
* (+0.07 retention at 3200 on 18 MP ISO 6400) but was rejected: the corpus
|
||||
* guard measured grain 0.52 -> 1.30 and chroma 0.50 -> 1.20 at 3200. A sharper
|
||||
* base is not more detail, it is grain the crossfade then has to keep.
|
||||
*/
|
||||
baseEdge: number;
|
||||
/** Scale below which content is treated as detail worth protecting. */
|
||||
detailRadius: number;
|
||||
/**
|
||||
* Radius of the second, coarser detail band. 0 disables it.
|
||||
*
|
||||
* The fine band (radius 2) is what the original gate judged, and it leaves
|
||||
* near-isotropic 3-8 px texture unread: the texture that survives is the
|
||||
* part that happens to be coherent at 2 px. The coarse band is the difference
|
||||
* of two low-passes, so it sees that scale while rejecting both gradients and
|
||||
* pixel-scale grain -- measured in docs/PLAN.md.
|
||||
*/
|
||||
coarseRadius: number;
|
||||
/** Coarse-band thresholds, in fine-band noise units. */
|
||||
coarseLo: number;
|
||||
coarseHi: number;
|
||||
/**
|
||||
* Below this measured global grain the frame is clean and the pipeline tapers
|
||||
* itself to an identity. Without it a base-ISO file loses real micro-texture
|
||||
* to a denoise it never needed: measured at 36% of high-frequency energy on a
|
||||
* clean ISO 100 D700 frame.
|
||||
*/
|
||||
cleanSigma: number;
|
||||
gate: GateOptions;
|
||||
}
|
||||
|
||||
export const DEFAULT_OPTIONS: DenoiseOptions = {
|
||||
amount: 1,
|
||||
baseEdge: 1600,
|
||||
detailRadius: 2,
|
||||
coarseRadius: 6,
|
||||
coarseLo: 1.2,
|
||||
coarseHi: 2.0,
|
||||
cleanSigma: 2.5,
|
||||
gate: DEFAULT_GATE,
|
||||
};
|
||||
|
||||
export interface StageTimings {
|
||||
noise: number;
|
||||
base: number;
|
||||
detail: number;
|
||||
coarse: number;
|
||||
structure: number;
|
||||
reconstruct: number;
|
||||
total: number;
|
||||
}
|
||||
|
||||
export interface DenoiseStats {
|
||||
width: number;
|
||||
height: number;
|
||||
baseWidth: number;
|
||||
baseHeight: number;
|
||||
/** How much the base plane was reduced, e.g. 3.25 for a 6000px proxy. */
|
||||
backscale: number;
|
||||
amount: number;
|
||||
noise: { a: number; b: number; trend: 'fit' | 'flat'; global: number; atMid: number };
|
||||
/** Mean gate value: the share of the frame given back as structure. */
|
||||
gateCoverage: number;
|
||||
/** How much of the requested amount survived the clean-image taper (0..1). */
|
||||
autoGate: number;
|
||||
timings: StageTimings;
|
||||
}
|
||||
|
||||
export interface DenoiseOutput {
|
||||
rgb: Uint8Array;
|
||||
/** Luma of the denoised base, before detail re-injection, for inspection. */
|
||||
base: { data: Float32Array; width: number; height: number };
|
||||
stats: DenoiseStats;
|
||||
}
|
||||
|
||||
const now = () => performance.now();
|
||||
|
||||
/**
|
||||
* Prefiltered decimation of interleaved RGB to the base plane.
|
||||
*
|
||||
* The prefilter is load-bearing, and the coarse gate is what exposed it. A bare
|
||||
* bilinear tap reads four of every ~42 source pixels at `backscale` 3.25, so
|
||||
* pixel-scale grain is aliased into the base and comes back wherever the gate
|
||||
* is closed. Measured on the three mid-ISO frames at sigma 6, with the coarse
|
||||
* band on: grain 0.32/0.20/0.35 with bilinear against 0.22/0.20/0.22 with the
|
||||
* box prefilter, for 1.9% less high-frequency energy. The gate protects detail
|
||||
* and cannot protect grain out of an aliased base, so this belongs in the
|
||||
* decimator rather than in a threshold.
|
||||
*
|
||||
* One channel at a time through the tested `resample`, so the peak extra memory
|
||||
* is a single full-resolution plane, not three.
|
||||
*/
|
||||
function resampleRgb(
|
||||
image: RgbImage,
|
||||
width: number,
|
||||
height: number,
|
||||
prefilterRadius: number,
|
||||
): BaseImage {
|
||||
const out = new Float32Array(width * height * 3);
|
||||
const src = new Float32Array(image.width * image.height);
|
||||
for (let k = 0; k < 3; k++) {
|
||||
for (let i = 0, p = k; i < src.length; i++, p += 3) src[i] = image.rgb[p];
|
||||
if (prefilterRadius > 0) boxBlur(src, image.width, image.height, prefilterRadius, src);
|
||||
const small = resample(src, image.width, image.height, width, height);
|
||||
for (let i = 0, p = k; i < small.length; i++, p += 3) out[p] = small[i];
|
||||
}
|
||||
return { rgb: out, width, height };
|
||||
}
|
||||
|
||||
/**
|
||||
* Bilinear upscale of the base to full resolution, quantised to 8 bits so the
|
||||
* tested `toYcc` can be reused rather than duplicating the colour maths here.
|
||||
*/
|
||||
function upsampleBase(base: BaseImage, width: number, height: number): RgbImage {
|
||||
const rgb = new Uint8Array(width * height * 3);
|
||||
const xRatio = base.width / width;
|
||||
const yRatio = base.height / height;
|
||||
for (let y = 0; y < height; y++) {
|
||||
const sy = clamp((y + 0.5) * yRatio - 0.5, 0, base.height - 1);
|
||||
const y0 = Math.floor(sy);
|
||||
const y1 = Math.min(y0 + 1, base.height - 1);
|
||||
const wy = sy - y0;
|
||||
for (let x = 0; x < width; x++) {
|
||||
const sx = clamp((x + 0.5) * xRatio - 0.5, 0, base.width - 1);
|
||||
const x0 = Math.floor(sx);
|
||||
const x1 = Math.min(x0 + 1, base.width - 1);
|
||||
const wx = sx - x0;
|
||||
const a = (y0 * base.width + x0) * 3;
|
||||
const b = (y0 * base.width + x1) * 3;
|
||||
const c = (y1 * base.width + x0) * 3;
|
||||
const d = (y1 * base.width + x1) * 3;
|
||||
const o = (y * width + x) * 3;
|
||||
for (let k = 0; k < 3; k++) {
|
||||
const top = base.rgb[a + k] * (1 - wx) + base.rgb[b + k] * wx;
|
||||
const bot = base.rgb[c + k] * (1 - wx) + base.rgb[d + k] * wx;
|
||||
const v = top * (1 - wy) + bot * wy;
|
||||
rgb[o + k] = v < 0 ? 0 : v > 255 ? 255 : v + 0.5;
|
||||
}
|
||||
}
|
||||
}
|
||||
return { rgb, width, height };
|
||||
}
|
||||
|
||||
export async function denoiseRgb(
|
||||
image: RgbImage,
|
||||
options: Partial<DenoiseOptions>,
|
||||
runBase: BaseDenoiser,
|
||||
): Promise<DenoiseOutput> {
|
||||
const opts: DenoiseOptions = { ...DEFAULT_OPTIONS, ...options, gate: { ...DEFAULT_GATE, ...options.gate } };
|
||||
const started = now();
|
||||
const { width, height } = image;
|
||||
const pixels = width * height;
|
||||
|
||||
const { y, cb, cr } = toYcc(image);
|
||||
|
||||
let mark = now();
|
||||
const noise: NoiseModel = estimateNoise(y, width, height);
|
||||
const timings: StageTimings = {
|
||||
noise: now() - mark,
|
||||
base: 0,
|
||||
detail: 0,
|
||||
coarse: 0,
|
||||
structure: 0,
|
||||
reconstruct: 0,
|
||||
total: 0,
|
||||
};
|
||||
|
||||
// --- base: the inference scale -------------------------------------------
|
||||
const longEdge = Math.max(width, height);
|
||||
const scale = opts.baseEdge > 0 ? Math.min(1, opts.baseEdge / longEdge) : 1;
|
||||
const baseWidth = Math.max(8, Math.round(width * scale));
|
||||
const baseHeight = Math.max(8, Math.round(height * scale));
|
||||
const backscale = width / baseWidth;
|
||||
|
||||
mark = now();
|
||||
const prefilterRadius = backscale > 1.001 ? Math.max(0, Math.round((backscale - 1) / 2)) : 0;
|
||||
const baseInput = resampleRgb(image, baseWidth, baseHeight, prefilterRadius);
|
||||
// What the base denoiser is told about the noise it will see.
|
||||
//
|
||||
// The decimator is box(W) followed by the two bilinear taps. Along one axis
|
||||
// the taps overlap in W-1 samples at weight 1/W each and contribute
|
||||
// (1-t)^2 + t^2 at the two ends, which averages 2/3 over t, so the per-axis
|
||||
// *variance* gain is (W - 1/3) / W^2. Both axes are equal, so the standard
|
||||
// deviation falls by the same factor squared, i.e. by that number again:
|
||||
// 0.296 at W=3 against 1/backscale = 0.373.
|
||||
//
|
||||
// The old `/ backscale` was a guess -- and with bare bilinear (W=1) the true
|
||||
// figure is 2/3, which is why it read ~2x low. The classical stand-ins never
|
||||
// noticed (`planeSigma` re-measures each plane), but a model consumes this as
|
||||
// a prior, so it has to describe the filter that actually ran.
|
||||
const prefilterWidth = 2 * prefilterRadius + 1;
|
||||
const decimatedSigma =
|
||||
backscale > 1.001 ? (prefilterWidth - 1 / 3) / (prefilterWidth * prefilterWidth) : 1;
|
||||
const baseSigma = noise.sigmaAt(110) * decimatedSigma;
|
||||
const baseOut = await runBase(baseInput, baseSigma);
|
||||
const baseUp = toYcc(upsampleBase(baseOut, width, height));
|
||||
timings.base = now() - mark;
|
||||
|
||||
// --- detail gate at full resolution --------------------------------------
|
||||
//
|
||||
// The split filter is a plain low-pass, deliberately, and not an
|
||||
// edge-preserving one. An edge-aware filter follows strong edges, which
|
||||
// leaves them in the low band; the base cannot represent them after the
|
||||
// downscale, and nothing would put them back -- measured as 41% of edge
|
||||
// contrast lost. A low-pass pushes edges into `detail`, where the gate sees
|
||||
// them as signal.
|
||||
mark = now();
|
||||
const smooth = boxBlur(y, width, height, opts.detailRadius);
|
||||
const detail = new Float32Array(pixels);
|
||||
for (let i = 0; i < pixels; i++) detail[i] = y[i] - smooth[i];
|
||||
timings.detail = now() - mark;
|
||||
|
||||
mark = now();
|
||||
// The tensor is measured on the *original* luma, not on `smooth`.
|
||||
//
|
||||
// `smooth` is the same 5x5 low-pass that defines the detail band, so 2-3 px
|
||||
// texture has already been attenuated by the time the tensor sees it: the
|
||||
// gate was judging fine texture with a measurement that could not see it, and
|
||||
// coverage on a texture-rich frame came out *lower* than on a smooth one
|
||||
// (3.8% vs 9.3%). `structureMap` resamples to half resolution first, which
|
||||
// halves the noise while leaving 2 px structure intact, so this reads the
|
||||
// scale it is being asked about.
|
||||
const structure = structureMap(y, width, height, 2, 2, noise.global);
|
||||
const coherence = resample(structure.data, structure.width, structure.height, width, height);
|
||||
const sigmaMap = new Float32Array(pixels);
|
||||
for (let i = 0; i < pixels; i++) sigmaMap[i] = noise.sigmaAt(smooth[i]);
|
||||
timings.structure = now() - mark;
|
||||
|
||||
mark = now();
|
||||
let gate = detailGate(detail, width, height, sigmaMap, coherence, opts.gate);
|
||||
|
||||
// Second, coarser band: `smooth2 - smooth6` is a band-pass around 3-8 px. It
|
||||
// rejects gradients (both low-passes follow them) and pixel-scale grain (both
|
||||
// average it), so it can open on texture that the fine band reads as noise
|
||||
// without opening on flat noisy sky. The isolated-point path is a fine-band
|
||||
// instrument and is deliberately disabled here.
|
||||
if (opts.coarseRadius > opts.detailRadius && opts.coarseHi > opts.coarseLo) {
|
||||
const coarseSmooth = boxBlur(y, width, height, opts.coarseRadius);
|
||||
const coarse = new Float32Array(pixels);
|
||||
for (let i = 0; i < pixels; i++) coarse[i] = smooth[i] - coarseSmooth[i];
|
||||
const coarseGate = detailGate(coarse, width, height, sigmaMap, coherence, {
|
||||
...opts.gate,
|
||||
lo: opts.coarseLo,
|
||||
hi: opts.coarseHi,
|
||||
pointHi: 0,
|
||||
});
|
||||
for (let i = 0; i < pixels; i++) if (coarseGate[i] > gate[i]) gate[i] = coarseGate[i];
|
||||
timings.coarse = now() - mark;
|
||||
}
|
||||
|
||||
// Clean frames get their amount tapered to nothing: 0.8 sigma of measured
|
||||
// grain is quantisation, 2.5 is a genuinely noisy file.
|
||||
const autoGate = opts.cleanSigma > 0 ? smoothstep(0.8, opts.cleanSigma, noise.global) : 1;
|
||||
const amount = clamp01(opts.amount) * autoGate;
|
||||
|
||||
const outY = new Float32Array(pixels);
|
||||
const outCb = new Float32Array(pixels);
|
||||
const outCr = new Float32Array(pixels);
|
||||
let gateSum = 0;
|
||||
for (let i = 0; i < pixels; i++) {
|
||||
gateSum += gate[i];
|
||||
// Crossfade, never additive re-injection: additive detail lands on top of a
|
||||
// base that already contains a softened copy of the same edge and overshoots
|
||||
// by ~40%. A crossfade is bounded by its two inputs, so it cannot ring, and
|
||||
// where the gate opens the pixels are bit-identical to the original.
|
||||
outY[i] = y[i] + amount * (1 - gate[i]) * (baseUp.y[i] - y[i]);
|
||||
// Chroma follows the same gate, for a different reason than luma does. The
|
||||
// base carries chroma upsampled from `backscale` times smaller, so replacing
|
||||
// it outright smears colour across every sharp edge: on a small aircraft
|
||||
// against bright sky that is a magenta fringe along the wing and red/white
|
||||
// paint that loses its boundary. Keeping the original chroma where the gate
|
||||
// says "structure" keeps the paint edge registered with the luma edge it
|
||||
// belongs to. Flat areas still take the base chroma, which is where the
|
||||
// chroma noise lives.
|
||||
outCb[i] = cb[i] + amount * (1 - gate[i]) * (baseUp.cb[i] - cb[i]);
|
||||
outCr[i] = cr[i] + amount * (1 - gate[i]) * (baseUp.cr[i] - cr[i]);
|
||||
}
|
||||
|
||||
const rgb = fromYcc({ y: outY, cb: outCb, cr: outCr }, width, height);
|
||||
timings.reconstruct = now() - mark;
|
||||
timings.total = now() - started;
|
||||
|
||||
const baseLuma = new Float32Array(baseWidth * baseHeight);
|
||||
for (let i = 0, p = 0; i < baseLuma.length; i++, p += 3) {
|
||||
baseLuma[i] = 0.299 * baseOut.rgb[p] + 0.587 * baseOut.rgb[p + 1] + 0.114 * baseOut.rgb[p + 2];
|
||||
}
|
||||
|
||||
return {
|
||||
rgb,
|
||||
base: { data: baseLuma, width: baseWidth, height: baseHeight },
|
||||
stats: {
|
||||
width,
|
||||
height,
|
||||
baseWidth,
|
||||
baseHeight,
|
||||
backscale,
|
||||
amount,
|
||||
noise: {
|
||||
a: noise.a,
|
||||
b: noise.b,
|
||||
trend: noise.trend,
|
||||
global: noise.global,
|
||||
atMid: noise.sigmaAt(110),
|
||||
},
|
||||
gateCoverage: gateSum / pixels,
|
||||
autoGate,
|
||||
timings,
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
/**
|
||||
* Stand-in denoisers for the reduced-resolution base.
|
||||
*
|
||||
* These occupy exactly the slot the ONNX model occupies: take an interleaved
|
||||
* RGB plane at inference scale plus the noise level there, return a denoised
|
||||
* plane of the same shape. Having credible classical implementations in that
|
||||
* slot is what lets the pipeline, the harness and the baselines be finished and
|
||||
* measured before a model exists -- and they are the numbers the model has to
|
||||
* beat.
|
||||
*
|
||||
* The seam is RGB, not luma, deliberately: a denoiser trained on colour images
|
||||
* fed a replicated greyscale plane is out of distribution and underperforms a
|
||||
* plain guided filter. Chroma also comes from this plane, so the model gets a
|
||||
* say in colour noise, which is the part users actually complain about.
|
||||
*
|
||||
* `nlm` is the honest reference. `guided` is fast enough to iterate against.
|
||||
*/
|
||||
|
||||
import { guidedFilter } from './detail.ts';
|
||||
import { boxBlur } from './planes.ts';
|
||||
|
||||
export interface BaseImage {
|
||||
/** Interleaved RGB, `width * height * 3`, 0..255. */
|
||||
rgb: Float32Array;
|
||||
width: number;
|
||||
height: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Synchronous for the classical stand-ins, a promise for a model session.
|
||||
* ONNX inference cannot be made synchronous, so the seam allows both and the
|
||||
* pipeline awaits the result.
|
||||
*/
|
||||
export type BaseDenoiser = (image: BaseImage, sigma: number) => BaseImage | Promise<BaseImage>;
|
||||
|
||||
export function deinterleave(image: BaseImage): [Float32Array, Float32Array, Float32Array] {
|
||||
const n = image.width * image.height;
|
||||
const r = new Float32Array(n);
|
||||
const g = new Float32Array(n);
|
||||
const b = new Float32Array(n);
|
||||
for (let i = 0, p = 0; i < n; i++, p += 3) {
|
||||
r[i] = image.rgb[p];
|
||||
g[i] = image.rgb[p + 1];
|
||||
b[i] = image.rgb[p + 2];
|
||||
}
|
||||
return [r, g, b];
|
||||
}
|
||||
|
||||
export function interleave(
|
||||
r: Float32Array,
|
||||
g: Float32Array,
|
||||
b: Float32Array,
|
||||
width: number,
|
||||
height: number,
|
||||
): BaseImage {
|
||||
const rgb = new Float32Array(width * height * 3);
|
||||
for (let i = 0, p = 0; i < r.length; i++, p += 3) {
|
||||
rgb[p] = r[i];
|
||||
rgb[p + 1] = g[i];
|
||||
rgb[p + 2] = b[i];
|
||||
}
|
||||
return { rgb, width, height };
|
||||
}
|
||||
|
||||
/**
|
||||
* Robust sigma of one plane, from its own 3x3 high-pass.
|
||||
*
|
||||
* The caller's `sigma` is a luma figure, and per-channel noise differs a lot on
|
||||
* a CFA sensor -- blue is the noisiest -- so filtering all three at the luma
|
||||
* level over-smooths one channel and under-smooths another. Measuring each
|
||||
* plane costs three cheap passes at base scale and removes the guesswork.
|
||||
*/
|
||||
function planeSigma(plane: Float32Array, width: number, height: number, fallback: number): number {
|
||||
const smooth = boxBlur(plane, width, height, 1);
|
||||
const residual = new Float32Array(plane.length);
|
||||
for (let i = 0; i < plane.length; i++) residual[i] = Math.abs(plane[i] - smooth[i]);
|
||||
const sorted = residual.sort();
|
||||
const median = sorted[sorted.length >> 1] ?? 0;
|
||||
const sigma = (median * 1.4826) / 0.943;
|
||||
return sigma > 0.5 ? sigma : Math.max(1, fallback);
|
||||
}
|
||||
|
||||
/** Guided filter per channel: cheap, edge-preserving, mildly waxy. */
|
||||
export function guidedDenoiser(radius = 3, strength = 2.6): BaseDenoiser {
|
||||
return (image, sigma) => {
|
||||
const [r, g, b] = deinterleave(image);
|
||||
const filter = (plane: Float32Array) => {
|
||||
const s = planeSigma(plane, image.width, image.height, sigma);
|
||||
return guidedFilter(plane, image.width, image.height, radius, (strength * s) ** 2);
|
||||
};
|
||||
return interleave(filter(r), filter(g), filter(b), image.width, image.height);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Non-local means, per channel. Slow, and deliberately so: it is the quality
|
||||
* reference the neural model must beat, not a shipping path.
|
||||
*/
|
||||
export function nlmDenoiser(search = 2, patch = 1): BaseDenoiser {
|
||||
const patchW = 2 * patch + 1;
|
||||
const patchArea = patchW * patchW;
|
||||
return (image) => {
|
||||
const [r, g, b] = deinterleave(image);
|
||||
const planes = [r, g, b].map(
|
||||
(plane) => nlmPlane(plane, image.width, image.height, search, patch, patchW, patchArea),
|
||||
);
|
||||
return interleave(planes[0], planes[1], planes[2], image.width, image.height);
|
||||
};
|
||||
}
|
||||
|
||||
function nlmPlane(
|
||||
plane: Float32Array,
|
||||
width: number,
|
||||
height: number,
|
||||
search: number,
|
||||
patch: number,
|
||||
patchW: number,
|
||||
patchArea: number,
|
||||
): Float32Array {
|
||||
const out = new Float32Array(plane.length);
|
||||
const s = Math.max(1, search | 0);
|
||||
const clampX = (v: number) => (v < 0 ? 0 : v >= width ? width - 1 : v);
|
||||
const clampY = (v: number) => (v < 0 ? 0 : v >= height ? height - 1 : v);
|
||||
|
||||
let sumSq = 0;
|
||||
let count = 0;
|
||||
for (let i = 0; i < plane.length; i += 7) {
|
||||
sumSq += plane[i] * plane[i];
|
||||
count++;
|
||||
}
|
||||
const h = Math.max(2, Math.sqrt(sumSq / Math.max(1, count)) * 0.18);
|
||||
const cutoff = 4 * h * h;
|
||||
|
||||
for (let y = 0; y < height; y++) {
|
||||
for (let x = 0; x < width; x++) {
|
||||
const centre = plane[y * width + x];
|
||||
let acc = 0;
|
||||
let weight = 0;
|
||||
for (let dy = -s; dy <= s; dy++) {
|
||||
for (let dx = -s; dx <= s; dx++) {
|
||||
if (dx === 0 && dy === 0) continue;
|
||||
const ny = y + dy;
|
||||
const nx = x + dx;
|
||||
if (ny < 0 || ny >= height || nx < 0 || nx >= width) continue;
|
||||
|
||||
let dist = 0;
|
||||
for (let py = -patch; py <= patch; py++) {
|
||||
const ay = clampY(y + py) * width;
|
||||
const by = clampY(ny + py) * width;
|
||||
for (let px = -patch; px <= patch; px++) {
|
||||
const d = plane[ay + clampX(x + px)] - plane[by + clampX(nx + px)];
|
||||
dist += d * d;
|
||||
}
|
||||
}
|
||||
dist /= patchArea;
|
||||
if (dist > cutoff) continue;
|
||||
const w = Math.exp(-dist / (h * h));
|
||||
acc += w * plane[ny * width + nx];
|
||||
weight += w;
|
||||
}
|
||||
}
|
||||
out[y * width + x] = (acc + centre) / (weight + 1);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
import zlib from 'node:zlib';
|
||||
import { RAW_PREVIEW_EDGE } from './config.mjs';
|
||||
|
||||
let sharpModule = null;
|
||||
let sharpFailed = false;
|
||||
|
||||
/** sharp gives us JPEG encoding and resizing; without it we fall back to PNG. */
|
||||
export async function loadSharp() {
|
||||
if (sharpModule) return sharpModule;
|
||||
if (sharpFailed) return null;
|
||||
try {
|
||||
const mod = await import('sharp');
|
||||
sharpModule = mod.default;
|
||||
return sharpModule;
|
||||
} catch {
|
||||
sharpFailed = true;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
const CRC_TABLE = (() => {
|
||||
const table = new Int32Array(256);
|
||||
for (let n = 0; n < 256; n++) {
|
||||
let c = n;
|
||||
for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
|
||||
table[n] = c;
|
||||
}
|
||||
return table;
|
||||
})();
|
||||
|
||||
function crc32(buf) {
|
||||
let c = 0xffffffff;
|
||||
for (let i = 0; i < buf.length; i++) c = CRC_TABLE[(c ^ buf[i]) & 0xff] ^ (c >>> 8);
|
||||
return (c ^ 0xffffffff) >>> 0;
|
||||
}
|
||||
|
||||
function chunk(type, data) {
|
||||
const out = Buffer.alloc(8 + data.length + 4);
|
||||
out.writeUInt32BE(data.length, 0);
|
||||
out.write(type, 4, 'ascii');
|
||||
data.copy(out, 8);
|
||||
out.writeUInt32BE(crc32(Buffer.concat([Buffer.from(type, 'ascii'), data])), 8 + data.length);
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Minimal dependency-free 8-bit RGB PNG encoder (used only when sharp is absent). */
|
||||
export function encodePng(rgb, width, height) {
|
||||
const stride = width * 3;
|
||||
const raw = Buffer.alloc((stride + 1) * height);
|
||||
for (let y = 0; y < height; y++) {
|
||||
raw[y * (stride + 1)] = 0;
|
||||
Buffer.from(rgb.buffer, rgb.byteOffset + y * stride, stride).copy(raw, y * (stride + 1) + 1);
|
||||
}
|
||||
const idat = zlib.deflateSync(raw, { level: 6 });
|
||||
const ihdr = Buffer.alloc(13);
|
||||
ihdr.writeUInt32BE(width, 0);
|
||||
ihdr.writeUInt32BE(height, 4);
|
||||
ihdr[8] = 8;
|
||||
ihdr[9] = 2;
|
||||
ihdr[10] = 0;
|
||||
ihdr[11] = 0;
|
||||
ihdr[12] = 0;
|
||||
return Buffer.concat([
|
||||
Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
|
||||
chunk('IHDR', ihdr),
|
||||
chunk('IDAT', idat),
|
||||
chunk('IEND', Buffer.alloc(0)),
|
||||
]);
|
||||
}
|
||||
|
||||
/** Encode an interleaved RGB byte buffer as JPEG (sharp) or PNG (fallback). */
|
||||
export async function encodeRgb(rgb, width, height, quality = 92, maxEdge = 0) {
|
||||
const sharp = await loadSharp();
|
||||
if (!sharp) {
|
||||
return { data: encodePng(rgb, width, height), ext: 'png', width, height };
|
||||
}
|
||||
let img = sharp(Buffer.from(rgb.buffer, rgb.byteOffset, rgb.byteLength), {
|
||||
raw: { width, height, channels: 3 },
|
||||
});
|
||||
if (maxEdge > 0 && Math.max(width, height) > maxEdge) img = img.resize({ width: width >= height ? maxEdge : null, height: height > width ? maxEdge : null, fit: 'inside' });
|
||||
const data = await img.jpeg({ quality, chromaSubsampling: '4:4:4' }).toBuffer();
|
||||
const meta = await sharp(data).metadata();
|
||||
return { data, ext: 'jpg', width: Number(meta.width ?? width), height: Number(meta.height ?? height) };
|
||||
}
|
||||
|
||||
export async function jpegInfo(buffer) {
|
||||
const sharp = await loadSharp();
|
||||
if (!sharp) return null;
|
||||
try {
|
||||
const meta = await sharp(buffer).metadata();
|
||||
return { width: Number(meta.width ?? 0), height: Number(meta.height ?? 0), format: meta.format };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Re-encode any decodable image to a normalised JPEG proxy. */
|
||||
export async function toJpegProxy(buffer, maxEdge = RAW_PREVIEW_EDGE) {
|
||||
const sharp = await loadSharp();
|
||||
if (!sharp) return null;
|
||||
try {
|
||||
let img = sharp(buffer, { failOn: 'none' }).rotate();
|
||||
const meta = await img.metadata();
|
||||
const w = Number(meta.width ?? 0);
|
||||
const h = Number(meta.height ?? 0);
|
||||
if (!w || !h) return null;
|
||||
if (maxEdge > 0 && Math.max(w, h) > maxEdge) img = img.resize({ width: maxEdge, height: maxEdge, fit: 'inside' });
|
||||
const data = await img.jpeg({ quality: 92, chromaSubsampling: '4:4:4' }).toBuffer();
|
||||
const outMeta = await sharp(data).metadata();
|
||||
return { data, width: Number(outMeta.width ?? w), height: Number(outMeta.height ?? h), ext: 'jpg' };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export async function makeThumb(buffer, edge = 512) {
|
||||
const sharp = await loadSharp();
|
||||
if (!sharp) return null;
|
||||
try {
|
||||
const data = await sharp(buffer, { failOn: 'none' })
|
||||
.rotate()
|
||||
.resize({ width: edge, height: edge, fit: 'inside', withoutEnlargement: true })
|
||||
.jpeg({ quality: 82 })
|
||||
.toBuffer();
|
||||
return data;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
+1453
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,120 @@
|
||||
import { RAW_IDLE_MS, RAW_WORKERS } from './config.mjs';
|
||||
import { installLibrawRuntime } from './libraw-runtime.mjs';
|
||||
|
||||
let ctorPromise = null;
|
||||
|
||||
/** Load the decoder class once; installs the Node worker shim on first use. */
|
||||
export function loadLibRaw() {
|
||||
if (!ctorPromise) {
|
||||
ctorPromise = (async () => {
|
||||
await installLibrawRuntime();
|
||||
const mod = await import('libraw-wasm');
|
||||
const ctor = mod.default?.default ?? mod.default;
|
||||
if (typeof ctor !== 'function') throw new Error('libraw-wasm did not export a constructor');
|
||||
return ctor;
|
||||
})();
|
||||
}
|
||||
return ctorPromise;
|
||||
}
|
||||
|
||||
/**
|
||||
* Bounded pool of decoder instances. Each instance owns one worker thread, so
|
||||
* this caps how much demosaicing runs at the same time; extra jobs queue.
|
||||
* Idle instances are disposed after RAW_IDLE_MS to give the memory back.
|
||||
*/
|
||||
class LibRawPool {
|
||||
constructor(size = RAW_WORKERS) {
|
||||
this.size = Math.max(1, Math.floor(size));
|
||||
this.free = [];
|
||||
this.total = 0;
|
||||
this.waiters = [];
|
||||
this.closed = false;
|
||||
}
|
||||
|
||||
async acquire() {
|
||||
const entry = this.free.pop();
|
||||
if (entry) {
|
||||
if (entry.timer) clearTimeout(entry.timer);
|
||||
return entry.lib;
|
||||
}
|
||||
if (this.total < this.size) {
|
||||
this.total++;
|
||||
try {
|
||||
const Ctor = await loadLibRaw();
|
||||
return new Ctor();
|
||||
} catch (err) {
|
||||
this.total--;
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
return new Promise((resolve, reject) => this.waiters.push({ resolve, reject }));
|
||||
}
|
||||
|
||||
release(lib, healthy = true) {
|
||||
if (this.closed || !healthy) {
|
||||
this.discard(lib);
|
||||
return;
|
||||
}
|
||||
const waiter = this.waiters.shift();
|
||||
if (waiter) {
|
||||
waiter.resolve(lib);
|
||||
return;
|
||||
}
|
||||
const entry = { lib, timer: null };
|
||||
entry.timer = setTimeout(() => {
|
||||
const idx = this.free.indexOf(entry);
|
||||
if (idx >= 0) {
|
||||
this.free.splice(idx, 1);
|
||||
this.discard(lib);
|
||||
}
|
||||
}, RAW_IDLE_MS);
|
||||
entry.timer.unref?.();
|
||||
this.free.push(entry);
|
||||
}
|
||||
|
||||
discard(lib) {
|
||||
try {
|
||||
lib.dispose();
|
||||
} catch {
|
||||
/* worker already gone */
|
||||
}
|
||||
this.total = Math.max(0, this.total - 1);
|
||||
const waiter = this.waiters.shift();
|
||||
if (waiter) {
|
||||
this.total++;
|
||||
loadLibRaw()
|
||||
.then((Ctor) => new Ctor())
|
||||
.then(waiter.resolve, waiter.reject);
|
||||
}
|
||||
}
|
||||
|
||||
/** Run `fn` with a decoder instance; the instance returns to the pool after. */
|
||||
async use(fn) {
|
||||
const lib = await this.acquire();
|
||||
let healthy = true;
|
||||
try {
|
||||
return await fn(lib);
|
||||
} catch (err) {
|
||||
// A dead worker keeps failing, so recycle it instead of handing it back.
|
||||
if (/worker|terminated|disposed|memory/i.test(String(err?.message ?? ''))) healthy = false;
|
||||
throw err;
|
||||
} finally {
|
||||
this.release(lib, healthy);
|
||||
}
|
||||
}
|
||||
|
||||
get stats() {
|
||||
return {
|
||||
size: this.size,
|
||||
busy: this.total - this.free.length,
|
||||
idle: this.free.length,
|
||||
queued: this.waiters.length,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export const rawPool = new LibRawPool();
|
||||
|
||||
export function poolSupport() {
|
||||
return { size: rawPool.size, workers: RAW_WORKERS };
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
/**
|
||||
* libraw-wasm is browser-first: the wrapper spawns a Web Worker and the
|
||||
* Emscripten build loads libraw.wasm with fetch(). Node has neither a global
|
||||
* Worker nor file:// support in fetch, so the decoder runs in a worker_thread
|
||||
* with a tiny browser-globals shim (see libraw-worker.mjs).
|
||||
*
|
||||
* This is a no-op in the browser, where the real Worker already exists.
|
||||
*/
|
||||
let installed = false;
|
||||
|
||||
export async function installLibrawRuntime() {
|
||||
if (installed) return;
|
||||
installed = true;
|
||||
if (typeof globalThis.Worker === 'function') return;
|
||||
|
||||
const { Worker: NodeWorker } = await import('node:worker_threads');
|
||||
const entry = new URL('./libraw-worker.mjs', import.meta.url);
|
||||
|
||||
class BrowserWorker {
|
||||
constructor() {
|
||||
this._worker = new NodeWorker(entry);
|
||||
this._worker.on('message', (data) => this.onmessage?.({ data }));
|
||||
this._worker.on('error', (err) => this.onerror?.(err));
|
||||
}
|
||||
postMessage(message, transfer) {
|
||||
this._worker.postMessage(message, transfer);
|
||||
}
|
||||
terminate() {
|
||||
return this._worker.terminate();
|
||||
}
|
||||
}
|
||||
|
||||
globalThis.Worker = BrowserWorker;
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import { parentPort } from 'node:worker_threads';
|
||||
import fs from 'node:fs/promises';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
// libraw-wasm targets browsers: emulate the worker globals its build expects.
|
||||
globalThis.self = globalThis;
|
||||
globalThis.WorkerGlobalScope = globalThis;
|
||||
globalThis.postMessage = (msg, transfer) => parentPort.postMessage(msg, transfer);
|
||||
globalThis.addEventListener = () => {};
|
||||
|
||||
// Emscripten loads libraw.wasm through fetch(); Node's fetch rejects file:// URLs.
|
||||
const realFetch = globalThis.fetch;
|
||||
globalThis.fetch = async (url, init) => {
|
||||
const href = typeof url === 'string' ? url : url instanceof URL ? url.href : String(url);
|
||||
if (href.startsWith('file:')) {
|
||||
const buf = await fs.readFile(fileURLToPath(href));
|
||||
return new Response(buf, { status: 200, headers: { 'content-type': 'application/wasm' } });
|
||||
}
|
||||
return realFetch(url, init);
|
||||
};
|
||||
|
||||
// Buffer anything that arrives before the module registers `onmessage`.
|
||||
const queue = [];
|
||||
parentPort.on('message', (data) => {
|
||||
if (typeof globalThis.onmessage === 'function') globalThis.onmessage({ data });
|
||||
else queue.push(data);
|
||||
});
|
||||
|
||||
await import('libraw-wasm/dist/worker.js');
|
||||
|
||||
for (const data of queue.splice(0)) globalThis.onmessage({ data });
|
||||
+129
@@ -0,0 +1,129 @@
|
||||
import nodemailer from 'nodemailer';
|
||||
import { kv } from './db.mjs';
|
||||
import {
|
||||
SMTP_APP_PASSWORD,
|
||||
SMTP_FROM,
|
||||
SMTP_HOST,
|
||||
SMTP_PORT,
|
||||
SMTP_SECURE,
|
||||
SMTP_USER,
|
||||
} from './config.mjs';
|
||||
|
||||
const SETTINGS_KEY = 'mailSettings';
|
||||
|
||||
function savedSettings() {
|
||||
const value = kv.get(SETTINGS_KEY);
|
||||
return value && typeof value === 'object' ? value : {};
|
||||
}
|
||||
|
||||
/** Never returns the app password; `hasPassword` is enough for the admin UI. */
|
||||
export function mailStatus() {
|
||||
const saved = savedSettings();
|
||||
const user = String(saved.user || SMTP_USER || '').trim();
|
||||
const appPassword = String(saved.appPassword || SMTP_APP_PASSWORD || '');
|
||||
const from = String(saved.from || SMTP_FROM || user).trim();
|
||||
const host = String(saved.host || SMTP_HOST || 'smtp.gmail.com').trim();
|
||||
const port = Number(saved.port || SMTP_PORT || 465);
|
||||
const secure = typeof saved.secure === 'boolean' ? saved.secure : SMTP_SECURE;
|
||||
return {
|
||||
configured: Boolean(user && appPassword),
|
||||
source: saved.user || saved.appPassword ? 'admin' : user || appPassword ? 'environment' : 'none',
|
||||
host,
|
||||
port,
|
||||
secure,
|
||||
user,
|
||||
from,
|
||||
hasPassword: Boolean(appPassword),
|
||||
gmail: host === 'smtp.gmail.com',
|
||||
};
|
||||
}
|
||||
|
||||
function validateSettings(input) {
|
||||
const current = savedSettings();
|
||||
const user = String(input.user ?? current.user ?? SMTP_USER ?? '').trim();
|
||||
const appPassword = String(
|
||||
(input.appPassword && String(input.appPassword).trim()) ||
|
||||
current.appPassword ||
|
||||
SMTP_APP_PASSWORD ||
|
||||
'',
|
||||
).trim();
|
||||
const from = String(input.from ?? current.from ?? SMTP_FROM ?? user).trim();
|
||||
const host = String(input.host ?? current.host ?? SMTP_HOST ?? 'smtp.gmail.com').trim();
|
||||
const port = Number(input.port ?? current.port ?? SMTP_PORT ?? 465);
|
||||
const secure = typeof input.secure === 'boolean' ? input.secure : port === 465;
|
||||
|
||||
if (!/^[^@\s]+@[^@\s]+\.[^@\s]{2,}$/.test(user)) {
|
||||
throw new Error('Enter the Gmail address that will send notifications');
|
||||
}
|
||||
if (!appPassword) throw new Error('Enter the Google app password for that Gmail account');
|
||||
if (appPassword.length < 8) throw new Error('That app password looks too short');
|
||||
if (from && !/^[^@\s]+@[^@\s]+\.[^@\s]{2,}$/.test(from)) {
|
||||
throw new Error('The From address is not a valid email address');
|
||||
}
|
||||
if (!host) throw new Error('Enter an SMTP host');
|
||||
if (!Number.isInteger(port) || port < 1 || port > 65535) {
|
||||
throw new Error('Enter a valid SMTP port');
|
||||
}
|
||||
|
||||
return { user, appPassword, from: from || user, host, port, secure };
|
||||
}
|
||||
|
||||
export function saveMailSettings(input) {
|
||||
const next = validateSettings(input ?? {});
|
||||
kv.set(SETTINGS_KEY, next);
|
||||
return mailStatus();
|
||||
}
|
||||
|
||||
export async function sendAppMail({ to, subject, text, html }) {
|
||||
const settings = mailStatus();
|
||||
if (!settings.configured) {
|
||||
throw new Error(
|
||||
'Email is not configured. Add the Gmail address and Google app password in Administration → Quotas.',
|
||||
);
|
||||
}
|
||||
if (!to) throw new Error('A recipient email address is required');
|
||||
|
||||
const saved = savedSettings();
|
||||
const appPassword = saved.appPassword || SMTP_APP_PASSWORD;
|
||||
const transporter = nodemailer.createTransport({
|
||||
host: settings.host,
|
||||
port: settings.port,
|
||||
secure: settings.secure,
|
||||
auth: { user: settings.user, pass: appPassword },
|
||||
connectionTimeout: 12_000,
|
||||
greetingTimeout: 12_000,
|
||||
socketTimeout: 20_000,
|
||||
});
|
||||
|
||||
try {
|
||||
return await transporter.sendMail({
|
||||
from: settings.from || settings.user,
|
||||
replyTo: settings.from || settings.user,
|
||||
to,
|
||||
subject,
|
||||
text,
|
||||
html,
|
||||
});
|
||||
} finally {
|
||||
transporter.close();
|
||||
}
|
||||
}
|
||||
|
||||
export async function sendTestMail(to) {
|
||||
return sendAppMail({
|
||||
to,
|
||||
subject: 'Luminary email notifications are working',
|
||||
text:
|
||||
'This is a test message from Luminary. Your Gmail app password is configured correctly, ' +
|
||||
'so quota warnings and scheduled storage-prune notices can reach your team.\n\n' +
|
||||
'— Luminary',
|
||||
html: `
|
||||
<div style="font-family:Arial,Helvetica,sans-serif;line-height:1.55;color:#222">
|
||||
<h2 style="margin:0 0 12px">Luminary email is working</h2>
|
||||
<p>Your Gmail app password is configured correctly. Quota warnings and scheduled
|
||||
storage-prune notices can now reach your team.</p>
|
||||
<p style="color:#777;font-size:12px">— Luminary</p>
|
||||
</div>
|
||||
`,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,454 @@
|
||||
import {
|
||||
QUOTA_BYTES,
|
||||
QUOTA_TARGET_RATIO,
|
||||
QUOTA_WARN_RATIO,
|
||||
PUBLIC_URL,
|
||||
} from './config.mjs';
|
||||
import {
|
||||
allQuotaRows,
|
||||
deletedPhotoBytes,
|
||||
getPhoto,
|
||||
listEvents,
|
||||
listPhotos,
|
||||
livePhotoBytesByOwner,
|
||||
quotaRow,
|
||||
removeEvent,
|
||||
removePhoto,
|
||||
saveQuota,
|
||||
users,
|
||||
} from './db.mjs';
|
||||
import { removeAsset } from './storage.mjs';
|
||||
import { clearDenoised } from './denoise.mjs';
|
||||
import { mailStatus, sendAppMail } from './mail.mjs';
|
||||
|
||||
const GIB = 1024 ** 3;
|
||||
const PRUNE_GRACE_MS = 24 * 60 * 60 * 1000;
|
||||
const WARNING_COOLDOWN_MS = 24 * 60 * 60 * 1000;
|
||||
|
||||
const fmtBytes = (bytes) => {
|
||||
if (bytes >= GIB) return `${(bytes / GIB).toFixed(1)} GB`;
|
||||
if (bytes >= 1024 ** 2) return `${Math.round(bytes / 1024 ** 2)} MB`;
|
||||
return `${Math.max(0, Math.round(bytes / 1024))} KB`;
|
||||
};
|
||||
|
||||
const fmtDate = (ms) =>
|
||||
new Date(ms).toLocaleString(undefined, {
|
||||
weekday: 'short',
|
||||
month: 'short',
|
||||
day: 'numeric',
|
||||
hour: 'numeric',
|
||||
minute: '2-digit',
|
||||
});
|
||||
|
||||
const appUrl = () => PUBLIC_URL || 'http://localhost:8787';
|
||||
|
||||
function safePlan(value) {
|
||||
if (!value) return null;
|
||||
if (typeof value === 'object') return value;
|
||||
try {
|
||||
return JSON.parse(value);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function limitFor(userId) {
|
||||
const row = quotaRow(userId);
|
||||
return Math.max(1, Number(row?.bytes_limit) || QUOTA_BYTES);
|
||||
}
|
||||
|
||||
/** Total bytes represented by an account's photo records, including Trash. */
|
||||
export function quotaUsage(userId) {
|
||||
return livePhotoBytesByOwner(userId) + deletedPhotoBytes(userId);
|
||||
}
|
||||
|
||||
export function quotaState(userId) {
|
||||
const row = quotaRow(userId);
|
||||
const limit = limitFor(userId);
|
||||
const used = quotaUsage(userId);
|
||||
const ratio = limit > 0 ? used / limit : 0;
|
||||
return {
|
||||
userId,
|
||||
limit,
|
||||
used,
|
||||
remaining: Math.max(0, limit - used),
|
||||
ratio,
|
||||
percent: Math.min(999, Math.round(ratio * 100)),
|
||||
warn: used >= limit * QUOTA_WARN_RATIO,
|
||||
over: used > limit,
|
||||
warnAt: Math.round(limit * QUOTA_WARN_RATIO),
|
||||
pruneAt: row?.prune_at ?? null,
|
||||
prunePlan: safePlan(row?.prune_plan),
|
||||
pruneNotifiedAt: row?.prune_notified_at ?? null,
|
||||
lastWarningAt: row?.last_quota_email_at ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Oldest events are removed first. If the oldest events are not enough, loose
|
||||
* photos are added oldest-first. The stored plan is what the warning email
|
||||
* describes, so a later upload cannot silently get caught up in the prune.
|
||||
*/
|
||||
export function prunePlan(userId, limit = limitFor(userId)) {
|
||||
const photos = listPhotos(userId);
|
||||
const groups = new Map();
|
||||
for (const photo of photos) {
|
||||
const key = photo.eventId || '';
|
||||
if (!groups.has(key)) groups.set(key, []);
|
||||
groups.get(key).push(photo);
|
||||
}
|
||||
|
||||
const events = listEvents(userId)
|
||||
.map((event) => {
|
||||
const members = groups.get(event.id) ?? [];
|
||||
return {
|
||||
id: event.id,
|
||||
name: event.name || 'Untitled event',
|
||||
createdAt: event.createdAt ?? 0,
|
||||
photos: members.map((photo) => photo.id),
|
||||
bytes: members.reduce((sum, photo) => sum + (Number(photo.size) || 0), 0),
|
||||
};
|
||||
})
|
||||
.filter((event) => event.photos.length)
|
||||
.sort((a, b) => a.createdAt - b.createdAt);
|
||||
|
||||
const target = Math.max(0, Math.floor(limit * QUOTA_TARGET_RATIO));
|
||||
const used = photos.reduce((sum, photo) => sum + (Number(photo.size) || 0), 0);
|
||||
let projected = used;
|
||||
const chosenEvents = [];
|
||||
const chosenPhotoIds = new Set();
|
||||
|
||||
for (const event of events) {
|
||||
if (projected <= target) break;
|
||||
chosenEvents.push(event);
|
||||
event.photos.forEach((id) => chosenPhotoIds.add(id));
|
||||
projected -= event.bytes;
|
||||
}
|
||||
|
||||
const loosePhotos = [];
|
||||
if (projected > target) {
|
||||
const remaining = photos
|
||||
.filter((photo) => !chosenPhotoIds.has(photo.id))
|
||||
.filter((photo) => !events.some((event) => event.id === photo.eventId))
|
||||
.sort((a, b) => (a.createdAt ?? 0) - (b.createdAt ?? 0));
|
||||
for (const photo of remaining) {
|
||||
if (projected <= target) break;
|
||||
const bytes = Number(photo.size) || 0;
|
||||
loosePhotos.push({ id: photo.id, name: photo.name || photo.id, bytes });
|
||||
projected -= bytes;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
targetBytes: target,
|
||||
usedBytes: used,
|
||||
projectedBytes: Math.max(0, projected),
|
||||
freedBytes: Math.max(0, used - Math.max(0, projected)),
|
||||
events: chosenEvents,
|
||||
photos: loosePhotos,
|
||||
};
|
||||
}
|
||||
|
||||
function planText(plan) {
|
||||
const lines = [];
|
||||
for (const event of plan.events) {
|
||||
lines.push(`• ${event.name} — ${event.photos.length} photo${event.photos.length === 1 ? '' : 's'}, ${fmtBytes(event.bytes)}`);
|
||||
}
|
||||
if (plan.photos.length) {
|
||||
lines.push(
|
||||
`• ${plan.photos.length} loose photo${plan.photos.length === 1 ? '' : 's'} — ${fmtBytes(plan.photos.reduce((sum, photo) => sum + photo.bytes, 0))}`,
|
||||
);
|
||||
}
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
function planHtml(plan) {
|
||||
const rows = plan.events
|
||||
.map(
|
||||
(event) =>
|
||||
`<li><strong>${escapeHtml(event.name)}</strong> — ${event.photos.length} photo${event.photos.length === 1 ? '' : 's'}, ${fmtBytes(event.bytes)}</li>`,
|
||||
)
|
||||
.join('');
|
||||
const loose = plan.photos.length
|
||||
? `<li>${plan.photos.length} unassigned photo${plan.photos.length === 1 ? '' : 's'} — ${fmtBytes(plan.photos.reduce((sum, photo) => sum + photo.bytes, 0))}</li>`
|
||||
: '';
|
||||
return `<ul>${rows}${loose}</ul>`;
|
||||
}
|
||||
|
||||
function escapeHtml(value) {
|
||||
return String(value)
|
||||
.replaceAll('&', '&')
|
||||
.replaceAll('<', '<')
|
||||
.replaceAll('>', '>')
|
||||
.replaceAll('"', '"');
|
||||
}
|
||||
|
||||
async function pruneWarningEmail(user, state, plan, pruneAt) {
|
||||
const when = fmtDate(pruneAt);
|
||||
const subject = `Luminary: ${fmtBytes(plan.freedBytes)} will be pruned in 24 hours`;
|
||||
const text = [
|
||||
`Hi ${user.name || user.email},`,
|
||||
'',
|
||||
`Your Luminary storage is ${state.percent}% full (${fmtBytes(state.used)} of ${fmtBytes(state.limit)}).`,
|
||||
`An administrator scheduled a storage cleanup for ${when} — about 24 hours from now.`,
|
||||
'',
|
||||
'Unless you free space before then, Luminary will permanently remove the oldest content listed below:',
|
||||
planText(plan) || '• No individual items were identified.',
|
||||
'',
|
||||
`This should free about ${fmtBytes(plan.freedBytes)} and leave your library around ${fmtBytes(plan.projectedBytes)}.`,
|
||||
'',
|
||||
`Review your library now: ${appUrl()}`,
|
||||
'',
|
||||
'Deleting photos or emptying Trash before the scheduled time will cancel or reduce the cleanup.',
|
||||
'— Luminary',
|
||||
].join('\n');
|
||||
|
||||
const html = `
|
||||
<div style="font-family:Arial,Helvetica,sans-serif;line-height:1.55;color:#222;max-width:640px">
|
||||
<h2 style="margin:0 0 12px">Storage cleanup scheduled</h2>
|
||||
<p>Hi ${escapeHtml(user.name || user.email)},</p>
|
||||
<p>Your Luminary storage is <strong>${state.percent}% full</strong>
|
||||
(${fmtBytes(state.used)} of ${fmtBytes(state.limit)}).</p>
|
||||
<p style="padding:12px 14px;background:#fff4dd;border-left:4px solid #d99a20">
|
||||
An administrator scheduled a storage cleanup for
|
||||
<strong>${escapeHtml(when)}</strong> — about 24 hours from now.
|
||||
</p>
|
||||
<p>Unless you free space before then, Luminary will permanently remove the oldest content
|
||||
listed below:</p>
|
||||
${planHtml(plan) || '<p>No individual items were identified.</p>'}
|
||||
<p>This should free about <strong>${fmtBytes(plan.freedBytes)}</strong> and leave your
|
||||
library around ${fmtBytes(plan.projectedBytes)}.</p>
|
||||
<p><a href="${escapeHtml(appUrl())}" style="display:inline-block;padding:9px 16px;background:#3d7eff;color:#fff;text-decoration:none;border-radius:6px">Review your library</a></p>
|
||||
<p style="color:#777;font-size:12px">Deleting photos or emptying Trash before the scheduled
|
||||
time will cancel or reduce the cleanup.<br>— Luminary</p>
|
||||
</div>
|
||||
`;
|
||||
await sendAppMail({ to: user.email, subject, text, html });
|
||||
}
|
||||
|
||||
async function quotaWarningEmail(user, state) {
|
||||
const subject = `Luminary: your storage is ${state.percent}% full`;
|
||||
const text = [
|
||||
`Hi ${user.name || user.email},`,
|
||||
'',
|
||||
`You are nearing your Luminary storage quota: ${fmtBytes(state.used)} used of ${fmtBytes(state.limit)} (${state.percent}%).`,
|
||||
'',
|
||||
'Free some space by deleting photos you no longer need or emptying Trash. If the quota is exceeded, an administrator can schedule a 24-hour storage cleanup.',
|
||||
'',
|
||||
`Open Luminary: ${appUrl()}`,
|
||||
'',
|
||||
'— Luminary',
|
||||
].join('\n');
|
||||
const html = `
|
||||
<div style="font-family:Arial,Helvetica,sans-serif;line-height:1.55;color:#222;max-width:640px">
|
||||
<h2 style="margin:0 0 12px">You are nearing your storage quota</h2>
|
||||
<p>Hi ${escapeHtml(user.name || user.email)},</p>
|
||||
<p>You have used <strong>${fmtBytes(state.used)}</strong> of your
|
||||
<strong>${fmtBytes(state.limit)}</strong> Luminary quota (${state.percent}%).</p>
|
||||
<p>Delete photos you no longer need or empty Trash to free space. If the quota is exceeded,
|
||||
an administrator can schedule a 24-hour storage cleanup.</p>
|
||||
<p><a href="${escapeHtml(appUrl())}" style="display:inline-block;padding:9px 16px;background:#3d7eff;color:#fff;text-decoration:none;border-radius:6px">Open Luminary</a></p>
|
||||
<p style="color:#777;font-size:12px">— Luminary</p>
|
||||
</div>
|
||||
`;
|
||||
await sendAppMail({ to: user.email, subject, text, html });
|
||||
}
|
||||
|
||||
export async function schedulePrune(userId) {
|
||||
const user = users.byId(userId);
|
||||
if (!user) throw new Error('No such account');
|
||||
if (!mailStatus().configured) {
|
||||
throw new Error(
|
||||
'Email notifications must be configured before a prune can be scheduled, so the 24-hour warning can reach the user.',
|
||||
);
|
||||
}
|
||||
const state = quotaState(userId);
|
||||
const plan = prunePlan(userId, state.limit);
|
||||
if (plan.freedBytes <= 0) {
|
||||
throw new Error('There is nothing old enough to prune. The account is already below the cleanup target.');
|
||||
}
|
||||
if (plan.projectedBytes > state.limit) {
|
||||
throw new Error(
|
||||
'The oldest content cannot bring this account under its quota. Raise the limit or remove large events manually.',
|
||||
);
|
||||
}
|
||||
|
||||
const pruneAt = Date.now() + PRUNE_GRACE_MS;
|
||||
await pruneWarningEmail(user, state, plan, pruneAt);
|
||||
saveQuota(userId, {
|
||||
pruneAt,
|
||||
prunePlan: plan,
|
||||
pruneNotifiedAt: Date.now(),
|
||||
});
|
||||
return { pruneAt, plan, state: quotaState(userId), warningSent: true };
|
||||
}
|
||||
|
||||
export function cancelPrune(userId) {
|
||||
saveQuota(userId, { pruneAt: null, prunePlan: null, pruneNotifiedAt: null });
|
||||
return quotaState(userId);
|
||||
}
|
||||
|
||||
export async function warnUser(userId) {
|
||||
const user = users.byId(userId);
|
||||
if (!user) throw new Error('No such account');
|
||||
const state = quotaState(userId);
|
||||
if (!state.warn && !state.over) throw new Error('This account is below its warning threshold');
|
||||
await quotaWarningEmail(user, state);
|
||||
saveQuota(userId, { lastQuotaEmailAt: Date.now() });
|
||||
return state;
|
||||
}
|
||||
|
||||
export function setUserQuota(userId, bytes) {
|
||||
if (!users.byId(userId)) throw new Error('No such account');
|
||||
const limit = Number(bytes);
|
||||
const min = GIB;
|
||||
const max = 10_000 * GIB;
|
||||
if (!Number.isFinite(limit) || limit < min || limit > max) {
|
||||
throw new Error('Choose a quota between 1 GB and 10 TB');
|
||||
}
|
||||
saveQuota(userId, { bytesLimit: Math.round(limit) });
|
||||
return quotaState(userId);
|
||||
}
|
||||
|
||||
export function quotasForAdmin() {
|
||||
return users.list().map((user) => {
|
||||
const state = quotaState(user.id);
|
||||
return {
|
||||
...state,
|
||||
user,
|
||||
plan: state.prunePlan ?? prunePlan(user.id, state.limit),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export async function sendTestNotification(to) {
|
||||
if (!mailStatus().configured) {
|
||||
throw new Error('Add the Gmail address and app password first');
|
||||
}
|
||||
await sendAppMail({
|
||||
to,
|
||||
subject: 'Luminary email notifications are working',
|
||||
text: 'This is a test message from Luminary. Quota warnings and prune notices are configured correctly.',
|
||||
html: '<p>This is a test message from Luminary. Quota warnings and prune notices are configured correctly.</p>',
|
||||
});
|
||||
}
|
||||
|
||||
async function executePlan(userId, plan) {
|
||||
let removedPhotos = 0;
|
||||
let freedBytes = 0;
|
||||
const eventIds = new Set();
|
||||
|
||||
for (const event of plan.events ?? []) eventIds.add(event.id);
|
||||
|
||||
for (const event of plan.events ?? []) {
|
||||
for (const photoId of event.photos ?? []) {
|
||||
const photo = getPhoto(photoId);
|
||||
if (!photo) continue;
|
||||
freedBytes += Number(photo.size) || 0;
|
||||
removePhoto(photoId);
|
||||
clearDenoised(photoId);
|
||||
await removeAsset(photoId);
|
||||
removedPhotos += 1;
|
||||
}
|
||||
}
|
||||
for (const entry of plan.photos ?? []) {
|
||||
const photo = getPhoto(entry.id);
|
||||
if (!photo) continue;
|
||||
freedBytes += Number(photo.size) || 0;
|
||||
removePhoto(entry.id);
|
||||
clearDenoised(entry.id);
|
||||
await removeAsset(entry.id);
|
||||
removedPhotos += 1;
|
||||
}
|
||||
for (const eventId of eventIds) {
|
||||
if (!listPhotos(userId).some((photo) => photo.eventId === eventId)) removeEvent(eventId);
|
||||
}
|
||||
return { removedPhotos, freedBytes };
|
||||
}
|
||||
|
||||
async function pruneDueAccounts() {
|
||||
const now = Date.now();
|
||||
for (const row of allQuotaRows()) {
|
||||
if (!row.prune_at || Number(row.prune_at) > now) continue;
|
||||
const user = users.byId(row.user_id);
|
||||
const plan = safePlan(row.prune_plan);
|
||||
if (!user || !plan) {
|
||||
saveQuota(row.user_id, { pruneAt: null, prunePlan: null, pruneNotifiedAt: null });
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
const before = quotaUsage(row.user_id);
|
||||
const result = await executePlan(row.user_id, plan);
|
||||
const after = quotaUsage(row.user_id);
|
||||
saveQuota(row.user_id, {
|
||||
pruneAt: null,
|
||||
prunePlan: null,
|
||||
pruneNotifiedAt: null,
|
||||
});
|
||||
const state = quotaState(row.user_id);
|
||||
await sendAppMail({
|
||||
to: user.email,
|
||||
subject: 'Luminary: your scheduled storage cleanup is complete',
|
||||
text: [
|
||||
`Hi ${user.name || user.email},`,
|
||||
'',
|
||||
`The scheduled Luminary cleanup removed ${result.removedPhotos} photo${result.removedPhotos === 1 ? '' : 's'} and freed ${fmtBytes(before - after)}.`,
|
||||
`Your library is now ${fmtBytes(after)} of ${fmtBytes(state.limit)} (${state.percent}%).`,
|
||||
'',
|
||||
`Open Luminary: ${appUrl()}`,
|
||||
'',
|
||||
'— Luminary',
|
||||
].join('\n'),
|
||||
html: `
|
||||
<div style="font-family:Arial,Helvetica,sans-serif;line-height:1.55;color:#222;max-width:640px">
|
||||
<h2 style="margin:0 0 12px">Scheduled cleanup complete</h2>
|
||||
<p>Hi ${escapeHtml(user.name || user.email)},</p>
|
||||
<p>The scheduled Luminary cleanup removed
|
||||
<strong>${result.removedPhotos} photo${result.removedPhotos === 1 ? '' : 's'}</strong>
|
||||
and freed <strong>${fmtBytes(before - after)}</strong>.</p>
|
||||
<p>Your library is now ${fmtBytes(after)} of ${fmtBytes(state.limit)} (${state.percent}%).</p>
|
||||
<p style="color:#777;font-size:12px">— Luminary</p>
|
||||
</div>
|
||||
`,
|
||||
}).catch((err) => console.error(`[luminary] prune email to ${user.email} failed: ${err.message}`));
|
||||
} catch (err) {
|
||||
console.error(`[luminary] prune for ${user.email} failed: ${err.message}`);
|
||||
saveQuota(row.user_id, { pruneAt: null, prunePlan: null, pruneNotifiedAt: null });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function sendQuotaWarnings() {
|
||||
if (!mailStatus().configured) return;
|
||||
const now = Date.now();
|
||||
for (const user of users.list()) {
|
||||
if (user.disabled) continue;
|
||||
const row = quotaRow(user.id);
|
||||
if (row?.prune_at) continue;
|
||||
const state = quotaState(user.id);
|
||||
if (!state.warn) continue;
|
||||
if (row?.last_quota_email_at && now - Number(row.last_quota_email_at) < WARNING_COOLDOWN_MS) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
await quotaWarningEmail(user, state);
|
||||
saveQuota(user.id, { lastQuotaEmailAt: now });
|
||||
} catch (err) {
|
||||
console.error(`[luminary] quota warning to ${user.email} failed: ${err.message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function startQuotaWorker() {
|
||||
const tick = () => {
|
||||
void pruneDueAccounts().catch((err) =>
|
||||
console.error(`[luminary] quota worker: ${err.message}`),
|
||||
);
|
||||
void sendQuotaWarnings().catch((err) =>
|
||||
console.error(`[luminary] quota warning worker: ${err.message}`),
|
||||
);
|
||||
};
|
||||
const timer = setInterval(tick, 5 * 60 * 1000);
|
||||
timer.unref?.();
|
||||
setTimeout(tick, 7000).unref?.();
|
||||
}
|
||||
+214
@@ -0,0 +1,214 @@
|
||||
import { RAW_PREVIEW_EDGE } from './config.mjs';
|
||||
import { encodeRgb, jpegInfo, loadSharp, toJpegProxy } from './imaging.mjs';
|
||||
import { loadLibRaw, rawPool } from './libraw-pool.mjs';
|
||||
|
||||
/** Every raw container the pipeline will attempt, grouped by vendor family. */
|
||||
export const RAW_EXTENSIONS = new Set([
|
||||
// Canon
|
||||
'cr2', 'cr3', 'crw',
|
||||
// Nikon
|
||||
'nef', 'nrw',
|
||||
// Sony
|
||||
'arw', 'srf', 'sr2',
|
||||
// Olympus / OM System
|
||||
'orf',
|
||||
// Panasonic / Leica
|
||||
'rw2', 'raw', 'rwl',
|
||||
// Fujifilm
|
||||
'raf',
|
||||
// Pentax / Ricoh
|
||||
'pef', 'dng',
|
||||
// Samsung, Hasselblad, Leaf, Phase One, Sigma, Epson, Kodak, Minolta
|
||||
'srw', '3fr', 'fff', 'iiq', 'x3f', 'erf', 'k25', 'kdc', 'dcr', 'mos', 'mrw', 'mef', 'sraw',
|
||||
]);
|
||||
|
||||
export function isRawName(name = '') {
|
||||
const ext = name.split('.').pop()?.toLowerCase() ?? '';
|
||||
return RAW_EXTENSIONS.has(ext);
|
||||
}
|
||||
|
||||
/** True when the buffer starts with a container signature LibRaw can open. */
|
||||
export function looksLikeRaw(buffer) {
|
||||
if (!buffer || buffer.length < 64) return false;
|
||||
const hex4 = buffer.subarray(0, 4).toString('hex');
|
||||
const ascii = buffer.subarray(0, 16).toString('latin1');
|
||||
if (hex4 === '49492a00' || hex4 === '4d4d002a') return true; // TIFF family
|
||||
if (hex4 === '4949524f' || hex4 === '4d4d4f52') return true; // ORF
|
||||
if (hex4 === '49495500') return true; // RW2
|
||||
if (hex4 === '49494949') return true; // Phase One IIQ
|
||||
if (ascii.startsWith('FUJIFILMCCD-RAW')) return true; // RAF
|
||||
if (ascii.startsWith('FOVb')) return true; // X3F
|
||||
if (buffer.subarray(4, 8).toString('latin1') === 'ftyp') return true; // CR3
|
||||
return false;
|
||||
}
|
||||
|
||||
let engineState = 'unloaded';
|
||||
|
||||
export async function rawEngine() {
|
||||
if (engineState === 'unloaded') {
|
||||
try {
|
||||
await loadLibRaw();
|
||||
engineState = 'ready';
|
||||
} catch {
|
||||
engineState = 'missing';
|
||||
}
|
||||
}
|
||||
return engineState;
|
||||
}
|
||||
|
||||
const DECODE_SETTINGS = {
|
||||
outputBps: 8,
|
||||
useCameraWb: true,
|
||||
outputColor: 1, // sRGB
|
||||
userQual: 3,
|
||||
highlight: 0,
|
||||
noAutoBright: false,
|
||||
// Use the orientation stored in the raw container: phone and DSLR files often
|
||||
// record the shot rotated (EXIF 6/8), and demosaicing without it produces a
|
||||
// sideways proxy that no later step can fix without losing the original axes.
|
||||
userFlip: -1,
|
||||
useFujiRotate: -1,
|
||||
};
|
||||
|
||||
/** Turns one LibRaw `imageData()` result into an interleaved RGB buffer. */
|
||||
function toRgb(img) {
|
||||
if (!img || !img.width || !img.height || !img.data) throw new Error('LibRaw returned no pixels');
|
||||
const width = Number(img.width);
|
||||
const height = Number(img.height);
|
||||
const colors = Number(img.colors ?? 3);
|
||||
const bits = Number(img.bits ?? 8);
|
||||
const src = img.data;
|
||||
const pixelCount = width * height;
|
||||
const needed = pixelCount * colors * (bits > 8 ? 2 : 1);
|
||||
if (src.length < needed) {
|
||||
throw new Error(`LibRaw buffer too small (${src.length} bytes for ${width}×${height}×${colors})`);
|
||||
}
|
||||
|
||||
const rgb = Buffer.alloc(pixelCount * 3);
|
||||
if (bits > 8) {
|
||||
const view = new Uint16Array(src.buffer, src.byteOffset, Math.floor(src.byteLength / 2));
|
||||
for (let i = 0; i < pixelCount; i++) {
|
||||
const s = i * colors;
|
||||
rgb[i * 3] = view[s] >> 8;
|
||||
rgb[i * 3 + 1] = view[s + 1] >> 8;
|
||||
rgb[i * 3 + 2] = view[s + 2] >> 8;
|
||||
}
|
||||
} else {
|
||||
for (let i = 0; i < pixelCount; i++) {
|
||||
const s = i * colors;
|
||||
rgb[i * 3] = src[s];
|
||||
rgb[i * 3 + 1] = src[s + 1];
|
||||
rgb[i * 3 + 2] = src[s + 2];
|
||||
}
|
||||
}
|
||||
return { rgb, width, height };
|
||||
}
|
||||
|
||||
/**
|
||||
* Full demosaic through a pooled LibRaw worker. `open()` only unpacks the file;
|
||||
* the pixels come from `imageData()`, which rejects when the camera is unsupported.
|
||||
*/
|
||||
async function demosaic(buffer) {
|
||||
if ((await rawEngine()) !== 'ready') throw new Error('LibRaw is not installed');
|
||||
return rawPool.use(async (lib) => {
|
||||
// LibRaw transfers the buffer to its worker, which detaches it here. Hand it
|
||||
// a copy so the caller's bytes survive for the embedded-preview fallback.
|
||||
await lib.open(Buffer.from(buffer), DECODE_SETTINGS);
|
||||
return toRgb(await lib.imageData());
|
||||
});
|
||||
}
|
||||
|
||||
const SOI = Buffer.from([0xff, 0xd8, 0xff]);
|
||||
const EOI = Buffer.from([0xff, 0xd9]);
|
||||
|
||||
/** Pull the largest embedded JPEG straight out of a raw container. */
|
||||
export function extractEmbeddedJpeg(buffer) {
|
||||
let best = null;
|
||||
let from = 0;
|
||||
while (from < buffer.length - 3) {
|
||||
const start = buffer.indexOf(SOI, from);
|
||||
if (start < 0) break;
|
||||
const end = buffer.indexOf(EOI, start + 3);
|
||||
if (end < 0) break;
|
||||
const length = end + 2 - start;
|
||||
if (length > 4096 && (!best || length > best.length)) best = buffer.subarray(start, end + 2);
|
||||
from = end + 2;
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
/** Camera preview, preferably the one LibRaw knows the offset and length of. */
|
||||
async function embeddedPreview(buffer) {
|
||||
if ((await rawEngine()) === 'ready') {
|
||||
try {
|
||||
const thumb = await rawPool.use(async (lib) => {
|
||||
await lib.open(Buffer.from(buffer), { useCameraWb: true });
|
||||
return lib.thumbnailData();
|
||||
});
|
||||
if (thumb?.data && thumb.format === 'jpeg' && thumb.data.length > 4096) {
|
||||
return Buffer.from(thumb.data);
|
||||
}
|
||||
} catch {
|
||||
/* fall through to the byte scan */
|
||||
}
|
||||
}
|
||||
return extractEmbeddedJpeg(buffer);
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert a raw file into an editable JPEG. LibRaw demosaics where possible and
|
||||
* falls back to the camera's own embedded preview when it cannot.
|
||||
*/
|
||||
export async function decodeRaw(buffer) {
|
||||
let librawError = null;
|
||||
if (looksLikeRaw(buffer)) {
|
||||
try {
|
||||
const { rgb, width, height } = await demosaic(buffer);
|
||||
const encoded = await encodeRgb(rgb, width, height, 92, RAW_PREVIEW_EDGE);
|
||||
return {
|
||||
jpeg: encoded.data,
|
||||
width: encoded.width,
|
||||
height: encoded.height,
|
||||
engine: 'libraw',
|
||||
ext: encoded.ext,
|
||||
};
|
||||
} catch (err) {
|
||||
librawError = err instanceof Error ? err.message : String(err);
|
||||
}
|
||||
} else {
|
||||
librawError = 'not a recognised raw container';
|
||||
}
|
||||
|
||||
const embedded = await embeddedPreview(buffer);
|
||||
if (embedded) {
|
||||
const proxy = await toJpegProxy(embedded, RAW_PREVIEW_EDGE);
|
||||
if (proxy) {
|
||||
const size = await jpegInfo(proxy.data);
|
||||
return {
|
||||
jpeg: proxy.data,
|
||||
width: size?.width || proxy.width,
|
||||
height: size?.height || proxy.height,
|
||||
engine: 'embedded',
|
||||
ext: proxy.ext,
|
||||
note: `LibRaw could not decode this file (${librawError}); using the camera preview.`,
|
||||
};
|
||||
}
|
||||
return { jpeg: embedded, width: 0, height: 0, engine: 'embedded', ext: 'jpg', note: librawError ?? undefined };
|
||||
}
|
||||
|
||||
throw new Error(
|
||||
`Could not decode this raw file. ${librawError ? `LibRaw said: ${librawError}.` : 'LibRaw is not installed.'}`,
|
||||
);
|
||||
}
|
||||
|
||||
export async function rawSupport() {
|
||||
const engine = await rawEngine();
|
||||
const sharp = await loadSharp();
|
||||
return {
|
||||
libraw: engine === 'ready',
|
||||
sharp: Boolean(sharp),
|
||||
workers: rawPool.size,
|
||||
busy: rawPool.stats.busy,
|
||||
formats: [...RAW_EXTENSIONS].sort(),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,325 @@
|
||||
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 };
|
||||
}
|
||||
+123
@@ -0,0 +1,123 @@
|
||||
/**
|
||||
* Minimal stored-ZIP writer for server-side gallery downloads. JPEGs are
|
||||
* already compressed, so entries are stored rather than deflated.
|
||||
*/
|
||||
|
||||
const MAX_ENTRIES = 0xffff;
|
||||
const MAX_SIZE = 0xffffffff;
|
||||
|
||||
const CRC_TABLE = (() => {
|
||||
const table = new Uint32Array(256);
|
||||
for (let i = 0; i < 256; i++) {
|
||||
let c = i;
|
||||
for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
|
||||
table[i] = c >>> 0;
|
||||
}
|
||||
return table;
|
||||
})();
|
||||
|
||||
function crc32(bytes) {
|
||||
let c = 0xffffffff;
|
||||
for (let i = 0; i < bytes.length; i++) c = CRC_TABLE[(c ^ bytes[i]) & 0xff] ^ (c >>> 8);
|
||||
return (c ^ 0xffffffff) >>> 0;
|
||||
}
|
||||
|
||||
function dosStamp(date) {
|
||||
const year = Math.min(2107, Math.max(1980, date.getFullYear()));
|
||||
const time = (date.getHours() << 11) | (date.getMinutes() << 5) | (date.getSeconds() >> 1);
|
||||
const day = ((year - 1980) << 9) | ((date.getMonth() + 1) << 5) | date.getDate();
|
||||
return { time, day };
|
||||
}
|
||||
|
||||
function uniqueName(name, used) {
|
||||
const clean = String(name || 'photo.jpg')
|
||||
.replace(/[\\/]+/g, '-')
|
||||
.replace(/[\u0000-\u001f]/g, '')
|
||||
.trim() || 'photo.jpg';
|
||||
if (!used.has(clean.toLowerCase())) {
|
||||
used.add(clean.toLowerCase());
|
||||
return clean;
|
||||
}
|
||||
const dot = clean.lastIndexOf('.');
|
||||
const stem = dot > 0 ? clean.slice(0, dot) : clean;
|
||||
const ext = dot > 0 ? clean.slice(dot) : '';
|
||||
let n = 2;
|
||||
while (used.has(`${stem} (${n})${ext}`.toLowerCase())) n += 1;
|
||||
const result = `${stem} (${n})${ext}`;
|
||||
used.add(result.toLowerCase());
|
||||
return result;
|
||||
}
|
||||
|
||||
export function createZip(entries, date = new Date()) {
|
||||
if (!entries.length) throw new Error('Nothing to archive');
|
||||
if (entries.length > MAX_ENTRIES) throw new Error('Too many files for one ZIP archive');
|
||||
|
||||
const { time, day } = dosStamp(date);
|
||||
const locals = [];
|
||||
const central = [];
|
||||
const used = new Set();
|
||||
let offset = 0;
|
||||
|
||||
for (const entry of entries) {
|
||||
if (!Buffer.isBuffer(entry.data)) throw new Error('ZIP entries must contain buffers');
|
||||
const name = Buffer.from(uniqueName(entry.name, used), 'utf8');
|
||||
const data = entry.data;
|
||||
if (data.length > MAX_SIZE) throw new Error(`${entry.name} is too large for a ZIP archive`);
|
||||
const crc = crc32(data);
|
||||
|
||||
const local = Buffer.alloc(30);
|
||||
local.writeUInt32LE(0x04034b50, 0);
|
||||
local.writeUInt16LE(20, 4);
|
||||
local.writeUInt16LE(0x0800, 6);
|
||||
local.writeUInt16LE(0, 8);
|
||||
local.writeUInt16LE(time, 10);
|
||||
local.writeUInt16LE(day, 12);
|
||||
local.writeUInt32LE(crc, 14);
|
||||
local.writeUInt32LE(data.length, 18);
|
||||
local.writeUInt32LE(data.length, 22);
|
||||
local.writeUInt16LE(name.length, 26);
|
||||
local.writeUInt16LE(0, 28);
|
||||
|
||||
locals.push(local, name, data);
|
||||
central.push({ name, crc, size: data.length, offset });
|
||||
offset += local.length + name.length + data.length;
|
||||
}
|
||||
|
||||
const centralStart = offset;
|
||||
let centralSize = 0;
|
||||
for (const file of central) {
|
||||
const record = Buffer.alloc(46);
|
||||
record.writeUInt32LE(0x02014b50, 0);
|
||||
record.writeUInt16LE(20, 4);
|
||||
record.writeUInt16LE(20, 6);
|
||||
record.writeUInt16LE(0x0800, 8);
|
||||
record.writeUInt16LE(0, 10);
|
||||
record.writeUInt16LE(time, 12);
|
||||
record.writeUInt16LE(day, 14);
|
||||
record.writeUInt32LE(file.crc, 16);
|
||||
record.writeUInt32LE(file.size, 20);
|
||||
record.writeUInt32LE(file.size, 24);
|
||||
record.writeUInt16LE(file.name.length, 28);
|
||||
record.writeUInt16LE(0, 30);
|
||||
record.writeUInt16LE(0, 32);
|
||||
record.writeUInt16LE(0, 34);
|
||||
record.writeUInt16LE(0, 36);
|
||||
record.writeUInt32LE(0, 38);
|
||||
record.writeUInt32LE(file.offset, 42);
|
||||
locals.push(record, file.name);
|
||||
centralSize += record.length + file.name.length;
|
||||
}
|
||||
|
||||
const end = Buffer.alloc(22);
|
||||
end.writeUInt32LE(0x06054b50, 0);
|
||||
end.writeUInt16LE(0, 4);
|
||||
end.writeUInt16LE(0, 6);
|
||||
end.writeUInt16LE(central.length, 8);
|
||||
end.writeUInt16LE(central.length, 10);
|
||||
end.writeUInt32LE(centralSize, 12);
|
||||
end.writeUInt32LE(centralStart, 16);
|
||||
end.writeUInt16LE(0, 20);
|
||||
locals.push(end);
|
||||
|
||||
return Buffer.concat(locals);
|
||||
}
|
||||
Reference in New Issue
Block a user