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,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?.();
|
||||
}
|
||||
Reference in New Issue
Block a user