0c113e7a91
Camera profiles, proofing tables and the half-float sidecar all have to agree with the pixels the editor actually grades, so they land together with the preset filter menu that was unusable while thumbnails streamed in. 🤖 Generated with Codebuff Co-Authored-By: Codebuff <noreply@codebuff.com>
1116 lines
39 KiB
JavaScript
1116 lines
39 KiB
JavaScript
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 gallery_settings (
|
|
token TEXT PRIMARY KEY,
|
|
password_hash TEXT NOT NULL DEFAULT '',
|
|
password_salt TEXT NOT NULL DEFAULT '',
|
|
expires_at INTEGER,
|
|
watermark TEXT NOT NULL DEFAULT '',
|
|
allow_downloads INTEGER NOT NULL DEFAULT 1,
|
|
download_cap INTEGER NOT NULL DEFAULT 0,
|
|
download_count INTEGER NOT NULL DEFAULT 0,
|
|
updated_at INTEGER NOT NULL
|
|
);
|
|
|
|
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 immich_albums (
|
|
event_id TEXT PRIMARY KEY,
|
|
owner_id TEXT NOT NULL,
|
|
server_url TEXT NOT NULL,
|
|
album_id TEXT NOT NULL,
|
|
album_name TEXT NOT NULL DEFAULT '',
|
|
asset_count INTEGER NOT NULL DEFAULT 0,
|
|
kind TEXT NOT NULL DEFAULT 'import',
|
|
last_sync_at INTEGER,
|
|
created_at INTEGER NOT NULL
|
|
);
|
|
|
|
CREATE UNIQUE INDEX IF NOT EXISTS immich_albums_key
|
|
ON immich_albums(owner_id, server_url, album_id);
|
|
|
|
CREATE TABLE IF NOT EXISTS immich_assets (
|
|
event_id TEXT NOT NULL,
|
|
asset_id TEXT NOT NULL,
|
|
photo_id TEXT NOT NULL,
|
|
owner_id TEXT NOT NULL,
|
|
album_id TEXT NOT NULL,
|
|
checksum TEXT NOT NULL DEFAULT '',
|
|
file_name TEXT NOT NULL DEFAULT '',
|
|
imported_at INTEGER NOT NULL,
|
|
PRIMARY KEY (event_id, asset_id)
|
|
);
|
|
|
|
CREATE INDEX IF NOT EXISTS immich_assets_photo ON immich_assets(photo_id);
|
|
|
|
CREATE TABLE IF NOT EXISTS immich_settings (
|
|
owner_id TEXT PRIMARY KEY,
|
|
server_url TEXT NOT NULL DEFAULT '',
|
|
api_key TEXT NOT NULL DEFAULT '',
|
|
enabled INTEGER NOT NULL DEFAULT 0,
|
|
auto_sync INTEGER NOT NULL DEFAULT 0,
|
|
sync_minutes INTEGER NOT NULL DEFAULT 60,
|
|
trash_original INTEGER NOT NULL DEFAULT 0,
|
|
sync_metadata INTEGER NOT NULL DEFAULT 1,
|
|
last_sync_at INTEGER,
|
|
last_error TEXT,
|
|
created_at INTEGER NOT NULL
|
|
);
|
|
|
|
CREATE TABLE IF NOT EXISTS immich_pushes (
|
|
id TEXT PRIMARY KEY,
|
|
owner_id TEXT NOT NULL,
|
|
photo_id TEXT NOT NULL,
|
|
source_asset_id TEXT NOT NULL,
|
|
new_asset_id TEXT,
|
|
checksum TEXT NOT NULL,
|
|
edits_hash TEXT NOT NULL DEFAULT '',
|
|
state TEXT NOT NULL,
|
|
trashed_source INTEGER NOT NULL DEFAULT 0,
|
|
error TEXT,
|
|
created_at INTEGER NOT NULL
|
|
);
|
|
|
|
CREATE INDEX IF NOT EXISTS immich_pushes_photo ON immich_pushes(photo_id, checksum);
|
|
|
|
CREATE TABLE IF NOT EXISTS immich_meta (
|
|
photo_id TEXT PRIMARY KEY,
|
|
owner_id TEXT NOT NULL,
|
|
asset_id TEXT NOT NULL,
|
|
local_fingerprint TEXT NOT NULL DEFAULT '',
|
|
remote_fingerprint TEXT NOT NULL DEFAULT '',
|
|
remote_updated_at INTEGER,
|
|
last_synced_at INTEGER,
|
|
last_error TEXT
|
|
);
|
|
|
|
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)');
|
|
|
|
/* Metadata round-tripping arrived after the first Immich release. */
|
|
const immichSettingsColumns = db.prepare('PRAGMA table_info(immich_settings)').all().map((c) => c.name);
|
|
if (!immichSettingsColumns.includes('sync_metadata')) {
|
|
db.exec('ALTER TABLE immich_settings ADD COLUMN sync_metadata INTEGER NOT NULL DEFAULT 1');
|
|
}
|
|
|
|
/* Manual pushes remember which edit version reached Immich. */
|
|
const immichPushColumns = db.prepare('PRAGMA table_info(immich_pushes)').all().map((c) => c.name);
|
|
if (!immichPushColumns.includes('edits_hash')) {
|
|
db.exec("ALTER TABLE immich_pushes ADD COLUMN edits_hash TEXT NOT NULL DEFAULT ''");
|
|
}
|
|
|
|
/* Galleries created from an event are destinations, not import sources. */
|
|
const immichAlbumColumns = db.prepare('PRAGMA table_info(immich_albums)').all().map((c) => c.name);
|
|
if (!immichAlbumColumns.includes('kind')) {
|
|
db.exec("ALTER TABLE immich_albums ADD COLUMN kind TEXT NOT NULL DEFAULT 'import'");
|
|
}
|
|
|
|
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'),
|
|
|
|
event: db.prepare('SELECT data FROM events WHERE id = ?'),
|
|
immichAlbum: db.prepare(
|
|
'SELECT * FROM immich_albums WHERE owner_id = ? AND server_url = ? AND album_id = ?',
|
|
),
|
|
immichAlbumForEvent: db.prepare('SELECT * FROM immich_albums WHERE event_id = ?'),
|
|
immichAlbumByAlbum: db.prepare(
|
|
'SELECT * FROM immich_albums WHERE owner_id = ? AND album_id = ? LIMIT 1',
|
|
),
|
|
immichAlbumsByOwner: db.prepare(
|
|
'SELECT * FROM immich_albums WHERE owner_id = ? ORDER BY last_sync_at DESC, created_at DESC',
|
|
),
|
|
upsertImmichAlbum: db.prepare(`
|
|
INSERT INTO immich_albums (event_id, owner_id, server_url, album_id, album_name, asset_count, kind, last_sync_at, created_at)
|
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
ON CONFLICT(event_id) DO UPDATE SET
|
|
server_url = excluded.server_url,
|
|
album_id = excluded.album_id,
|
|
album_name = excluded.album_name,
|
|
asset_count = excluded.asset_count,
|
|
kind = excluded.kind,
|
|
last_sync_at = excluded.last_sync_at
|
|
`),
|
|
deleteImmichAlbum: db.prepare('DELETE FROM immich_albums WHERE event_id = ?'),
|
|
immichAssetsByEvent: db.prepare('SELECT * FROM immich_assets WHERE event_id = ?'),
|
|
upsertImmichAsset: db.prepare(`
|
|
INSERT INTO immich_assets (event_id, asset_id, photo_id, owner_id, album_id, checksum, file_name, imported_at)
|
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
|
ON CONFLICT(event_id, asset_id) DO UPDATE SET
|
|
photo_id = excluded.photo_id,
|
|
checksum = excluded.checksum,
|
|
file_name = excluded.file_name,
|
|
imported_at = excluded.imported_at
|
|
`),
|
|
deleteImmichAsset: db.prepare('DELETE FROM immich_assets WHERE event_id = ? AND asset_id = ?'),
|
|
deleteImmichAssetsForPhoto: db.prepare('DELETE FROM immich_assets WHERE photo_id = ?'),
|
|
immichAssetForPhoto: db.prepare('SELECT * FROM immich_assets WHERE photo_id = ? LIMIT 1'),
|
|
immichSettings: db.prepare('SELECT * FROM immich_settings WHERE owner_id = ?'),
|
|
allImmichSettings: db.prepare('SELECT * FROM immich_settings'),
|
|
upsertImmichSettings: db.prepare(`
|
|
INSERT INTO immich_settings (owner_id, server_url, api_key, enabled, auto_sync, sync_minutes, trash_original, sync_metadata, last_sync_at, last_error, created_at)
|
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
ON CONFLICT(owner_id) DO UPDATE SET
|
|
server_url = excluded.server_url,
|
|
api_key = excluded.api_key,
|
|
enabled = excluded.enabled,
|
|
auto_sync = excluded.auto_sync,
|
|
sync_minutes = excluded.sync_minutes,
|
|
trash_original = excluded.trash_original,
|
|
sync_metadata = excluded.sync_metadata,
|
|
last_sync_at = excluded.last_sync_at,
|
|
last_error = excluded.last_error
|
|
`),
|
|
deleteImmichSettings: db.prepare('DELETE FROM immich_settings WHERE owner_id = ?'),
|
|
setImmichSyncState: db.prepare(
|
|
'UPDATE immich_settings SET last_sync_at = ?, last_error = ? WHERE owner_id = ?',
|
|
),
|
|
immichPush: db.prepare(
|
|
'SELECT * FROM immich_pushes WHERE photo_id = ? AND checksum = ? ORDER BY created_at DESC LIMIT 1',
|
|
),
|
|
immichPushedForPhoto: db.prepare(
|
|
"SELECT * FROM immich_pushes WHERE photo_id = ? AND state = 'done' AND new_asset_id IS NOT NULL ORDER BY created_at DESC LIMIT 1",
|
|
),
|
|
immichPhotoIdsByEvent: db.prepare(
|
|
'SELECT id FROM photos WHERE event_id = ? AND owner_id = ? ORDER BY sort_index ASC, updated_at ASC',
|
|
),
|
|
immichPendingByEvent: db.prepare(`
|
|
SELECT p.data FROM photos p
|
|
WHERE p.event_id = ? AND p.owner_id = ?
|
|
AND NOT EXISTS (SELECT 1 FROM immich_assets a WHERE a.photo_id = p.id)
|
|
AND NOT EXISTS (
|
|
SELECT 1 FROM immich_pushes u
|
|
WHERE u.photo_id = p.id AND u.state = 'done' AND u.new_asset_id IS NOT NULL
|
|
)
|
|
ORDER BY p.sort_index ASC, p.updated_at ASC
|
|
`),
|
|
upsertImmichPush: db.prepare(`
|
|
INSERT INTO immich_pushes (id, owner_id, photo_id, source_asset_id, new_asset_id, checksum, edits_hash, state, trashed_source, error, created_at)
|
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
ON CONFLICT(id) DO UPDATE SET
|
|
new_asset_id = excluded.new_asset_id,
|
|
edits_hash = excluded.edits_hash,
|
|
state = excluded.state,
|
|
trashed_source = excluded.trashed_source,
|
|
error = excluded.error
|
|
`),
|
|
deleteImmichPushesForPhoto: db.prepare('DELETE FROM immich_pushes WHERE photo_id = ?'),
|
|
immichMeta: db.prepare('SELECT * FROM immich_meta WHERE photo_id = ?'),
|
|
upsertImmichMeta: db.prepare(`
|
|
INSERT INTO immich_meta (photo_id, owner_id, asset_id, local_fingerprint, remote_fingerprint, remote_updated_at, last_synced_at, last_error)
|
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
|
ON CONFLICT(photo_id) DO UPDATE SET
|
|
owner_id = excluded.owner_id,
|
|
asset_id = excluded.asset_id,
|
|
local_fingerprint = excluded.local_fingerprint,
|
|
remote_fingerprint = excluded.remote_fingerprint,
|
|
remote_updated_at = excluded.remote_updated_at,
|
|
last_synced_at = excluded.last_synced_at,
|
|
last_error = excluded.last_error
|
|
`),
|
|
deleteImmichMeta: db.prepare('DELETE FROM immich_meta WHERE photo_id = ?'),
|
|
immichPushAssets: db.prepare(
|
|
"SELECT DISTINCT new_asset_id FROM immich_pushes WHERE photo_id = ? AND state = 'done' AND new_asset_id IS NOT NULL",
|
|
),
|
|
patchPhotoMeta: db.prepare(`
|
|
UPDATE photos
|
|
SET data = json_set(data, '$.rating', ?, '$.flag', ?, '$.keywords', json(?)), updated_at = ?
|
|
WHERE id = ?
|
|
`),
|
|
|
|
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);
|
|
// An album link must not outlive the event it points at.
|
|
q.deleteImmichAlbum.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,
|
|
}));
|
|
}
|
|
|
|
const gallerySettingsStmt = db.prepare('SELECT * FROM gallery_settings WHERE token = ?');
|
|
const upsertGallerySettings = db.prepare(`
|
|
INSERT INTO gallery_settings
|
|
(token, password_hash, password_salt, expires_at, watermark, allow_downloads, download_cap, download_count, updated_at)
|
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
ON CONFLICT(token) DO UPDATE SET
|
|
password_hash = excluded.password_hash,
|
|
password_salt = excluded.password_salt,
|
|
expires_at = excluded.expires_at,
|
|
watermark = excluded.watermark,
|
|
allow_downloads = excluded.allow_downloads,
|
|
download_cap = excluded.download_cap,
|
|
updated_at = excluded.updated_at
|
|
`);
|
|
const deleteGallerySettings = db.prepare('DELETE FROM gallery_settings WHERE token = ?');
|
|
const bumpGalleryDownload = db.prepare(
|
|
'UPDATE gallery_settings SET download_count = download_count + 1 WHERE token = ?',
|
|
);
|
|
const readGalleryDownloads = db.prepare(
|
|
'SELECT download_count FROM gallery_settings WHERE token = ?',
|
|
);
|
|
|
|
/** Access rules for a public proofing link; defaults when none were saved. */
|
|
export function gallerySettingsFor(token) {
|
|
const row = gallerySettingsStmt.get(token);
|
|
return {
|
|
passwordHash: row?.password_hash ?? '',
|
|
passwordSalt: row?.password_salt ?? '',
|
|
expiresAt: row?.expires_at ?? null,
|
|
watermark: row?.watermark ?? '',
|
|
allowDownloads: row ? Boolean(row.allow_downloads) : true,
|
|
downloadCap: row?.download_cap ?? 0,
|
|
downloadCount: row?.download_count ?? 0,
|
|
};
|
|
}
|
|
|
|
/**
|
|
* The download counter is deliberately preserved across settings edits: an
|
|
* owner tightening or loosening a cap must not hand out a fresh allowance.
|
|
*/
|
|
export function saveGallerySettings(token, settings) {
|
|
upsertGallerySettings.run(
|
|
token,
|
|
settings.passwordHash ?? '',
|
|
settings.passwordSalt ?? '',
|
|
settings.expiresAt ?? null,
|
|
settings.watermark ?? '',
|
|
settings.allowDownloads === false ? 0 : 1,
|
|
Math.max(0, Math.round(settings.downloadCap ?? 0)),
|
|
0,
|
|
Date.now(),
|
|
);
|
|
return gallerySettingsFor(token);
|
|
}
|
|
|
|
export function clearGallerySettings(token) {
|
|
deleteGallerySettings.run(token);
|
|
}
|
|
|
|
/** Counts a gallery download and reports the new total, or 0 when uncapped. */
|
|
export function noteGalleryDownload(token) {
|
|
bumpGalleryDownload.run(token);
|
|
return readGalleryDownloads.get(token)?.download_count ?? 0;
|
|
}
|
|
|
|
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 getEvent(id) {
|
|
const row = q.event.get(id);
|
|
return row ? parse(row.data) : null;
|
|
}
|
|
|
|
/** The Luminary event already linked to an Immich album, if any. */
|
|
export function immichAlbumFor(ownerId, serverUrl, albumId) {
|
|
const row = q.immichAlbum.get(ownerId, serverUrl, albumId);
|
|
return row ? albumLinkFromRow(row) : null;
|
|
}
|
|
|
|
export function immichAlbumLinks(ownerId) {
|
|
return q.immichAlbumsByOwner.all(ownerId).map(albumLinkFromRow);
|
|
}
|
|
|
|
export function immichAlbumForEvent(eventId) {
|
|
const row = q.immichAlbumForEvent.get(eventId);
|
|
return row ? albumLinkFromRow(row) : null;
|
|
}
|
|
|
|
export function immichAlbumByAlbum(ownerId, albumId) {
|
|
const row = q.immichAlbumByAlbum.get(ownerId, albumId);
|
|
return row ? albumLinkFromRow(row) : null;
|
|
}
|
|
|
|
function albumLinkFromRow(row) {
|
|
return {
|
|
eventId: row.event_id,
|
|
ownerId: row.owner_id,
|
|
serverUrl: row.server_url,
|
|
albumId: row.album_id,
|
|
albumName: row.album_name,
|
|
assetCount: Number(row.asset_count ?? 0),
|
|
kind: row.kind ?? 'import',
|
|
lastSyncAt: row.last_sync_at ?? null,
|
|
createdAt: row.created_at,
|
|
};
|
|
}
|
|
|
|
export function saveImmichAlbum(link) {
|
|
q.upsertImmichAlbum.run(
|
|
link.eventId,
|
|
link.ownerId,
|
|
link.serverUrl,
|
|
link.albumId,
|
|
link.albumName ?? '',
|
|
Number(link.assetCount ?? 0),
|
|
link.kind === 'gallery' ? 'gallery' : 'import',
|
|
link.lastSyncAt ?? Date.now(),
|
|
link.createdAt ?? Date.now(),
|
|
);
|
|
}
|
|
|
|
export function immichAssetsForEvent(eventId) {
|
|
return q.immichAssetsByEvent.all(eventId).map((row) => ({
|
|
eventId: row.event_id,
|
|
assetId: row.asset_id,
|
|
photoId: row.photo_id,
|
|
ownerId: row.owner_id,
|
|
albumId: row.album_id,
|
|
checksum: row.checksum,
|
|
fileName: row.file_name,
|
|
importedAt: row.imported_at,
|
|
}));
|
|
}
|
|
|
|
export function saveImmichAsset(asset) {
|
|
q.upsertImmichAsset.run(
|
|
asset.eventId,
|
|
asset.assetId,
|
|
asset.photoId,
|
|
asset.ownerId,
|
|
asset.albumId,
|
|
asset.checksum ?? '',
|
|
asset.fileName ?? '',
|
|
asset.importedAt ?? Date.now(),
|
|
);
|
|
}
|
|
|
|
export function removeImmichAsset(eventId, assetId) {
|
|
q.deleteImmichAsset.run(eventId, assetId);
|
|
}
|
|
|
|
/** The Immich source row for a photo, used when sending an edit back. */
|
|
export function immichAssetForPhoto(photoId) {
|
|
const row = q.immichAssetForPhoto.get(photoId);
|
|
if (!row) return null;
|
|
return {
|
|
eventId: row.event_id,
|
|
assetId: row.asset_id,
|
|
photoId: row.photo_id,
|
|
ownerId: row.owner_id,
|
|
albumId: row.album_id,
|
|
checksum: row.checksum,
|
|
fileName: row.file_name,
|
|
importedAt: row.imported_at,
|
|
};
|
|
}
|
|
|
|
function immichSettingsFromRow(row) {
|
|
if (!row) return null;
|
|
return {
|
|
ownerId: row.owner_id,
|
|
serverUrl: row.server_url,
|
|
apiKey: row.api_key,
|
|
enabled: Boolean(row.enabled),
|
|
autoSync: Boolean(row.auto_sync),
|
|
syncMinutes: Number(row.sync_minutes ?? 60),
|
|
trashOriginal: Boolean(row.trash_original),
|
|
syncMetadata: Boolean(row.sync_metadata ?? 1),
|
|
lastSyncAt: row.last_sync_at ?? null,
|
|
lastError: row.last_error ?? null,
|
|
createdAt: row.created_at,
|
|
};
|
|
}
|
|
|
|
export function immichSettingsFor(ownerId) {
|
|
return immichSettingsFromRow(q.immichSettings.get(ownerId));
|
|
}
|
|
|
|
export function allImmichSettings() {
|
|
return q.allImmichSettings.all().map(immichSettingsFromRow);
|
|
}
|
|
|
|
export function saveImmichSettingsRecord(record) {
|
|
q.upsertImmichSettings.run(
|
|
record.ownerId,
|
|
record.serverUrl ?? '',
|
|
record.apiKey ?? '',
|
|
record.enabled ? 1 : 0,
|
|
record.autoSync ? 1 : 0,
|
|
Math.max(15, Math.min(1440, Number(record.syncMinutes) || 60)),
|
|
record.trashOriginal ? 1 : 0,
|
|
record.syncMetadata === false ? 0 : 1,
|
|
record.lastSyncAt ?? null,
|
|
record.lastError ?? null,
|
|
record.createdAt ?? Date.now(),
|
|
);
|
|
}
|
|
|
|
export function deleteImmichSettingsRecord(ownerId) {
|
|
q.deleteImmichSettings.run(ownerId);
|
|
}
|
|
|
|
export function setImmichSyncState(ownerId, lastSyncAt, lastError) {
|
|
q.setImmichSyncState.run(lastSyncAt ?? null, lastError ?? null, ownerId);
|
|
}
|
|
|
|
export function immichPushFor(photoId, checksum) {
|
|
const row = q.immichPush.get(photoId, checksum);
|
|
if (!row) return null;
|
|
return {
|
|
id: row.id,
|
|
ownerId: row.owner_id,
|
|
photoId: row.photo_id,
|
|
sourceAssetId: row.source_asset_id,
|
|
newAssetId: row.new_asset_id ?? null,
|
|
checksum: row.checksum,
|
|
state: row.state,
|
|
trashedSource: Boolean(row.trashed_source),
|
|
error: row.error ?? null,
|
|
createdAt: row.created_at,
|
|
};
|
|
}
|
|
|
|
export function saveImmichPush(record) {
|
|
q.upsertImmichPush.run(
|
|
record.id,
|
|
record.ownerId,
|
|
record.photoId,
|
|
record.sourceAssetId,
|
|
record.newAssetId ?? null,
|
|
record.checksum,
|
|
record.editsHash ?? '',
|
|
record.state,
|
|
record.trashedSource ? 1 : 0,
|
|
record.error ?? null,
|
|
record.createdAt ?? Date.now(),
|
|
);
|
|
}
|
|
|
|
export function immichMetaFor(photoId) {
|
|
const row = q.immichMeta.get(photoId);
|
|
if (!row) return null;
|
|
return {
|
|
photoId: row.photo_id,
|
|
ownerId: row.owner_id,
|
|
assetId: row.asset_id,
|
|
localFingerprint: row.local_fingerprint,
|
|
remoteFingerprint: row.remote_fingerprint,
|
|
remoteUpdatedAt: row.remote_updated_at ?? null,
|
|
lastSyncedAt: row.last_synced_at ?? null,
|
|
lastError: row.last_error ?? null,
|
|
};
|
|
}
|
|
|
|
export function saveImmichMeta(record) {
|
|
q.upsertImmichMeta.run(
|
|
record.photoId,
|
|
record.ownerId,
|
|
record.assetId,
|
|
record.localFingerprint,
|
|
record.remoteFingerprint,
|
|
record.remoteUpdatedAt ?? null,
|
|
record.lastSyncedAt ?? Date.now(),
|
|
record.lastError ?? null,
|
|
);
|
|
}
|
|
|
|
export function immichPushAssetsForPhoto(photoId) {
|
|
return q.immichPushAssets.all(photoId).map((row) => row.new_asset_id);
|
|
}
|
|
|
|
/** The first successful upload for a photo, whatever checksum produced it. */
|
|
export function immichPushDoneForPhoto(photoId) {
|
|
return q.immichPushedForPhoto.get(photoId) ?? null;
|
|
}
|
|
|
|
/** Every photo id in an event, in the order it is shown. */
|
|
export function photoIdsForEvent(eventId, ownerId) {
|
|
return q.immichPhotoIdsByEvent.all(eventId, ownerId).map((row) => row.id);
|
|
}
|
|
|
|
/** Live photo ids in an event that still need to reach its Immich gallery. */
|
|
export function immichPendingForEvent(eventId, ownerId) {
|
|
return q.immichPendingByEvent
|
|
.all(eventId, ownerId)
|
|
.map((row) => parse(row.data))
|
|
.filter((photo) => photo && !photo.deletedAt)
|
|
.map((photo) => photo.id);
|
|
}
|
|
|
|
/** Updates only metadata fields in the stored record, preserving sort order. */
|
|
export function patchPhotoMeta(photoId, patch, updatedAt = Date.now()) {
|
|
q.patchPhotoMeta.run(
|
|
Math.max(0, Math.min(5, Number(patch.rating) || 0)),
|
|
patch.flag ?? 'none',
|
|
JSON.stringify(Array.isArray(patch.keywords) ? patch.keywords : []),
|
|
updatedAt,
|
|
photoId,
|
|
);
|
|
return getPhoto(photoId);
|
|
}
|
|
|
|
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);
|
|
q.deleteImmichAssetsForPhoto.run(id);
|
|
q.deleteImmichPushesForPhoto.run(id);
|
|
q.deleteImmichMeta.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)),
|
|
};
|