diff --git a/README.md b/README.md index 7860747..04d9528 100644 --- a/README.md +++ b/README.md @@ -199,6 +199,8 @@ storage, while quotas are stored per account in the database. | `PORT` | `8787` | HTTP port (**not** prefixed with `LUMINARY_`) | | `HOST` | `0.0.0.0` | Bind address (**not** prefixed) | | `LUMINARY_DATA` | `server/data` | Where the database and image folders live | +| `LUMINARY_SECRET_KEY` | *(auto)* | Key for encrypting the saved SMTP password and bridge service tokens; when empty, a generated key is kept in `/secret.key` — back it up with the database | +| `LUMINARY_TRUST_PROXY` | *(empty)* | Set to `1` only behind a proxy that overwrites `X-Forwarded-For`; makes login limits and `Secure` cookie detection use the real client address | | `LUMINARY_INVITE` | *(empty)* | Shared registration code for teammates; personal invite links work without it | | `LUMINARY_MAX_UPLOAD` | `314572800` (300 MB) | Largest accepted upload, in bytes | | `LUMINARY_RAW_EDGE` | `6000` | Long edge of the editable JPEG proxy made from a raw | @@ -230,6 +232,15 @@ directly and have no legacy alias. per-user salt and a 64-byte derived key. - The session cookie is named `lumen_session` and is `HttpOnly; SameSite=Lax`. It is marked `Secure` only when the request arrives with `X-Forwarded-Proto: https`. +- Responses carry `X-Content-Type-Options: nosniff` and a self-only CSP, and stored + photo MIME types are limited to raster images. A member cannot make a gallery link + serve HTML or SVG, even by uploading a file with that content. +- Sign-in is throttled per account and address (8 failures per account per 15 minutes; + 50 per client address, or 500 when a proxy's address is shared). Set + `LUMINARY_TRUST_PROXY=1` behind a proxy so `X-Forwarded-For` identifies the caller. + Gallery writes are limited to 120 per minute per link. +- Uploads are streamed to disk and charged to the uploader's quota before their catalog + row exists, so an interrupted import cannot leave unbilled files behind. - There is no TLS in the server. Terminate HTTPS at a reverse proxy. - The SQLite file, the IndexedDB database and the Compose volume all keep the `lumenroom` name so older deployments upgrade in place. @@ -299,7 +310,9 @@ Two independent things to back up: 1. **The catalog plus originals** — copy the whole data directory (or the Docker volume). Stop the server, or accept that SQLite is in WAL mode and copy - `lumenroom.db`, `lumenroom.db-wal` and `lumenroom.db-shm` together. + `lumenroom.db`, `lumenroom.db-wal` and `lumenroom.db-shm` together. Keep + `secret.key` with it (unless `LUMINARY_SECRET_KEY` is set): without it the saved + SMTP password and bridge tokens cannot be decrypted. 2. **A logical catalog export** — an admin can download a JSON backup (events, photo records, presets and key/value settings) from the admin panel, or via `GET /api/admin/catalog`, and restore it with `POST /api/admin/catalog`. This does @@ -439,7 +452,7 @@ SQLite is created and migrated at boot. All statements are prepared once in `db. | `gallery_comments` | per-token client comments with author name and timestamp | | `gallery_reviews` | per-token, per-photo, per-client approved / changes status | | `invites` | token, optional email lock, role, expiry, acceptance and revocation | -| `bridge_events` | imported event id, dashboard session, encrypted-at-rest token, TTL | +| `bridge_events` | imported event id, dashboard session, AES-GCM-sealed service token, TTL | | `user_quota` | limit, scheduled prune time/plan, last warning timestamps | Photo and event records are JSON documents with a few extracted columns for ordering, @@ -524,7 +537,7 @@ routes are public and are gated only by the share token. | GET | `/api/galleries/:token/photos/:id/thumb` | public | Gallery thumbnail | | GET | `/api/galleries/:token/photos/:id/preview` | public | Gallery preview | | GET | `/api/galleries/:token/photos/:id/download` | public | Download one proof | -| GET | `/api/galleries/:token/download-all?client=` | public | ZIP of the event's proofs, generated in-stream | +| GET | `/api/galleries/:token/download-all?client=` | public | ZIP of the event's proofs; at most 400 files / 512 MB, one archive at a time | | POST | `/api/galleries/:token/picks` | public | Add or remove a client favourite | | POST | `/api/galleries/:token/comments` | public | Append a client comment | | POST | `/api/galleries/:token/reviews` | public | Set approved / changes / none | @@ -665,6 +678,106 @@ Empty `GLENLOCH_URL` or `BRIDGE_SECRET` disables the bridge entirely. --- +## Immich album sync + +Immich support is optional. An administrator can configure one server-wide connection, and +nothing appears in the app for accounts until that connection is enabled. Per-account +connections are still supported as a fallback when no shared connection exists. + +Open **Administration → Immich** as an administrator: + +1. Enter your Immich server address and an API key from Account Settings → API Keys. + The key is sealed with AES-256-GCM, stays on the server, and is never returned by the + API — the browser only ever sees `hasKey`. Back up `LUMINARY_SECRET_KEY` (or the + generated `/secret.key`) with the database. +2. Leave **Automatically publish event photos and edits** on and **Test connection**. +3. Users can then **Refresh albums** in the per-account Immich panel and import one. + Imports run as a background job with progress. + +Required key permissions: `album.read`, `album.create`, `albumAsset.create`, `asset.read`, +`asset.download`, `asset.upload` and `asset.update`. Add `tag.read`, `tag.create` and +`tag.asset` for keyword sync. Add `asset.delete` only if you intend to move originals to +the Immich trash after an edit is uploaded. + +### Pull + +- Streams each image to disk; raws use the normal LibRaw pipeline, so the editable proxy + matches an upload exactly. +- One Luminary event per album, reused on every sync. Every source asset is recorded in + `immich_assets`, so a re-import adds only missing photos and never duplicates one. +- Capture date and basic EXIF (camera, lens, ISO, aperture, shutter, focal length) are + carried across. Ratings, flags, edits and keywords stay Luminary-side. +- Formats the browser cannot display (for example HEIC) keep their original bytes and get + a server-rendered JPEG proxy. +- Uses the account storage quota; a full quota stops the job with a message. + +### Event galleries + +When importing into an event, Luminary creates a matching Immich album by default, links +it to the event, and makes that album the destination for originals and edits. The checkbox +in the import dialog can turn this off for one import. Unlike an imported album, a gallery +is never re-imported and is skipped by scheduled sync, so the versions uploaded from +Luminary do not come back as new photos. + +Every successful import into an event with a gallery is added automatically: the server +uploads each original (converting non-JPEG and raw files to JPEG) and the existing checksum +record prevents a retry from uploading the same file twice. Import failures are reported per +photo and do not stop the rest of the set. + +### Push back + +Edits are saved automatically after you stop adjusting a photo: Luminary waits briefly, +renders the current edit at full resolution as a JPEG, uploads it to the event's Immich album, +and uses the checksum record to skip an unchanged render. You can still use **Send edit to +Immich** from the context menu to send immediately. Luminary: + +1. Uploads it as a **new** Immich asset — current Immich removed in-place replacement, so + the original is never overwritten. +2. Copies album, stack, favourite and sidecar associations from the source asset using the + version-appropriate copy endpoint, then adds the new asset to the same album explicitly + as a fallback. Photos without an Immich original go straight into their event's gallery. +3. Optionally moves the original to the Immich trash (`force: false`, recoverable, never + a permanent delete). This is off by default and needs `asset.delete`. +4. Records the checksum in `immich_pushes`, so sending the same render twice returns the + existing asset instead of uploading a duplicate. + +The action only appears for accounts that enabled the integration, on photos with an +Immich source or an event gallery. Select several photos and use **Send to Immich** in the selection +bar, or the right-click action, to send a queue: each edit is rendered and uploaded in +turn, with a progress card, per-photo failure isolation and checksum skipping for edits +that are already there. **Open in Immich** jumps straight to the source asset. + +### Metadata + +With **Keep ratings, flags and keywords in sync** enabled (the default), Luminary and +Immich stay aligned: + +- Luminary stars map to Immich's 1–5 rating; no stars map to unrated. +- A rejected flag maps to Immich's −1 rating; a pick maps to the favourite flag. +- Keywords map to Immich tags; removing a keyword removes that tag from the imported + asset and any edits pushed from it. + +Edits made in Luminary are debounced and sent to Immich for the imported original and +every edit asset pushed from it. Album sync also reconciles in the other direction: a +rating, favourite or tag changed in Immich is written back to Luminary. Each photo keeps +a local/remote fingerprint snapshot in `immich_meta`, so only genuinely changed sides are +acted on; if both changed, the Luminary value wins. Metadata sync needs `asset.update` +and the tag permissions above, and can be turned off per account. + +### Scheduled sync + +Each account can enable **Keep linked albums in sync automatically** and choose 15 minutes +to once a day. The worker only touches imported albums that account already linked; it +never imports a new album on its own and never re-imports an event gallery. A sync respects the per-album interval, one job per account, and the +storage quota. Manual and automatic syncs share the same job path, so re-imports remain +idempotent. Last run time and the last error are shown in the panel. + +Version differences are handled at runtime: the client reads `/api/server/version`, asks +for album assets inline first, retries with `withoutAssets=false`, and falls back to +`/api/search/metadata` on builds that paginate album contents. + +--- + ## Raw pipeline The browser cannot demosaic camera raw, so the server does it during upload: @@ -879,7 +992,7 @@ including Lensfun's CC BY-SA 3.0 database, which the MIT licence does not relice | tinyxml2 | bundled in Lensfun WASM | [leethomason/tinyxml2](https://github.com/leethomason/tinyxml2) | zlib | | | utf8proc | bundled in Lensfun WASM | [JuliaStrings/utf8proc](https://github.com/JuliaStrings/utf8proc) | MIT | | | `exifr` | 7.1.3 | [MikeKovarik/exifr](https://github.com/MikeKovarik/exifr) | MIT | Browser EXIF parsing | -| `nodemailer` | 7.0.13 | [nodemailer](https://github.com/nodemailer/nodemailer) | MIT-0 | SMTP notifications | +| `nodemailer` | 10.6.1 | [nodemailer](https://github.com/nodemailer/nodemailer) | MIT-0 | SMTP notifications | | React / React DOM | 18.3.1 | [facebook/react](https://github.com/facebook/react) | MIT | | | Vite / Vitest / plugin-react | 5.4.21 / 2.1.9 / 4.7.0 | [vitejs/vite](https://github.com/vitejs/vite) | MIT | | | TypeScript | 5.9.3 | [microsoft/TypeScript](https://github.com/microsoft/TypeScript) | Apache-2.0 | | diff --git a/package-lock.json b/package-lock.json index aec1631..ab70c24 100644 --- a/package-lock.json +++ b/package-lock.json @@ -7,11 +7,12 @@ "": { "name": "luminary", "version": "1.0.0", + "license": "MIT", "dependencies": { "@neoanaloglabkk/lensfun-wasm": "^0.1.3", "exifr": "^7.1.3", "libraw-wasm": "^1.6.0", - "nodemailer": "^7.0.13", + "nodemailer": "^10.6.1", "react": "^18.3.1", "react-dom": "^18.3.1", "sharp": "^0.35.5" @@ -2330,12 +2331,12 @@ } }, "node_modules/nodemailer": { - "version": "7.0.13", - "resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-7.0.13.tgz", - "integrity": "sha512-PNDFSJdP+KFgdsG3ZzMXCgquO7I6McjY2vlqILjtJd0hy8wEvtugS9xKRF2NWlPNGxvLCXlTNIae4serI7dinw==", + "version": "10.6.1", + "resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-10.6.1.tgz", + "integrity": "sha512-d7kfFfS/tR4Aca+SBvRaQ+MXKNv7d2JiRe5TxaRcFT/kYMh4GGPnW9aKksTIEvyEbA7d/7HYWE4YPDEHxzJj/g==", "license": "MIT-0", "engines": { - "node": ">=6.0.0" + "node": ">=20.0.0" } }, "node_modules/pathe": { diff --git a/package.json b/package.json index 427340e..28a0395 100644 --- a/package.json +++ b/package.json @@ -18,7 +18,7 @@ "@neoanaloglabkk/lensfun-wasm": "^0.1.3", "exifr": "^7.1.3", "libraw-wasm": "^1.6.0", - "nodemailer": "^7.0.13", + "nodemailer": "^10.6.1", "react": "^18.3.1", "react-dom": "^18.3.1", "sharp": "^0.35.5" diff --git a/server/auth.mjs b/server/auth.mjs index c21d0e0..5f38f83 100644 --- a/server/auth.mjs +++ b/server/auth.mjs @@ -1,23 +1,40 @@ import crypto from 'node:crypto'; +import { promisify } from 'node:util'; import { SESSION_DAYS } from './config.mjs'; import { sessions, users } from './db.mjs'; const KEYLEN = 64; +const scrypt = promisify(crypto.scrypt); -export function hashPassword(password) { +export async function hashPassword(password) { const salt = crypto.randomBytes(16); - const hash = crypto.scryptSync(password, salt, KEYLEN); + const hash = await scrypt(password, salt, KEYLEN); return `scrypt$${salt.toString('hex')}$${hash.toString('hex')}`; } -export function verifyPassword(password, stored) { +export async function verifyPassword(password, stored) { const [scheme, saltHex, hashHex] = String(stored).split('$'); if (scheme !== 'scrypt' || !saltHex || !hashHex) return false; const expected = Buffer.from(hashHex, 'hex'); - const actual = crypto.scryptSync(password, Buffer.from(saltHex, 'hex'), expected.length); + const actual = await scrypt(password, Buffer.from(saltHex, 'hex'), expected.length); return expected.length === actual.length && crypto.timingSafeEqual(expected, actual); } +/** + * A fixed hash for addresses that do not exist, so a failed login costs the + * same scrypt work as a real one and does not reveal registration by timing. + * Built synchronously once at boot; this is not on a request path. + */ +const DUMMY_HASH = (() => { + const salt = crypto.randomBytes(16); + const hash = crypto.scryptSync('luminary-timing-equalizer', salt, KEYLEN); + return `scrypt$${salt.toString('hex')}$${hash.toString('hex')}`; +})(); + +export async function spendPasswordCheck(password) { + await verifyPassword(password, DUMMY_HASH); +} + export function createSession(userId) { const token = crypto.randomBytes(32).toString('hex'); const expiresAt = Date.now() + SESSION_DAYS * 24 * 60 * 60 * 1000; diff --git a/server/bridge.mjs b/server/bridge.mjs index b7966ec..6e61d1c 100644 --- a/server/bridge.mjs +++ b/server/bridge.mjs @@ -11,6 +11,7 @@ import crypto from 'node:crypto'; import { BRIDGE_SECRET, BRIDGE_TTL_HOURS, GLENLOCH_URL } from './config.mjs'; import { db, removeEvent, removePhoto, saveEvent, savePhoto } from './db.mjs'; import { removeAsset } from './storage.mjs'; +import { open, seal } from './secrets.mjs'; const VERSION = 'g1'; @@ -119,7 +120,14 @@ export function bridgePhotoId(sourcePhotoId) { } export function bridgeForEvent(eventId) { - return bridgeGet.get(eventId) ?? null; + const row = bridgeGet.get(eventId); + if (!row) return null; + try { + return { ...row, token: open(row.token) }; + } catch (err) { + console.error(`[luminary] could not decrypt the bridge token for ${eventId}: ${err.message}`); + return { ...row, token: '' }; + } } /** Deletes an imported event, its rows and any cached previews/thumbnails. */ @@ -208,7 +216,7 @@ export async function importBridgeEvent({ serviceToken, sessionId, ownerId = '' bridgeInsert.run( eventId, sessionId, - serviceToken, + seal(serviceToken), GLENLOCH_URL, listing.event.id, returnUrl, diff --git a/server/config.mjs b/server/config.mjs index 9f68ce1..2e85f4b 100644 --- a/server/config.mjs +++ b/server/config.mjs @@ -33,6 +33,13 @@ export const GLENLOCH_URL = (process.env.GLENLOCH_URL || '').replace(/\/+$/, '') /** Shared HMAC secret for bridge tokens; must match the dashboard's value. */ export const BRIDGE_SECRET = process.env.BRIDGE_SECRET || ''; + +/** Optional key for encrypting saved SMTP and bridge credentials at rest. */ +export const SECRET_KEY = setting('SECRET_KEY'); + +/** Trust X-Forwarded-For for rate limits; only behind a proxy that sets it. */ +export const TRUST_PROXY = setting('TRUST_PROXY') === '1'; + /** How long an imported bridge event survives without being reopened. */ export const BRIDGE_TTL_HOURS = Number(setting('BRIDGE_TTL_HOURS', '12')); diff --git a/server/db.mjs b/server/db.mjs index 25efdb1..4ec75ab 100644 --- a/server/db.mjs +++ b/server/db.mjs @@ -114,6 +114,76 @@ db.exec(` 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), @@ -162,6 +232,24 @@ if (!eventColumns.includes('share_token')) { } 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 (?, ?, ?, ?, ?) @@ -255,6 +343,115 @@ const q = { 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 (?, ?, ?, ?, ?, ?)', @@ -361,6 +558,8 @@ export function saveEvent(record, sortIndex = 0, ownerId = '') { 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) { @@ -479,6 +678,250 @@ export function getPhoto(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; } @@ -501,6 +944,9 @@ export function removePhoto(id) { 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() { diff --git a/server/immich.mjs b/server/immich.mjs new file mode 100644 index 0000000..c6f2892 --- /dev/null +++ b/server/immich.mjs @@ -0,0 +1,1540 @@ +/** + * Immich integration — opt-in, per account. + * + * Each user connects their own Immich server and API key from the Immich sync + * panel; nothing exists for a user until they save a connection and enable it. + * The integration then provides three things: + * + * - pull: import an album into a Luminary event, recording each source asset; + * - push: on demand only, render an edit (or the original) and upload it as a + * new Immich asset, copying album, stack, favourite and sidecar + * associations from the imported original. + * + * The API key is sealed at rest and never returned to the browser. All network + * access is server-side, so the key is not exposed to page scripts either. + */ + +import crypto from 'node:crypto'; +import fs from 'node:fs'; +import fsp from 'node:fs/promises'; +import { Readable, Transform } from 'node:stream'; +import { pipeline } from 'node:stream/promises'; +import { MAX_UPLOAD, RAW_PREVIEW_EDGE } from './config.mjs'; +import { + allImmichSettings, + deleteImmichSettingsRecord, + getEvent, + getPhoto, + immichAlbumByAlbum, + immichAlbumFor, + immichAlbumForEvent, + immichAlbumLinks, + immichAssetForPhoto, + immichAssetsForEvent, + immichMetaFor, + immichPendingForEvent, + immichPushAssetsForPhoto, + immichPushDoneForPhoto, + immichPushFor, + immichSettingsFor, + kv, + patchPhotoMeta, + photoIdsForEvent, + saveImmichMeta, + removeImmichAsset, + saveEvent, + saveImmichAlbum, + saveImmichAsset, + saveImmichPush, + saveImmichSettingsRecord, + savePhoto, + setImmichSyncState, +} from './db.mjs'; +import { decodeRaw, isRawName } from './raw.mjs'; +import { jpegInfo, makeThumb, toJpegProxy } from './imaging.mjs'; +import { findOriginal, findPreview, originalTarget, writePreview, writeThumb } from './storage.mjs'; +import { quotaState } from './quota.mjs'; +import { open, seal } from './secrets.mjs'; + +const REQUEST_TIMEOUT_MS = 20_000; +const DOWNLOAD_TIMEOUT_MS = 5 * 60 * 1000; +const MAX_JOB_HISTORY = 20; +const MAX_JOB_ERRORS = 5; +const SYNC_TICK_MS = 5 * 60 * 1000; + +const MIME_BY_EXT = { + jpg: 'image/jpeg', + jpeg: 'image/jpeg', + png: 'image/png', + webp: 'image/webp', + gif: 'image/gif', + avif: 'image/avif', + tif: 'image/tiff', + tiff: 'image/tiff', + heic: 'image/heic', + heif: 'image/heif', +}; + +const BROWSER_IMAGE_EXT = new Set(['jpg', 'jpeg', 'png', 'webp', 'gif', 'avif']); + +/* ------------------------------------------------------------------ settings */ + +const versionCache = new Map(); +const SHARED_OWNER_ID = '__shared__'; +const SHARED_SETTINGS_KEY = 'immich.shared'; + +/** The server-wide connection saved from Administration → Immich. */ +function sharedSettingsRow() { + const saved = kv.get(SHARED_SETTINGS_KEY); + if (!saved || typeof saved !== 'object') return null; + return { + ownerId: SHARED_OWNER_ID, + serverUrl: String(saved.serverUrl ?? ''), + apiKey: String(saved.apiKey ?? ''), + enabled: Boolean(saved.enabled), + autoSync: false, + syncMinutes: 60, + trashOriginal: Boolean(saved.trashOriginal), + syncMetadata: saved.syncMetadata !== false, + lastSyncAt: saved.lastSyncAt ?? null, + lastError: saved.lastError ?? null, + createdAt: saved.createdAt ?? Date.now(), + }; +} + +function openedSettings(ownerId) { + // A connection configured by an administrator applies to every account. + // Per-account settings remain as a fallback for installations without one. + const shared = sharedSettingsRow(); + const row = shared ?? (ownerId === SHARED_OWNER_ID ? null : immichSettingsFor(ownerId)); + if (!row) return null; + let apiKey = row.apiKey; + if (apiKey) { + try { + apiKey = open(apiKey); + } catch (err) { + console.error(`[luminary] could not decrypt the Immich key for ${ownerId}:`, err.message); + apiKey = ''; + } + } + return { ...row, apiKey }; +} + +export function normalizeImmichUrl(input) { + const raw = String(input ?? '').trim(); + if (!raw) throw new Error('Enter the address of your Immich server'); + let url; + try { + url = new URL(raw); + } catch { + throw new Error('Enter a full address, for example http://192.168.1.10:2283'); + } + if (url.protocol !== 'http:' && url.protocol !== 'https:') { + throw new Error('Immich must be reachable over http or https'); + } + if (url.username || url.password) { + throw new Error('Put the API key in the key field, not in the server address'); + } + url.search = ''; + url.hash = ''; + let pathname = url.pathname.replace(/\/+$/, ''); + if (/\/api$/i.test(pathname)) pathname = pathname.slice(0, -4); + url.pathname = pathname; + return `${url.origin}${pathname}`; +} + +/** Safe for the browser: never includes the API key. */ +export function immichStatusFor(ownerId) { + const row = openedSettings(ownerId); + let url = row?.serverUrl ?? ''; + let valid = true; + try { + if (url) url = normalizeImmichUrl(url); + } catch { + valid = false; + } + const hasKey = Boolean(row?.apiKey); + const configured = Boolean(valid && url && hasKey); + return { + configured, + enabled: Boolean(configured && row?.enabled), + managed: Boolean(sharedSettingsRow()), + url, + hasKey, + autoSync: Boolean(row?.autoSync), + syncMinutes: Number(row?.syncMinutes ?? 60), + trashOriginal: Boolean(row?.trashOriginal), + syncMetadata: Boolean(row?.syncMetadata ?? true), + lastSyncAt: row?.lastSyncAt ?? null, + lastError: row?.lastError ?? null, + version: versionCache.get(ownerId) ?? versionCache.get(SHARED_OWNER_ID) ?? null, + albumCount: immichAlbumLinks(ownerId).length, + }; +} + +export function immichConfigured(ownerId) { + return immichStatusFor(ownerId).configured; +} + +export function saveImmichUserSettings(ownerId, input = {}) { + const current = openedSettings(ownerId); + const url = normalizeImmichUrl(input.url !== undefined ? input.url : current?.serverUrl ?? ''); + const apiKey = String( + (input.apiKey && String(input.apiKey).trim()) || current?.apiKey || '', + ).trim(); + if (!apiKey) throw new Error('Paste an Immich API key'); + if (apiKey.length < 8) throw new Error('That API key looks too short'); + + const record = { + ownerId, + serverUrl: url, + apiKey: seal(apiKey), + enabled: input.enabled === undefined ? (current?.enabled ?? true) : Boolean(input.enabled), + autoSync: + input.autoSync === undefined ? (current?.autoSync ?? false) : Boolean(input.autoSync), + syncMinutes: Math.max( + 15, + Math.min(1440, Number(input.syncMinutes ?? current?.syncMinutes ?? 60) || 60), + ), + trashOriginal: + input.trashOriginal === undefined + ? (current?.trashOriginal ?? false) + : Boolean(input.trashOriginal), + syncMetadata: + input.syncMetadata === undefined ? (current?.syncMetadata ?? true) : Boolean(input.syncMetadata), + lastSyncAt: current?.lastSyncAt ?? null, + lastError: null, + createdAt: current?.createdAt ?? Date.now(), + }; + saveImmichSettingsRecord(record); + if (!current || input.apiKey || url !== current.serverUrl) versionCache.delete(ownerId); + return immichStatusFor(ownerId); +} + +export function saveImmichAdminSettings(input = {}) { + const current = openedSettings(SHARED_OWNER_ID); + const url = normalizeImmichUrl(input.url !== undefined ? input.url : current?.serverUrl ?? ''); + const apiKey = String( + (input.apiKey && String(input.apiKey).trim()) || current?.apiKey || '', + ).trim(); + if (!apiKey) throw new Error('Paste an Immich API key'); + if (apiKey.length < 8) throw new Error('That API key looks too short'); + + const previous = kv.get(SHARED_SETTINGS_KEY) ?? {}; + kv.set(SHARED_SETTINGS_KEY, { + serverUrl: url, + apiKey: seal(apiKey), + enabled: input.enabled === undefined ? (current?.enabled ?? true) : Boolean(input.enabled), + trashOriginal: + input.trashOriginal === undefined + ? (current?.trashOriginal ?? false) + : Boolean(input.trashOriginal), + syncMetadata: + input.syncMetadata === undefined ? (current?.syncMetadata ?? true) : Boolean(input.syncMetadata), + lastSyncAt: current?.lastSyncAt ?? null, + lastError: null, + createdAt: previous.createdAt ?? Date.now(), + }); + if (!current || input.apiKey || url !== current.serverUrl) versionCache.delete(SHARED_OWNER_ID); + return immichStatusFor(SHARED_OWNER_ID); +} + +export function disconnectImmichAdmin() { + kv.set(SHARED_SETTINGS_KEY, null); + versionCache.delete(SHARED_OWNER_ID); + return immichStatusFor(SHARED_OWNER_ID); +} + +export function immichAdminStatus() { + return immichStatusFor(SHARED_OWNER_ID); +} + +export function immichAdminPing() { + return immichPing(SHARED_OWNER_ID); +} + +export function disconnectImmich(ownerId) { + deleteImmichSettingsRecord(ownerId); + versionCache.delete(ownerId); + return immichStatusFor(ownerId); +} + +function credentials(ownerId) { + const row = openedSettings(ownerId); + if (!row?.serverUrl || !row.apiKey) { + throw new Error('Connect your Immich server in the Immich sync panel first'); + } + return { url: normalizeImmichUrl(row.serverUrl), apiKey: row.apiKey, settings: row }; +} + +/* ---------------------------------------------------------------------- api */ + +function messageFromBody(body, status) { + const raw = body?.message ?? body?.error; + if (Array.isArray(raw)) return raw.join('; '); + if (typeof raw === 'string' && raw.trim()) return raw.trim(); + return `Immich request failed (${status})`; +} + +async function apiRequest(ownerId, path, init = {}) { + const { url, apiKey } = credentials(ownerId); + const controller = new AbortController(); + const timer = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS); + try { + const res = await fetch(`${url}/api${path}`, { + ...init, + headers: { + accept: 'application/json', + 'x-api-key': apiKey, + ...(init.headers ?? {}), + }, + signal: controller.signal, + }); + const text = await res.text(); + let body = null; + try { + body = text ? JSON.parse(text) : null; + } catch { + body = text; + } + if (!res.ok) { + if (res.status === 401 || res.status === 403) { + throw new Error( + 'Immich rejected the API key or it lacks permission. Check album.read, albumAsset.create, asset.read, asset.download and asset.upload.', + ); + } + throw new Error(messageFromBody(body, res.status)); + } + return body; + } catch (err) { + if (err instanceof Error && err.name === 'AbortError') { + throw new Error('The Immich server did not respond in time'); + } + if (err instanceof TypeError) { + throw new Error(`Could not reach Immich at ${url}`); + } + throw err; + } finally { + clearTimeout(timer); + } +} + +async function immichVersion(ownerId) { + const body = await apiRequest(ownerId, '/server/version'); + let major = 0; + let minor = 0; + let patch = 0; + let version = 'unknown'; + if (typeof body === 'string') { + version = body; + const parts = body.split('.').map(Number); + [major = 0, minor = 0, patch = 0] = parts; + } else if (body && typeof body === 'object') { + major = Number(body.major ?? 0) || 0; + minor = Number(body.minor ?? 0) || 0; + patch = Number(body.patch ?? 0) || 0; + version = String(body.version ?? (major ? `${major}.${minor}.${patch}` : 'unknown')); + } + if (major) versionCache.set(ownerId, version); + return { major, minor, patch, version }; +} + +function normalizeAlbum(album) { + return { + id: String(album.id), + name: String(album.albumName ?? album.name ?? 'Untitled album'), + assetCount: Number(album.assetCount ?? album.assets?.length ?? 0) || 0, + updatedAt: album.updatedAt ? Date.parse(album.updatedAt) || null : null, + startDate: album.startDate ? Date.parse(album.startDate) || null : null, + endDate: album.endDate ? Date.parse(album.endDate) || null : null, + thumbnailAssetId: album.albumThumbnailAssetId ?? null, + }; +} + +export async function listImmichAlbums(ownerId) { + const body = await apiRequest(ownerId, '/albums'); + const items = Array.isArray(body) ? body : Array.isArray(body?.albums) ? body.albums : []; + return items + .filter((album) => album && album.id) + .map(normalizeAlbum) + .sort( + (a, b) => + (b.updatedAt ?? 0) - (a.updatedAt ?? 0) || + a.name.localeCompare(b.name, undefined, { sensitivity: 'base' }), + ); +} + +/** Creates an Immich album for an event and records it as that event's gallery. */ +export async function createImmichAlbumForEvent({ ownerId, eventId, name }) { + const settings = openedSettings(ownerId); + if (!settings?.enabled) { + throw new Error('Immich sync is not enabled for this account'); + } + const event = getEvent(eventId); + if (!event) throw new Error('No such event'); + if (event.immich || immichAlbumForEvent(eventId)) { + throw new Error('This event already has an Immich gallery'); + } + + const { url } = credentials(ownerId); + const albumName = String(name || event.name || 'Luminary event').trim().slice(0, 120); + const created = await apiRequest(ownerId, '/albums', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ albumName, description: 'Created from Luminary' }), + }); + const albumId = created?.id ? String(created.id) : ''; + if (!albumId) throw new Error('Immich did not return the new album'); + + const now = Date.now(); + saveImmichAlbum({ + eventId, + ownerId, + serverUrl: url, + albumId, + albumName, + assetCount: 0, + kind: 'gallery', + lastSyncAt: now, + createdAt: now, + }); + const updated = { + ...event, + immich: { albumId, albumName, serverUrl: url, lastSyncAt: now }, + }; + saveEvent(updated, event.order ?? event.createdAt ?? now, ownerId); + return { album: normalizeAlbum(created), event: updated }; +} + +export async function immichPing(ownerId) { + const version = await immichVersion(ownerId); + const albums = await listImmichAlbums(ownerId); + const { url } = credentials(ownerId); + return { + ok: true, + url, + version: version.version, + major: version.major, + albumCount: albums.length, + }; +} + +/* -------------------------------------------------------------------- albums */ + +async function searchAlbumAssets(ownerId, albumId) { + const body = await apiRequest(ownerId, '/search/metadata', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ albumIds: [albumId], size: 1000, page: 1, withExif: true }), + }); + if (Array.isArray(body?.assets?.items)) return body.assets.items; + if (Array.isArray(body?.items)) return body.items; + return []; +} + +async function fetchImmichAlbum(ownerId, albumId) { + let album = await apiRequest(ownerId, `/albums/${encodeURIComponent(albumId)}`); + if (!album || typeof album !== 'object') { + throw new Error('Immich returned an unexpected album response'); + } + let assets = Array.isArray(album.assets) ? album.assets : []; + + if (!assets.length) { + const full = await apiRequest( + ownerId, + `/albums/${encodeURIComponent(albumId)}?withoutAssets=false`, + ).catch(() => null); + if (full && typeof full === 'object') { + album = { ...album, ...full }; + if (Array.isArray(full.assets)) assets = full.assets; + } + } + + const expected = Number(album.assetCount ?? 0) || 0; + if (expected && assets.length < expected) { + const items = await searchAlbumAssets(ownerId, albumId).catch(() => []); + if (items.length > assets.length) assets = items; + } + return { album, assets, expected }; +} + +function assetFileName(asset) { + const name = String(asset.originalFileName ?? '').trim(); + if (name) return name; + const fromPath = String(asset.originalPath ?? '').split('/').pop()?.trim(); + if (fromPath) return fromPath; + return `${asset.id}.jpg`; +} + +function assetTakenAt(asset) { + const value = asset.fileCreatedAt || asset.exifInfo?.dateTimeOriginal || asset.createdAt; + const ms = value ? Date.parse(value) : NaN; + return Number.isFinite(ms) ? ms : undefined; +} + +function assetMeta(asset) { + const exif = asset.exifInfo ?? {}; + const camera = [exif.make, exif.model].filter(Boolean).join(' ').trim(); + const iso = Number(exif.iso) || undefined; + const aperture = Number(exif.fNumber) || undefined; + const focal = Number(exif.focalLength) || undefined; + const shutter = exif.exposureTime ? String(exif.exposureTime) : undefined; + return { + ...(camera ? { camera } : {}), + ...(exif.lensModel ? { lens: String(exif.lensModel) } : {}), + ...(iso ? { iso } : {}), + ...(aperture ? { aperture } : {}), + ...(shutter ? { shutter } : {}), + ...(focal ? { focal } : {}), + }; +} + +function extensionOf(name) { + const raw = String(name ?? ''); + const dot = raw.lastIndexOf('.'); + const ext = dot > 0 ? raw.slice(dot + 1).toLowerCase() : ''; + return /^[a-z0-9]{1,10}$/.test(ext) ? ext : 'jpg'; +} + +async function downloadImmichAsset(ownerId, assetId, target) { + const { url, apiKey } = credentials(ownerId); + const controller = new AbortController(); + const timer = setTimeout(() => controller.abort(), DOWNLOAD_TIMEOUT_MS); + const temp = `${target}.part-${crypto.randomBytes(6).toString('hex')}`; + let size = 0; + + try { + const res = await fetch(`${url}/api/assets/${encodeURIComponent(assetId)}/original`, { + headers: { 'x-api-key': apiKey }, + signal: controller.signal, + }); + if (!res.ok || !res.body) { + throw new Error(`Immich could not send this file (${res.status})`); + } + + const counter = new Transform({ + transform(chunk, _encoding, callback) { + size += chunk.length; + if (size > MAX_UPLOAD) { + callback(new Error('This file is larger than the upload limit')); + return; + } + callback(null, chunk); + }, + }); + + await pipeline(Readable.fromWeb(res.body), counter, fs.createWriteStream(temp, { flags: 'wx' })); + await fsp.rename(temp, target); + return size; + } catch (err) { + await fsp.rm(temp, { force: true }).catch(() => undefined); + if (err instanceof Error && err.name === 'AbortError') { + throw new Error('The Immich download timed out'); + } + throw err; + } finally { + clearTimeout(timer); + } +} + +async function prepareImportedFile({ photoId, fileName, raw, target, exifSize }) { + if (raw) { + const decoded = await decodeRaw(await fsp.readFile(target)); + await writePreview(photoId, decoded.jpeg, decoded.ext); + const info = await jpegInfo(decoded.jpeg); + const thumb = await makeThumb(decoded.jpeg, 512); + if (thumb) await writeThumb(photoId, thumb); + return { + mime: 'image/jpeg', + width: info?.width || decoded.width || exifSize?.width || 0, + height: info?.height || decoded.height || exifSize?.height || 0, + previewUrl: `/api/photos/${photoId}/preview`, + thumbUrl: `/api/photos/${photoId}/thumb`, + decode: decoded.engine, + }; + } + + const ext = extensionOf(fileName); + const buffer = await fsp.readFile(target); + const info = await jpegInfo(buffer); + + let previewUrl; + let previewBuffer; + if (!BROWSER_IMAGE_EXT.has(ext)) { + const proxy = await toJpegProxy(buffer, RAW_PREVIEW_EDGE); + if (proxy) { + await writePreview(photoId, proxy.data, proxy.ext); + previewUrl = `/api/photos/${photoId}/preview`; + previewBuffer = proxy.data; + } + } + + const thumb = await makeThumb(previewBuffer ?? buffer, 512); + if (thumb) await writeThumb(photoId, thumb); + + return { + mime: MIME_BY_EXT[ext] ?? 'application/octet-stream', + width: info?.width || exifSize?.width || 0, + height: info?.height || exifSize?.height || 0, + previewUrl, + thumbUrl: `/api/photos/${photoId}/thumb`, + }; +} + +/* --------------------------------------------------------------------- jobs */ + +const jobs = new Map(); + +function pruneJobs() { + if (jobs.size <= MAX_JOB_HISTORY) return; + const finished = [...jobs.values()] + .filter((job) => job.state !== 'running') + .sort((a, b) => (a.finishedAt ?? a.startedAt) - (b.finishedAt ?? b.startedAt)); + while (jobs.size > MAX_JOB_HISTORY && finished.length) { + jobs.delete(finished.shift().id); + } +} + +function runningJobFor(ownerId) { + for (const job of jobs.values()) { + if (job.ownerId === ownerId && job.state === 'running') return job; + } + return null; +} + +function publicJob(job) { + return { + id: job.id, + albumId: job.albumId, + albumName: job.albumName, + eventId: job.eventId, + state: job.state, + scheduled: Boolean(job.scheduled), + total: job.total, + done: job.done, + skipped: job.skipped, + failed: job.failed, + bytes: job.bytes, + message: job.message, + errors: job.errors.slice(), + startedAt: job.startedAt, + finishedAt: job.finishedAt, + }; +} + +export function immichJobFor(id, user) { + const job = jobs.get(id); + if (!job) return null; + if (job.ownerId !== user.id && user.role !== 'admin') return null; + return publicJob(job); +} + +function makeJob(ownerId, albumId, scheduled) { + pruneJobs(); + const job = { + id: crypto.randomUUID(), + ownerId, + albumId, + albumName: '', + eventId: null, + scheduled: Boolean(scheduled), + state: 'running', + total: 0, + done: 0, + skipped: 0, + failed: 0, + bytes: 0, + message: '', + errors: [], + startedAt: Date.now(), + finishedAt: null, + }; + job.completion = new Promise((resolve) => { + job.settle = resolve; + }); + jobs.set(job.id, job); + + void runImport(job) + .catch((err) => { + job.state = 'error'; + job.message = err instanceof Error ? err.message : 'The import could not be completed'; + job.finishedAt = Date.now(); + }) + .finally(() => job.settle(job)); + + return job; +} + +export function startImmichImport({ albumId, ownerId }) { + const status = immichStatusFor(ownerId); + if (!status.configured) { + throw new Error('Connect your Immich server in the Immich sync panel first'); + } + if (!status.enabled) { + throw new Error('Turn on Immich sync in the Immich sync panel first'); + } + if (typeof albumId !== 'string' || !/^[A-Za-z0-9_-]{1,64}$/.test(albumId)) { + throw new Error('Choose an Immich album to import'); + } + const gallery = immichAlbumByAlbum(ownerId, albumId); + if (gallery?.kind === 'gallery') { + throw new Error('This album is an event gallery. Its edits are uploaded from Luminary.'); + } + if (runningJobFor(ownerId)) { + throw new Error('An Immich import is already running for this account. Wait for it to finish.'); + } + return publicJob(makeJob(ownerId, albumId, false)); +} + +async function runImport(job) { + await immichVersion(job.ownerId); + const { album, assets, expected } = await fetchImmichAlbum(job.ownerId, job.albumId); + const syncMeta = Boolean(openedSettings(job.ownerId)?.syncMetadata); + job.albumName = String(album.albumName ?? 'Untitled album'); + + const images = assets.filter( + (asset) => asset && asset.id && (!asset.type || asset.type === 'IMAGE') && !asset.isTrashed, + ); + job.total = images.length; + if (expected && images.length < expected) { + job.message = `Immich reported ${expected} items; ${images.length} images were available to import.`; + } + + const { url } = credentials(job.ownerId); + const existingLink = immichAlbumFor(job.ownerId, url, job.albumId); + const eventId = existingLink?.eventId ?? `immich-${crypto.randomUUID()}`; + job.eventId = eventId; + + const existingEvent = existingLink ? getEvent(eventId) : null; + const known = new Map(immichAssetsForEvent(eventId).map((row) => [row.assetId, row])); + const now = Date.now(); + + let nextOrder = 0; + for (const row of known.values()) { + const photo = getPhoto(row.photoId); + if (photo) nextOrder = Math.max(nextOrder, (photo.order ?? 0) + 1); + } + + let newestTaken = existingEvent?.date ?? 0; + let budget = quotaState(job.ownerId).remaining; + + for (const asset of images) { + const previous = known.get(String(asset.id)); + if (previous) { + const existingPhoto = getPhoto(previous.photoId); + if (existingPhoto) { + if (syncMeta) { + const saved = immichMetaFor(previous.photoId); + const stamp = asset.updatedAt ? Date.parse(asset.updatedAt) || 0 : 0; + if (!saved || !stamp || stamp !== saved.remoteUpdatedAt) { + await reconcileImmichMetadata({ + photoId: previous.photoId, + ownerId: job.ownerId, + remoteAsset: asset, + }).catch(() => undefined); + } + } + job.skipped += 1; + continue; + } + removeImmichAsset(eventId, previous.assetId); + known.delete(previous.assetId); + } + + if (budget <= 0) { + job.message = 'The account storage quota is full; the remaining photos were not imported.'; + break; + } + + const fileName = assetFileName(asset); + const raw = isRawName(fileName); + const photoId = `im-${crypto.randomUUID()}`; + const target = originalTarget(photoId, extensionOf(fileName)); + const exif = asset.exifInfo ?? {}; + const exifWidth = Number(exif.exifImageWidth ?? 0) || 0; + const exifHeight = Number(exif.exifImageHeight ?? 0) || 0; + const exifSize = exifWidth && exifHeight ? { width: exifWidth, height: exifHeight } : null; + const takenAt = assetTakenAt(asset); + const pulled = syncMeta ? await importAssetMetadata(job.ownerId, asset) : null; + + try { + const size = await downloadImmichAsset(job.ownerId, String(asset.id), target); + const prepared = await prepareImportedFile({ + photoId, + fileName, + raw, + target, + exifSize, + }); + + savePhoto( + { + id: photoId, + eventId, + order: nextOrder, + name: fileName, + width: prepared.width, + height: prepared.height, + size, + mime: prepared.mime, + addedAt: Date.now(), + takenAt, + meta: assetMeta(asset), + thumb: '', + thumbUrl: prepared.thumbUrl, + rating: pulled?.meta.rating ?? 0, + flag: pulled?.meta.flag ?? 'none', + color: '', + keywords: pulled?.meta.keywords ?? [], + edits: {}, + history: [], + raw, + ...(raw && prepared.decode ? { decode: prepared.decode } : {}), + ...(prepared.previewUrl ? { previewUrl: prepared.previewUrl } : {}), + immich: { + albumId: job.albumId, + assetId: String(asset.id), + checksum: String(asset.checksum ?? ''), + }, + }, + Date.now(), + job.ownerId, + ); + saveImmichAsset({ + eventId, + assetId: String(asset.id), + photoId, + ownerId: job.ownerId, + albumId: job.albumId, + checksum: String(asset.checksum ?? ''), + fileName, + }); + if (pulled) { + rememberImmichMeta({ + photoId, + ownerId: job.ownerId, + assetId: String(asset.id), + local: { + rating: pulled.meta.rating, + flag: pulled.meta.flag, + keywords: pulled.meta.keywords ?? [], + }, + remote: pulled.meta, + }); + } + + nextOrder += 1; + job.done += 1; + job.bytes += size; + budget -= size; + if (takenAt) newestTaken = Math.max(newestTaken, takenAt); + } catch (err) { + job.failed += 1; + if (job.errors.length < MAX_JOB_ERRORS) { + job.errors.push( + `${fileName}: ${err instanceof Error ? err.message : 'could not be imported'}`, + ); + } + await fsp.rm(target, { force: true }).catch(() => undefined); + } + } + + const record = { + ...(existingEvent ?? { + id: eventId, + name: job.albumName, + createdAt: now, + date: newestTaken || now, + notes: `Imported from Immich (${url})`, + }), + id: eventId, + name: existingEvent?.name || job.albumName, + date: newestTaken || existingEvent?.date || now, + immich: { + albumId: job.albumId, + albumName: job.albumName, + serverUrl: url, + lastSyncAt: Date.now(), + }, + }; + saveEvent(record, existingEvent?.order ?? existingEvent?.createdAt ?? now, job.ownerId); + saveImmichAlbum({ + eventId, + ownerId: job.ownerId, + serverUrl: url, + albumId: job.albumId, + albumName: job.albumName, + assetCount: images.length, + lastSyncAt: Date.now(), + createdAt: existingLink?.createdAt ?? now, + }); + setImmichSyncState(job.ownerId, Date.now(), null); + + if (job.failed) { + job.message = `${job.failed} file${job.failed === 1 ? '' : 's'} could not be imported.`; + } else if (!job.message) { + job.message = job.done + ? `Imported ${job.done} new photo${job.done === 1 ? '' : 's'}.` + : 'Everything in this album is already in the library.'; + } + job.state = 'done'; + job.finishedAt = Date.now(); +} + +/** Links already created by this account, keyed for the album picker. */ +export function immichLinksForOwner(ownerId) { + return immichAlbumLinks(ownerId); +} + +/** + * Photos in an event that are not in its Immich gallery yet. Only local + * bookkeeping is read here, so the caller can plan a backfill without + * touching Immich. + */ +export function immichPendingPhotos({ eventId, ownerId }) { + const settings = openedSettings(ownerId); + if (!settings?.enabled) { + throw new Error('Immich sync is not enabled for this account'); + } + const event = getEvent(eventId); + if (!event) throw new Error('No such event'); + if (!event.immich && !immichAlbumForEvent(eventId)) { + throw new Error('This event has no Immich gallery yet'); + } + const pending = immichPendingForEvent(eventId, ownerId); + return { pending, total: pending.length }; +} + +/** + * The manual push plan for one event: originals Immich has never seen, plus the + * current edit of any photo whose edits changed since the last push. This only + * reads local bookkeeping - the client renders and uploads each entry. + */ +export function immichEventQueue({ eventId, ownerId }) { + const settings = openedSettings(ownerId); + if (!settings?.enabled) { + throw new Error('Immich sync is not enabled for this account'); + } + const event = getEvent(eventId); + if (!event) throw new Error('No such event'); + if (!immichAlbumForEvent(eventId)) { + throw new Error('This event has no Immich gallery'); + } + + const queue = []; + for (const photoId of photoIdsForEvent(eventId, ownerId)) { + const photo = getPhoto(photoId); + if (!photo || photo.deletedAt) continue; + const link = immichAssetForPhoto(photoId); + const pushed = immichPushDoneForPhoto(photoId); + if (!photo.copyOf && !link && !pushed) { + queue.push({ photoId, name: photo.name, mode: 'original' }); + continue; + } + // Virtual copies have no bytes of their own, so they are always rendered. + if (pushed && !photo.copyOf && pushed.edits_hash === editsHash(photo)) continue; + queue.push({ photoId, name: photo.name, mode: 'edit' }); + } + return { queue, total: queue.length }; +} + +/* --------------------------------------------------------------------- push */ + +/** Identifies the edit version, so a repeat push can skip unchanged photos. */ +function editsHash(photo) { + return crypto.createHash('sha1').update(JSON.stringify(photo?.edits ?? null)).digest('base64'); +} + +function fileStamp(photo) { + const ms = Number(photo.takenAt ?? photo.addedAt ?? Date.now()); + return new Date(Number.isFinite(ms) ? ms : Date.now()).toISOString(); +} + +function outputName(photo) { + const base = String(photo.name || 'photo').replace(/\.[^.]+$/, '') || 'photo'; + return `${base}-luminary.jpg`; +} + +/* ------------------------------------------------------------------ metadata */ + +function normalizeKeywords(list) { + const seen = new Set(); + const out = []; + for (const value of list ?? []) { + const word = String(value ?? '').trim(); + if (!word) continue; + const key = word.toLowerCase(); + if (seen.has(key)) continue; + seen.add(key); + out.push(word.slice(0, 64)); + if (out.length >= 100) break; + } + return out; +} + +/** Immich stars + favourite/rejected map onto Luminary rating + flag. */ +function remoteMetadata(asset) { + const raw = Number(asset?.rating ?? asset?.exifInfo?.rating); + const rating = Number.isFinite(raw) ? Math.trunc(raw) : 0; + const tags = Array.isArray(asset?.tags) + ? normalizeKeywords(asset.tags.map((tag) => tag?.value ?? tag?.name)) + : null; + return { + rating: rating < 0 ? 0 : Math.min(5, rating), + flag: rating < 0 ? 'reject' : asset?.isFavorite ? 'pick' : 'none', + keywords: tags, + updatedAt: asset?.updatedAt ? Date.parse(asset.updatedAt) || 0 : 0, + }; +} + +function localMetadata(photo) { + return { + rating: Math.max(0, Math.min(5, Math.trunc(Number(photo.rating) || 0))), + flag: photo.flag === 'pick' || photo.flag === 'reject' ? photo.flag : 'none', + keywords: normalizeKeywords(photo.keywords), + }; +} + +function metadataFingerprint(meta) { + return JSON.stringify([meta.rating, meta.flag, meta.keywords ?? null]); +} + +function immichRating(local, major) { + if (local.flag === 'reject') return -1; + if (local.rating > 0) return local.rating; + // v3 rejects 0 as a rating; older servers use 0 for unrated. + return major >= 3 ? null : 0; +} + +function rememberImmichMeta({ photoId, ownerId, assetId, local, remote }) { + saveImmichMeta({ + photoId, + ownerId, + assetId, + localFingerprint: metadataFingerprint(local), + remoteFingerprint: metadataFingerprint(remote), + remoteUpdatedAt: remote.updatedAt ?? null, + lastSyncedAt: Date.now(), + lastError: null, + }); +} + +/** Uses the album payload when it already carries tags, otherwise asks for the asset. */ +async function importAssetMetadata(ownerId, asset) { + if (Array.isArray(asset?.tags)) return { asset, meta: remoteMetadata(asset) }; + const detail = await apiRequest(ownerId, `/assets/${encodeURIComponent(String(asset.id))}`).catch( + () => null, + ); + return detail ? { asset: detail, meta: remoteMetadata(detail) } : { asset, meta: remoteMetadata(asset) }; +} + +function tagKey(tag) { + return String(tag?.value ?? tag?.name ?? '').trim().toLowerCase(); +} + +/** + * Immich has no batch tag-remove across tags, so removals walk the tags that are + * currently on the source asset. Adding uses the upsert endpoint then tags both + * the original and any pushed edits. + */ +async function syncAssetTags(ownerId, assetIds, wanted, currentTags) { + if (!assetIds.length) return; + const wantedList = normalizeKeywords(wanted); + const wantedKeys = new Set(wantedList.map((word) => word.toLowerCase())); + const current = Array.isArray(currentTags) ? currentTags : []; + const currentKeys = new Set(current.map(tagKey)); + + for (const tag of current) { + if (!tag?.id || wantedKeys.has(tagKey(tag))) continue; + await apiRequest(ownerId, `/tags/${encodeURIComponent(tag.id)}/assets`, { + method: 'DELETE', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ ids: assetIds }), + }); + } + + const missing = wantedList.filter((word) => !currentKeys.has(word.toLowerCase())); + if (!missing.length) return; + const upserted = await apiRequest(ownerId, '/tags', { + method: 'PUT', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ tags: missing }), + }); + const list = Array.isArray(upserted) ? upserted : Array.isArray(upserted?.tags) ? upserted.tags : []; + const byKey = new Map(list.map((tag) => [tagKey(tag), tag])); + for (const word of missing) { + const tag = byKey.get(word.toLowerCase()); + if (!tag?.id) continue; + await apiRequest(ownerId, `/tags/${encodeURIComponent(tag.id)}/assets`, { + method: 'PUT', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ ids: assetIds }), + }); + } +} + +async function writeMetadataToAssets(ownerId, assetIds, local, currentTags) { + const ids = [...new Set(assetIds.filter(Boolean))]; + if (!ids.length) return; + const version = await immichVersion(ownerId); + await apiRequest(ownerId, '/assets', { + method: 'PUT', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ + ids, + rating: immichRating(local, version.major), + isFavorite: local.flag === 'pick', + }), + }); + await syncAssetTags(ownerId, ids, local.keywords, currentTags); +} + +function remoteMetadataPatch(remote) { + return { + rating: remote.rating, + flag: remote.flag, + ...(remote.keywords ? { keywords: remote.keywords } : {}), + }; +} + +/** Push the local rating/flag/keywords for a photo to its source and pushed edits. */ +export async function pushImmichPhotoMetadata({ photoId, ownerId, local }) { + const settings = openedSettings(ownerId); + if (!settings?.enabled) throw new Error('Immich sync is not enabled for this account'); + if (!settings.syncMetadata) return { ok: true, action: 'disabled' }; + + const photo = getPhoto(photoId); + if (!photo) throw new Error('No such photo'); + const link = immichAssetForPhoto(photoId); + if (!link) { + throw new Error('This photo was not imported from Immich, so there is no original to update'); + } + + const desired = localMetadata({ ...photo, ...(local ?? {}) }); + const detail = await importAssetMetadata(ownerId, { id: link.assetId }); + await writeMetadataToAssets( + ownerId, + [link.assetId, ...immichPushAssetsForPhoto(photoId)], + desired, + detail.asset?.tags ?? [], + ); + // Keep the stored record aligned so a later reconcile does not treat the + // pre-save value as a fresh local edit and push it back. + patchPhotoMeta(photoId, desired); + rememberImmichMeta({ + photoId, + ownerId, + assetId: link.assetId, + local: desired, + remote: { ...desired, updatedAt: Date.now() }, + }); + return { ok: true, action: 'push' }; +} + +/** + * Reconciles one imported photo. A local edit wins when both sides changed; a + * remote-only change is written back to the stored photo without reordering it. + */ +export async function reconcileImmichMetadata({ photoId, ownerId, remoteAsset }) { + const settings = openedSettings(ownerId); + if (!settings?.enabled || !settings.syncMetadata) return { action: 'skipped' }; + + const photo = getPhoto(photoId); + const link = immichAssetForPhoto(photoId); + if (!photo || !link) return { action: 'skipped' }; + + let asset = remoteAsset; + if (!asset || !Array.isArray(asset.tags)) { + asset = await apiRequest(ownerId, `/assets/${encodeURIComponent(link.assetId)}`).catch( + () => asset, + ); + } + if (!asset) return { action: 'skipped' }; + + const remote = remoteMetadata(asset); + const local = localMetadata(photo); + const saved = immichMetaFor(photoId); + const localFp = metadataFingerprint(local); + const remoteFp = metadataFingerprint(remote); + const localChanged = saved + ? localFp !== saved.localFingerprint + : local.rating > 0 || local.flag !== 'none' || local.keywords.length > 0; + const remoteChanged = saved + ? remoteFp !== saved.remoteFingerprint + : remote.rating > 0 || remote.flag !== 'none' || (remote.keywords?.length ?? 0) > 0; + + if (localChanged) { + await writeMetadataToAssets( + ownerId, + [link.assetId, ...immichPushAssetsForPhoto(photoId)], + local, + asset.tags ?? [], + ); + rememberImmichMeta({ + photoId, + ownerId, + assetId: link.assetId, + local, + remote: { ...local, updatedAt: Date.now() }, + }); + return { action: 'push' }; + } + + if (remoteChanged) { + const next = patchPhotoMeta(photoId, remoteMetadataPatch(remote)); + rememberImmichMeta({ + photoId, + ownerId, + assetId: link.assetId, + local: localMetadata(next), + remote, + }); + return { action: 'pull', photo: next }; + } + + rememberImmichMeta({ photoId, ownerId, assetId: link.assetId, local, remote }); + return { action: 'none' }; +} + +export async function pushImmichPhoto({ photoId, ownerId, jpeg }) { + const settings = openedSettings(ownerId); + if (!settings?.enabled) { + throw new Error('Immich sync is not enabled for this account'); + } + credentials(ownerId); + + const photo = getPhoto(photoId); + if (!photo) throw new Error('No such photo'); + const link = immichAssetForPhoto(photoId); + const gallery = immichAlbumForEvent(photo.eventId); + if (!link && !gallery) { + throw new Error( + 'This photo was not imported from Immich and its event has no Immich gallery to send it to', + ); + } + + const checksum = crypto.createHash('sha1').update(jpeg).digest('base64'); + const previous = immichPushFor(photoId, checksum); + if (previous?.state === 'done' && previous.newAssetId) { + let warning = ''; + if (settings.syncMetadata && link) { + try { + await pushImmichPhotoMetadata({ photoId, ownerId, local: localMetadata(photo) }); + } catch (err) { + warning = `The edit is already in Immich, but metadata did not sync: ${ + err instanceof Error ? err.message : 'unknown error' + }`; + } + } + return { + ok: true, + assetId: previous.newAssetId, + alreadyPushed: true, + trashed: previous.trashedSource, + associations: {}, + warning, + }; + } + + const version = await immichVersion(ownerId); + const form = new FormData(); + form.append('assetData', new Blob([jpeg], { type: 'image/jpeg' }), outputName(photo)); + form.append('fileCreatedAt', fileStamp(photo)); + form.append('fileModifiedAt', new Date().toISOString()); + if (version.major > 0 && version.major < 3) { + // Immich v3 removed the device identity fields from the upload contract. + form.append('deviceAssetId', `luminary-${photoId}-${checksum.slice(0, 8)}`); + form.append('deviceId', 'luminary'); + } + + let newAssetId; + try { + const uploaded = await apiRequest(ownerId, '/assets', { + method: 'POST', + headers: { 'x-immich-checksum': checksum }, + body: form, + }); + // Immich answers a byte-identical upload with a trashed placeholder and + // points at the asset it kept. Recording the placeholder would leave the + // photo out of the album (and look pushed forever), so keep the survivor. + newAssetId = uploaded?.duplicateId || uploaded?.id; + if (!newAssetId) throw new Error('Immich did not return the uploaded asset'); + } catch (err) { + saveImmichPush({ + id: crypto.randomUUID(), + ownerId, + photoId, + sourceAssetId: link?.assetId ?? '', + newAssetId: null, + checksum, + editsHash: editsHash(photo), + state: 'error', + trashedSource: false, + error: err instanceof Error ? err.message : 'upload failed', + createdAt: Date.now(), + }); + throw err; + } + + const associations = { albums: false, stack: false, favorite: false, sidecar: false }; + const failures = []; + try { + if (link && version.major >= 3) { + await apiRequest(ownerId, '/assets/copy', { + method: 'PUT', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ + sourceId: link.assetId, + targetId: newAssetId, + albums: true, + stack: true, + sidecar: true, + favorite: true, + sharedLinks: true, + }), + }); + associations.albums = true; + associations.stack = true; + associations.favorite = true; + associations.sidecar = true; + } else if (link && version.major > 0) { + await apiRequest(ownerId, `/assets/${encodeURIComponent(newAssetId)}/copy`, { + method: 'PUT', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ + sourceId: link.assetId, + albums: true, + stack: true, + sidecar: true, + }), + }); + associations.albums = true; + associations.stack = true; + associations.sidecar = true; + } + } catch { + if (link) failures.push('album, stack and favourite associations'); + } + + // The destination album must not be lost; adding it is idempotent, so do it + // even when the copy endpoint claimed success. An event gallery is added as + // well, which lets plain Luminary uploads publish into that gallery. + const albumIds = [...new Set([link?.albumId, gallery?.albumId].filter(Boolean))]; + for (const albumId of albumIds) { + try { + await apiRequest(ownerId, `/albums/${encodeURIComponent(albumId)}/assets`, { + method: 'PUT', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ ids: [newAssetId] }), + }); + associations.albums = true; + } catch (err) { + failures.push( + `the album could not be updated (${err instanceof Error ? err.message : 'unknown error'})`, + ); + } + } + + let metaWarning = ''; + if (settings.syncMetadata) { + try { + const local = localMetadata(photo); + if (link) { + const detail = await importAssetMetadata(ownerId, { id: link.assetId }); + await writeMetadataToAssets( + ownerId, + [link.assetId, newAssetId], + local, + detail.asset?.tags ?? [], + ); + rememberImmichMeta({ + photoId, + ownerId, + assetId: link.assetId, + local, + remote: { ...local, updatedAt: Date.now() }, + }); + } else { + await writeMetadataToAssets(ownerId, [newAssetId], local, []); + } + } catch (err) { + metaWarning = `The edit is in Immich, but ratings, flags or tags did not sync: ${ + err instanceof Error ? err.message : 'unknown error' + }`; + } + } + + let trashed = false; + let warning = ''; + if (settings.trashOriginal && link) { + try { + await apiRequest(ownerId, '/assets', { + method: 'DELETE', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ ids: [link.assetId], force: false }), + }); + trashed = true; + } catch (err) { + warning = `The edit is in Immich, but the original could not be moved to trash: ${ + err instanceof Error ? err.message : 'unknown error' + }`; + } + } + + saveImmichPush({ + id: crypto.randomUUID(), + ownerId, + photoId, + sourceAssetId: link?.assetId ?? '', + newAssetId, + checksum, + editsHash: editsHash(photo), + state: 'done', + trashedSource: trashed, + error: null, + createdAt: Date.now(), + }); + + return { + ok: true, + assetId: newAssetId, + alreadyPushed: false, + trashed, + associations, + warning: + warning || + metaWarning || + (failures.length ? `Some metadata was not copied: ${failures.join('; ')}` : ''), + }; +} + +/** + * Adds a photo's original to its event's Immich gallery. Local imports use + * this so the whole set lands in the gallery without a manual send; the + * existing checksum record keeps a retry from uploading it twice. + */ +export async function publishImmichOriginal({ photoId, ownerId }) { + const settings = openedSettings(ownerId); + if (!settings?.enabled) { + throw new Error('Immich sync is not enabled for this account'); + } + const photo = getPhoto(photoId); + if (!photo) throw new Error('No such photo'); + if (!immichAlbumForEvent(photo.eventId)) { + throw new Error('This event has no Immich gallery'); + } + + const existing = immichAssetForPhoto(photoId); + if (existing) { + // The photo already exists in Immich; uploading the original again would + // create a duplicate rather than adding anything to the gallery. + return { + ok: true, + assetId: existing.assetId, + alreadyPushed: true, + skipped: true, + trashed: false, + associations: {}, + warning: '', + }; + } + + const alreadyUploaded = immichPushDoneForPhoto(photoId); + if (alreadyUploaded) { + // An edit or an earlier original is already in Immich; uploading the + // original again would create a duplicate instead of adding anything. + return { + ok: true, + assetId: alreadyUploaded.new_asset_id, + alreadyPushed: true, + skipped: true, + trashed: false, + associations: {}, + warning: '', + }; + } + + const original = findOriginal(photoId); + // Raws whose bytes were lost still have a server preview; sending that keeps + // the photo in the gallery instead of failing the whole push. + const preview = original ? null : findPreview(photoId); + if (!original && !preview) { + throw new Error('The original is not on the server, so it cannot be added to Immich'); + } + const source = original ?? preview; + const bytes = await fsp.readFile(source); + const ext = source.split('.').pop()?.toLowerCase() ?? ''; + let jpeg = bytes; + if (!['jpg', 'jpeg'].includes(ext) || bytes[0] !== 0xff || bytes[1] !== 0xd8) { + if (isRawName(source) || isRawName(photo.name)) { + const decoded = await decodeRaw(bytes); + jpeg = decoded?.jpeg; + } else { + const proxy = await toJpegProxy(bytes, 0); + jpeg = proxy?.data; + } + } + if (!jpeg || jpeg.length < 4 || jpeg[0] !== 0xff || jpeg[1] !== 0xd8) { + throw new Error('The original could not be prepared as a JPEG for Immich'); + } + const result = await pushImmichPhoto({ photoId, ownerId, jpeg }); + if (original) return result; + const note = 'the raw original is missing on the server, so its preview was sent'; + return { ...result, warning: result.warning ? `${result.warning} · ${note}` : note }; +} + +/* ---------------------------------------------------------------- scheduler */ + +export function startImmichWorker() { + const tick = () => { + void syncDueAccounts().catch((err) => + console.error(`[luminary] Immich sync worker: ${err.message}`), + ); + }; + const timer = setInterval(tick, SYNC_TICK_MS); + timer.unref?.(); + // Give the server a moment to settle before the first pass. + setTimeout(tick, 15_000).unref?.(); +} + +export async function syncDueAccounts() { + const now = Date.now(); + for (const row of allImmichSettings()) { + if (!row.enabled || !row.autoSync || !row.serverUrl || !row.apiKey) continue; + if (runningJobFor(row.ownerId)) continue; + + const settings = openedSettings(row.ownerId); + if (!settings?.apiKey) continue; + + const interval = Math.max(15, Number(settings.syncMinutes) || 60) * 60_000; + if (settings.lastSyncAt && now - settings.lastSyncAt < interval) continue; + + const links = immichAlbumLinks(row.ownerId); + if (!links.length) continue; + + if (quotaState(row.ownerId).remaining <= 0) { + setImmichSyncState(row.ownerId, now, 'Storage quota is full; automatic sync was skipped.'); + continue; + } + + let lastError = null; + for (const link of links) { + if (link.kind === 'gallery') continue; + if (link.lastSyncAt && now - link.lastSyncAt < interval) continue; + if (runningJobFor(row.ownerId)) { + lastError = 'Automatic sync stopped because another import started.'; + break; + } + let job; + try { + job = makeJob(row.ownerId, link.albumId, true); + } catch (err) { + lastError = err instanceof Error ? err.message : 'Could not start automatic sync'; + break; + } + await job.completion; + if (job.state === 'error') lastError = job.message; + } + setImmichSyncState(row.ownerId, Date.now(), lastError); + } +} diff --git a/server/index.mjs b/server/index.mjs index 591db4c..7cebaf3 100644 --- a/server/index.mjs +++ b/server/index.mjs @@ -11,6 +11,7 @@ import { MAX_UPLOAD, PORT, RAW_PREVIEW_EDGE, + TRUST_PROXY, } from './config.mjs'; import { authenticate, @@ -18,6 +19,7 @@ import { hashPassword, normalizeEmail, publicUser, + spendPasswordCheck, validEmail, verifyPassword, } from './auth.mjs'; @@ -58,11 +60,11 @@ import { findProofThumb, findThumb, isCustomRoot, + originalTarget, removeAsset, setStorageRoot, storageBytes, storageRoot, - writeOriginal, writePreview, writeProof, writeProofThumb, @@ -91,10 +93,47 @@ import { warnUser, } from './quota.mjs'; import { mailStatus, saveMailSettings, sendTestMail } from './mail.mjs'; +import { + createImmichAlbumForEvent, + disconnectImmich, + disconnectImmichAdmin, + immichAdminPing, + immichAdminStatus, + immichConfigured, + immichEventQueue, + immichJobFor, + immichLinksForOwner, + immichPendingPhotos, + immichPing, + immichStatusFor, + listImmichAlbums, + publishImmichOriginal, + pushImmichPhoto, + pushImmichPhotoMetadata, + saveImmichAdminSettings, + saveImmichUserSettings, + startImmichImport, +} from './immich.mjs'; const VERSION = '1.0.0'; const COOKIE = 'lumen_session'; +/** Self-only policy; must allow the wasm engines and React inline styles. */ +const CSP = [ + "default-src 'self'", + "script-src 'self' 'wasm-unsafe-eval' 'unsafe-eval'", + "style-src 'self' 'unsafe-inline'", + "img-src 'self' data: blob:", + "font-src 'self' data:", + "connect-src 'self'", + "media-src 'self' blob:", + "worker-src 'self' blob:", + "object-src 'none'", + "base-uri 'self'", + "form-action 'self'", + "frame-ancestors 'self'", +].join('; '); + /* ------------------------------------------------------------------ helpers */ function json(res, status, payload, extraHeaders = {}) { @@ -108,8 +147,95 @@ function json(res, status, payload, extraHeaders = {}) { res.end(body); } -function error(res, status, message) { - json(res, status, { error: message }); +class PayloadTooLarge extends Error {} + +function error(res, status, message, extraHeaders = {}) { + json(res, status, { error: message }, extraHeaders); +} + +/** Failed sign-ins are bucketed per socket address and per account. */ +const AUTH_WINDOW_MS = 15 * 60 * 1000; +const authBuckets = new Map(); + +function clientIp(req) { + // X-Forwarded-For is spoofable unless a proxy overwrites it, so it is only + // consulted when the operator opts in with LUMINARY_TRUST_PROXY=1. + if (TRUST_PROXY) { + const forwarded = String(req.headers['x-forwarded-for'] ?? '').split(',')[0].trim(); + if (forwarded) return forwarded; + } + return String(req.socket?.remoteAddress ?? 'unknown'); +} + +/** + * Per-address cap. Behind a proxy without TRUST_PROXY every client shares the + * proxy address, so the cap is higher to avoid turning noise into a lock-out; + * the per-account limit is the real brute-force bound. + */ +const LOGIN_IP_LIMIT = TRUST_PROXY ? 50 : 500; + +function authFailures(key) { + const bucket = authBuckets.get(key); + if (!bucket || Date.now() - bucket.start >= AUTH_WINDOW_MS) return 0; + return bucket.count; +} + +function recordAuthFailure(key) { + const now = Date.now(); + const bucket = authBuckets.get(key); + if (!bucket || now - bucket.start >= AUTH_WINDOW_MS) { + authBuckets.set(key, { start: now, count: 1 }); + } else { + bucket.count += 1; + } + if (authBuckets.size > 10_000) { + for (const [name, value] of authBuckets) { + if (now - value.start >= AUTH_WINDOW_MS) authBuckets.delete(name); + } + } +} + +function clearAuthFailures(key) { + authBuckets.delete(key); +} + +/** Coarse fixed-window limiter for public gallery writes. */ +const galleryBuckets = new Map(); +function allowGalleryWrite(req, token) { + const key = `${clientIp(req)}:${token}`; + const now = Date.now(); + const bucket = galleryBuckets.get(key); + if (!bucket || now - bucket.start >= 60_000) { + galleryBuckets.set(key, { start: now, count: 1 }); + if (galleryBuckets.size > 5_000) { + for (const [name, value] of galleryBuckets) { + if (now - value.start >= 60_000) galleryBuckets.delete(name); + } + } + return true; + } + bucket.count += 1; + return bucket.count <= 120; +} + +const PHOTO_MIME_BY_EXT = { + jpg: 'image/jpeg', + jpeg: 'image/jpeg', + png: 'image/png', + webp: 'image/webp', + gif: 'image/gif', + avif: 'image/avif', + tif: 'image/tiff', + tiff: 'image/tiff', +}; +const PHOTO_MIMES = new Set(Object.values(PHOTO_MIME_BY_EXT)); + +/** Only raster types the browser cannot turn into script are served inline. */ +function normalizePhotoMime(value, name = '') { + const mime = String(value ?? '').split(';')[0].trim().toLowerCase(); + if (PHOTO_MIMES.has(mime)) return mime; + const ext = String(name).split('.').pop()?.toLowerCase() ?? ''; + return PHOTO_MIME_BY_EXT[ext] ?? 'application/octet-stream'; } function parseCookies(req) { @@ -117,7 +243,11 @@ function parseCookies(req) { for (const part of String(req.headers.cookie ?? '').split(';')) { const idx = part.indexOf('='); if (idx < 0) continue; - out[part.slice(0, idx).trim()] = decodeURIComponent(part.slice(idx + 1).trim()); + try { + out[part.slice(0, idx).trim()] = decodeURIComponent(part.slice(idx + 1).trim()); + } catch { + /* ignore malformed percent-encoding in a cookie */ + } } return out; } @@ -152,9 +282,14 @@ function requireAdmin(req, res) { return user; } -/** An ownerless row predates workspaces; anyone signed in may finish it. */ +/** + * A null owner means the row does not exist yet (new records are allowed). + * An empty owner is a legacy row from before workspaces; only an admin may + * touch it. Everyone else may only reach their own rows. + */ function ownedBy(owner, user) { - return !owner || owner === user.id; + if (owner === null || owner === undefined) return true; + return owner === user.id || (owner === '' && user.role === 'admin'); } function adminUser(row) { @@ -204,11 +339,16 @@ function readBody(req, limit = MAX_UPLOAD) { return new Promise((resolve, reject) => { const chunks = []; let size = 0; + let tooLarge = false; req.on('data', (chunk) => { + if (tooLarge) return; size += chunk.length; if (size > limit) { - reject(new Error(`Upload exceeds the ${Math.round(limit / (1024 * 1024))} MB limit`)); - req.destroy(); + tooLarge = true; + chunks.length = 0; + // Keep draining instead of destroying the socket so the 413 can flush. + req.resume(); + reject(new PayloadTooLarge(`Request exceeds the ${Math.round(limit / (1024 * 1024))} MB limit`)); return; } chunks.push(chunk); @@ -228,6 +368,51 @@ async function readJson(req, limit = 8 * 1024 * 1024) { } } +/** + * Streams an upload straight to disk. Buffering the body would let one request + * hold hundreds of megabytes of RAM. + */ +async function receiveUpload(req, target, limit) { + const temp = `${target}.part-${crypto.randomBytes(6).toString('hex')}`; + let size = 0; + try { + await new Promise((resolve, reject) => { + const out = fs.createWriteStream(temp, { flags: 'wx' }); + let settled = false; + const fail = (err) => { + if (settled) return; + settled = true; + req.unpipe(out); + out.destroy(); + req.resume(); + fs.rm(temp, { force: true }, () => reject(err)); + }; + req.on('data', (chunk) => { + if (settled) return; + size += chunk.length; + if (size > limit) fail(new PayloadTooLarge('Upload exceeds the size limit')); + }); + req.on('error', fail); + out.on('error', fail); + out.on('finish', () => { + if (settled) return; + settled = true; + resolve(); + }); + req.pipe(out); + }); + if (!size) { + await fsp.rm(temp, { force: true }); + return 0; + } + await fsp.rename(temp, target); + return size; + } catch (err) { + await fsp.rm(temp, { force: true }).catch(() => undefined); + throw err; + } +} + function match(pathname, pattern) { const p = pattern.split('/'); const a = pathname.split('/'); @@ -248,7 +433,7 @@ function sendBuffer(res, data, type, cache = 'private, max-age=3600') { 'Content-Type': type, 'Content-Length': data.length, 'Cache-Control': cache, - ...(type.startsWith('image/') ? { 'X-Content-Type-Options': 'nosniff' } : {}), + 'X-Content-Type-Options': 'nosniff', }); res.end(data); } @@ -271,7 +456,7 @@ async function sendFile(req, res, filePath, type, cache = 'private, max-age=8640 'Content-Type': type, 'Content-Length': stat.size, 'Cache-Control': cache, - ...(type.startsWith('image/') ? { 'X-Content-Type-Options': 'nosniff' } : {}), + 'X-Content-Type-Options': 'nosniff', ...extraHeaders, }); if (req.method === 'HEAD') return res.end(); @@ -288,6 +473,35 @@ function decodeDataUrl(value) { return { mime: `image/${m[1]}`, data: Buffer.from(m[2], 'base64') }; } +/** Health totals walk the filesystem, so cache them instead of scanning per hit. */ +let healthCache = { at: 0, photos: 0, bytes: 0, root: '', custom: false }; +function healthStats() { + if (Date.now() - healthCache.at < 30_000) return healthCache; + healthCache = { + at: Date.now(), + photos: countPhotos(), + bytes: storageBytes(), + root: storageRoot(), + custom: isCustomRoot(), + }; + return healthCache; +} + +const MAX_ARCHIVE_FILES = 400; +const MAX_ARCHIVE_BYTES = 512 * 1024 * 1024; +let archiveBuilding = false; + +/** Uploads accepted for an id that does not have a photo row yet. */ +const recentUploads = new Map(); + +function pendingBytes(ownerId) { + let total = 0; + for (const upload of recentUploads.values()) { + if (upload.pending && upload.ownerId === ownerId) total += upload.bytes; + } + return total; +} + /* --------------------------------------------------------------------- api */ import { clearDenoised, findDenoisedFor, getDenoiseJob, startDenoise } from './denoise.mjs'; @@ -297,17 +511,20 @@ function route(method, pattern, handler) { routes.push({ method, pattern, handler }); } -route('GET', '/api/health', async ({ res }) => { +route('GET', '/api/health', async ({ req, res }) => { const raw = await rawSupport(); + const user = currentUser(req); + const stats = healthStats(); json(res, 200, { ok: true, app: 'luminary', version: VERSION, needsSetup: users.count() === 0, registrationOpen: users.count() === 0 || Boolean(INVITE) || invites.pendingCount() > 0, - photos: countPhotos(), - bytes: storageBytes(), - storage: { root: storageRoot(), custom: isCustomRoot() }, + photos: stats.photos, + bytes: stats.bytes, + // The absolute data path is only for signed-in team members. + ...(user ? { storage: { root: stats.root, custom: stats.custom } } : {}), raw, }); }); @@ -351,7 +568,7 @@ route('POST', '/api/auth/register', async ({ req, res }) => { id, email, name: name || email.split('@')[0], - passHash: hashPassword(password), + passHash: await hashPassword(password), role: first ? 'admin' : inviteRow?.role === 'admin' ? 'admin' : 'member', }); if (inviteRow && !invites.accept(token, id)) { @@ -368,11 +585,38 @@ route('POST', '/api/auth/register', async ({ req, res }) => { }); route('POST', '/api/auth/login', async ({ req, res }) => { + const ipKey = `login:ip:${clientIp(req)}`; + if (authFailures(ipKey) >= LOGIN_IP_LIMIT) { + return error(res, 429, 'Too many sign-in attempts. Try again later.', { 'Retry-After': '900' }); + } + const body = await readJson(req, 64 * 1024); const email = normalizeEmail(body.email); const password = typeof body.password === 'string' ? body.password : ''; + const accountKey = `login:acct:${clientIp(req)}:${email}`; + if (authFailures(accountKey) >= 8) { + return error(res, 429, 'Too many sign-in attempts for this account. Try again later.', { + 'Retry-After': '900', + }); + } + const row = users.byEmail(email); - if (!row || !verifyPassword(password, row.pass_hash)) return error(res, 401, 'Email or password is not correct'); + if (!row) { + // Spend the same scrypt work as a real account so response timing does not + // reveal which addresses are registered. + await spendPasswordCheck(password); + recordAuthFailure(ipKey); + recordAuthFailure(accountKey); + return error(res, 401, 'Email or password is not correct'); + } + + const valid = await verifyPassword(password, row.pass_hash); + if (!valid) { + recordAuthFailure(ipKey); + recordAuthFailure(accountKey); + return error(res, 401, 'Email or password is not correct'); + } + clearAuthFailures(accountKey); if (row.disabled) return error(res, 403, 'This account has been disabled by an administrator'); const token = createSession(row.id); json( @@ -445,6 +689,7 @@ route('GET', '/api/admin/overview', async ({ req, res }) => { }, quotas: quotasForAdmin(), mail: mailStatus(), + immich: immichAdminStatus(), }); }); @@ -464,7 +709,7 @@ route('POST', '/api/admin/users', async ({ req, res }) => { id, email, name: name || email.split('@')[0], - passHash: hashPassword(password), + passHash: await hashPassword(password), role, }); json(res, 201, { user: adminUser(users.byId(id)) }); @@ -482,7 +727,7 @@ route('PATCH', '/api/admin/users/:id', async ({ req, res, params }) => { if (typeof body.password === 'string' && body.password) { if (body.password.length < 8) return error(res, 400, 'Use at least 8 characters for the password'); - patch.passHash = hashPassword(body.password); + patch.passHash = await hashPassword(body.password); } if (typeof body.role === 'string') { @@ -718,6 +963,208 @@ route('POST', '/api/admin/mail/test', async ({ req, res }) => { } }); +route('GET', '/api/admin/immich', async ({ req, res }) => { + if (!requireAdmin(req, res)) return; + json(res, 200, { immich: immichAdminStatus() }); +}); + +route('PUT', '/api/admin/immich', async ({ req, res }) => { + if (!requireAdmin(req, res)) return; + const body = await readJson(req, 16 * 1024); + try { + json(res, 200, { immich: saveImmichAdminSettings(body) }); + } catch (err) { + return error(res, 400, err instanceof Error ? err.message : 'Could not save the Immich connection'); + } +}); + +route('POST', '/api/admin/immich/test', async ({ req, res }) => { + if (!requireAdmin(req, res)) return; + try { + json(res, 200, await immichAdminPing()); + } catch (err) { + return error(res, 502, err instanceof Error ? err.message : 'Could not reach Immich'); + } +}); + +route('DELETE', '/api/admin/immich', async ({ req, res }) => { + if (!requireAdmin(req, res)) return; + json(res, 200, { immich: disconnectImmichAdmin() }); +}); + +/* ------------------------------------------------------------------ immich */ + +route('GET', '/api/immich', async ({ req, res }) => { + const user = currentUser(req); + if (!user) return error(res, 401, 'Not signed in'); + json(res, 200, { immich: immichStatusFor(user.id) }); +}); + +route('PUT', '/api/immich', async ({ req, res }) => { + const user = currentUser(req); + if (!user) return error(res, 401, 'Not signed in'); + const body = await readJson(req, 16 * 1024); + try { + json(res, 200, { immich: saveImmichUserSettings(user.id, body) }); + } catch (err) { + return error(res, 400, err instanceof Error ? err.message : 'Could not save the Immich connection'); + } +}); + +route('DELETE', '/api/immich', async ({ req, res }) => { + const user = currentUser(req); + if (!user) return error(res, 401, 'Not signed in'); + json(res, 200, { immich: disconnectImmich(user.id) }); +}); + +route('POST', '/api/immich/test', async ({ req, res }) => { + const user = currentUser(req); + if (!user) return error(res, 401, 'Not signed in'); + try { + json(res, 200, await immichPing(user.id)); + } catch (err) { + return error(res, 502, err instanceof Error ? err.message : 'Could not reach Immich'); + } +}); + +/** Albums are listed for any signed-in user; the API key still stays server-side. */ +route('GET', '/api/immich/albums', async ({ req, res }) => { + const user = currentUser(req); + if (!user) return error(res, 401, 'Not signed in'); + if (!immichConfigured(user.id)) return error(res, 503, 'Immich is not configured yet'); + try { + const links = new Map(immichLinksForOwner(user.id).map((link) => [link.albumId, link])); + const albums = await listImmichAlbums(user.id); + json(res, 200, { + albums: albums.map((album) => ({ + ...album, + eventId: links.get(album.id)?.eventId ?? null, + lastSyncAt: links.get(album.id)?.lastSyncAt ?? null, + kind: links.get(album.id)?.kind ?? 'import', + })), + }); + } catch (err) { + return error(res, 502, err instanceof Error ? err.message : 'Could not reach Immich'); + } +}); + +route('POST', '/api/immich/albums', async ({ req, res }) => { + const user = currentUser(req); + if (!user) return error(res, 401, 'Not signed in'); + const body = await readJson(req, 16 * 1024); + if (typeof body.eventId !== 'string' || !body.eventId) { + return error(res, 400, 'Choose the event for the gallery'); + } + if (!ownedBy(eventOwner(body.eventId), user)) return error(res, 404, 'No such event'); + try { + json(res, 201, await createImmichAlbumForEvent({ + ownerId: user.id, + eventId: body.eventId, + name: body.name, + })); + } catch (err) { + return error(res, 502, err instanceof Error ? err.message : 'Could not create the Immich gallery'); + } +}); + +route('POST', '/api/immich/albums/:id/import', async ({ req, res, params }) => { + const user = currentUser(req); + if (!user) return error(res, 401, 'Not signed in'); + try { + json(res, 202, { job: startImmichImport({ albumId: params.id, ownerId: user.id }) }); + } catch (err) { + return error(res, 400, err instanceof Error ? err.message : 'Could not start the import'); + } +}); + +route('GET', '/api/immich/jobs/:id', async ({ req, res, params }) => { + const user = currentUser(req); + if (!user) return error(res, 401, 'Not signed in'); + const job = immichJobFor(params.id, user); + if (!job) return error(res, 404, 'Import job not found'); + json(res, 200, { job }); +}); + +route('POST', '/api/immich/photos/:id/metadata', async ({ req, res, params }) => { + const user = currentUser(req); + if (!user) return error(res, 401, 'Not signed in'); + if (!ownedBy(photoOwner(params.id), user)) return error(res, 404, 'No such photo'); + + const body = await readJson(req, 64 * 1024); + const rating = Math.max(0, Math.min(5, Math.trunc(Number(body.rating) || 0))); + const flag = body.flag === 'pick' || body.flag === 'reject' ? body.flag : 'none'; + const keywords = Array.isArray(body.keywords) + ? body.keywords.filter((word) => typeof word === 'string').slice(0, 100) + : []; + try { + json(res, 200, await pushImmichPhotoMetadata({ + photoId: params.id, + ownerId: user.id, + local: { rating, flag, keywords }, + })); + } catch (err) { + return error(res, 502, err instanceof Error ? err.message : 'Could not sync Immich metadata'); + } +}); + +/** Photo ids still missing from an event's gallery, for a backfill run. */ +route('GET', '/api/immich/events/:id/pending', async ({ req, res, params }) => { + const user = currentUser(req); + if (!user) return error(res, 401, 'Not signed in'); + if (!ownedBy(eventOwner(params.id), user)) return error(res, 404, 'No such event'); + try { + json(res, 200, immichPendingPhotos({ eventId: params.id, ownerId: user.id })); + } catch (err) { + return error(res, 400, err instanceof Error ? err.message : 'Could not read the Immich queue'); + } +}); + +/** + * The manual push plan for an event: originals Immich has never seen plus the + * edits that changed since the last push. Nothing uploads from this route. + */ +route('GET', '/api/immich/events/:id/queue', async ({ req, res, params }) => { + const user = currentUser(req); + if (!user) return error(res, 401, 'Not signed in'); + if (!ownedBy(eventOwner(params.id), user)) return error(res, 404, 'No such event'); + try { + json(res, 200, immichEventQueue({ eventId: params.id, ownerId: user.id })); + } catch (err) { + return error(res, 400, err instanceof Error ? err.message : 'Could not plan the Immich push'); + } +}); + +route('POST', '/api/immich/photos/:id/publish', async ({ req, res, params }) => { + const user = currentUser(req); + if (!user) return error(res, 401, 'Not signed in'); + if (!ownedBy(photoOwner(params.id), user)) return error(res, 404, 'No such photo'); + try { + json(res, 200, await publishImmichOriginal({ photoId: params.id, ownerId: user.id })); + } catch (err) { + return error(res, 502, err instanceof Error ? err.message : 'Could not publish the photo'); + } +}); + +route('POST', '/api/immich/photos/:id/push', async ({ req, res, params }) => { + const user = currentUser(req); + if (!user) return error(res, 401, 'Not signed in'); + if (!ownedBy(photoOwner(params.id), user)) return error(res, 404, 'No such photo'); + + const body = await readJson(req, 96 * 1024 * 1024); + if (typeof body.jpeg !== 'string' || !body.jpeg) { + return error(res, 400, 'A rendered JPEG is required'); + } + const jpeg = Buffer.from(body.jpeg, 'base64'); + if (jpeg.length < 4 || jpeg[0] !== 0xff || jpeg[1] !== 0xd8) { + return error(res, 400, 'The edited file is not a JPEG image'); + } + try { + json(res, 200, await pushImmichPhoto({ photoId: params.id, ownerId: user.id, jpeg })); + } catch (err) { + return error(res, 502, err instanceof Error ? err.message : 'Could not send the edit to Immich'); + } +}); + route('GET', '/api/bridge/login', async ({ req, res, url }) => { if (!bridgeConfigured()) { return error(res, 503, 'The advanced editor bridge is not configured'); @@ -742,7 +1189,7 @@ route('GET', '/api/bridge/login', async ({ req, res, url }) => { id, email, name: payload.name || email.split('@')[0], - passHash: hashPassword(crypto.randomBytes(24).toString('hex')), + passHash: await hashPassword(crypto.randomBytes(24).toString('hex')), role: 'member', }); row = users.byId(id); @@ -962,7 +1409,16 @@ route('GET', '/api/galleries/:token/photos/:id/preview', async ({ req, res, para if (!hit) return error(res, 404, 'Not found'); const proof = findProof(params.id); const file = proof ?? findPreview(params.id) ?? findOriginal(params.id); - return sendFile(req, res, file, proof ? 'image/jpeg' : hit.photo.mime || 'image/jpeg', 'private, max-age=3600'); + if (!file) return error(res, 404, 'Not found'); + const mime = proof ? 'image/jpeg' : normalizePhotoMime(hit.photo.mime, hit.photo.name); + return sendFile( + req, + res, + file, + mime, + 'private, max-age=3600', + mime === 'application/octet-stream' ? { 'Content-Disposition': 'attachment' } : {}, + ); }); /** Client download of the edited proof, named like the delivered file. */ @@ -973,7 +1429,8 @@ route('GET', '/api/galleries/:token/photos/:id/download', async ({ req, res, par const file = proof ?? findPreview(params.id) ?? findOriginal(params.id); const originalName = String(hit.photo.name || 'photo.jpg'); const safe = (proof ? originalName.replace(/\.[^.]+$/, '.jpg') : originalName).replace(/["\\/:*?<>|]+/g, '-'); - return sendFile(req, res, file, proof ? 'image/jpeg' : hit.photo.mime || 'image/jpeg', 'private, max-age=3600', { + const mime = proof ? 'image/jpeg' : normalizePhotoMime(hit.photo.mime, hit.photo.name); + return sendFile(req, res, file, mime, 'private, max-age=3600', { 'Content-Disposition': `attachment; filename="${safe}"`, }); }); @@ -987,44 +1444,68 @@ route('GET', '/api/galleries/:token/download-all', async ({ req, res, params, ur (pick) => pick.picked && (!clientId || pick.clientId === clientId), ); if (!picks.length) return error(res, 404, 'There are no favourites to download yet'); - - const entries = []; - const seen = new Set(); - for (const pick of picks) { - if (seen.has(pick.photoId)) continue; - seen.add(pick.photoId); - const photo = getPhoto(pick.photoId); - if (!photo || photo.eventId !== shared.id || photo.deletedAt) continue; - const proof = findProof(photo.id); - const file = proof ?? findPreview(photo.id) ?? findOriginal(photo.id); - if (!file) continue; - try { - const data = await fsp.readFile(file); - const originalName = String(photo.name || 'photo.jpg'); - const name = proof - ? originalName.replace(/\.[^.]+$/, '.jpg') - : originalName; - entries.push({ name, data }); - } catch { - /* skip an unreadable file rather than losing the whole archive */ - } + if (archiveBuilding) { + return error(res, 429, 'Another gallery download is being prepared. Try again shortly.', { + 'Retry-After': '30', + }); } - if (!entries.length) return error(res, 404, 'There are no downloadable favourites yet'); - const archive = createZip(entries); - const eventName = String(shared.event.name || 'proofing') - .replace(/[^a-z0-9._ -]+/gi, '-') - .trim() || 'proofing'; - res.writeHead(200, { - 'Content-Type': 'application/zip', - 'Content-Length': archive.length, - 'Cache-Control': 'no-store', - 'Content-Disposition': `attachment; filename="${eventName}-favourites.zip"`, - }); - res.end(archive); + archiveBuilding = true; + try { + const entries = []; + const seen = new Set(); + let totalBytes = 0; + for (const pick of picks) { + if (seen.has(pick.photoId)) continue; + seen.add(pick.photoId); + const photo = getPhoto(pick.photoId); + if (!photo || photo.eventId !== shared.id || photo.deletedAt) continue; + const proof = findProof(photo.id); + const file = proof ?? findPreview(photo.id) ?? findOriginal(photo.id); + if (!file) continue; + if (entries.length >= MAX_ARCHIVE_FILES) { + return error(res, 413, 'Too many favourites for one archive. Download in smaller batches.'); + } + try { + const stat = await fsp.stat(file); + if (totalBytes + stat.size > MAX_ARCHIVE_BYTES) { + return error( + res, + 413, + 'This selection is too large for one archive. Download in smaller batches.', + ); + } + const data = await fsp.readFile(file); + totalBytes += data.length; + const originalName = String(photo.name || 'photo.jpg'); + const name = proof ? originalName.replace(/\.[^.]+$/, '.jpg') : originalName; + entries.push({ name, data }); + } catch { + /* skip an unreadable file rather than losing the whole archive */ + } + } + if (!entries.length) return error(res, 404, 'There are no downloadable favourites yet'); + + const archive = createZip(entries); + const eventName = String(shared.event.name || 'proofing') + .replace(/[^a-z0-9._ -]+/gi, '-') + .trim() || 'proofing'; + res.writeHead(200, { + 'Content-Type': 'application/zip', + 'Content-Length': archive.length, + 'Cache-Control': 'no-store', + 'Content-Disposition': `attachment; filename="${eventName}-favourites.zip"`, + }); + res.end(archive); + } finally { + archiveBuilding = false; + } }); route('POST', '/api/galleries/:token/comments', async ({ req, res, params }) => { + if (!allowGalleryWrite(req, params.token)) { + return error(res, 429, 'Too many gallery requests. Try again shortly.', { 'Retry-After': '60' }); + } if (!eventByShareToken(params.token)) { return error(res, 404, 'This proofing gallery is no longer available'); } @@ -1048,6 +1529,9 @@ route('POST', '/api/galleries/:token/comments', async ({ req, res, params }) => }); route('POST', '/api/galleries/:token/reviews', async ({ req, res, params }) => { + if (!allowGalleryWrite(req, params.token)) { + return error(res, 429, 'Too many gallery requests. Try again shortly.', { 'Retry-After': '60' }); + } if (!eventByShareToken(params.token)) { return error(res, 404, 'This proofing gallery is no longer available'); } @@ -1068,6 +1552,9 @@ route('POST', '/api/galleries/:token/reviews', async ({ req, res, params }) => { }); route('POST', '/api/galleries/:token/picks', async ({ req, res, params }) => { + if (!allowGalleryWrite(req, params.token)) { + return error(res, 429, 'Too many gallery requests. Try again shortly.', { 'Retry-After': '60' }); + } if (!eventByShareToken(params.token)) { return error(res, 404, 'This proofing gallery is no longer available'); } @@ -1118,19 +1605,82 @@ route('PUT', '/api/presets', async ({ req, res }) => { route('POST', '/api/photos/:id/original', async ({ req, res, params }) => { const user = currentUser(req); if (!user) return error(res, 401, 'Not signed in'); - if (!ownedBy(photoOwner(params.id), user)) return error(res, 404, 'No such photo'); + const owner = photoOwner(params.id); + if (owner !== null && !ownedBy(owner, user)) return error(res, 404, 'No such photo'); + const url = new URL(req.url ?? '/', 'http://localhost'); const name = url.searchParams.get('name') || 'upload'; - const mime = url.searchParams.get('mime') || 'application/octet-stream'; const drop = url.searchParams.get('drop') === '1'; - const data = await readBody(req); - if (!data.length) return error(res, 400, 'Empty upload'); - + const mime = normalizePhotoMime(url.searchParams.get('mime') || '', name); const ext = (name.split('.').pop() || 'bin').toLowerCase(); - await writeOriginal(params.id, ext, data); + const raw = isRawName(name) || drop; - if (isRawName(name) || drop) { + // New ids are part of the normal import flow: the client uploads bytes first + // and PUTs the record afterwards. Until that row exists the bytes are charged + // to this user's quota, so nobody can fill the disk with unclaimed files. + const limit = owner + ? MAX_UPLOAD + : Math.min(MAX_UPLOAD, Math.max(0, quotaState(user.id).remaining - pendingBytes(user.id))); + if (limit < 1) { + return error(res, 413, 'This account has no storage quota left for a new upload'); + } + const announced = Number(req.headers['content-length']); + if (Number.isFinite(announced) && announced > limit) { + return error( + res, + 413, + owner + ? `Upload exceeds the ${Math.round(MAX_UPLOAD / (1024 * 1024))} MB limit` + : 'This upload does not fit in the remaining storage quota', + ); + } + + // Reserve the announced size synchronously: otherwise two parallel uploads + // could each pass the same remaining-quota check before either writes. + if (owner === null) { + recentUploads.set(params.id, { + ownerId: user.id, + bytes: Number.isFinite(announced) && announced > 0 ? announced : limit, + at: Date.now(), + pending: true, + }); + } + + const target = originalTarget(params.id, ext); + const previous = findOriginal(params.id); + if (previous) await fsp.rm(previous, { force: true }).catch(() => undefined); + + let size = 0; + try { + size = await receiveUpload(req, target, limit); + } catch (err) { + if (owner === null) recentUploads.delete(params.id); + if (err instanceof PayloadTooLarge) { + return error( + res, + 413, + owner + ? `Upload exceeds the ${Math.round(MAX_UPLOAD / (1024 * 1024))} MB limit` + : 'This upload does not fit in the remaining storage quota', + ); + } + throw err; + } + if (!size) { + if (owner === null) recentUploads.delete(params.id); + return error(res, 400, 'Empty upload'); + } + + recentUploads.set(params.id, { + ownerId: user.id, + bytes: size, + at: Date.now(), + pending: owner === null, + }); + + if (raw) { try { + const data = await fsp.readFile(target); const decoded = await decodeRaw(data); await writePreview(params.id, decoded.jpeg, decoded.ext); const info = await jpegInfo(decoded.jpeg); @@ -1146,11 +1696,13 @@ route('POST', '/api/photos/:id/original', async ({ req, res, params }) => { maxEdge: RAW_PREVIEW_EDGE, }); } catch (err) { + recentUploads.delete(params.id); + await removeAsset(params.id).catch(() => undefined); return error(res, 422, err instanceof Error ? err.message : 'Could not decode this raw file'); } } - return json(res, 201, { raw: false, mime, size: data.length }); + return json(res, 201, { raw: false, mime, size }); }); route('GET', '/api/photos/:id/thumb', async ({ req, res, params }) => { @@ -1292,7 +1844,7 @@ route('GET', '/api/photos/:id/original', async ({ req, res, params }) => { const upstream = await fetchBridgeImage(linked.bridge, linked.sourceId, 'original'); if (!upstream.ok) return error(res, 404, 'Original unavailable'); const data = Buffer.from(await upstream.arrayBuffer()); - return sendBuffer(res, data, linked.photo.mime || 'application/octet-stream'); + return sendBuffer(res, data, normalizePhotoMime(linked.photo.mime, linked.photo.name)); }); route('POST', '/api/bridge/export', async ({ req, res }) => { @@ -1326,6 +1878,15 @@ route('PUT', '/api/photos/:id', async ({ req, res, params }) => { if (body.id && body.id !== params.id) return error(res, 400, 'Photo id does not match the URL'); const record = { ...body, id: params.id }; + // Quota accounting uses bytes the server actually received, not the client's + // claim, for an upload that just finished. + const upload = recentUploads.get(params.id); + if (upload && upload.ownerId === user.id) { + record.size = upload.bytes; + recentUploads.delete(params.id); + } + record.mime = record.raw ? 'image/jpeg' : normalizePhotoMime(record.mime, record.name); + const thumb = decodeDataUrl(record.thumb); if (thumb) { await writeThumb(params.id, thumb.data); @@ -1353,6 +1914,7 @@ route('DELETE', '/api/photos/:id', async ({ req, res, params }) => { const user = currentUser(req); if (!user) return error(res, 401, 'Not signed in'); if (!ownedBy(photoOwner(params.id), user)) return error(res, 404, 'No such photo'); + recentUploads.delete(params.id); removePhoto(params.id); clearDenoised(params.id); await removeAsset(params.id); @@ -1378,9 +1940,18 @@ const MIME = { }; async function serveStatic(req, res, url) { - const pathname = decodeURIComponent(url.pathname); - const candidate = path.join(DIST_DIR, pathname === '/' ? 'index.html' : pathname); - if (candidate.startsWith(DIST_DIR)) { + let pathname; + try { + pathname = decodeURIComponent(url.pathname); + } catch { + return error(res, 400, 'Bad request'); + } + if (pathname.includes('\0')) return error(res, 400, 'Bad request'); + // path.relative, not startsWith: a sibling such as /srv/dist-private shares + // the dist prefix and would otherwise pass a bare prefix check. + const candidate = path.resolve(path.join(DIST_DIR, pathname === '/' ? 'index.html' : pathname)); + const relative = path.relative(DIST_DIR, candidate); + if (relative && !relative.startsWith('..') && !path.isAbsolute(relative)) { try { const stat = await fsp.stat(candidate); if (stat.isFile()) { @@ -1413,8 +1984,15 @@ async function serveStatic(req, res, url) { const server = http.createServer(async (req, res) => { const url = new URL(req.url ?? '/', `http://${req.headers.host ?? 'localhost'}`); + res.setHeader('Content-Security-Policy', CSP); + res.setHeader('X-Content-Type-Options', 'nosniff'); res.setHeader('X-Frame-Options', 'SAMEORIGIN'); res.setHeader('Referrer-Policy', 'same-origin'); + res.setHeader('Cross-Origin-Opener-Policy', 'same-origin-allow-popups'); + res.setHeader('Permissions-Policy', 'camera=(), microphone=(), geolocation=()'); + if (String(req.headers['x-forwarded-proto'] ?? '').split(',')[0].trim() === 'https') { + res.setHeader('Strict-Transport-Security', 'max-age=15552000'); + } try { if (url.pathname.startsWith('/api/')) { for (const r of routes) { @@ -1429,11 +2007,39 @@ const server = http.createServer(async (req, res) => { } catch (err) { const message = err instanceof Error ? err.message : 'Unexpected error'; console.error(`[luminary] ${req.method} ${url.pathname} → ${message}`); - if (!res.headersSent) return error(res, 500, message); + if (!res.headersSent) { + if (err instanceof PayloadTooLarge) return error(res, 413, message); + // Do not leak internals from an unexpected failure. + return error(res, 500, 'Unexpected server error'); + } res.end(); } }); +/** Drop uploads that were streamed to disk but never became a photo record. */ +async function sweepStaleUploads() { + const cutoff = Date.now() - 60 * 60 * 1000; + for (const [id, upload] of recentUploads) { + if (upload.at > cutoff) continue; + recentUploads.delete(id); + if (!getPhoto(id)) await removeAsset(id).catch(() => undefined); + } +} + +/** Remove pre-upgrade orphans: originals with no catalog row, older than a day. */ +async function sweepOrphanOriginals() { + const dir = path.join(storageRoot(), 'originals'); + const names = await fsp.readdir(dir).catch(() => []); + const cutoff = Date.now() - 24 * 60 * 60 * 1000; + for (const name of names) { + const id = name.replace(/\.[^.]+$/, ''); + if (/^[A-Za-z0-9_-]{1,80}$/.test(id) && getPhoto(id)) continue; + const file = path.join(dir, name); + const stat = await fsp.stat(file).catch(() => null); + if (stat && stat.mtimeMs < cutoff) await fsp.rm(file, { force: true }).catch(() => undefined); + } +} + server.listen(PORT, HOST, async () => { startQuotaWorker(); const raw = await rawSupport(); @@ -1446,6 +2052,16 @@ server.listen(PORT, HOST, async () => { if (!raw.libraw) console.log(' note: install libraw-wasm for full raw demosaic (embedded previews still work)'); }); +setInterval(() => { + void sweepStaleUploads().catch((err) => + console.error(`[luminary] upload sweep: ${err.message}`), + ); +}, 10 * 60 * 1000).unref?.(); + +void sweepOrphanOriginals().catch((err) => + console.error(`[luminary] orphan sweep: ${err.message}`), +); + for (const signal of ['SIGINT', 'SIGTERM']) { process.on(signal, () => { server.close(() => process.exit(0)); diff --git a/server/mail.mjs b/server/mail.mjs index a7f66bc..79b0a9b 100644 --- a/server/mail.mjs +++ b/server/mail.mjs @@ -1,5 +1,6 @@ import nodemailer from 'nodemailer'; import { kv } from './db.mjs'; +import { open, seal } from './secrets.mjs'; import { SMTP_APP_PASSWORD, SMTP_FROM, @@ -13,7 +14,16 @@ const SETTINGS_KEY = 'mailSettings'; function savedSettings() { const value = kv.get(SETTINGS_KEY); - return value && typeof value === 'object' ? value : {}; + if (!value || typeof value !== 'object') return {}; + if (typeof value.appPassword === 'string' && value.appPassword) { + try { + return { ...value, appPassword: open(value.appPassword) }; + } catch (err) { + console.error('[luminary] could not decrypt the saved SMTP password:', err.message); + return { ...value, appPassword: '' }; + } + } + return value; } /** Never returns the app password; `hasPassword` is enough for the admin UI. */ @@ -70,7 +80,7 @@ function validateSettings(input) { export function saveMailSettings(input) { const next = validateSettings(input ?? {}); - kv.set(SETTINGS_KEY, next); + kv.set(SETTINGS_KEY, { ...next, appPassword: seal(next.appPassword) }); return mailStatus(); } diff --git a/server/secrets.mjs b/server/secrets.mjs new file mode 100644 index 0000000..b542c7b --- /dev/null +++ b/server/secrets.mjs @@ -0,0 +1,73 @@ +/** + * Small AES-256-GCM helper for credentials stored in SQLite (SMTP app password, + * bridge service tokens). Values written before this file existed are plain + * strings and are still readable; they are sealed the next time they are saved. + */ + +import crypto from 'node:crypto'; +import fs from 'node:fs'; +import path from 'node:path'; +import { DATA_DIR, SECRET_KEY } from './config.mjs'; + +const PREFIX = 'enc:v1:'; +let cachedKey = null; + +function loadKey() { + if (cachedKey) return cachedKey; + + if (SECRET_KEY) { + cachedKey = crypto.createHash('sha256').update(SECRET_KEY).digest(); + return cachedKey; + } + + // Without an explicit key, keep one beside the database. It protects copies + // of the database (backups, dumps) but not an attacker who has the whole + // data directory. + const file = path.join(DATA_DIR, 'secret.key'); + const existing = fs.existsSync(file) ? fs.readFileSync(file, 'utf8').trim() : ''; + if (existing) { + cachedKey = crypto.createHash('sha256').update(existing).digest(); + return cachedKey; + } + + const generated = crypto.randomBytes(32).toString('hex'); + fs.mkdirSync(DATA_DIR, { recursive: true }); + try { + fs.writeFileSync(file, generated, { mode: 0o600, flag: 'wx' }); + cachedKey = crypto.createHash('sha256').update(generated).digest(); + } catch { + cachedKey = crypto + .createHash('sha256') + .update(fs.readFileSync(file, 'utf8').trim()) + .digest(); + } + return cachedKey; +} + +export function isSealed(value) { + return typeof value === 'string' && value.startsWith(PREFIX); +} + +export function seal(value) { + if (typeof value !== 'string' || !value) return value; + if (isSealed(value)) return value; + const iv = crypto.randomBytes(12); + const cipher = crypto.createCipheriv('aes-256-gcm', loadKey(), iv); + const ciphertext = Buffer.concat([cipher.update(value, 'utf8'), cipher.final()]); + return `${PREFIX}${iv.toString('base64url')}.${cipher.getAuthTag().toString('base64url')}.${ciphertext.toString('base64url')}`; +} + +export function open(value) { + if (!isSealed(value)) return value; + const [iv, tag, ciphertext] = String(value).slice(PREFIX.length).split('.'); + const decipher = crypto.createDecipheriv( + 'aes-256-gcm', + loadKey(), + Buffer.from(iv, 'base64url'), + ); + decipher.setAuthTag(Buffer.from(tag, 'base64url')); + return Buffer.concat([ + decipher.update(Buffer.from(ciphertext, 'base64url')), + decipher.final(), + ]).toString('utf8'); +} diff --git a/server/storage.mjs b/server/storage.mjs index a1341d6..421afe8 100644 --- a/server/storage.mjs +++ b/server/storage.mjs @@ -83,6 +83,11 @@ export async function writeOriginal(id, ext, data) { return target; } +/** Final path for a streamed upload; the caller writes it without buffering. */ +export function originalTarget(id, ext = 'bin') { + return originalPath(id, ext); +} + export function findOriginal(id) { const safe = lookupId(id); if (!safe) return null; diff --git a/src/App.tsx b/src/App.tsx index 31954d3..0d8b964 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -9,6 +9,7 @@ import ExportModal from './components/ExportModal'; import CompareView from './components/CompareView'; import FilterBar from './components/FilterBar'; import ImportModal from './components/ImportModal'; +import ImmichPanel from './components/ImmichPanel'; import LibraryGrid from './components/LibraryGrid'; import MergeModal from './components/MergeModal'; import PasteSettingsModal from './components/PasteSettingsModal'; @@ -22,18 +23,23 @@ import { currentUser, deleteEventRemote, deletePhotoRemote, + createImmichEventAlbum, getHealth, + getImmichStatus, getQuota, + immichEventQueue, login as apiLogin, logout as apiLogout, pullAll, pullProofs, pushEvent, + publishImmichOriginal, + pushImmichPhoto, pushPhoto, register as apiRegister, uploadOriginal, } from './lib/api'; -import type { Health, ProofSummary, QuotaState, SessionUser } from './lib/api'; +import type { Health, ImmichStatus, ProofSummary, QuotaState, SessionUser } from './lib/api'; import { deleteEventRecord, deletePhotoRecord, @@ -136,6 +142,41 @@ export default function App() { const [cloudUser, setCloudUser] = useState(null); const [cloudOpen, setCloudOpen] = useState(false); const [adminOpen, setAdminOpen] = useState(false); + const [immichOpen, setImmichOpen] = useState(false); + const [immichStatus, setImmichStatus] = useState(null); + const [immichProgress, setImmichProgress] = useState<{ + done: number; + total: number; + current: string; + } | null>(null); + const immichStatusRef = useRef(null); + immichStatusRef.current = immichStatus; + const immichBusyRef = useRef(false); + + // The Immich entry points only appear when this account has opted in. + useEffect(() => { + if (!cloudUser) { + setImmichStatus(null); + return; + } + let alive = true; + getImmichStatus() + .then((status) => { + if (alive) setImmichStatus(status); + }) + .catch(() => { + if (alive) setImmichStatus(null); + }); + return () => { + alive = false; + }; + }, [cloudUser]); + + useEffect( + () => () => { + }, + [], + ); const [cloudBusy, setCloudBusy] = useState(false); const [cloudError, setCloudError] = useState(null); const [cloudNote, setCloudNote] = useState(null); @@ -337,6 +378,16 @@ export default function App() { [queueSave], ); + const immichEventIds = useMemo( + () => new Set(events.filter((event) => event.immich).map((event) => event.id)), + [events], + ); + const canSendToImmich = useCallback( + (photo: PhotoRecord) => + Boolean(immichStatus?.enabled && (photo.immich || immichEventIds.has(photo.eventId))), + [immichStatus?.enabled, immichEventIds], + ); + const livePhotos = useMemo(() => photos.filter((p) => !p.deletedAt), [photos]); const trashCount = photos.length - livePhotos.length; const proofCounts = useMemo(() => { @@ -475,19 +526,56 @@ export default function App() { [activeId], ); - const createEvent = useCallback(async (name: string) => { - const event: EventRecord = { - id: uid(), - name: name.trim() || `Event ${new Date().toLocaleDateString()}`, - createdAt: Date.now(), - date: Date.now(), - order: eventsRef.current.length, - workspace: userRef.current?.id, - }; - await putEvent(event); - if (userRef.current) pushEvent(event).catch(() => undefined); - setEvents((prev) => [...prev, event].sort(byOrder)); - return event; + const createEvent = useCallback( + async (name: string, options: { immichGallery?: boolean } = {}) => { + const event: EventRecord = { + id: uid(), + name: name.trim() || `Event ${new Date().toLocaleDateString()}`, + createdAt: Date.now(), + date: Date.now(), + order: eventsRef.current.length, + workspace: userRef.current?.id, + }; + await putEvent(event); + // The gallery endpoint looks the event up server-side, so let this land first. + if (userRef.current) await pushEvent(event).catch(() => undefined); + let created = event; + if (options.immichGallery && userRef.current && immichStatusRef.current?.enabled) { + try { + const result = await createImmichEventAlbum(event.id, event.name); + created = result.event; + await putEvent(created); + setToast(`Immich gallery created for ${created.name}`); + } catch (err) { + setToast( + `Event created, but the Immich gallery failed: ${ + err instanceof Error ? err.message : 'unknown error' + }`, + ); + } + } + const nextEvents = [...eventsRef.current.filter((e) => e.id !== created.id), created].sort(byOrder); + // ImportModal creates an event and immediately asks for its Immich gallery. + // Update the ref now so that follow-up call can find the new event. + eventsRef.current = nextEvents; + setEvents(nextEvents); + return created; + }, + [], + ); + + const createImmichGalleryForEvent = useCallback(async (id: string) => { + const event = eventsRef.current.find((item) => item.id === id); + if (!event) throw new Error('No such event'); + const result = await createImmichEventAlbum(id, event.name); + await putEvent(result.event); + const nextEvents = eventsRef.current + .map((item) => (item.id === id ? result.event : item)) + .sort(byOrder); + eventsRef.current = nextEvents; + setEvents(nextEvents); + setToast(`Immich gallery created for ${event.name}`); + return result.event; }, []); const renameEvent = useCallback(async (id: string, name: string) => { @@ -1236,6 +1324,169 @@ export default function App() { } }, [activePhoto, bridgeEvent]); + /** + * Renders each edit and uploads the queue one at a time. Checksums make a + * repeat send of an unchanged edit a no-op on the server. + */ + const pushImmichQueue = useCallback(async (targets: PhotoRecord[]) => { + if (immichBusyRef.current) return; + const queue = targets.filter( + (photo) => photo.immich || immichEventIds.has(photo.eventId), + ); + const localCount = targets.length - queue.length; + if (!queue.length) { + setToast('None of the selected photos can go to Immich yet'); + return; + } + immichBusyRef.current = true; + let sent = 0; + let skipped = 0; + let failed = 0; + let trashed = 0; + let warning = ''; + setImmichProgress({ done: 0, total: queue.length, current: queue[0].name }); + try { + for (let i = 0; i < queue.length; i += 1) { + const photo = queue[i]; + setImmichProgress({ done: i, total: queue.length, current: photo.name }); + try { + const blob = await renderPhotoBlob(photo, { + ...DEFAULT_EXPORT, + format: 'jpeg', + quality: 92, + resize: 'none', + }); + const result = await pushImmichPhoto(photo.id, await blobToBase64(blob)); + if (result.alreadyPushed) skipped += 1; + else sent += 1; + if (result.trashed) trashed += 1; + if (result.warning && !warning) warning = result.warning; + } catch (err) { + failed += 1; + if (!warning) warning = err instanceof Error ? err.message : 'A photo could not be sent'; + } + setImmichProgress({ done: i + 1, total: queue.length, current: photo.name }); + // Let the progress paint before the next full-resolution render. + await new Promise((resolve) => setTimeout(resolve, 0)); + } + } finally { + immichBusyRef.current = false; + setImmichProgress(null); + } + const parts = []; + if (sent) parts.push(`Sent ${sent} edit${sent === 1 ? '' : 's'}`); + if (skipped) parts.push(`${skipped} already in Immich`); + if (localCount) parts.push(`${localCount} not from Immich`); + if (trashed) parts.push(`${trashed} original${trashed === 1 ? '' : 's'} in trash`); + if (failed) parts.push(`${failed} failed`); + let message = parts.length ? parts.join(' · ') : 'Nothing to send'; + if (warning) message += ` · ${warning}`; + setToast(message); + }, [immichEventIds]); + + /** + * Manual push for one event. Photos Immich has never seen upload their + * original from the server; photos edited since the last push are rendered + * here so the gallery receives the current look. Nothing runs on its own - + * this only happens when the button is pressed, and each finished upload is + * recorded so a repeat press skips everything that is already up to date. + */ + const syncEventGallery = useCallback(async (targetEventId: string) => { + if (immichBusyRef.current) { + setToast('An Immich upload is already running'); + return; + } + if (!immichStatusRef.current?.enabled) { + setToast('Turn on Immich in the Immich sync panel first'); + return; + } + + let plan: { photoId: string; mode: 'original' | 'edit' }[]; + try { + plan = (await immichEventQueue(targetEventId)).queue; + } catch (err) { + setToast(err instanceof Error ? err.message : 'Could not read the Immich queue'); + return; + } + const byId = new Map( + photosRef.current.filter((photo) => !photo.deletedAt).map((photo) => [photo.id, photo]), + ); + const queue: { entry: { photoId: string; mode: 'original' | 'edit' }; photo: PhotoRecord }[] = []; + for (const entry of plan) { + const photo = byId.get(entry.photoId); + if (!photo) continue; + // A photo Immich already has only needs a new upload once it is edited. + if (entry.mode === 'edit' && !isEdited(photo.edits)) continue; + queue.push({ entry, photo }); + } + if (!queue.length) { + setToast('Everything in this event is already in Immich'); + return; + } + + immichBusyRef.current = true; + let sent = 0; + let skipped = 0; + let failed = 0; + let warning = ''; + setImmichProgress({ done: 0, total: queue.length, current: queue[0].photo.name }); + try { + for (let i = 0; i < queue.length; i += 1) { + const { entry, photo } = queue[i]; + setImmichProgress({ done: i, total: queue.length, current: photo.name }); + try { + const result = entry.mode === 'edit' + ? await pushImmichPhoto( + photo.id, + await blobToBase64( + await renderPhotoBlob(photo, { + ...DEFAULT_EXPORT, + format: 'jpeg', + quality: 92, + resize: 'none', + }), + ), + ) + : await publishImmichOriginal(photo.id); + if (result.alreadyPushed || result.skipped) skipped += 1; + else sent += 1; + if (result.warning && !warning) warning = result.warning; + } catch (err) { + failed += 1; + if (!warning) { + warning = `${photo.name}: ${ + err instanceof Error ? err.message : 'could not be sent' + }`; + } + } + setImmichProgress({ done: i + 1, total: queue.length, current: photo.name }); + // Let the progress paint before the next render or upload. + await new Promise((resolve) => setTimeout(resolve, 0)); + } + } finally { + immichBusyRef.current = false; + setImmichProgress(null); + } + + const parts = []; + if (sent) parts.push(`Sent ${sent} photo${sent === 1 ? '' : 's'}`); + if (skipped) parts.push(`${skipped} already in Immich`); + if (failed) parts.push(`${failed} failed`); + let message = parts.length ? parts.join(' · ') : 'Nothing to send'; + if (warning) message += ` · ${warning}`; + setToast(message); + }, []); + + const openImmichAsset = useCallback((photo: PhotoRecord) => { + const status = immichStatusRef.current; + if (!status?.url || !photo.immich) return; + window.open( + `${status.url.replace(/\/+$/, '')}/photos/${encodeURIComponent(photo.immich.assetId)}`, + '_blank', + 'noopener,noreferrer', + ); + }, []); + const handleCloudLogin = useCallback( async (email: string, password: string) => { setCloudBusy(true); @@ -1754,9 +2005,11 @@ export default function App() { setTrashOpen(false); setEventId(id); }} - onCreate={async (name) => { - await createEvent(name); + immichEnabled={Boolean(immichStatus?.enabled)} + onCreate={async (name, immichGallery) => { + await createEvent(name, { immichGallery }); }} + onSyncGallery={syncEventGallery} onRename={renameEvent} onDelete={removeEvent} onReorderEvents={reorderEvents} @@ -1855,6 +2108,15 @@ export default function App() { onBulkRate={(rating) => bulkUpdate(selected, { rating })} onBulkFlag={(flag) => bulkUpdate(selected, { flag })} onBulkColor={(color) => bulkUpdate(selected, { color })} + onSendToImmich={ + selected.some((id) => { + const photo = photos.find((item) => item.id === id); + return photo ? canSendToImmich(photo) : false; + }) + ? () => void pushImmichQueue(photos.filter((photo) => selected.includes(photo.id))) + : undefined + } + immichBusy={Boolean(immichProgress)} onDelete={() => (trashOpen ? void removePhotos(selected) : trashPhotos(selected))} onExport={openExport} onCompare={() => setCompareOpen(true)} @@ -1899,6 +2161,11 @@ export default function App() { onLocalClipboard={setLocalClipboard} onExport={openExport} onPrint={() => setPrintOpen(true)} + canPushImmich={canSendToImmich(activePhoto)} + onPushImmich={() => void pushImmichQueue([activePhoto])} + onOpenImmich={ + activePhoto.immich ? () => openImmichAsset(activePhoto) : undefined + } presets={[...PRESETS, ...customPresets]} onSavePreset={savePreset} onDelete={() => trashPhotos([activePhoto.id])} @@ -1949,6 +2216,8 @@ export default function App() { setToast(`Imported ${imported.length} photo${imported.length === 1 ? '' : 's'}`); }} onCreateEvent={createEvent} + immichEnabled={Boolean(immichStatus?.enabled)} + onCreateImmichGallery={createImmichGalleryForEvent} /> )} @@ -2061,6 +2330,10 @@ export default function App() { setCloudOpen(false); setAdminOpen(true); }} + onImmich={() => { + setCloudOpen(false); + setImmichOpen(true); + }} onClose={() => setCloudOpen(false)} /> )} @@ -2071,11 +2344,23 @@ export default function App() { onClose={() => setAdminOpen(false)} onChanged={() => { void getHealth().then((health) => setCloudHealth(health)); + void getImmichStatus().then(setImmichStatus).catch(() => undefined); }} onRestored={() => void refreshCatalogFromServer()} /> )} + {immichOpen && cloudUser && ( + setImmichOpen(false)} + onChanged={() => { + void getImmichStatus().then(setImmichStatus).catch(() => undefined); + void refreshCatalogFromServer(); + }} + onToast={setToast} + /> + )} + {menu && (() => { const targets = photos.filter((p) => menu.ids.includes(p.id)); @@ -2133,6 +2418,21 @@ export default function App() { disabled: menu.ids.length < 2, onSelect: () => setMergeOpen(true), }, + ...(targets.some(canSendToImmich) + ? ([ + { + label: + targets.filter(canSendToImmich).length === 1 + ? 'Send edit to Immich' + : `Send ${targets.filter(canSendToImmich).length} edits to Immich`, + disabled: Boolean(immichProgress), + onSelect: () => void pushImmichQueue(targets), + }, + ...(lead.immich + ? [{ label: 'Open in Immich', onSelect: () => openImmichAsset(lead) }] + : []), + ] as MenuEntry[]) + : []), { label: 'Export…', onSelect: openExport }, { label: 'Print…', onSelect: () => setPrintOpen(true) }, { @@ -2168,6 +2468,25 @@ export default function App() { /> )} + {immichProgress && ( +
+
+ Sending to Immich + + {immichProgress.done} / {immichProgress.total} + +
+
+ +
+ {immichProgress.current} +
+ )} + {toast && (
{toast} diff --git a/src/components/AdminPanel.tsx b/src/components/AdminPanel.tsx index c80c4d2..9cbe500 100644 --- a/src/components/AdminPanel.tsx +++ b/src/components/AdminPanel.tsx @@ -15,14 +15,17 @@ import { adminCreateUser, adminDeleteEvent, adminDeleteUser, + adminDisconnectImmich, adminRestoreCatalog, adminRevokeInvite, adminOverview, adminRenameEvent, + adminSaveImmich, adminSaveMail, adminSchedulePrune, adminSetQuota, adminSetStorage, + adminTestImmich, adminTestMail, adminUpdateUser, adminWarnUser, @@ -68,7 +71,7 @@ const planSummary = (quota: AdminQuota) => { return parts.length ? parts.join(', ') : 'nothing'; }; -type Tab = 'users' | 'invites' | 'content' | 'storage' | 'quotas' | 'backup'; +type Tab = 'users' | 'invites' | 'content' | 'storage' | 'quotas' | 'immich' | 'backup'; const inviteUrl = (token: string) => `${window.location.origin}/join/${token}`; @@ -112,6 +115,8 @@ export default function AdminPanel({ user, onClose, onChanged, onRestored }: Pro const [quotaDrafts, setQuotaDrafts] = useState>({}); const [mailDraft, setMailDraft] = useState({ user: '', appPassword: '', from: '' }); const [mail, setMail] = useState(null); + const [immichDraft, setImmichDraft] = useState({ url: '', apiKey: '', enabled: true }); + const restoreCatalog = async (file: File | undefined) => { if (!file || busy) return; @@ -161,6 +166,11 @@ export default function AdminPanel({ user, onClose, onChanged, onRestored }: Pro user: current.user || next.mail.user, from: current.from || next.mail.from, })); + setImmichDraft((current) => ({ + url: next.immich.hasKey ? current.url || next.immich.url : next.immich.url, + apiKey: '', + enabled: next.immich.hasKey ? (current.url ? current.enabled : next.immich.enabled) : true, + })); setRootInput((current) => (current ? current : next.storage.root)); onChanged(); }, [onChanged]); @@ -174,6 +184,13 @@ export default function AdminPanel({ user, onClose, onChanged, onRestored }: Pro setOverview(next); setMail(next.mail); setMailDraft({ user: next.mail.user, appPassword: '', from: next.mail.from }); + // A connection being set up for the first time defaults to on; the box + // would otherwise be unchecked and silently save publishing as off. + setImmichDraft({ + url: next.immich.url, + apiKey: '', + enabled: next.immich.hasKey ? next.immich.enabled : true, + }); setRootInput(next.storage.root); setQuotaDrafts( Object.fromEntries( @@ -345,6 +362,42 @@ export default function AdminPanel({ user, onClose, onChanged, onRestored }: Pro setNote(`Test email sent to ${user.email}`); }); + const saveImmich = () => + run(async () => { + const next = await adminSaveImmich({ + url: immichDraft.url.trim(), + apiKey: immichDraft.apiKey, + enabled: immichDraft.enabled, + }); + setImmichDraft({ url: next.url, apiKey: '', enabled: next.enabled }); + setNote( + next.enabled + ? 'Immich connection saved for every account' + : 'Immich connection saved; automatic publishing is off', + ); + }); + + const testImmich = () => + run(async () => { + const result = await adminTestImmich(); + setNote( + `Connected to Immich ${result.version} · ${result.albumCount} album${ + result.albumCount === 1 ? '' : 's' + }`, + ); + }); + + const disconnectImmichConnection = () => { + if (!window.confirm('Remove the server-wide Immich connection? Existing albums and photos stay in Immich.')) { + return; + } + void run(async () => { + const next = await adminDisconnectImmich(); + setImmichDraft({ url: next.url, apiKey: '', enabled: next.enabled }); + setNote('Immich connection removed'); + }); + }; + const renameEvent = () => { if (!editEvent) return; const name = editEvent.name.trim(); @@ -404,6 +457,9 @@ export default function AdminPanel({ user, onClose, onChanged, onRestored }: Pro + @@ -926,6 +982,108 @@ export default function AdminPanel({ user, onClose, onChanged, onRestored }: Pro

+ ) : tab === 'immich' ? ( +
+

Immich connection

+

+ One connection is shared by every account. When it is enabled, importing into a + Luminary event creates a matching Immich album, publishes the originals there, and + saves edited versions to the same album. +

+ + + + +
+ + + {overview.immich.hasKey && ( + + )} +
+ + {overview.immich.configured ? ( +
+ {overview.immich.enabled + ? 'Connected and automatic publishing is on.' + : 'Connection saved; automatic publishing is off.'}{' '} + {overview.immich.version ? `Immich ${overview.immich.version}.` : 'Test it to verify access.'} +
+ ) : ( +
+ Add the server address and API key to enable Immich publishing. +
+ )} + +
+

+ The key needs album.read, album.create,{' '} + albumAsset.create, asset.read,{' '} + asset.download, asset.upload and{' '} + asset.update. Add asset.delete only if originals should + move to the Immich trash after an edited version is uploaded. +

+

+ The key is encrypted on the server and never sent back to a browser. Existing + albums already in Immich stay untouched if the connection is removed. +

+
+
) : tab === 'backup' ? (

Catalog backup

diff --git a/src/components/CloudPanel.tsx b/src/components/CloudPanel.tsx index 7e8ca5a..ba57d89 100644 --- a/src/components/CloudPanel.tsx +++ b/src/components/CloudPanel.tsx @@ -12,6 +12,7 @@ interface Props { onLogout: () => void; onSync: () => void; onAdmin: () => void; + onImmich: () => void; onClose: () => void; } @@ -32,6 +33,7 @@ export default function CloudPanel({ onLogout, onSync, onAdmin, + onImmich, onClose, }: Props) { const [mode, setMode] = useState<'signin' | 'signup'>('signin'); @@ -121,6 +123,14 @@ export default function CloudPanel({ Administration )} + {note &&
{note}
} diff --git a/src/components/Develop.tsx b/src/components/Develop.tsx index 3728987..9193fe2 100644 --- a/src/components/Develop.tsx +++ b/src/components/Develop.tsx @@ -128,6 +128,9 @@ interface Props { onLocalClipboard: (layer: LocalLayer | null) => void; onExport: () => void; onPrint: () => void; + canPushImmich?: boolean; + onPushImmich?: () => void; + onOpenImmich?: () => void; presets: Preset[]; onSavePreset: (name: string, edits: Edits) => void; onDelete: () => void; @@ -155,6 +158,9 @@ export default function Develop({ onLocalClipboard, onExport, onPrint, + canPushImmich = false, + onPushImmich, + onOpenImmich, presets, onSavePreset, onDelete, @@ -1453,6 +1459,12 @@ export default function Develop({ { label: 'Paste settings', shortcut: '⌘V', onSelect: onPaste, disabled: !clipboard }, { label: 'Reset settings', onSelect: resetAll }, 'separator', + ...(canPushImmich && onPushImmich + ? ([{ label: 'Send edit to Immich', onSelect: onPushImmich }] as MenuEntry[]) + : []), + ...(onOpenImmich + ? ([{ label: 'Open in Immich', onSelect: onOpenImmich }] as MenuEntry[]) + : []), { label: 'Export…', onSelect: onExport }, { label: 'Delete photo…', danger: true, onSelect: onDelete }, ]; @@ -1462,6 +1474,12 @@ export default function Develop({ { label: 'Paste settings', onSelect: onPaste, disabled: !clipboard }, { label: 'Reset settings', onSelect: resetAll }, 'separator', + ...(canPushImmich && onPushImmich + ? ([{ label: 'Send edit to Immich', onSelect: onPushImmich }] as MenuEntry[]) + : []), + ...(onOpenImmich + ? ([{ label: 'Open in Immich', onSelect: onOpenImmich }] as MenuEntry[]) + : []), { label: 'Export…', onSelect: onExport }, { label: 'Delete photo…', danger: true, onSelect: onDelete }, ]; diff --git a/src/components/EventSidebar.tsx b/src/components/EventSidebar.tsx index c64083a..4a3f254 100644 --- a/src/components/EventSidebar.tsx +++ b/src/components/EventSidebar.tsx @@ -17,9 +17,11 @@ interface Props { photos: PhotoRecord[]; eventId: string; onSelectEvent: (id: string) => void; - onCreate: (name: string) => Promise | void; + immichEnabled?: boolean; + onCreate: (name: string, immichGallery?: boolean) => Promise | void; onRename: (id: string, name: string) => void; onDelete: (id: string) => void; + onSyncGallery?: (id: string) => void; onReorderEvents: (dragId: string, targetId: string) => void; onDropPhotos: (ids: string[], eventId: string) => void; trashOpen: boolean; @@ -39,9 +41,11 @@ export default function EventSidebar({ photos, eventId, onSelectEvent, + immichEnabled = false, onCreate, onRename, onDelete, + onSyncGallery, onReorderEvents, onDropPhotos, trashOpen, @@ -55,6 +59,7 @@ export default function EventSidebar({ }: Props) { const [adding, setAdding] = useState(false); const [name, setName] = useState(''); + const [createGallery, setCreateGallery] = useState(false); const [dropTarget, setDropTarget] = useState(null); const counts = new Map(); @@ -72,8 +77,9 @@ export default function EventSidebar({ setAdding(false); return; } - await onCreate(name); + await onCreate(name, createGallery); setName(''); + setCreateGallery(false); setAdding(false); }; @@ -189,6 +195,16 @@ export default function EventSidebar({ + {immichEnabled && ( + + )} )} @@ -234,6 +250,15 @@ export default function EventSidebar({ {counts.get(event.id) ?? 0}
+ {immichEnabled && event.immich && onSyncGallery && ( + + )} + + +
+

+ {managed + ? 'This server uses an Immich connection managed by an administrator. You can import albums, but the server address and API key are managed centrally.' + : 'Optional and private to your account. Your API key is stored encrypted on the server and is never sent to the browser. Nothing changes in the library until you turn this on.'} +

+ + {managed && status?.url && ( +
+ Shared Immich server: {status.url} +
+ )} + + {loading && !status ? ( +

Checking…

+ ) : ( + <> + + +
+ + + {configured && !managed && ( + + )} +
+

+ Create a key in Immich under Account Settings → API Keys. It needs{' '} + album.read, album.create, albumAsset.create,{' '} + asset.read, + asset.download, asset.upload and asset.update; + add tag.read, tag.create and tag.asset for + keyword sync, and asset.delete only if you want originals moved to the + Immich trash after an upload. +

+ + {configured && ( + <> +
+ Integration + + {status?.version ? `Immich ${status.version}` : 'Not tested yet'} + +
+ + + +

+ Nothing is uploaded while you edit. Press the ☁ button on an event to push + its edited photos and any originals Immich has not seen yet. +

+ + +

+ Recoverable in Immich. Luminary never permanently deletes the Immich original. +

+ + {enabled && ( + <> +
+ Albums + Only linked albums sync automatically +
+ +
+
+ Album + Photos + Last sync + Actions +
+ {albums === null ? ( +

+ {albumsLoading + ? 'Loading albums…' + : 'Choose Refresh to list albums from this Immich account.'} +

+ ) : albums.length === 0 ? ( +

This Immich account has no albums.

+ ) : ( + albums.map((album) => ( +
+
+ {album.name} +
+ {album.updatedAt + ? `Updated ${fmtDate(album.updatedAt)}` + : 'Immich album'} +
+
+ {album.assetCount} + + {album.lastSyncAt ? fmtDate(album.lastSyncAt) : '—'} + +
+ {album.kind === 'gallery' ? ( + Gallery + ) : ( + + )} +
+
+ )) + )} +
+ +
+ +
+ + )} + + {job && ( +
+

+ {job.albumName || 'Album'} ·{' '} + {job.state === 'running' + ? job.scheduled + ? 'Syncing in the background…' + : 'Importing…' + : job.state === 'done' + ? 'Complete' + : 'Stopped'} +

+
+ +
+

+ {job.done} imported · {job.skipped} already present + {job.failed ? ` · ${job.failed} failed` : ''} +

+ {job.message &&

{job.message}

} + {job.errors.length > 0 && ( +
    + {job.errors.map((message) => ( +
  • {message}
  • + ))} +
+ )} +
+ )} + + )} + + )} + + {error &&
{error}
} +
+ +
+ + Nothing uploads automatically. Use ☁ on an event to push its edits and originals. + + +
+
+ + ); +} diff --git a/src/components/ImportModal.tsx b/src/components/ImportModal.tsx index e74c36c..ca58c23 100644 --- a/src/components/ImportModal.tsx +++ b/src/components/ImportModal.tsx @@ -1,4 +1,5 @@ import { useEffect, useMemo, useRef, useState } from 'react'; +import { publishImmichOriginal } from '../lib/api'; import type { CloudImport, ImportProgress } from '../lib/import'; import { importFiles, isSupportedFile } from '../lib/import'; import { isRawFile, RAW_ACCEPT } from '../lib/raw'; @@ -13,6 +14,9 @@ interface Props { onClose: () => void; onImported: (photos: PhotoRecord[], eventId: string) => void; onCreateEvent: (name: string) => Promise; + /** Turns on the optional Immich gallery for the created/target event. */ + immichEnabled?: boolean; + onCreateImmichGallery?: (eventId: string) => Promise; cloud?: CloudImport | null; onNeedServer: () => void; } @@ -25,6 +29,8 @@ export default function ImportModal({ onClose, onImported, onCreateEvent, + immichEnabled = false, + onCreateImmichGallery, cloud, onNeedServer, }: Props) { @@ -37,11 +43,16 @@ export default function ImportModal({ const [progress, setProgress] = useState(null); const [failures, setFailures] = useState([]); const [allowDuplicates, setAllowDuplicates] = useState(false); + const [createGallery, setCreateGallery] = useState(immichEnabled); + const [galleryCreated, setGalleryCreated] = useState(false); + const [galleryError, setGalleryError] = useState(null); const [summary, setSummary] = useState<{ imported: number; failed: number; skipped: number; cancelled: boolean; + published: number; + publishFailed: number; } | null>(null); const inputRef = useRef(null); const abortRef = useRef(null); @@ -56,6 +67,12 @@ export default function ImportModal({ ); const readyFiles = allowDuplicates ? files : files.filter((file) => !duplicateFiles.includes(file)); + useEffect(() => { + setGalleryCreated(false); + setGalleryError(null); + setCreateGallery(immichEnabled); + }, [eventId, immichEnabled]); + useEffect(() => { // Capture phase: Escape closes this dialog even while a photo is open behind it. const onKey = (e: KeyboardEvent) => { @@ -91,16 +108,67 @@ export default function ImportModal({ const created = await onCreateEvent(newName || `Event ${new Date().toLocaleDateString()}`); targetId = created.id; } + let hasGallery = Boolean(events.find((event) => event.id === targetId)?.immich); + if ( + createGallery && + !galleryCreated && + onCreateImmichGallery && + !hasGallery + ) { + try { + await onCreateImmichGallery(targetId); + hasGallery = true; + setGalleryCreated(true); + } catch (err) { + setGalleryError( + err instanceof Error ? err.message : 'The Immich gallery could not be created', + ); + } + } const result = await importFiles(readyFiles, targetId, [], setProgress, cloud ?? null, controller.signal); if (result.photos.length) onImported(result.photos, targetId); + + let published = 0; + let publishFailed = 0; + const publishFailures: string[] = []; + if (hasGallery && immichEnabled && cloud && result.photos.length) { + const total = result.photos.length; + for (let index = 0; index < total; index++) { + if (controller.signal.aborted) break; + const photo = result.photos[index]; + setProgress({ + done: index, + total, + current: `Adding ${photo.name} to the Immich gallery…`, + }); + try { + const pushed = await publishImmichOriginal(photo.id); + if (!pushed.skipped) published += 1; + } catch (err) { + publishFailed += 1; + publishFailures.push( + `${photo.name} — Immich: ${err instanceof Error ? err.message : 'upload failed'}`, + ); + } + } + setProgress({ done: total, total, current: '' }); + } + const skipped = allowDuplicates ? 0 : duplicateFiles.length; setSummary({ imported: result.photos.length, failed: result.failed.length, skipped, cancelled: Boolean(result.cancelled), + published, + publishFailed, }); - if (result.failed.length) setFailures(result.failed.map((f) => `${f.name} — ${f.reason}`)); + if (result.failed.length || publishFailures.length) { + setFailures([ + ...result.failed.map((f) => `${f.name} — ${f.reason}`), + ...publishFailures, + ]); + } } catch (err) { setFailures([err instanceof Error ? err.message : 'Import failed']); } finally { @@ -152,6 +220,45 @@ export default function ImportModal({ )} + {immichEnabled && + !galleryCreated && + !events.find((event) => event.id === eventId)?.immich && ( + <> + +

+ Luminary creates a matching album in Immich, uploads each original into it, and + saves edited versions to the same album as you work. +

+ + )} + {galleryCreated && ( +

+ Immich album linked. Imported originals will upload automatically, and edits will be + saved there as new versions. +

+ )} + {!galleryCreated && + immichEnabled && + Boolean(events.find((event) => event.id === eventId)?.immich) && ( +

+ Imported originals will be added to this event's Immich album automatically. + Edits will be saved there too. +

+ )} + {galleryError && ( +
+ Immich gallery not created. {galleryError} +
+ )} +
{ @@ -260,18 +367,25 @@ export default function ImportModal({ {summary.imported} imported {summary.skipped ? ` · ${summary.skipped} duplicate${summary.skipped === 1 ? '' : 's'} skipped` : ''} {summary.failed ? ` · ${summary.failed} failed` : ''} + {summary.published ? ` · ${summary.published} added to Immich` : ''} + {summary.publishFailed + ? ` · ${summary.publishFailed} Immich upload${summary.publishFailed === 1 ? '' : 's'} failed` + : ''}

{summary.cancelled ? 'Files already in progress were allowed to finish. The imported photos are in the catalog.' : 'New photos are selected in the library and ready to review.'} + {summary.published + ? ' The imported photos were added to the event\'s Immich gallery.' + : ''}

)} {failures.length > 0 && (
- Some files could not be imported + Some files had problems
    {failures.map((f) => (
  • {f}
  • diff --git a/src/components/LibraryGrid.tsx b/src/components/LibraryGrid.tsx index 03ce2b8..11204ad 100644 --- a/src/components/LibraryGrid.tsx +++ b/src/components/LibraryGrid.tsx @@ -15,6 +15,8 @@ interface Props { onBulkRate: (rating: number) => void; onBulkFlag: (flag: Flag) => void; onBulkColor: (color: ColorLabel) => void; + onSendToImmich?: () => void; + immichBusy?: boolean; onDelete: () => void; onExport: () => void; onCompare: () => void; @@ -51,6 +53,8 @@ export default function LibraryGrid({ onBulkRate, onBulkFlag, onBulkColor, + onSendToImmich, + immichBusy = false, onDelete, onExport, onCompare, @@ -277,6 +281,16 @@ export default function LibraryGrid({ + {onSendToImmich && ( + + )} diff --git a/src/gl/masks.ts b/src/gl/masks.ts index 01c1927..5e4e80b 100644 --- a/src/gl/masks.ts +++ b/src/gl/masks.ts @@ -131,6 +131,27 @@ function drawBrush(ctx: CanvasRenderingContext2D, layer: LocalLayer, w: number, ctx.globalCompositeOperation = 'source-over'; } +/** + * Softens a mask rim without thinning what was painted. A plain blur pulls the + * stroke edge inward and drops thin strokes below full coverage, which reads as + * a weaker, uneven adjustment. Blurring a copy and keeping the original on top + * (lighten = max) softens only the outside of the edge: the painted core stays + * at 100% and the falloff grows past the brush outline. + */ +function featherMask(canvas: HTMLCanvasElement, radius: number) { + const out = makeCanvas(canvas.width, canvas.height); + const ctx = out.getContext('2d'); + if (!ctx) return canvas; + // A sub-pixel blur keeps a feather of 0 from aliasing along the brush edge. + ctx.filter = `blur(${Math.max(0.4, radius)}px)`; + ctx.drawImage(canvas, 0, 0); + ctx.filter = 'none'; + ctx.globalCompositeOperation = 'lighten'; + ctx.drawImage(canvas, 0, 0); + ctx.globalCompositeOperation = 'source-over'; + return out; +} + export function buildLocalMasks(layers: LocalLayer[], srcW: number, srcH: number): PackedMasks { const w = 800; const h = Math.max(120, Math.min(1400, Math.round((w * Math.max(1, srcH)) / Math.max(1, srcW)))); @@ -151,14 +172,19 @@ export function buildLocalMasks(layers: LocalLayer[], srcW: number, srcH: number else drawBrush(ctx, layer, w, h); let source = canvas; - if ((layer.kind === 'brush' || layer.kind === 'raster') && layer.feather > 0) { - const blur = makeCanvas(w, h); - const bctx = blur.getContext('2d'); - if (bctx) { - bctx.filter = `blur(${Math.max(0.1, ((layer.feather / 100) * w) / 16)}px)`; - bctx.drawImage(canvas, 0, 0); - source = blur; + if (layer.kind === 'brush') { + // Feather follows the brush, not the frame: 100% softens the edge by + // roughly three quarters of the stroke's half width, so a small dab and a + // wide sweep both feel the same under the slider. + let widest = 0; + for (const stroke of layer.brush.strokes) { + widest = Math.max(widest, stroke.size * 2 * w); } + source = featherMask(canvas, (layer.feather / 100) * widest * 0.75); + } else if (layer.kind === 'raster') { + // Generated masks are low-resolution coverage, so their feather is tied + // to the frame width and only ever loosens the outside edge. + source = featherMask(canvas, ((layer.feather / 100) * w) / 16); } const pixels = source.getContext('2d')?.getImageData(0, 0, w, h).data; diff --git a/src/gl/renderer.ts b/src/gl/renderer.ts index 9513ea4..ed0097f 100644 --- a/src/gl/renderer.ts +++ b/src/gl/renderer.ts @@ -427,7 +427,15 @@ void main(){ float ll = clamp(luma(local), 0.0, 1.0); local += (adj2.z / 100.0) * 0.45 * pow(1.0 - ll, 3.0); local += (adj2.y / 100.0) * 0.50 * pow(ll, 2.0); - local = mix(vec3(luma(local)), local, clamp(1.0 + adj2.x / 100.0, 0.0, 3.0)); + // Desaturate in linear light. Mixing towards a gamma-space luma drags a + // saturated colour towards a much darker grey (a pure red collapses to + // near black), so pulling saturation down made the masked area look muddy + // instead of simply calmer. Scaling chroma around the linear luminance + // keeps the brightness of the patch where it was. + vec3 localLin = toLinear(clamp(local, 0.0, 1.0)); + float localLuma = luma(localLin); + localLin = mix(vec3(localLuma), localLin, clamp(1.0 + adj2.x / 100.0, 0.0, 2.0)); + local = clamp(toSRGB(max(localLin, vec3(0.0))), 0.0, 1.0); srgb = mix(srgb, clamp(local, 0.0, 1.0), m); } } diff --git a/src/lib/api.ts b/src/lib/api.ts index 96fc447..df29b4f 100644 --- a/src/lib/api.ts +++ b/src/lib/api.ts @@ -1,4 +1,4 @@ -import type { EventRecord, PhotoRecord, Preset } from '../types'; +import type { EventRecord, Flag, PhotoRecord, Preset } from '../types'; export interface Health { ok: boolean; @@ -418,6 +418,75 @@ export interface MailStatus { gmail: boolean; } +export interface ImmichStatus { + configured: boolean; + enabled: boolean; + /** The connection is configured server-wide by an administrator. */ + managed?: boolean; + url: string; + hasKey: boolean; + autoSync: boolean; + syncMinutes: number; + trashOriginal: boolean; + syncMetadata: boolean; + lastSyncAt: number | null; + lastError: string | null; + version: string | null; + albumCount: number; +} + +export interface ImmichAlbum { + id: string; + name: string; + assetCount: number; + /** A gallery created from a Luminary event is an upload destination, not an import source. */ + kind?: 'import' | 'gallery'; + updatedAt: number | null; + startDate: number | null; + endDate: number | null; + thumbnailAssetId: string | null; + /** Set when this account already imported the album. */ + eventId?: string | null; + lastSyncAt?: number | null; +} + +export interface ImmichImportJob { + id: string; + albumId: string; + albumName: string; + eventId: string | null; + state: 'running' | 'done' | 'error'; + scheduled?: boolean; + total: number; + done: number; + skipped: number; + failed: number; + bytes: number; + message: string; + errors: string[]; + startedAt: number; + finishedAt: number | null; +} + +export interface ImmichTestResult { + ok: boolean; + url: string; + version: string; + major: number; + albumCount: number; +} + +export interface ImmichPushResult { + ok: boolean; + assetId: string; + alreadyPushed: boolean; + /** True when the photo already existed in Immich and no upload was made. */ + skipped?: boolean; + trashed: boolean; + associations: Partial>; + warning: string; +} + export interface AdminOverview { users: AdminUser[]; events: AdminEvent[]; @@ -426,6 +495,7 @@ export interface AdminOverview { storage: { root: string; defaultRoot: string; custom: boolean; diskBytes?: number }; quotas: AdminQuota[]; mail: MailStatus; + immich: ImmichStatus; } export interface StorageChange { @@ -576,6 +646,118 @@ export function adminSetStorage(root: string): Promise { }); } +export function adminSaveImmich(input: { + url: string; + apiKey?: string; + enabled?: boolean; +}): Promise { + return request<{ immich: ImmichStatus }>('/api/admin/immich', { + method: 'PUT', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(input), + }).then((res) => res.immich); +} + +export function adminTestImmich(): Promise { + return request('/api/admin/immich/test', { method: 'POST' }); +} + +export function adminDisconnectImmich(): Promise { + return request<{ immich: ImmichStatus }>('/api/admin/immich', { method: 'DELETE' }).then( + (res) => res.immich, + ); +} + +export function getImmichStatus(): Promise { + return request<{ immich: ImmichStatus }>('/api/immich').then((res) => res.immich); +} + +export function saveImmichSettings(input: { + url: string; + apiKey?: string; + enabled?: boolean; + autoSync?: boolean; + syncMinutes?: number; + trashOriginal?: boolean; + syncMetadata?: boolean; +}): Promise { + return request<{ immich: ImmichStatus }>('/api/immich', { + method: 'PUT', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(input), + }).then((res) => res.immich); +} + +export function disconnectImmich(): Promise { + return request<{ immich: ImmichStatus }>('/api/immich', { method: 'DELETE' }).then( + (res) => res.immich, + ); +} + +export function testImmich(): Promise { + return request('/api/immich/test', { method: 'POST' }); +} + +export function pushImmichPhoto(photoId: string, jpegBase64: string): Promise { + return request( + `/api/immich/photos/${encodeURIComponent(photoId)}/push`, + { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ jpeg: jpegBase64 }), + }, + ); +} + +export interface ImmichQueueEntry { + photoId: string; + name: string; + /** Upload the untouched original, or the current rendered edit. */ + mode: 'original' | 'edit'; +} + +/** The manual push plan for an event: originals and edits changed since last push. */ +export function immichEventQueue( + eventId: string, +): Promise<{ queue: ImmichQueueEntry[]; total: number }> { + return request(`/api/immich/events/${encodeURIComponent(eventId)}/queue`); +} + +export function publishImmichOriginal(photoId: string): Promise { + return request( + `/api/immich/photos/${encodeURIComponent(photoId)}/publish`, + { method: 'POST' }, + ); +} + +export function createImmichEventAlbum( + eventId: string, + name: string, +): Promise<{ album: ImmichAlbum; event: EventRecord }> { + return request('/api/immich/albums', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ eventId, name }), + }); +} + +export function immichAlbums(): Promise { + return request<{ albums: ImmichAlbum[] }>('/api/immich/albums').then((res) => res.albums ?? []); +} + +export function immichImportAlbum(albumId: string): Promise { + return request<{ job: ImmichImportJob }>( + `/api/immich/albums/${encodeURIComponent(albumId)}/import`, + { method: 'POST' }, + ).then((res) => res.job); +} + +export function getImmichJob(jobId: string): Promise { + return request<{ job: ImmichImportJob }>( + `/api/immich/jobs/${encodeURIComponent(jobId)}`, + ).then((res) => res.job); +} + export function pushPresets(presets: Preset[]): Promise { return request('/api/presets', { method: 'PUT', diff --git a/src/lib/presets.ts b/src/lib/presets.ts index 3c167a9..07ba72b 100644 --- a/src/lib/presets.ts +++ b/src/lib/presets.ts @@ -106,6 +106,14 @@ const PRINT: [number, number][] = [ [1, 0.98], ]; +/** Ektar's steeper negative curve: dense blacks without a slide's clipped highlights. */ +const EKTAR: [number, number][] = [ + [0, 0.015], + [0.25, 0.23], + [0.75, 0.79], + [1, 0.985], +]; + /** Lifted blacks of instant film. */ const INSTANT: [number, number][] = [ [0, 0.09], @@ -164,15 +172,24 @@ const FILM_PACK: FilmSpec[] = [ id: 'film-ektar-100', name: 'Kodak Ektar 100', group: 'Kodak', - contrast: 18, - blacks: -10, - vibrance: 26, - saturation: 8, - clarity: 6, - curve: SLIDE, - hsl: { red: { sat: 12 }, green: { sat: 6, hue: -4 }, blue: { sat: 14, lum: -4 }, aqua: { sat: 8 } }, - grade: { shadows: [214, 6], highlights: [45, 4] }, - grain: [6, 22], + temp: -2, + contrast: 10, + highlights: -4, + shadows: 3, + blacks: -6, + vibrance: 14, + saturation: 2, + clarity: 3, + curve: EKTAR, + hsl: { + red: { sat: 8 }, + orange: { sat: 4, lum: 2 }, + green: { sat: 3, hue: -2 }, + blue: { sat: 9, lum: -2 }, + aqua: { sat: 4 }, + }, + grade: { shadows: [214, 4], highlights: [45, 3] }, + grain: [5, 20], }, { id: 'film-gold-200', @@ -463,11 +480,11 @@ const FILM_PACK: FilmSpec[] = [ name: 'Fujifilm Velvia 50', group: 'Fujifilm', temp: -8, - contrast: 26, - blacks: -14, - clarity: 8, - vibrance: 34, - saturation: 18, + contrast: 20, + blacks: -10, + clarity: 6, + vibrance: 26, + saturation: 12, curve: SLIDE, hsl: { red: { sat: 18 }, @@ -484,11 +501,11 @@ const FILM_PACK: FilmSpec[] = [ name: 'Fujifilm Velvia 100', group: 'Fujifilm', temp: -7, - contrast: 24, - blacks: -12, - clarity: 6, - vibrance: 30, - saturation: 14, + contrast: 18, + blacks: -8, + clarity: 5, + vibrance: 22, + saturation: 8, curve: SLIDE, hsl: { red: { sat: 16 }, @@ -532,10 +549,10 @@ const FILM_PACK: FilmSpec[] = [ name: 'Fujifilm Fortia SP', group: 'Fujifilm', temp: -4, - contrast: 20, - blacks: -10, - vibrance: 30, - saturation: 24, + contrast: 16, + blacks: -8, + vibrance: 22, + saturation: 16, curve: SLIDE, hsl: { green: { sat: 18 }, red: { sat: 20 }, blue: { sat: 16 }, magenta: { sat: 12 } }, grain: [6, 22], @@ -687,9 +704,9 @@ const FILM_PACK: FilmSpec[] = [ name: 'Agfa Ultra 100', group: 'Agfa', temp: 4, - contrast: 14, - vibrance: 20, - saturation: 26, + contrast: 10, + vibrance: 14, + saturation: 16, curve: SLIDE, hsl: { red: { sat: 18 }, blue: { sat: 12 }, green: { sat: 8 } }, grain: [8, 24], @@ -765,9 +782,9 @@ const FILM_PACK: FilmSpec[] = [ name: 'Lomography Color Negative 100', group: 'Lomography', temp: 6, - contrast: 18, - vibrance: 20, - saturation: 14, + contrast: 14, + vibrance: 14, + saturation: 8, curve: SLIDE, hsl: { green: { sat: 14 }, blue: { sat: 10 }, red: { sat: 8 } }, grade: { shadows: [220, 10], highlights: [45, 6] }, diff --git a/src/styles.css b/src/styles.css index 6878ce7..97dc915 100644 --- a/src/styles.css +++ b/src/styles.css @@ -2381,6 +2381,18 @@ figcaption { .field-row .field.narrow { flex: 0 0 96px; } .cloud-modal { width: 520px; } +.immich-modal { width: 640px; } +.immich-intro { margin: 0 0 14px; max-width: 60ch; } +.immich-progress { + bottom: 64px; + min-width: min(320px, calc(100vw - 32px)); + display: flex; + flex-direction: column; + align-items: stretch; + gap: 6px; +} +.immich-progress-head { display: flex; justify-content: space-between; gap: 18px; } +.new-event-gallery { flex: 1 0 100%; margin-top: 4px; } .cloud-offline strong { display: block; margin-bottom: 6px; } .code-block { background: #16161a; diff --git a/src/types.ts b/src/types.ts index d828539..6a5a01b 100644 --- a/src/types.ts +++ b/src/types.ts @@ -268,6 +268,8 @@ export interface PhotoRecord { previewUrl?: string; /** server URL for the grid thumbnail */ thumbUrl?: string; + /** set when this photo was imported from an Immich album */ + immich?: { albumId: string; assetId: string; checksum: string }; /** timestamp of the last rendered client proof published to the server */ proofAt?: number; /** Account this cached record belongs to (server workspaces). */ @@ -289,6 +291,13 @@ export interface EventRecord { order?: number; /** Account this cached record belongs to (server workspaces). */ workspace?: string; + /** Set when this event mirrors an Immich album. */ + immich?: { + albumId: string; + albumName: string; + serverUrl: string; + lastSyncAt: number; + }; /** Set when this event is a temporary import from the dashboard bridge. */ bridge?: { sessionId: string;