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) => `
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)}.
Deleting photos or emptying Trash before the scheduled
time will cancel or reduce the cleanup.
— Luminary
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.
— Luminary
This is a test message from Luminary. Quota warnings and prune notices are configured correctly.
', }); } 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: `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