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; 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) => `
  • ${escapeHtml(event.name)} — ${event.photos.length} photo${event.photos.length === 1 ? '' : 's'}, ${fmtBytes(event.bytes)}
  • `, ) .join(''); const loose = plan.photos.length ? `
  • ${plan.photos.length} unassigned photo${plan.photos.length === 1 ? '' : 's'} — ${fmtBytes(plan.photos.reduce((sum, photo) => sum + photo.bytes, 0))}
  • ` : ''; return ``; } function escapeHtml(value) { return String(value) .replaceAll('&', '&') .replaceAll('<', '<') .replaceAll('>', '>') .replaceAll('"', '"'); } async function pruneWarningEmail(user, state, plan, pruneAt) { const when = fmtDate(pruneAt); const link = appUrl(); 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)}.`, ...(link ? ['', `Review your library now: ${link}`] : []), '', 'Deleting photos or emptying Trash before the scheduled time will cancel or reduce the cleanup.', '— Luminary', ].join('\n'); const html = `

    Storage cleanup scheduled

    Hi ${escapeHtml(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 ${escapeHtml(when)} — about 24 hours from now.

    Unless you free space before then, Luminary will permanently remove the oldest content listed below:

    ${planHtml(plan) || '

    No individual items were identified.

    '}

    This should free about ${fmtBytes(plan.freedBytes)} and leave your library around ${fmtBytes(plan.projectedBytes)}.

    ${link ? `

    Review your library

    ` : ''}

    Deleting photos or emptying Trash before the scheduled time will cancel or reduce the cleanup.
    — Luminary

    `; await sendAppMail({ to: user.email, subject, text, html }); } async function quotaWarningEmail(user, state) { const link = appUrl(); 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.', ...(link ? ['', `Open Luminary: ${link}`] : []), '', '— Luminary', ].join('\n'); const html = `

    You are nearing your storage quota

    Hi ${escapeHtml(user.name || user.email)},

    You have used ${fmtBytes(state.used)} of your ${fmtBytes(state.limit)} Luminary quota (${state.percent}%).

    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.

    ${link ? `

    Open Luminary

    ` : ''}

    — Luminary

    `; 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), }; }); } async function executePlan(userId, plan, targetBytes) { let removedPhotos = 0; let freedBytes = 0; let current = quotaUsage(userId); const eventIds = new Set(); for (const event of plan.events ?? []) { if (current <= targetBytes) break; eventIds.add(event.id); for (const photoId of event.photos ?? []) { const photo = getPhoto(photoId); if (!photo) continue; const bytes = Number(photo.size) || 0; freedBytes += bytes; current -= bytes; removePhoto(photoId); clearDenoised(photoId); await removeAsset(photoId); removedPhotos += 1; } } for (const entry of plan.photos ?? []) { if (current <= targetBytes) break; const photo = getPhoto(entry.id); if (!photo) continue; const bytes = Number(photo.size) || 0; freedBytes += bytes; current -= bytes; 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 stateBefore = quotaState(row.user_id); const targetBytes = Math.floor(stateBefore.limit * QUOTA_TARGET_RATIO); if (stateBefore.used <= targetBytes) { saveQuota(row.user_id, { pruneAt: null, prunePlan: null, pruneNotifiedAt: null, }); const link = appUrl(); await sendAppMail({ to: user.email, subject: 'Luminary: scheduled storage cleanup cancelled', text: [ `Hi ${user.name || user.email},`, '', 'Your scheduled Luminary storage cleanup was cancelled because your library is now below the cleanup target. Nothing was deleted.', ...(link ? ['', `Open Luminary: ${link}`] : []), '', '— Luminary', ].join('\n'), html: `

    Scheduled cleanup cancelled

    Hi ${escapeHtml(user.name || user.email)},

    Your scheduled Luminary storage cleanup was cancelled because your library is now below the cleanup target. Nothing was deleted.

    — Luminary

    `, }).catch((err) => console.error(`[luminary] cancel email to ${user.email} failed: ${err.message}`)); continue; } const before = stateBefore.used; const result = await executePlan(row.user_id, plan, targetBytes); const after = quotaUsage(row.user_id); saveQuota(row.user_id, { pruneAt: null, prunePlan: null, pruneNotifiedAt: null, }); const state = quotaState(row.user_id); const link = appUrl(); 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}%).`, ...(link ? ['', `Open Luminary: ${link}`] : []), '', '— Luminary', ].join('\n'), html: `

    Scheduled cleanup complete

    Hi ${escapeHtml(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}%).

    — Luminary

    `, }).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?.(); }