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)), };