Add the optional Immich integration and manual gallery push
Immich connections stay server-side with an encrypted API key, albums can be imported, and photos are only sent back when an event's push button is pressed: originals upload once, edited photos re-render, and edits hashes plus checksums skip anything already in Immich. This also lands the accompanying editor, cloud and administration work that was still uncommitted. 🤖 Generated with Codebuff Co-Authored-By: Codebuff <noreply@codebuff.com>
This commit is contained in:
@@ -199,6 +199,8 @@ storage, while quotas are stored per account in the database.
|
|||||||
| `PORT` | `8787` | HTTP port (**not** prefixed with `LUMINARY_`) |
|
| `PORT` | `8787` | HTTP port (**not** prefixed with `LUMINARY_`) |
|
||||||
| `HOST` | `0.0.0.0` | Bind address (**not** prefixed) |
|
| `HOST` | `0.0.0.0` | Bind address (**not** prefixed) |
|
||||||
| `LUMINARY_DATA` | `server/data` | Where the database and image folders live |
|
| `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 `<data>/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_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_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 |
|
| `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.
|
per-user salt and a 64-byte derived key.
|
||||||
- The session cookie is named `lumen_session` and is `HttpOnly; SameSite=Lax`. It is
|
- 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`.
|
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.
|
- 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
|
- The SQLite file, the IndexedDB database and the Compose volume all keep the
|
||||||
`lumenroom` name so older deployments upgrade in place.
|
`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
|
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
|
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
|
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
|
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
|
`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_comments` | per-token client comments with author name and timestamp |
|
||||||
| `gallery_reviews` | per-token, per-photo, per-client approved / changes status |
|
| `gallery_reviews` | per-token, per-photo, per-client approved / changes status |
|
||||||
| `invites` | token, optional email lock, role, expiry, acceptance and revocation |
|
| `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 |
|
| `user_quota` | limit, scheduled prune time/plan, last warning timestamps |
|
||||||
|
|
||||||
Photo and event records are JSON documents with a few extracted columns for ordering,
|
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/thumb` | public | Gallery thumbnail |
|
||||||
| GET | `/api/galleries/:token/photos/:id/preview` | public | Gallery preview |
|
| 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/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/picks` | public | Add or remove a client favourite |
|
||||||
| POST | `/api/galleries/:token/comments` | public | Append a client comment |
|
| POST | `/api/galleries/:token/comments` | public | Append a client comment |
|
||||||
| POST | `/api/galleries/:token/reviews` | public | Set approved / changes / none |
|
| 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 `<data>/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
|
## Raw pipeline
|
||||||
|
|
||||||
The browser cannot demosaic camera raw, so the server does it during upload:
|
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 | |
|
| 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 | |
|
| 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 |
|
| `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 | |
|
| 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 | |
|
| 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 | |
|
| TypeScript | 5.9.3 | [microsoft/TypeScript](https://github.com/microsoft/TypeScript) | Apache-2.0 | |
|
||||||
|
|||||||
Generated
+6
-5
@@ -7,11 +7,12 @@
|
|||||||
"": {
|
"": {
|
||||||
"name": "luminary",
|
"name": "luminary",
|
||||||
"version": "1.0.0",
|
"version": "1.0.0",
|
||||||
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@neoanaloglabkk/lensfun-wasm": "^0.1.3",
|
"@neoanaloglabkk/lensfun-wasm": "^0.1.3",
|
||||||
"exifr": "^7.1.3",
|
"exifr": "^7.1.3",
|
||||||
"libraw-wasm": "^1.6.0",
|
"libraw-wasm": "^1.6.0",
|
||||||
"nodemailer": "^7.0.13",
|
"nodemailer": "^10.6.1",
|
||||||
"react": "^18.3.1",
|
"react": "^18.3.1",
|
||||||
"react-dom": "^18.3.1",
|
"react-dom": "^18.3.1",
|
||||||
"sharp": "^0.35.5"
|
"sharp": "^0.35.5"
|
||||||
@@ -2330,12 +2331,12 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/nodemailer": {
|
"node_modules/nodemailer": {
|
||||||
"version": "7.0.13",
|
"version": "10.6.1",
|
||||||
"resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-7.0.13.tgz",
|
"resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-10.6.1.tgz",
|
||||||
"integrity": "sha512-PNDFSJdP+KFgdsG3ZzMXCgquO7I6McjY2vlqILjtJd0hy8wEvtugS9xKRF2NWlPNGxvLCXlTNIae4serI7dinw==",
|
"integrity": "sha512-d7kfFfS/tR4Aca+SBvRaQ+MXKNv7d2JiRe5TxaRcFT/kYMh4GGPnW9aKksTIEvyEbA7d/7HYWE4YPDEHxzJj/g==",
|
||||||
"license": "MIT-0",
|
"license": "MIT-0",
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=6.0.0"
|
"node": ">=20.0.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/pathe": {
|
"node_modules/pathe": {
|
||||||
|
|||||||
+1
-1
@@ -18,7 +18,7 @@
|
|||||||
"@neoanaloglabkk/lensfun-wasm": "^0.1.3",
|
"@neoanaloglabkk/lensfun-wasm": "^0.1.3",
|
||||||
"exifr": "^7.1.3",
|
"exifr": "^7.1.3",
|
||||||
"libraw-wasm": "^1.6.0",
|
"libraw-wasm": "^1.6.0",
|
||||||
"nodemailer": "^7.0.13",
|
"nodemailer": "^10.6.1",
|
||||||
"react": "^18.3.1",
|
"react": "^18.3.1",
|
||||||
"react-dom": "^18.3.1",
|
"react-dom": "^18.3.1",
|
||||||
"sharp": "^0.35.5"
|
"sharp": "^0.35.5"
|
||||||
|
|||||||
+21
-4
@@ -1,23 +1,40 @@
|
|||||||
import crypto from 'node:crypto';
|
import crypto from 'node:crypto';
|
||||||
|
import { promisify } from 'node:util';
|
||||||
import { SESSION_DAYS } from './config.mjs';
|
import { SESSION_DAYS } from './config.mjs';
|
||||||
import { sessions, users } from './db.mjs';
|
import { sessions, users } from './db.mjs';
|
||||||
|
|
||||||
const KEYLEN = 64;
|
const KEYLEN = 64;
|
||||||
|
const scrypt = promisify(crypto.scrypt);
|
||||||
|
|
||||||
export function hashPassword(password) {
|
export async function hashPassword(password) {
|
||||||
const salt = crypto.randomBytes(16);
|
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')}`;
|
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('$');
|
const [scheme, saltHex, hashHex] = String(stored).split('$');
|
||||||
if (scheme !== 'scrypt' || !saltHex || !hashHex) return false;
|
if (scheme !== 'scrypt' || !saltHex || !hashHex) return false;
|
||||||
const expected = Buffer.from(hashHex, 'hex');
|
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);
|
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) {
|
export function createSession(userId) {
|
||||||
const token = crypto.randomBytes(32).toString('hex');
|
const token = crypto.randomBytes(32).toString('hex');
|
||||||
const expiresAt = Date.now() + SESSION_DAYS * 24 * 60 * 60 * 1000;
|
const expiresAt = Date.now() + SESSION_DAYS * 24 * 60 * 60 * 1000;
|
||||||
|
|||||||
+10
-2
@@ -11,6 +11,7 @@ import crypto from 'node:crypto';
|
|||||||
import { BRIDGE_SECRET, BRIDGE_TTL_HOURS, GLENLOCH_URL } from './config.mjs';
|
import { BRIDGE_SECRET, BRIDGE_TTL_HOURS, GLENLOCH_URL } from './config.mjs';
|
||||||
import { db, removeEvent, removePhoto, saveEvent, savePhoto } from './db.mjs';
|
import { db, removeEvent, removePhoto, saveEvent, savePhoto } from './db.mjs';
|
||||||
import { removeAsset } from './storage.mjs';
|
import { removeAsset } from './storage.mjs';
|
||||||
|
import { open, seal } from './secrets.mjs';
|
||||||
|
|
||||||
const VERSION = 'g1';
|
const VERSION = 'g1';
|
||||||
|
|
||||||
@@ -119,7 +120,14 @@ export function bridgePhotoId(sourcePhotoId) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function bridgeForEvent(eventId) {
|
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. */
|
/** Deletes an imported event, its rows and any cached previews/thumbnails. */
|
||||||
@@ -208,7 +216,7 @@ export async function importBridgeEvent({ serviceToken, sessionId, ownerId = ''
|
|||||||
bridgeInsert.run(
|
bridgeInsert.run(
|
||||||
eventId,
|
eventId,
|
||||||
sessionId,
|
sessionId,
|
||||||
serviceToken,
|
seal(serviceToken),
|
||||||
GLENLOCH_URL,
|
GLENLOCH_URL,
|
||||||
listing.event.id,
|
listing.event.id,
|
||||||
returnUrl,
|
returnUrl,
|
||||||
|
|||||||
@@ -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. */
|
/** Shared HMAC secret for bridge tokens; must match the dashboard's value. */
|
||||||
export const BRIDGE_SECRET = process.env.BRIDGE_SECRET || '';
|
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. */
|
/** How long an imported bridge event survives without being reopened. */
|
||||||
export const BRIDGE_TTL_HOURS = Number(setting('BRIDGE_TTL_HOURS', '12'));
|
export const BRIDGE_TTL_HOURS = Number(setting('BRIDGE_TTL_HOURS', '12'));
|
||||||
|
|
||||||
|
|||||||
+446
@@ -114,6 +114,76 @@ db.exec(`
|
|||||||
created_at INTEGER NOT NULL
|
created_at INTEGER NOT NULL
|
||||||
);
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS immich_albums (
|
||||||
|
event_id TEXT PRIMARY KEY,
|
||||||
|
owner_id TEXT NOT NULL,
|
||||||
|
server_url TEXT NOT NULL,
|
||||||
|
album_id TEXT NOT NULL,
|
||||||
|
album_name TEXT NOT NULL DEFAULT '',
|
||||||
|
asset_count INTEGER NOT NULL DEFAULT 0,
|
||||||
|
kind TEXT NOT NULL DEFAULT 'import',
|
||||||
|
last_sync_at INTEGER,
|
||||||
|
created_at INTEGER NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS immich_albums_key
|
||||||
|
ON immich_albums(owner_id, server_url, album_id);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS immich_assets (
|
||||||
|
event_id TEXT NOT NULL,
|
||||||
|
asset_id TEXT NOT NULL,
|
||||||
|
photo_id TEXT NOT NULL,
|
||||||
|
owner_id TEXT NOT NULL,
|
||||||
|
album_id TEXT NOT NULL,
|
||||||
|
checksum TEXT NOT NULL DEFAULT '',
|
||||||
|
file_name TEXT NOT NULL DEFAULT '',
|
||||||
|
imported_at INTEGER NOT NULL,
|
||||||
|
PRIMARY KEY (event_id, asset_id)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS immich_assets_photo ON immich_assets(photo_id);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS immich_settings (
|
||||||
|
owner_id TEXT PRIMARY KEY,
|
||||||
|
server_url TEXT NOT NULL DEFAULT '',
|
||||||
|
api_key TEXT NOT NULL DEFAULT '',
|
||||||
|
enabled INTEGER NOT NULL DEFAULT 0,
|
||||||
|
auto_sync INTEGER NOT NULL DEFAULT 0,
|
||||||
|
sync_minutes INTEGER NOT NULL DEFAULT 60,
|
||||||
|
trash_original INTEGER NOT NULL DEFAULT 0,
|
||||||
|
sync_metadata INTEGER NOT NULL DEFAULT 1,
|
||||||
|
last_sync_at INTEGER,
|
||||||
|
last_error TEXT,
|
||||||
|
created_at INTEGER NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS immich_pushes (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
owner_id TEXT NOT NULL,
|
||||||
|
photo_id TEXT NOT NULL,
|
||||||
|
source_asset_id TEXT NOT NULL,
|
||||||
|
new_asset_id TEXT,
|
||||||
|
checksum TEXT NOT NULL,
|
||||||
|
edits_hash TEXT NOT NULL DEFAULT '',
|
||||||
|
state TEXT NOT NULL,
|
||||||
|
trashed_source INTEGER NOT NULL DEFAULT 0,
|
||||||
|
error TEXT,
|
||||||
|
created_at INTEGER NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS immich_pushes_photo ON immich_pushes(photo_id, checksum);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS immich_meta (
|
||||||
|
photo_id TEXT PRIMARY KEY,
|
||||||
|
owner_id TEXT NOT NULL,
|
||||||
|
asset_id TEXT NOT NULL,
|
||||||
|
local_fingerprint TEXT NOT NULL DEFAULT '',
|
||||||
|
remote_fingerprint TEXT NOT NULL DEFAULT '',
|
||||||
|
remote_updated_at INTEGER,
|
||||||
|
last_synced_at INTEGER,
|
||||||
|
last_error TEXT
|
||||||
|
);
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS user_quota (
|
CREATE TABLE IF NOT EXISTS user_quota (
|
||||||
user_id TEXT PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE,
|
user_id TEXT PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE,
|
||||||
bytes_limit INTEGER NOT NULL DEFAULT (100 * 1024 * 1024 * 1024),
|
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)');
|
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 = {
|
const q = {
|
||||||
upsertEvent: db.prepare(`
|
upsertEvent: db.prepare(`
|
||||||
INSERT INTO events (id, owner_id, sort_index, created_at, data) VALUES (?, ?, ?, ?, ?)
|
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 = ?'),
|
photo: db.prepare('SELECT data FROM photos WHERE id = ?'),
|
||||||
photoCount: db.prepare('SELECT COUNT(*) AS n FROM photos'),
|
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 = ?'),
|
findUserByEmail: db.prepare('SELECT * FROM users WHERE email = ?'),
|
||||||
insertUser: db.prepare(
|
insertUser: db.prepare(
|
||||||
'INSERT INTO users (id, email, name, pass_hash, role, created_at) VALUES (?, ?, ?, ?, ?, ?)',
|
'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) {
|
export function removeEvent(id) {
|
||||||
q.deleteEvent.run(id);
|
q.deleteEvent.run(id);
|
||||||
|
// An album link must not outlive the event it points at.
|
||||||
|
q.deleteImmichAlbum.run(id);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function shareTokenFor(id) {
|
export function shareTokenFor(id) {
|
||||||
@@ -479,6 +678,250 @@ export function getPhoto(id) {
|
|||||||
return row ? parse(row.data) : null;
|
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) {
|
export function photoOwner(id) {
|
||||||
return q.photoOwner.get(id)?.owner_id ?? null;
|
return q.photoOwner.get(id)?.owner_id ?? null;
|
||||||
}
|
}
|
||||||
@@ -501,6 +944,9 @@ export function removePhoto(id) {
|
|||||||
q.deletePicksForPhoto.run(id);
|
q.deletePicksForPhoto.run(id);
|
||||||
q.deleteCommentsForPhoto.run(id);
|
q.deleteCommentsForPhoto.run(id);
|
||||||
q.deleteReviewsForPhoto.run(id);
|
q.deleteReviewsForPhoto.run(id);
|
||||||
|
q.deleteImmichAssetsForPhoto.run(id);
|
||||||
|
q.deleteImmichPushesForPhoto.run(id);
|
||||||
|
q.deleteImmichMeta.run(id);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function countPhotos() {
|
export function countPhotos() {
|
||||||
|
|||||||
+1540
File diff suppressed because it is too large
Load Diff
+683
-67
@@ -11,6 +11,7 @@ import {
|
|||||||
MAX_UPLOAD,
|
MAX_UPLOAD,
|
||||||
PORT,
|
PORT,
|
||||||
RAW_PREVIEW_EDGE,
|
RAW_PREVIEW_EDGE,
|
||||||
|
TRUST_PROXY,
|
||||||
} from './config.mjs';
|
} from './config.mjs';
|
||||||
import {
|
import {
|
||||||
authenticate,
|
authenticate,
|
||||||
@@ -18,6 +19,7 @@ import {
|
|||||||
hashPassword,
|
hashPassword,
|
||||||
normalizeEmail,
|
normalizeEmail,
|
||||||
publicUser,
|
publicUser,
|
||||||
|
spendPasswordCheck,
|
||||||
validEmail,
|
validEmail,
|
||||||
verifyPassword,
|
verifyPassword,
|
||||||
} from './auth.mjs';
|
} from './auth.mjs';
|
||||||
@@ -58,11 +60,11 @@ import {
|
|||||||
findProofThumb,
|
findProofThumb,
|
||||||
findThumb,
|
findThumb,
|
||||||
isCustomRoot,
|
isCustomRoot,
|
||||||
|
originalTarget,
|
||||||
removeAsset,
|
removeAsset,
|
||||||
setStorageRoot,
|
setStorageRoot,
|
||||||
storageBytes,
|
storageBytes,
|
||||||
storageRoot,
|
storageRoot,
|
||||||
writeOriginal,
|
|
||||||
writePreview,
|
writePreview,
|
||||||
writeProof,
|
writeProof,
|
||||||
writeProofThumb,
|
writeProofThumb,
|
||||||
@@ -91,10 +93,47 @@ import {
|
|||||||
warnUser,
|
warnUser,
|
||||||
} from './quota.mjs';
|
} from './quota.mjs';
|
||||||
import { mailStatus, saveMailSettings, sendTestMail } from './mail.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 VERSION = '1.0.0';
|
||||||
const COOKIE = 'lumen_session';
|
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 */
|
/* ------------------------------------------------------------------ helpers */
|
||||||
|
|
||||||
function json(res, status, payload, extraHeaders = {}) {
|
function json(res, status, payload, extraHeaders = {}) {
|
||||||
@@ -108,8 +147,95 @@ function json(res, status, payload, extraHeaders = {}) {
|
|||||||
res.end(body);
|
res.end(body);
|
||||||
}
|
}
|
||||||
|
|
||||||
function error(res, status, message) {
|
class PayloadTooLarge extends Error {}
|
||||||
json(res, status, { error: message });
|
|
||||||
|
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) {
|
function parseCookies(req) {
|
||||||
@@ -117,7 +243,11 @@ function parseCookies(req) {
|
|||||||
for (const part of String(req.headers.cookie ?? '').split(';')) {
|
for (const part of String(req.headers.cookie ?? '').split(';')) {
|
||||||
const idx = part.indexOf('=');
|
const idx = part.indexOf('=');
|
||||||
if (idx < 0) continue;
|
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;
|
return out;
|
||||||
}
|
}
|
||||||
@@ -152,9 +282,14 @@ function requireAdmin(req, res) {
|
|||||||
return user;
|
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) {
|
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) {
|
function adminUser(row) {
|
||||||
@@ -204,11 +339,16 @@ function readBody(req, limit = MAX_UPLOAD) {
|
|||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
const chunks = [];
|
const chunks = [];
|
||||||
let size = 0;
|
let size = 0;
|
||||||
|
let tooLarge = false;
|
||||||
req.on('data', (chunk) => {
|
req.on('data', (chunk) => {
|
||||||
|
if (tooLarge) return;
|
||||||
size += chunk.length;
|
size += chunk.length;
|
||||||
if (size > limit) {
|
if (size > limit) {
|
||||||
reject(new Error(`Upload exceeds the ${Math.round(limit / (1024 * 1024))} MB limit`));
|
tooLarge = true;
|
||||||
req.destroy();
|
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;
|
return;
|
||||||
}
|
}
|
||||||
chunks.push(chunk);
|
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) {
|
function match(pathname, pattern) {
|
||||||
const p = pattern.split('/');
|
const p = pattern.split('/');
|
||||||
const a = pathname.split('/');
|
const a = pathname.split('/');
|
||||||
@@ -248,7 +433,7 @@ function sendBuffer(res, data, type, cache = 'private, max-age=3600') {
|
|||||||
'Content-Type': type,
|
'Content-Type': type,
|
||||||
'Content-Length': data.length,
|
'Content-Length': data.length,
|
||||||
'Cache-Control': cache,
|
'Cache-Control': cache,
|
||||||
...(type.startsWith('image/') ? { 'X-Content-Type-Options': 'nosniff' } : {}),
|
'X-Content-Type-Options': 'nosniff',
|
||||||
});
|
});
|
||||||
res.end(data);
|
res.end(data);
|
||||||
}
|
}
|
||||||
@@ -271,7 +456,7 @@ async function sendFile(req, res, filePath, type, cache = 'private, max-age=8640
|
|||||||
'Content-Type': type,
|
'Content-Type': type,
|
||||||
'Content-Length': stat.size,
|
'Content-Length': stat.size,
|
||||||
'Cache-Control': cache,
|
'Cache-Control': cache,
|
||||||
...(type.startsWith('image/') ? { 'X-Content-Type-Options': 'nosniff' } : {}),
|
'X-Content-Type-Options': 'nosniff',
|
||||||
...extraHeaders,
|
...extraHeaders,
|
||||||
});
|
});
|
||||||
if (req.method === 'HEAD') return res.end();
|
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') };
|
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 */
|
/* --------------------------------------------------------------------- api */
|
||||||
|
|
||||||
import { clearDenoised, findDenoisedFor, getDenoiseJob, startDenoise } from './denoise.mjs';
|
import { clearDenoised, findDenoisedFor, getDenoiseJob, startDenoise } from './denoise.mjs';
|
||||||
@@ -297,17 +511,20 @@ function route(method, pattern, handler) {
|
|||||||
routes.push({ 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 raw = await rawSupport();
|
||||||
|
const user = currentUser(req);
|
||||||
|
const stats = healthStats();
|
||||||
json(res, 200, {
|
json(res, 200, {
|
||||||
ok: true,
|
ok: true,
|
||||||
app: 'luminary',
|
app: 'luminary',
|
||||||
version: VERSION,
|
version: VERSION,
|
||||||
needsSetup: users.count() === 0,
|
needsSetup: users.count() === 0,
|
||||||
registrationOpen: users.count() === 0 || Boolean(INVITE) || invites.pendingCount() > 0,
|
registrationOpen: users.count() === 0 || Boolean(INVITE) || invites.pendingCount() > 0,
|
||||||
photos: countPhotos(),
|
photos: stats.photos,
|
||||||
bytes: storageBytes(),
|
bytes: stats.bytes,
|
||||||
storage: { root: storageRoot(), custom: isCustomRoot() },
|
// The absolute data path is only for signed-in team members.
|
||||||
|
...(user ? { storage: { root: stats.root, custom: stats.custom } } : {}),
|
||||||
raw,
|
raw,
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -351,7 +568,7 @@ route('POST', '/api/auth/register', async ({ req, res }) => {
|
|||||||
id,
|
id,
|
||||||
email,
|
email,
|
||||||
name: name || email.split('@')[0],
|
name: name || email.split('@')[0],
|
||||||
passHash: hashPassword(password),
|
passHash: await hashPassword(password),
|
||||||
role: first ? 'admin' : inviteRow?.role === 'admin' ? 'admin' : 'member',
|
role: first ? 'admin' : inviteRow?.role === 'admin' ? 'admin' : 'member',
|
||||||
});
|
});
|
||||||
if (inviteRow && !invites.accept(token, id)) {
|
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 }) => {
|
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 body = await readJson(req, 64 * 1024);
|
||||||
const email = normalizeEmail(body.email);
|
const email = normalizeEmail(body.email);
|
||||||
const password = typeof body.password === 'string' ? body.password : '';
|
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);
|
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');
|
if (row.disabled) return error(res, 403, 'This account has been disabled by an administrator');
|
||||||
const token = createSession(row.id);
|
const token = createSession(row.id);
|
||||||
json(
|
json(
|
||||||
@@ -445,6 +689,7 @@ route('GET', '/api/admin/overview', async ({ req, res }) => {
|
|||||||
},
|
},
|
||||||
quotas: quotasForAdmin(),
|
quotas: quotasForAdmin(),
|
||||||
mail: mailStatus(),
|
mail: mailStatus(),
|
||||||
|
immich: immichAdminStatus(),
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -464,7 +709,7 @@ route('POST', '/api/admin/users', async ({ req, res }) => {
|
|||||||
id,
|
id,
|
||||||
email,
|
email,
|
||||||
name: name || email.split('@')[0],
|
name: name || email.split('@')[0],
|
||||||
passHash: hashPassword(password),
|
passHash: await hashPassword(password),
|
||||||
role,
|
role,
|
||||||
});
|
});
|
||||||
json(res, 201, { user: adminUser(users.byId(id)) });
|
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 (typeof body.password === 'string' && body.password) {
|
||||||
if (body.password.length < 8) return error(res, 400, 'Use at least 8 characters for the 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') {
|
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 }) => {
|
route('GET', '/api/bridge/login', async ({ req, res, url }) => {
|
||||||
if (!bridgeConfigured()) {
|
if (!bridgeConfigured()) {
|
||||||
return error(res, 503, 'The advanced editor bridge is not configured');
|
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,
|
id,
|
||||||
email,
|
email,
|
||||||
name: payload.name || email.split('@')[0],
|
name: payload.name || email.split('@')[0],
|
||||||
passHash: hashPassword(crypto.randomBytes(24).toString('hex')),
|
passHash: await hashPassword(crypto.randomBytes(24).toString('hex')),
|
||||||
role: 'member',
|
role: 'member',
|
||||||
});
|
});
|
||||||
row = users.byId(id);
|
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');
|
if (!hit) return error(res, 404, 'Not found');
|
||||||
const proof = findProof(params.id);
|
const proof = findProof(params.id);
|
||||||
const file = proof ?? findPreview(params.id) ?? findOriginal(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. */
|
/** 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 file = proof ?? findPreview(params.id) ?? findOriginal(params.id);
|
||||||
const originalName = String(hit.photo.name || 'photo.jpg');
|
const originalName = String(hit.photo.name || 'photo.jpg');
|
||||||
const safe = (proof ? originalName.replace(/\.[^.]+$/, '.jpg') : originalName).replace(/["\\/:*?<>|]+/g, '-');
|
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}"`,
|
'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),
|
(pick) => pick.picked && (!clientId || pick.clientId === clientId),
|
||||||
);
|
);
|
||||||
if (!picks.length) return error(res, 404, 'There are no favourites to download yet');
|
if (!picks.length) return error(res, 404, 'There are no favourites to download yet');
|
||||||
|
if (archiveBuilding) {
|
||||||
const entries = [];
|
return error(res, 429, 'Another gallery download is being prepared. Try again shortly.', {
|
||||||
const seen = new Set();
|
'Retry-After': '30',
|
||||||
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 (!entries.length) return error(res, 404, 'There are no downloadable favourites yet');
|
|
||||||
|
|
||||||
const archive = createZip(entries);
|
archiveBuilding = true;
|
||||||
const eventName = String(shared.event.name || 'proofing')
|
try {
|
||||||
.replace(/[^a-z0-9._ -]+/gi, '-')
|
const entries = [];
|
||||||
.trim() || 'proofing';
|
const seen = new Set();
|
||||||
res.writeHead(200, {
|
let totalBytes = 0;
|
||||||
'Content-Type': 'application/zip',
|
for (const pick of picks) {
|
||||||
'Content-Length': archive.length,
|
if (seen.has(pick.photoId)) continue;
|
||||||
'Cache-Control': 'no-store',
|
seen.add(pick.photoId);
|
||||||
'Content-Disposition': `attachment; filename="${eventName}-favourites.zip"`,
|
const photo = getPhoto(pick.photoId);
|
||||||
});
|
if (!photo || photo.eventId !== shared.id || photo.deletedAt) continue;
|
||||||
res.end(archive);
|
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 }) => {
|
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)) {
|
if (!eventByShareToken(params.token)) {
|
||||||
return error(res, 404, 'This proofing gallery is no longer available');
|
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 }) => {
|
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)) {
|
if (!eventByShareToken(params.token)) {
|
||||||
return error(res, 404, 'This proofing gallery is no longer available');
|
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 }) => {
|
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)) {
|
if (!eventByShareToken(params.token)) {
|
||||||
return error(res, 404, 'This proofing gallery is no longer available');
|
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 }) => {
|
route('POST', '/api/photos/:id/original', async ({ req, res, params }) => {
|
||||||
const user = currentUser(req);
|
const user = currentUser(req);
|
||||||
if (!user) return error(res, 401, 'Not signed in');
|
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 url = new URL(req.url ?? '/', 'http://localhost');
|
||||||
const name = url.searchParams.get('name') || 'upload';
|
const name = url.searchParams.get('name') || 'upload';
|
||||||
const mime = url.searchParams.get('mime') || 'application/octet-stream';
|
|
||||||
const drop = url.searchParams.get('drop') === '1';
|
const drop = url.searchParams.get('drop') === '1';
|
||||||
const data = await readBody(req);
|
const mime = normalizePhotoMime(url.searchParams.get('mime') || '', name);
|
||||||
if (!data.length) return error(res, 400, 'Empty upload');
|
|
||||||
|
|
||||||
const ext = (name.split('.').pop() || 'bin').toLowerCase();
|
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 {
|
try {
|
||||||
|
const data = await fsp.readFile(target);
|
||||||
const decoded = await decodeRaw(data);
|
const decoded = await decodeRaw(data);
|
||||||
await writePreview(params.id, decoded.jpeg, decoded.ext);
|
await writePreview(params.id, decoded.jpeg, decoded.ext);
|
||||||
const info = await jpegInfo(decoded.jpeg);
|
const info = await jpegInfo(decoded.jpeg);
|
||||||
@@ -1146,11 +1696,13 @@ route('POST', '/api/photos/:id/original', async ({ req, res, params }) => {
|
|||||||
maxEdge: RAW_PREVIEW_EDGE,
|
maxEdge: RAW_PREVIEW_EDGE,
|
||||||
});
|
});
|
||||||
} catch (err) {
|
} 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 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 }) => {
|
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');
|
const upstream = await fetchBridgeImage(linked.bridge, linked.sourceId, 'original');
|
||||||
if (!upstream.ok) return error(res, 404, 'Original unavailable');
|
if (!upstream.ok) return error(res, 404, 'Original unavailable');
|
||||||
const data = Buffer.from(await upstream.arrayBuffer());
|
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 }) => {
|
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');
|
if (body.id && body.id !== params.id) return error(res, 400, 'Photo id does not match the URL');
|
||||||
const record = { ...body, id: params.id };
|
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);
|
const thumb = decodeDataUrl(record.thumb);
|
||||||
if (thumb) {
|
if (thumb) {
|
||||||
await writeThumb(params.id, thumb.data);
|
await writeThumb(params.id, thumb.data);
|
||||||
@@ -1353,6 +1914,7 @@ route('DELETE', '/api/photos/:id', async ({ req, res, params }) => {
|
|||||||
const user = currentUser(req);
|
const user = currentUser(req);
|
||||||
if (!user) return error(res, 401, 'Not signed in');
|
if (!user) return error(res, 401, 'Not signed in');
|
||||||
if (!ownedBy(photoOwner(params.id), user)) return error(res, 404, 'No such photo');
|
if (!ownedBy(photoOwner(params.id), user)) return error(res, 404, 'No such photo');
|
||||||
|
recentUploads.delete(params.id);
|
||||||
removePhoto(params.id);
|
removePhoto(params.id);
|
||||||
clearDenoised(params.id);
|
clearDenoised(params.id);
|
||||||
await removeAsset(params.id);
|
await removeAsset(params.id);
|
||||||
@@ -1378,9 +1940,18 @@ const MIME = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
async function serveStatic(req, res, url) {
|
async function serveStatic(req, res, url) {
|
||||||
const pathname = decodeURIComponent(url.pathname);
|
let pathname;
|
||||||
const candidate = path.join(DIST_DIR, pathname === '/' ? 'index.html' : pathname);
|
try {
|
||||||
if (candidate.startsWith(DIST_DIR)) {
|
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 {
|
try {
|
||||||
const stat = await fsp.stat(candidate);
|
const stat = await fsp.stat(candidate);
|
||||||
if (stat.isFile()) {
|
if (stat.isFile()) {
|
||||||
@@ -1413,8 +1984,15 @@ async function serveStatic(req, res, url) {
|
|||||||
|
|
||||||
const server = http.createServer(async (req, res) => {
|
const server = http.createServer(async (req, res) => {
|
||||||
const url = new URL(req.url ?? '/', `http://${req.headers.host ?? 'localhost'}`);
|
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('X-Frame-Options', 'SAMEORIGIN');
|
||||||
res.setHeader('Referrer-Policy', 'same-origin');
|
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 {
|
try {
|
||||||
if (url.pathname.startsWith('/api/')) {
|
if (url.pathname.startsWith('/api/')) {
|
||||||
for (const r of routes) {
|
for (const r of routes) {
|
||||||
@@ -1429,11 +2007,39 @@ const server = http.createServer(async (req, res) => {
|
|||||||
} catch (err) {
|
} catch (err) {
|
||||||
const message = err instanceof Error ? err.message : 'Unexpected error';
|
const message = err instanceof Error ? err.message : 'Unexpected error';
|
||||||
console.error(`[luminary] ${req.method} ${url.pathname} → ${message}`);
|
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();
|
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 () => {
|
server.listen(PORT, HOST, async () => {
|
||||||
startQuotaWorker();
|
startQuotaWorker();
|
||||||
const raw = await rawSupport();
|
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)');
|
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']) {
|
for (const signal of ['SIGINT', 'SIGTERM']) {
|
||||||
process.on(signal, () => {
|
process.on(signal, () => {
|
||||||
server.close(() => process.exit(0));
|
server.close(() => process.exit(0));
|
||||||
|
|||||||
+12
-2
@@ -1,5 +1,6 @@
|
|||||||
import nodemailer from 'nodemailer';
|
import nodemailer from 'nodemailer';
|
||||||
import { kv } from './db.mjs';
|
import { kv } from './db.mjs';
|
||||||
|
import { open, seal } from './secrets.mjs';
|
||||||
import {
|
import {
|
||||||
SMTP_APP_PASSWORD,
|
SMTP_APP_PASSWORD,
|
||||||
SMTP_FROM,
|
SMTP_FROM,
|
||||||
@@ -13,7 +14,16 @@ const SETTINGS_KEY = 'mailSettings';
|
|||||||
|
|
||||||
function savedSettings() {
|
function savedSettings() {
|
||||||
const value = kv.get(SETTINGS_KEY);
|
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. */
|
/** Never returns the app password; `hasPassword` is enough for the admin UI. */
|
||||||
@@ -70,7 +80,7 @@ function validateSettings(input) {
|
|||||||
|
|
||||||
export function saveMailSettings(input) {
|
export function saveMailSettings(input) {
|
||||||
const next = validateSettings(input ?? {});
|
const next = validateSettings(input ?? {});
|
||||||
kv.set(SETTINGS_KEY, next);
|
kv.set(SETTINGS_KEY, { ...next, appPassword: seal(next.appPassword) });
|
||||||
return mailStatus();
|
return mailStatus();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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');
|
||||||
|
}
|
||||||
@@ -83,6 +83,11 @@ export async function writeOriginal(id, ext, data) {
|
|||||||
return target;
|
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) {
|
export function findOriginal(id) {
|
||||||
const safe = lookupId(id);
|
const safe = lookupId(id);
|
||||||
if (!safe) return null;
|
if (!safe) return null;
|
||||||
|
|||||||
+335
-16
@@ -9,6 +9,7 @@ import ExportModal from './components/ExportModal';
|
|||||||
import CompareView from './components/CompareView';
|
import CompareView from './components/CompareView';
|
||||||
import FilterBar from './components/FilterBar';
|
import FilterBar from './components/FilterBar';
|
||||||
import ImportModal from './components/ImportModal';
|
import ImportModal from './components/ImportModal';
|
||||||
|
import ImmichPanel from './components/ImmichPanel';
|
||||||
import LibraryGrid from './components/LibraryGrid';
|
import LibraryGrid from './components/LibraryGrid';
|
||||||
import MergeModal from './components/MergeModal';
|
import MergeModal from './components/MergeModal';
|
||||||
import PasteSettingsModal from './components/PasteSettingsModal';
|
import PasteSettingsModal from './components/PasteSettingsModal';
|
||||||
@@ -22,18 +23,23 @@ import {
|
|||||||
currentUser,
|
currentUser,
|
||||||
deleteEventRemote,
|
deleteEventRemote,
|
||||||
deletePhotoRemote,
|
deletePhotoRemote,
|
||||||
|
createImmichEventAlbum,
|
||||||
getHealth,
|
getHealth,
|
||||||
|
getImmichStatus,
|
||||||
getQuota,
|
getQuota,
|
||||||
|
immichEventQueue,
|
||||||
login as apiLogin,
|
login as apiLogin,
|
||||||
logout as apiLogout,
|
logout as apiLogout,
|
||||||
pullAll,
|
pullAll,
|
||||||
pullProofs,
|
pullProofs,
|
||||||
pushEvent,
|
pushEvent,
|
||||||
|
publishImmichOriginal,
|
||||||
|
pushImmichPhoto,
|
||||||
pushPhoto,
|
pushPhoto,
|
||||||
register as apiRegister,
|
register as apiRegister,
|
||||||
uploadOriginal,
|
uploadOriginal,
|
||||||
} from './lib/api';
|
} from './lib/api';
|
||||||
import type { Health, ProofSummary, QuotaState, SessionUser } from './lib/api';
|
import type { Health, ImmichStatus, ProofSummary, QuotaState, SessionUser } from './lib/api';
|
||||||
import {
|
import {
|
||||||
deleteEventRecord,
|
deleteEventRecord,
|
||||||
deletePhotoRecord,
|
deletePhotoRecord,
|
||||||
@@ -136,6 +142,41 @@ export default function App() {
|
|||||||
const [cloudUser, setCloudUser] = useState<SessionUser | null>(null);
|
const [cloudUser, setCloudUser] = useState<SessionUser | null>(null);
|
||||||
const [cloudOpen, setCloudOpen] = useState(false);
|
const [cloudOpen, setCloudOpen] = useState(false);
|
||||||
const [adminOpen, setAdminOpen] = useState(false);
|
const [adminOpen, setAdminOpen] = useState(false);
|
||||||
|
const [immichOpen, setImmichOpen] = useState(false);
|
||||||
|
const [immichStatus, setImmichStatus] = useState<ImmichStatus | null>(null);
|
||||||
|
const [immichProgress, setImmichProgress] = useState<{
|
||||||
|
done: number;
|
||||||
|
total: number;
|
||||||
|
current: string;
|
||||||
|
} | null>(null);
|
||||||
|
const immichStatusRef = useRef<ImmichStatus | null>(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 [cloudBusy, setCloudBusy] = useState(false);
|
||||||
const [cloudError, setCloudError] = useState<string | null>(null);
|
const [cloudError, setCloudError] = useState<string | null>(null);
|
||||||
const [cloudNote, setCloudNote] = useState<string | null>(null);
|
const [cloudNote, setCloudNote] = useState<string | null>(null);
|
||||||
@@ -337,6 +378,16 @@ export default function App() {
|
|||||||
[queueSave],
|
[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 livePhotos = useMemo(() => photos.filter((p) => !p.deletedAt), [photos]);
|
||||||
const trashCount = photos.length - livePhotos.length;
|
const trashCount = photos.length - livePhotos.length;
|
||||||
const proofCounts = useMemo(() => {
|
const proofCounts = useMemo(() => {
|
||||||
@@ -475,19 +526,56 @@ export default function App() {
|
|||||||
[activeId],
|
[activeId],
|
||||||
);
|
);
|
||||||
|
|
||||||
const createEvent = useCallback(async (name: string) => {
|
const createEvent = useCallback(
|
||||||
const event: EventRecord = {
|
async (name: string, options: { immichGallery?: boolean } = {}) => {
|
||||||
id: uid(),
|
const event: EventRecord = {
|
||||||
name: name.trim() || `Event ${new Date().toLocaleDateString()}`,
|
id: uid(),
|
||||||
createdAt: Date.now(),
|
name: name.trim() || `Event ${new Date().toLocaleDateString()}`,
|
||||||
date: Date.now(),
|
createdAt: Date.now(),
|
||||||
order: eventsRef.current.length,
|
date: Date.now(),
|
||||||
workspace: userRef.current?.id,
|
order: eventsRef.current.length,
|
||||||
};
|
workspace: userRef.current?.id,
|
||||||
await putEvent(event);
|
};
|
||||||
if (userRef.current) pushEvent(event).catch(() => undefined);
|
await putEvent(event);
|
||||||
setEvents((prev) => [...prev, event].sort(byOrder));
|
// The gallery endpoint looks the event up server-side, so let this land first.
|
||||||
return event;
|
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) => {
|
const renameEvent = useCallback(async (id: string, name: string) => {
|
||||||
@@ -1236,6 +1324,169 @@ export default function App() {
|
|||||||
}
|
}
|
||||||
}, [activePhoto, bridgeEvent]);
|
}, [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(
|
const handleCloudLogin = useCallback(
|
||||||
async (email: string, password: string) => {
|
async (email: string, password: string) => {
|
||||||
setCloudBusy(true);
|
setCloudBusy(true);
|
||||||
@@ -1754,9 +2005,11 @@ export default function App() {
|
|||||||
setTrashOpen(false);
|
setTrashOpen(false);
|
||||||
setEventId(id);
|
setEventId(id);
|
||||||
}}
|
}}
|
||||||
onCreate={async (name) => {
|
immichEnabled={Boolean(immichStatus?.enabled)}
|
||||||
await createEvent(name);
|
onCreate={async (name, immichGallery) => {
|
||||||
|
await createEvent(name, { immichGallery });
|
||||||
}}
|
}}
|
||||||
|
onSyncGallery={syncEventGallery}
|
||||||
onRename={renameEvent}
|
onRename={renameEvent}
|
||||||
onDelete={removeEvent}
|
onDelete={removeEvent}
|
||||||
onReorderEvents={reorderEvents}
|
onReorderEvents={reorderEvents}
|
||||||
@@ -1855,6 +2108,15 @@ export default function App() {
|
|||||||
onBulkRate={(rating) => bulkUpdate(selected, { rating })}
|
onBulkRate={(rating) => bulkUpdate(selected, { rating })}
|
||||||
onBulkFlag={(flag) => bulkUpdate(selected, { flag })}
|
onBulkFlag={(flag) => bulkUpdate(selected, { flag })}
|
||||||
onBulkColor={(color) => bulkUpdate(selected, { color })}
|
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))}
|
onDelete={() => (trashOpen ? void removePhotos(selected) : trashPhotos(selected))}
|
||||||
onExport={openExport}
|
onExport={openExport}
|
||||||
onCompare={() => setCompareOpen(true)}
|
onCompare={() => setCompareOpen(true)}
|
||||||
@@ -1899,6 +2161,11 @@ export default function App() {
|
|||||||
onLocalClipboard={setLocalClipboard}
|
onLocalClipboard={setLocalClipboard}
|
||||||
onExport={openExport}
|
onExport={openExport}
|
||||||
onPrint={() => setPrintOpen(true)}
|
onPrint={() => setPrintOpen(true)}
|
||||||
|
canPushImmich={canSendToImmich(activePhoto)}
|
||||||
|
onPushImmich={() => void pushImmichQueue([activePhoto])}
|
||||||
|
onOpenImmich={
|
||||||
|
activePhoto.immich ? () => openImmichAsset(activePhoto) : undefined
|
||||||
|
}
|
||||||
presets={[...PRESETS, ...customPresets]}
|
presets={[...PRESETS, ...customPresets]}
|
||||||
onSavePreset={savePreset}
|
onSavePreset={savePreset}
|
||||||
onDelete={() => trashPhotos([activePhoto.id])}
|
onDelete={() => trashPhotos([activePhoto.id])}
|
||||||
@@ -1949,6 +2216,8 @@ export default function App() {
|
|||||||
setToast(`Imported ${imported.length} photo${imported.length === 1 ? '' : 's'}`);
|
setToast(`Imported ${imported.length} photo${imported.length === 1 ? '' : 's'}`);
|
||||||
}}
|
}}
|
||||||
onCreateEvent={createEvent}
|
onCreateEvent={createEvent}
|
||||||
|
immichEnabled={Boolean(immichStatus?.enabled)}
|
||||||
|
onCreateImmichGallery={createImmichGalleryForEvent}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
@@ -2061,6 +2330,10 @@ export default function App() {
|
|||||||
setCloudOpen(false);
|
setCloudOpen(false);
|
||||||
setAdminOpen(true);
|
setAdminOpen(true);
|
||||||
}}
|
}}
|
||||||
|
onImmich={() => {
|
||||||
|
setCloudOpen(false);
|
||||||
|
setImmichOpen(true);
|
||||||
|
}}
|
||||||
onClose={() => setCloudOpen(false)}
|
onClose={() => setCloudOpen(false)}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
@@ -2071,11 +2344,23 @@ export default function App() {
|
|||||||
onClose={() => setAdminOpen(false)}
|
onClose={() => setAdminOpen(false)}
|
||||||
onChanged={() => {
|
onChanged={() => {
|
||||||
void getHealth().then((health) => setCloudHealth(health));
|
void getHealth().then((health) => setCloudHealth(health));
|
||||||
|
void getImmichStatus().then(setImmichStatus).catch(() => undefined);
|
||||||
}}
|
}}
|
||||||
onRestored={() => void refreshCatalogFromServer()}
|
onRestored={() => void refreshCatalogFromServer()}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{immichOpen && cloudUser && (
|
||||||
|
<ImmichPanel
|
||||||
|
onClose={() => setImmichOpen(false)}
|
||||||
|
onChanged={() => {
|
||||||
|
void getImmichStatus().then(setImmichStatus).catch(() => undefined);
|
||||||
|
void refreshCatalogFromServer();
|
||||||
|
}}
|
||||||
|
onToast={setToast}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
{menu &&
|
{menu &&
|
||||||
(() => {
|
(() => {
|
||||||
const targets = photos.filter((p) => menu.ids.includes(p.id));
|
const targets = photos.filter((p) => menu.ids.includes(p.id));
|
||||||
@@ -2133,6 +2418,21 @@ export default function App() {
|
|||||||
disabled: menu.ids.length < 2,
|
disabled: menu.ids.length < 2,
|
||||||
onSelect: () => setMergeOpen(true),
|
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: 'Export…', onSelect: openExport },
|
||||||
{ label: 'Print…', onSelect: () => setPrintOpen(true) },
|
{ label: 'Print…', onSelect: () => setPrintOpen(true) },
|
||||||
{
|
{
|
||||||
@@ -2168,6 +2468,25 @@ export default function App() {
|
|||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{immichProgress && (
|
||||||
|
<div className="toast immich-progress" role="status" aria-live="polite">
|
||||||
|
<div className="immich-progress-head">
|
||||||
|
<strong>Sending to Immich</strong>
|
||||||
|
<span>
|
||||||
|
{immichProgress.done} / {immichProgress.total}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div className="quota-meter">
|
||||||
|
<span
|
||||||
|
style={{
|
||||||
|
width: `${immichProgress.total ? Math.round((immichProgress.done / immichProgress.total) * 100) : 0}%`,
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<span className="muted small">{immichProgress.current}</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
{toast && (
|
{toast && (
|
||||||
<div className="toast">
|
<div className="toast">
|
||||||
<span>{toast}</span>
|
<span>{toast}</span>
|
||||||
|
|||||||
@@ -15,14 +15,17 @@ import {
|
|||||||
adminCreateUser,
|
adminCreateUser,
|
||||||
adminDeleteEvent,
|
adminDeleteEvent,
|
||||||
adminDeleteUser,
|
adminDeleteUser,
|
||||||
|
adminDisconnectImmich,
|
||||||
adminRestoreCatalog,
|
adminRestoreCatalog,
|
||||||
adminRevokeInvite,
|
adminRevokeInvite,
|
||||||
adminOverview,
|
adminOverview,
|
||||||
adminRenameEvent,
|
adminRenameEvent,
|
||||||
|
adminSaveImmich,
|
||||||
adminSaveMail,
|
adminSaveMail,
|
||||||
adminSchedulePrune,
|
adminSchedulePrune,
|
||||||
adminSetQuota,
|
adminSetQuota,
|
||||||
adminSetStorage,
|
adminSetStorage,
|
||||||
|
adminTestImmich,
|
||||||
adminTestMail,
|
adminTestMail,
|
||||||
adminUpdateUser,
|
adminUpdateUser,
|
||||||
adminWarnUser,
|
adminWarnUser,
|
||||||
@@ -68,7 +71,7 @@ const planSummary = (quota: AdminQuota) => {
|
|||||||
return parts.length ? parts.join(', ') : 'nothing';
|
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}`;
|
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<Record<string, string>>({});
|
const [quotaDrafts, setQuotaDrafts] = useState<Record<string, string>>({});
|
||||||
const [mailDraft, setMailDraft] = useState({ user: '', appPassword: '', from: '' });
|
const [mailDraft, setMailDraft] = useState({ user: '', appPassword: '', from: '' });
|
||||||
const [mail, setMail] = useState<MailStatus | null>(null);
|
const [mail, setMail] = useState<MailStatus | null>(null);
|
||||||
|
const [immichDraft, setImmichDraft] = useState({ url: '', apiKey: '', enabled: true });
|
||||||
|
|
||||||
|
|
||||||
const restoreCatalog = async (file: File | undefined) => {
|
const restoreCatalog = async (file: File | undefined) => {
|
||||||
if (!file || busy) return;
|
if (!file || busy) return;
|
||||||
@@ -161,6 +166,11 @@ export default function AdminPanel({ user, onClose, onChanged, onRestored }: Pro
|
|||||||
user: current.user || next.mail.user,
|
user: current.user || next.mail.user,
|
||||||
from: current.from || next.mail.from,
|
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));
|
setRootInput((current) => (current ? current : next.storage.root));
|
||||||
onChanged();
|
onChanged();
|
||||||
}, [onChanged]);
|
}, [onChanged]);
|
||||||
@@ -174,6 +184,13 @@ export default function AdminPanel({ user, onClose, onChanged, onRestored }: Pro
|
|||||||
setOverview(next);
|
setOverview(next);
|
||||||
setMail(next.mail);
|
setMail(next.mail);
|
||||||
setMailDraft({ user: next.mail.user, appPassword: '', from: next.mail.from });
|
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);
|
setRootInput(next.storage.root);
|
||||||
setQuotaDrafts(
|
setQuotaDrafts(
|
||||||
Object.fromEntries(
|
Object.fromEntries(
|
||||||
@@ -345,6 +362,42 @@ export default function AdminPanel({ user, onClose, onChanged, onRestored }: Pro
|
|||||||
setNote(`Test email sent to ${user.email}`);
|
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 = () => {
|
const renameEvent = () => {
|
||||||
if (!editEvent) return;
|
if (!editEvent) return;
|
||||||
const name = editEvent.name.trim();
|
const name = editEvent.name.trim();
|
||||||
@@ -404,6 +457,9 @@ export default function AdminPanel({ user, onClose, onChanged, onRestored }: Pro
|
|||||||
<button className={`tab ${tab === 'quotas' ? 'on' : ''}`} onClick={() => setTab('quotas')}>
|
<button className={`tab ${tab === 'quotas' ? 'on' : ''}`} onClick={() => setTab('quotas')}>
|
||||||
Quotas
|
Quotas
|
||||||
</button>
|
</button>
|
||||||
|
<button className={`tab ${tab === 'immich' ? 'on' : ''}`} onClick={() => setTab('immich')}>
|
||||||
|
Immich
|
||||||
|
</button>
|
||||||
<button className={`tab ${tab === 'backup' ? 'on' : ''}`} onClick={() => setTab('backup')}>
|
<button className={`tab ${tab === 'backup' ? 'on' : ''}`} onClick={() => setTab('backup')}>
|
||||||
Backup
|
Backup
|
||||||
</button>
|
</button>
|
||||||
@@ -926,6 +982,108 @@ export default function AdminPanel({ user, onClose, onChanged, onRestored }: Pro
|
|||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
) : tab === 'immich' ? (
|
||||||
|
<section className="admin-section">
|
||||||
|
<h3>Immich connection</h3>
|
||||||
|
<p className="muted small">
|
||||||
|
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.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<label className="field">
|
||||||
|
<span>Immich server address</span>
|
||||||
|
<input
|
||||||
|
value={immichDraft.url}
|
||||||
|
spellCheck={false}
|
||||||
|
placeholder="http://192.168.1.10:2283"
|
||||||
|
onChange={(e) =>
|
||||||
|
setImmichDraft((current) => ({ ...current, url: e.target.value }))
|
||||||
|
}
|
||||||
|
onKeyDown={(e) => e.key === 'Enter' && saveImmich()}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<label className="field">
|
||||||
|
<span>API key</span>
|
||||||
|
<input
|
||||||
|
type="password"
|
||||||
|
autoComplete="off"
|
||||||
|
value={immichDraft.apiKey}
|
||||||
|
placeholder={overview.immich.hasKey ? 'Saved — type to replace' : 'Immich API key'}
|
||||||
|
onChange={(e) =>
|
||||||
|
setImmichDraft((current) => ({ ...current, apiKey: e.target.value }))
|
||||||
|
}
|
||||||
|
onKeyDown={(e) => e.key === 'Enter' && saveImmich()}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<label className="check-row">
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
checked={immichDraft.enabled}
|
||||||
|
disabled={busy}
|
||||||
|
onChange={(e) =>
|
||||||
|
setImmichDraft((current) => ({ ...current, enabled: e.target.checked }))
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
Automatically publish event photos and edits
|
||||||
|
</label>
|
||||||
|
<div className="btn-row">
|
||||||
|
<button
|
||||||
|
className="btn primary"
|
||||||
|
onClick={saveImmich}
|
||||||
|
disabled={
|
||||||
|
busy ||
|
||||||
|
!immichDraft.url.trim() ||
|
||||||
|
(!immichDraft.apiKey && !overview.immich.hasKey)
|
||||||
|
}
|
||||||
|
>
|
||||||
|
Save connection
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
className="btn ghost"
|
||||||
|
onClick={testImmich}
|
||||||
|
disabled={busy || !overview.immich.hasKey}
|
||||||
|
>
|
||||||
|
Test connection
|
||||||
|
</button>
|
||||||
|
{overview.immich.hasKey && (
|
||||||
|
<button
|
||||||
|
className="btn ghost"
|
||||||
|
onClick={disconnectImmichConnection}
|
||||||
|
disabled={busy}
|
||||||
|
>
|
||||||
|
Disconnect
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{overview.immich.configured ? (
|
||||||
|
<div className={`banner ${overview.immich.enabled ? 'ok' : 'info'}`}>
|
||||||
|
{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.'}
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="banner info">
|
||||||
|
Add the server address and API key to enable Immich publishing.
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="admin-note">
|
||||||
|
<p>
|
||||||
|
The key needs <code>album.read</code>, <code>album.create</code>,{' '}
|
||||||
|
<code>albumAsset.create</code>, <code>asset.read</code>,{' '}
|
||||||
|
<code>asset.download</code>, <code>asset.upload</code> and{' '}
|
||||||
|
<code>asset.update</code>. Add <code>asset.delete</code> only if originals should
|
||||||
|
move to the Immich trash after an edited version is uploaded.
|
||||||
|
</p>
|
||||||
|
<p className="muted small">
|
||||||
|
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.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
) : tab === 'backup' ? (
|
) : tab === 'backup' ? (
|
||||||
<section className="admin-section">
|
<section className="admin-section">
|
||||||
<h3>Catalog backup</h3>
|
<h3>Catalog backup</h3>
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ interface Props {
|
|||||||
onLogout: () => void;
|
onLogout: () => void;
|
||||||
onSync: () => void;
|
onSync: () => void;
|
||||||
onAdmin: () => void;
|
onAdmin: () => void;
|
||||||
|
onImmich: () => void;
|
||||||
onClose: () => void;
|
onClose: () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -32,6 +33,7 @@ export default function CloudPanel({
|
|||||||
onLogout,
|
onLogout,
|
||||||
onSync,
|
onSync,
|
||||||
onAdmin,
|
onAdmin,
|
||||||
|
onImmich,
|
||||||
onClose,
|
onClose,
|
||||||
}: Props) {
|
}: Props) {
|
||||||
const [mode, setMode] = useState<'signin' | 'signup'>('signin');
|
const [mode, setMode] = useState<'signin' | 'signup'>('signin');
|
||||||
@@ -121,6 +123,14 @@ export default function CloudPanel({
|
|||||||
Administration
|
Administration
|
||||||
</button>
|
</button>
|
||||||
)}
|
)}
|
||||||
|
<button
|
||||||
|
className="btn ghost"
|
||||||
|
onClick={onImmich}
|
||||||
|
disabled={busy}
|
||||||
|
title="Optional: sync albums with your own Immich server"
|
||||||
|
>
|
||||||
|
Immich sync
|
||||||
|
</button>
|
||||||
</div>
|
</div>
|
||||||
{note && <div className="banner ok">{note}</div>}
|
{note && <div className="banner ok">{note}</div>}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -128,6 +128,9 @@ interface Props {
|
|||||||
onLocalClipboard: (layer: LocalLayer | null) => void;
|
onLocalClipboard: (layer: LocalLayer | null) => void;
|
||||||
onExport: () => void;
|
onExport: () => void;
|
||||||
onPrint: () => void;
|
onPrint: () => void;
|
||||||
|
canPushImmich?: boolean;
|
||||||
|
onPushImmich?: () => void;
|
||||||
|
onOpenImmich?: () => void;
|
||||||
presets: Preset[];
|
presets: Preset[];
|
||||||
onSavePreset: (name: string, edits: Edits) => void;
|
onSavePreset: (name: string, edits: Edits) => void;
|
||||||
onDelete: () => void;
|
onDelete: () => void;
|
||||||
@@ -155,6 +158,9 @@ export default function Develop({
|
|||||||
onLocalClipboard,
|
onLocalClipboard,
|
||||||
onExport,
|
onExport,
|
||||||
onPrint,
|
onPrint,
|
||||||
|
canPushImmich = false,
|
||||||
|
onPushImmich,
|
||||||
|
onOpenImmich,
|
||||||
presets,
|
presets,
|
||||||
onSavePreset,
|
onSavePreset,
|
||||||
onDelete,
|
onDelete,
|
||||||
@@ -1453,6 +1459,12 @@ export default function Develop({
|
|||||||
{ label: 'Paste settings', shortcut: '⌘V', onSelect: onPaste, disabled: !clipboard },
|
{ label: 'Paste settings', shortcut: '⌘V', onSelect: onPaste, disabled: !clipboard },
|
||||||
{ label: 'Reset settings', onSelect: resetAll },
|
{ label: 'Reset settings', onSelect: resetAll },
|
||||||
'separator',
|
'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: 'Export…', onSelect: onExport },
|
||||||
{ label: 'Delete photo…', danger: true, onSelect: onDelete },
|
{ label: 'Delete photo…', danger: true, onSelect: onDelete },
|
||||||
];
|
];
|
||||||
@@ -1462,6 +1474,12 @@ export default function Develop({
|
|||||||
{ label: 'Paste settings', onSelect: onPaste, disabled: !clipboard },
|
{ label: 'Paste settings', onSelect: onPaste, disabled: !clipboard },
|
||||||
{ label: 'Reset settings', onSelect: resetAll },
|
{ label: 'Reset settings', onSelect: resetAll },
|
||||||
'separator',
|
'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: 'Export…', onSelect: onExport },
|
||||||
{ label: 'Delete photo…', danger: true, onSelect: onDelete },
|
{ label: 'Delete photo…', danger: true, onSelect: onDelete },
|
||||||
];
|
];
|
||||||
|
|||||||
@@ -17,9 +17,11 @@ interface Props {
|
|||||||
photos: PhotoRecord[];
|
photos: PhotoRecord[];
|
||||||
eventId: string;
|
eventId: string;
|
||||||
onSelectEvent: (id: string) => void;
|
onSelectEvent: (id: string) => void;
|
||||||
onCreate: (name: string) => Promise<void> | void;
|
immichEnabled?: boolean;
|
||||||
|
onCreate: (name: string, immichGallery?: boolean) => Promise<void> | void;
|
||||||
onRename: (id: string, name: string) => void;
|
onRename: (id: string, name: string) => void;
|
||||||
onDelete: (id: string) => void;
|
onDelete: (id: string) => void;
|
||||||
|
onSyncGallery?: (id: string) => void;
|
||||||
onReorderEvents: (dragId: string, targetId: string) => void;
|
onReorderEvents: (dragId: string, targetId: string) => void;
|
||||||
onDropPhotos: (ids: string[], eventId: string) => void;
|
onDropPhotos: (ids: string[], eventId: string) => void;
|
||||||
trashOpen: boolean;
|
trashOpen: boolean;
|
||||||
@@ -39,9 +41,11 @@ export default function EventSidebar({
|
|||||||
photos,
|
photos,
|
||||||
eventId,
|
eventId,
|
||||||
onSelectEvent,
|
onSelectEvent,
|
||||||
|
immichEnabled = false,
|
||||||
onCreate,
|
onCreate,
|
||||||
onRename,
|
onRename,
|
||||||
onDelete,
|
onDelete,
|
||||||
|
onSyncGallery,
|
||||||
onReorderEvents,
|
onReorderEvents,
|
||||||
onDropPhotos,
|
onDropPhotos,
|
||||||
trashOpen,
|
trashOpen,
|
||||||
@@ -55,6 +59,7 @@ export default function EventSidebar({
|
|||||||
}: Props) {
|
}: Props) {
|
||||||
const [adding, setAdding] = useState(false);
|
const [adding, setAdding] = useState(false);
|
||||||
const [name, setName] = useState('');
|
const [name, setName] = useState('');
|
||||||
|
const [createGallery, setCreateGallery] = useState(false);
|
||||||
const [dropTarget, setDropTarget] = useState<string | null>(null);
|
const [dropTarget, setDropTarget] = useState<string | null>(null);
|
||||||
|
|
||||||
const counts = new Map<string, number>();
|
const counts = new Map<string, number>();
|
||||||
@@ -72,8 +77,9 @@ export default function EventSidebar({
|
|||||||
setAdding(false);
|
setAdding(false);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
await onCreate(name);
|
await onCreate(name, createGallery);
|
||||||
setName('');
|
setName('');
|
||||||
|
setCreateGallery(false);
|
||||||
setAdding(false);
|
setAdding(false);
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -189,6 +195,16 @@ export default function EventSidebar({
|
|||||||
<button className="btn primary small" onClick={() => void submit()}>
|
<button className="btn primary small" onClick={() => void submit()}>
|
||||||
Add
|
Add
|
||||||
</button>
|
</button>
|
||||||
|
{immichEnabled && (
|
||||||
|
<label className="check-row small new-event-gallery">
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
checked={createGallery}
|
||||||
|
onChange={(e) => setCreateGallery(e.target.checked)}
|
||||||
|
/>
|
||||||
|
Create Immich gallery
|
||||||
|
</label>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
@@ -234,6 +250,15 @@ export default function EventSidebar({
|
|||||||
<span className="event-count">{counts.get(event.id) ?? 0}</span>
|
<span className="event-count">{counts.get(event.id) ?? 0}</span>
|
||||||
</button>
|
</button>
|
||||||
<div className="event-tools">
|
<div className="event-tools">
|
||||||
|
{immichEnabled && event.immich && onSyncGallery && (
|
||||||
|
<button
|
||||||
|
className="icon-btn"
|
||||||
|
title="Push edits and originals to this event's Immich gallery"
|
||||||
|
onClick={() => onSyncGallery(event.id)}
|
||||||
|
>
|
||||||
|
☁
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
<button
|
<button
|
||||||
className="icon-btn"
|
className="icon-btn"
|
||||||
title="Rename event"
|
title="Rename event"
|
||||||
|
|||||||
@@ -0,0 +1,431 @@
|
|||||||
|
import { useCallback, useEffect, useState } from 'react';
|
||||||
|
import type { ImmichAlbum, ImmichImportJob, ImmichStatus } from '../lib/api';
|
||||||
|
import {
|
||||||
|
disconnectImmich,
|
||||||
|
getImmichJob,
|
||||||
|
getImmichStatus,
|
||||||
|
immichAlbums,
|
||||||
|
immichImportAlbum,
|
||||||
|
saveImmichSettings,
|
||||||
|
testImmich,
|
||||||
|
} from '../lib/api';
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
onClose: () => void;
|
||||||
|
onChanged: () => void;
|
||||||
|
onToast: (message: string) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
const fmtDate = (ms: number | null) =>
|
||||||
|
ms
|
||||||
|
? new Date(ms).toLocaleString(undefined, {
|
||||||
|
month: 'short',
|
||||||
|
day: 'numeric',
|
||||||
|
hour: 'numeric',
|
||||||
|
minute: '2-digit',
|
||||||
|
})
|
||||||
|
: 'never';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Optional, per-account Immich setup. Nothing here is shown anywhere else in
|
||||||
|
* the app until the user saves a connection and turns the integration on.
|
||||||
|
*/
|
||||||
|
export default function ImmichPanel({ onClose, onChanged, onToast }: Props) {
|
||||||
|
const [status, setStatus] = useState<ImmichStatus | null>(null);
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
const [saving, setSaving] = useState(false);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
const [draft, setDraft] = useState({ url: '', apiKey: '' });
|
||||||
|
const [albums, setAlbums] = useState<ImmichAlbum[] | null>(null);
|
||||||
|
const [albumsLoading, setAlbumsLoading] = useState(false);
|
||||||
|
const [job, setJob] = useState<ImmichImportJob | null>(null);
|
||||||
|
|
||||||
|
const load = useCallback(async () => {
|
||||||
|
try {
|
||||||
|
const next = await getImmichStatus();
|
||||||
|
setStatus(next);
|
||||||
|
setDraft((current) => ({ url: current.url || next.url, apiKey: '' }));
|
||||||
|
} catch (err) {
|
||||||
|
setError(err instanceof Error ? err.message : 'Could not read the Immich settings');
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
void load();
|
||||||
|
}, [load]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const onKey = (event: KeyboardEvent) => {
|
||||||
|
if (event.key !== 'Escape') return;
|
||||||
|
event.preventDefault();
|
||||||
|
event.stopImmediatePropagation();
|
||||||
|
if (!saving) onClose();
|
||||||
|
};
|
||||||
|
window.addEventListener('keydown', onKey, true);
|
||||||
|
return () => window.removeEventListener('keydown', onKey, true);
|
||||||
|
}, [saving, onClose]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!job || job.state !== 'running') return;
|
||||||
|
let alive = true;
|
||||||
|
const timer = setInterval(() => {
|
||||||
|
void getImmichJob(job.id)
|
||||||
|
.then((next) => {
|
||||||
|
if (!alive) return;
|
||||||
|
setJob(next);
|
||||||
|
if (next.state === 'running') return;
|
||||||
|
onToast(next.message || 'Immich import finished');
|
||||||
|
setAlbums(null);
|
||||||
|
void load();
|
||||||
|
onChanged();
|
||||||
|
})
|
||||||
|
.catch((err) => {
|
||||||
|
if (!alive) return;
|
||||||
|
setError(err instanceof Error ? err.message : 'Could not check the import');
|
||||||
|
setJob({ ...job, state: 'error' });
|
||||||
|
});
|
||||||
|
}, 1500);
|
||||||
|
return () => {
|
||||||
|
alive = false;
|
||||||
|
clearInterval(timer);
|
||||||
|
};
|
||||||
|
}, [job, load, onChanged, onToast]);
|
||||||
|
|
||||||
|
const save = async (patch: Record<string, unknown> = {}) => {
|
||||||
|
if (saving) return null;
|
||||||
|
setSaving(true);
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
const next = await saveImmichSettings({
|
||||||
|
url: draft.url.trim(),
|
||||||
|
apiKey: draft.apiKey,
|
||||||
|
...patch,
|
||||||
|
});
|
||||||
|
setStatus(next);
|
||||||
|
setDraft({ url: next.url, apiKey: '' });
|
||||||
|
onChanged();
|
||||||
|
return next;
|
||||||
|
} catch (err) {
|
||||||
|
setError(err instanceof Error ? err.message : 'Could not save the Immich connection');
|
||||||
|
return null;
|
||||||
|
} finally {
|
||||||
|
setSaving(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const test = async () => {
|
||||||
|
if (saving) return;
|
||||||
|
setSaving(true);
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
const result = await testImmich();
|
||||||
|
onToast(
|
||||||
|
`Connected to Immich ${result.version} · ${result.albumCount} album${result.albumCount === 1 ? '' : 's'}`,
|
||||||
|
);
|
||||||
|
await load();
|
||||||
|
} catch (err) {
|
||||||
|
setError(err instanceof Error ? err.message : 'Could not reach Immich');
|
||||||
|
} finally {
|
||||||
|
setSaving(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const loadAlbums = async () => {
|
||||||
|
if (albumsLoading) return;
|
||||||
|
setAlbumsLoading(true);
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
setAlbums(await immichAlbums());
|
||||||
|
} catch (err) {
|
||||||
|
setError(err instanceof Error ? err.message : 'Could not load Immich albums');
|
||||||
|
} finally {
|
||||||
|
setAlbumsLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const startImport = async (album: ImmichAlbum) => {
|
||||||
|
if (job?.state === 'running') return;
|
||||||
|
if (
|
||||||
|
album.eventId &&
|
||||||
|
!window.confirm(
|
||||||
|
`“${album.name}” is already linked to a Luminary event. Importing again adds new photos and skips ones already here.`,
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
setJob(await immichImportAlbum(album.id));
|
||||||
|
} catch (err) {
|
||||||
|
setError(err instanceof Error ? err.message : 'Could not start the import');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const disconnect = async () => {
|
||||||
|
if (!window.confirm('Disconnect Immich? Imported events and photos stay in the library.')) return;
|
||||||
|
setSaving(true);
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
const next = await disconnectImmich();
|
||||||
|
setStatus(next);
|
||||||
|
setDraft({ url: next.url, apiKey: '' });
|
||||||
|
setAlbums(null);
|
||||||
|
setJob(null);
|
||||||
|
onChanged();
|
||||||
|
onToast('Immich disconnected');
|
||||||
|
} catch (err) {
|
||||||
|
setError(err instanceof Error ? err.message : 'Could not disconnect');
|
||||||
|
} finally {
|
||||||
|
setSaving(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const configured = Boolean(status?.configured);
|
||||||
|
const enabled = Boolean(status?.enabled);
|
||||||
|
const managed = Boolean(status?.managed);
|
||||||
|
const running = job?.state === 'running';
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="modal-backdrop" onPointerDown={(e) => e.target === e.currentTarget && onClose()}>
|
||||||
|
<div className="modal immich-modal">
|
||||||
|
<header className="modal-head">
|
||||||
|
<h2>Immich sync</h2>
|
||||||
|
<button className="icon-btn" onClick={onClose} title="Close (Esc)">
|
||||||
|
✕
|
||||||
|
</button>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<div className="modal-body">
|
||||||
|
<p className="muted small immich-intro">
|
||||||
|
{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.'}
|
||||||
|
</p>
|
||||||
|
|
||||||
|
{managed && status?.url && (
|
||||||
|
<div className="banner info">
|
||||||
|
Shared Immich server: <code>{status.url}</code>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{loading && !status ? (
|
||||||
|
<p className="muted small">Checking…</p>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<label className="field">
|
||||||
|
<span>Immich server</span>
|
||||||
|
<input
|
||||||
|
value={draft.url}
|
||||||
|
spellCheck={false}
|
||||||
|
placeholder="http://192.168.1.10:2283"
|
||||||
|
disabled={saving || managed}
|
||||||
|
onChange={(e) => setDraft((current) => ({ ...current, url: e.target.value }))}
|
||||||
|
onKeyDown={(e) => e.key === 'Enter' && void save()}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<label className="field">
|
||||||
|
<span>API key</span>
|
||||||
|
<input
|
||||||
|
type="password"
|
||||||
|
value={draft.apiKey}
|
||||||
|
disabled={saving || managed}
|
||||||
|
placeholder={
|
||||||
|
managed
|
||||||
|
? 'Managed by an administrator'
|
||||||
|
: status?.hasKey
|
||||||
|
? 'Saved — type to replace'
|
||||||
|
: 'Immich API key'
|
||||||
|
}
|
||||||
|
onChange={(e) => setDraft((current) => ({ ...current, apiKey: e.target.value }))}
|
||||||
|
onKeyDown={(e) => e.key === 'Enter' && void save()}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<div className="btn-row">
|
||||||
|
<button
|
||||||
|
className="btn primary"
|
||||||
|
onClick={() => void save()}
|
||||||
|
disabled={
|
||||||
|
saving || managed || !draft.url.trim() || (!draft.apiKey && !status?.hasKey)
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{saving ? 'Saving…' : configured ? 'Save connection' : 'Connect'}
|
||||||
|
</button>
|
||||||
|
<button className="btn ghost" onClick={() => void test()} disabled={saving || !status?.hasKey}>
|
||||||
|
Test connection
|
||||||
|
</button>
|
||||||
|
{configured && !managed && (
|
||||||
|
<button className="btn ghost" onClick={() => void disconnect()} disabled={saving}>
|
||||||
|
Disconnect
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<p className="muted small">
|
||||||
|
Create a key in Immich under Account Settings → API Keys. It needs{' '}
|
||||||
|
<code>album.read</code>, <code>album.create</code>, <code>albumAsset.create</code>,{' '}
|
||||||
|
<code>asset.read</code>,
|
||||||
|
<code>asset.download</code>, <code>asset.upload</code> and <code>asset.update</code>;
|
||||||
|
add <code>tag.read</code>, <code>tag.create</code> and <code>tag.asset</code> for
|
||||||
|
keyword sync, and <code>asset.delete</code> only if you want originals moved to the
|
||||||
|
Immich trash after an upload.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
{configured && (
|
||||||
|
<>
|
||||||
|
<div className="subhead">
|
||||||
|
<span>Integration</span>
|
||||||
|
<span className="muted small">
|
||||||
|
{status?.version ? `Immich ${status.version}` : 'Not tested yet'}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<label className="check-row">
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
checked={enabled}
|
||||||
|
disabled={saving || managed}
|
||||||
|
onChange={(e) => void save({ enabled: e.target.checked })}
|
||||||
|
/>
|
||||||
|
Show Immich tools in my account (import albums, send edits back)
|
||||||
|
</label>
|
||||||
|
|
||||||
|
<p className="muted small">
|
||||||
|
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.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<label className="check-row">
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
checked={Boolean(status?.trashOriginal)}
|
||||||
|
disabled={saving || !enabled || managed}
|
||||||
|
onChange={(e) => void save({ trashOriginal: e.target.checked })}
|
||||||
|
/>
|
||||||
|
After uploading an edit, move the original to the Immich trash
|
||||||
|
</label>
|
||||||
|
<p className="muted small">
|
||||||
|
Recoverable in Immich. Luminary never permanently deletes the Immich original.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
{enabled && (
|
||||||
|
<>
|
||||||
|
<div className="subhead">
|
||||||
|
<span>Albums</span>
|
||||||
|
<span className="muted small">Only linked albums sync automatically</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="admin-table">
|
||||||
|
<div className="admin-row admin-row-head content-row">
|
||||||
|
<span>Album</span>
|
||||||
|
<span>Photos</span>
|
||||||
|
<span>Last sync</span>
|
||||||
|
<span>Actions</span>
|
||||||
|
</div>
|
||||||
|
{albums === null ? (
|
||||||
|
<p className="muted small">
|
||||||
|
{albumsLoading
|
||||||
|
? 'Loading albums…'
|
||||||
|
: 'Choose Refresh to list albums from this Immich account.'}
|
||||||
|
</p>
|
||||||
|
) : albums.length === 0 ? (
|
||||||
|
<p className="muted small">This Immich account has no albums.</p>
|
||||||
|
) : (
|
||||||
|
albums.map((album) => (
|
||||||
|
<div className="admin-row content-row" key={album.id}>
|
||||||
|
<div className="admin-event-name">
|
||||||
|
<strong>{album.name}</strong>
|
||||||
|
<div className="muted small">
|
||||||
|
{album.updatedAt
|
||||||
|
? `Updated ${fmtDate(album.updatedAt)}`
|
||||||
|
: 'Immich album'}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<span className="admin-num">{album.assetCount}</span>
|
||||||
|
<span className="admin-num">
|
||||||
|
{album.lastSyncAt ? fmtDate(album.lastSyncAt) : '—'}
|
||||||
|
</span>
|
||||||
|
<div className="admin-actions">
|
||||||
|
{album.kind === 'gallery' ? (
|
||||||
|
<span className="muted small">Gallery</span>
|
||||||
|
) : (
|
||||||
|
<button
|
||||||
|
className="btn small"
|
||||||
|
disabled={running}
|
||||||
|
onClick={() => void startImport(album)}
|
||||||
|
>
|
||||||
|
{album.eventId ? 'Sync again' : 'Import'}
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="btn-row">
|
||||||
|
<button
|
||||||
|
className="btn ghost"
|
||||||
|
onClick={() => void loadAlbums()}
|
||||||
|
disabled={albumsLoading}
|
||||||
|
>
|
||||||
|
{albumsLoading ? 'Loading…' : 'Refresh albums'}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{job && (
|
||||||
|
<div className="admin-note">
|
||||||
|
<p>
|
||||||
|
<strong>{job.albumName || 'Album'}</strong> ·{' '}
|
||||||
|
{job.state === 'running'
|
||||||
|
? job.scheduled
|
||||||
|
? 'Syncing in the background…'
|
||||||
|
: 'Importing…'
|
||||||
|
: job.state === 'done'
|
||||||
|
? 'Complete'
|
||||||
|
: 'Stopped'}
|
||||||
|
</p>
|
||||||
|
<div className="quota-meter" aria-label="Import progress">
|
||||||
|
<span
|
||||||
|
className={job.state === 'error' ? 'warn' : ''}
|
||||||
|
style={{
|
||||||
|
width: `${job.total ? Math.round(((job.done + job.skipped + job.failed) / job.total) * 100) : 0}%`,
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<p className="muted small">
|
||||||
|
{job.done} imported · {job.skipped} already present
|
||||||
|
{job.failed ? ` · ${job.failed} failed` : ''}
|
||||||
|
</p>
|
||||||
|
{job.message && <p className="muted small">{job.message}</p>}
|
||||||
|
{job.errors.length > 0 && (
|
||||||
|
<ul className="muted small">
|
||||||
|
{job.errors.map((message) => (
|
||||||
|
<li key={message}>{message}</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{error && <div className="banner error">{error}</div>}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<footer className="modal-foot">
|
||||||
|
<span className="muted small">
|
||||||
|
Nothing uploads automatically. Use ☁ on an event to push its edits and originals.
|
||||||
|
</span>
|
||||||
|
<button className="btn" onClick={onClose}>
|
||||||
|
Done
|
||||||
|
</button>
|
||||||
|
</footer>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||||
|
import { publishImmichOriginal } from '../lib/api';
|
||||||
import type { CloudImport, ImportProgress } from '../lib/import';
|
import type { CloudImport, ImportProgress } from '../lib/import';
|
||||||
import { importFiles, isSupportedFile } from '../lib/import';
|
import { importFiles, isSupportedFile } from '../lib/import';
|
||||||
import { isRawFile, RAW_ACCEPT } from '../lib/raw';
|
import { isRawFile, RAW_ACCEPT } from '../lib/raw';
|
||||||
@@ -13,6 +14,9 @@ interface Props {
|
|||||||
onClose: () => void;
|
onClose: () => void;
|
||||||
onImported: (photos: PhotoRecord[], eventId: string) => void;
|
onImported: (photos: PhotoRecord[], eventId: string) => void;
|
||||||
onCreateEvent: (name: string) => Promise<EventRecord>;
|
onCreateEvent: (name: string) => Promise<EventRecord>;
|
||||||
|
/** Turns on the optional Immich gallery for the created/target event. */
|
||||||
|
immichEnabled?: boolean;
|
||||||
|
onCreateImmichGallery?: (eventId: string) => Promise<EventRecord>;
|
||||||
cloud?: CloudImport | null;
|
cloud?: CloudImport | null;
|
||||||
onNeedServer: () => void;
|
onNeedServer: () => void;
|
||||||
}
|
}
|
||||||
@@ -25,6 +29,8 @@ export default function ImportModal({
|
|||||||
onClose,
|
onClose,
|
||||||
onImported,
|
onImported,
|
||||||
onCreateEvent,
|
onCreateEvent,
|
||||||
|
immichEnabled = false,
|
||||||
|
onCreateImmichGallery,
|
||||||
cloud,
|
cloud,
|
||||||
onNeedServer,
|
onNeedServer,
|
||||||
}: Props) {
|
}: Props) {
|
||||||
@@ -37,11 +43,16 @@ export default function ImportModal({
|
|||||||
const [progress, setProgress] = useState<ImportProgress | null>(null);
|
const [progress, setProgress] = useState<ImportProgress | null>(null);
|
||||||
const [failures, setFailures] = useState<string[]>([]);
|
const [failures, setFailures] = useState<string[]>([]);
|
||||||
const [allowDuplicates, setAllowDuplicates] = useState(false);
|
const [allowDuplicates, setAllowDuplicates] = useState(false);
|
||||||
|
const [createGallery, setCreateGallery] = useState(immichEnabled);
|
||||||
|
const [galleryCreated, setGalleryCreated] = useState(false);
|
||||||
|
const [galleryError, setGalleryError] = useState<string | null>(null);
|
||||||
const [summary, setSummary] = useState<{
|
const [summary, setSummary] = useState<{
|
||||||
imported: number;
|
imported: number;
|
||||||
failed: number;
|
failed: number;
|
||||||
skipped: number;
|
skipped: number;
|
||||||
cancelled: boolean;
|
cancelled: boolean;
|
||||||
|
published: number;
|
||||||
|
publishFailed: number;
|
||||||
} | null>(null);
|
} | null>(null);
|
||||||
const inputRef = useRef<HTMLInputElement>(null);
|
const inputRef = useRef<HTMLInputElement>(null);
|
||||||
const abortRef = useRef<AbortController | null>(null);
|
const abortRef = useRef<AbortController | null>(null);
|
||||||
@@ -56,6 +67,12 @@ export default function ImportModal({
|
|||||||
);
|
);
|
||||||
const readyFiles = allowDuplicates ? files : files.filter((file) => !duplicateFiles.includes(file));
|
const readyFiles = allowDuplicates ? files : files.filter((file) => !duplicateFiles.includes(file));
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setGalleryCreated(false);
|
||||||
|
setGalleryError(null);
|
||||||
|
setCreateGallery(immichEnabled);
|
||||||
|
}, [eventId, immichEnabled]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
// Capture phase: Escape closes this dialog even while a photo is open behind it.
|
// Capture phase: Escape closes this dialog even while a photo is open behind it.
|
||||||
const onKey = (e: KeyboardEvent) => {
|
const onKey = (e: KeyboardEvent) => {
|
||||||
@@ -91,16 +108,67 @@ export default function ImportModal({
|
|||||||
const created = await onCreateEvent(newName || `Event ${new Date().toLocaleDateString()}`);
|
const created = await onCreateEvent(newName || `Event ${new Date().toLocaleDateString()}`);
|
||||||
targetId = created.id;
|
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);
|
const result = await importFiles(readyFiles, targetId, [], setProgress, cloud ?? null, controller.signal);
|
||||||
if (result.photos.length) onImported(result.photos, targetId);
|
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;
|
const skipped = allowDuplicates ? 0 : duplicateFiles.length;
|
||||||
setSummary({
|
setSummary({
|
||||||
imported: result.photos.length,
|
imported: result.photos.length,
|
||||||
failed: result.failed.length,
|
failed: result.failed.length,
|
||||||
skipped,
|
skipped,
|
||||||
cancelled: Boolean(result.cancelled),
|
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) {
|
} catch (err) {
|
||||||
setFailures([err instanceof Error ? err.message : 'Import failed']);
|
setFailures([err instanceof Error ? err.message : 'Import failed']);
|
||||||
} finally {
|
} finally {
|
||||||
@@ -152,6 +220,45 @@ export default function ImportModal({
|
|||||||
</label>
|
</label>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{immichEnabled &&
|
||||||
|
!galleryCreated &&
|
||||||
|
!events.find((event) => event.id === eventId)?.immich && (
|
||||||
|
<>
|
||||||
|
<label className="check-row">
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
checked={createGallery}
|
||||||
|
onChange={(e) => setCreateGallery(e.target.checked)}
|
||||||
|
disabled={busy}
|
||||||
|
/>
|
||||||
|
Create an Immich album and publish originals
|
||||||
|
</label>
|
||||||
|
<p className="muted small">
|
||||||
|
Luminary creates a matching album in Immich, uploads each original into it, and
|
||||||
|
saves edited versions to the same album as you work.
|
||||||
|
</p>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
{galleryCreated && (
|
||||||
|
<p className="muted small">
|
||||||
|
Immich album linked. Imported originals will upload automatically, and edits will be
|
||||||
|
saved there as new versions.
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
{!galleryCreated &&
|
||||||
|
immichEnabled &&
|
||||||
|
Boolean(events.find((event) => event.id === eventId)?.immich) && (
|
||||||
|
<p className="muted small">
|
||||||
|
Imported originals will be added to this event's Immich album automatically.
|
||||||
|
Edits will be saved there too.
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
{galleryError && (
|
||||||
|
<div className="banner warn">
|
||||||
|
<strong>Immich gallery not created.</strong> {galleryError}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
<div
|
<div
|
||||||
className={`dropzone ${dragOver ? 'over' : ''}`}
|
className={`dropzone ${dragOver ? 'over' : ''}`}
|
||||||
onDragOver={(e) => {
|
onDragOver={(e) => {
|
||||||
@@ -260,18 +367,25 @@ export default function ImportModal({
|
|||||||
{summary.imported} imported
|
{summary.imported} imported
|
||||||
{summary.skipped ? ` · ${summary.skipped} duplicate${summary.skipped === 1 ? '' : 's'} skipped` : ''}
|
{summary.skipped ? ` · ${summary.skipped} duplicate${summary.skipped === 1 ? '' : 's'} skipped` : ''}
|
||||||
{summary.failed ? ` · ${summary.failed} failed` : ''}
|
{summary.failed ? ` · ${summary.failed} failed` : ''}
|
||||||
|
{summary.published ? ` · ${summary.published} added to Immich` : ''}
|
||||||
|
{summary.publishFailed
|
||||||
|
? ` · ${summary.publishFailed} Immich upload${summary.publishFailed === 1 ? '' : 's'} failed`
|
||||||
|
: ''}
|
||||||
</span>
|
</span>
|
||||||
<p className="muted small">
|
<p className="muted small">
|
||||||
{summary.cancelled
|
{summary.cancelled
|
||||||
? 'Files already in progress were allowed to finish. The imported photos are in the catalog.'
|
? '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.'}
|
: 'New photos are selected in the library and ready to review.'}
|
||||||
|
{summary.published
|
||||||
|
? ' The imported photos were added to the event\'s Immich gallery.'
|
||||||
|
: ''}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{failures.length > 0 && (
|
{failures.length > 0 && (
|
||||||
<div className="failures">
|
<div className="failures">
|
||||||
<strong>Some files could not be imported</strong>
|
<strong>Some files had problems</strong>
|
||||||
<ul>
|
<ul>
|
||||||
{failures.map((f) => (
|
{failures.map((f) => (
|
||||||
<li key={f}>{f}</li>
|
<li key={f}>{f}</li>
|
||||||
|
|||||||
@@ -15,6 +15,8 @@ interface Props {
|
|||||||
onBulkRate: (rating: number) => void;
|
onBulkRate: (rating: number) => void;
|
||||||
onBulkFlag: (flag: Flag) => void;
|
onBulkFlag: (flag: Flag) => void;
|
||||||
onBulkColor: (color: ColorLabel) => void;
|
onBulkColor: (color: ColorLabel) => void;
|
||||||
|
onSendToImmich?: () => void;
|
||||||
|
immichBusy?: boolean;
|
||||||
onDelete: () => void;
|
onDelete: () => void;
|
||||||
onExport: () => void;
|
onExport: () => void;
|
||||||
onCompare: () => void;
|
onCompare: () => void;
|
||||||
@@ -51,6 +53,8 @@ export default function LibraryGrid({
|
|||||||
onBulkRate,
|
onBulkRate,
|
||||||
onBulkFlag,
|
onBulkFlag,
|
||||||
onBulkColor,
|
onBulkColor,
|
||||||
|
onSendToImmich,
|
||||||
|
immichBusy = false,
|
||||||
onDelete,
|
onDelete,
|
||||||
onExport,
|
onExport,
|
||||||
onCompare,
|
onCompare,
|
||||||
@@ -277,6 +281,16 @@ export default function LibraryGrid({
|
|||||||
<button className="btn ghost small" onClick={onMerge} disabled={selected.length < 2}>
|
<button className="btn ghost small" onClick={onMerge} disabled={selected.length < 2}>
|
||||||
Merge
|
Merge
|
||||||
</button>
|
</button>
|
||||||
|
{onSendToImmich && (
|
||||||
|
<button
|
||||||
|
className="btn ghost small"
|
||||||
|
onClick={onSendToImmich}
|
||||||
|
disabled={immichBusy}
|
||||||
|
title="Send rendered edits for this selection to Immich"
|
||||||
|
>
|
||||||
|
Send to Immich
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
<button className="btn ghost small" onClick={onExport}>
|
<button className="btn ghost small" onClick={onExport}>
|
||||||
Export
|
Export
|
||||||
</button>
|
</button>
|
||||||
|
|||||||
+33
-7
@@ -131,6 +131,27 @@ function drawBrush(ctx: CanvasRenderingContext2D, layer: LocalLayer, w: number,
|
|||||||
ctx.globalCompositeOperation = 'source-over';
|
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 {
|
export function buildLocalMasks(layers: LocalLayer[], srcW: number, srcH: number): PackedMasks {
|
||||||
const w = 800;
|
const w = 800;
|
||||||
const h = Math.max(120, Math.min(1400, Math.round((w * Math.max(1, srcH)) / Math.max(1, srcW))));
|
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);
|
else drawBrush(ctx, layer, w, h);
|
||||||
|
|
||||||
let source = canvas;
|
let source = canvas;
|
||||||
if ((layer.kind === 'brush' || layer.kind === 'raster') && layer.feather > 0) {
|
if (layer.kind === 'brush') {
|
||||||
const blur = makeCanvas(w, h);
|
// Feather follows the brush, not the frame: 100% softens the edge by
|
||||||
const bctx = blur.getContext('2d');
|
// roughly three quarters of the stroke's half width, so a small dab and a
|
||||||
if (bctx) {
|
// wide sweep both feel the same under the slider.
|
||||||
bctx.filter = `blur(${Math.max(0.1, ((layer.feather / 100) * w) / 16)}px)`;
|
let widest = 0;
|
||||||
bctx.drawImage(canvas, 0, 0);
|
for (const stroke of layer.brush.strokes) {
|
||||||
source = blur;
|
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;
|
const pixels = source.getContext('2d')?.getImageData(0, 0, w, h).data;
|
||||||
|
|||||||
+9
-1
@@ -427,7 +427,15 @@ void main(){
|
|||||||
float ll = clamp(luma(local), 0.0, 1.0);
|
float ll = clamp(luma(local), 0.0, 1.0);
|
||||||
local += (adj2.z / 100.0) * 0.45 * pow(1.0 - ll, 3.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 += (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);
|
srgb = mix(srgb, clamp(local, 0.0, 1.0), m);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+183
-1
@@ -1,4 +1,4 @@
|
|||||||
import type { EventRecord, PhotoRecord, Preset } from '../types';
|
import type { EventRecord, Flag, PhotoRecord, Preset } from '../types';
|
||||||
|
|
||||||
export interface Health {
|
export interface Health {
|
||||||
ok: boolean;
|
ok: boolean;
|
||||||
@@ -418,6 +418,75 @@ export interface MailStatus {
|
|||||||
gmail: boolean;
|
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<Record<'albums' | 'stack' | 'favorite' | 'sidecar', boolean>>;
|
||||||
|
warning: string;
|
||||||
|
}
|
||||||
|
|
||||||
export interface AdminOverview {
|
export interface AdminOverview {
|
||||||
users: AdminUser[];
|
users: AdminUser[];
|
||||||
events: AdminEvent[];
|
events: AdminEvent[];
|
||||||
@@ -426,6 +495,7 @@ export interface AdminOverview {
|
|||||||
storage: { root: string; defaultRoot: string; custom: boolean; diskBytes?: number };
|
storage: { root: string; defaultRoot: string; custom: boolean; diskBytes?: number };
|
||||||
quotas: AdminQuota[];
|
quotas: AdminQuota[];
|
||||||
mail: MailStatus;
|
mail: MailStatus;
|
||||||
|
immich: ImmichStatus;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface StorageChange {
|
export interface StorageChange {
|
||||||
@@ -576,6 +646,118 @@ export function adminSetStorage(root: string): Promise<StorageChange> {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function adminSaveImmich(input: {
|
||||||
|
url: string;
|
||||||
|
apiKey?: string;
|
||||||
|
enabled?: boolean;
|
||||||
|
}): Promise<ImmichStatus> {
|
||||||
|
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<ImmichTestResult> {
|
||||||
|
return request<ImmichTestResult>('/api/admin/immich/test', { method: 'POST' });
|
||||||
|
}
|
||||||
|
|
||||||
|
export function adminDisconnectImmich(): Promise<ImmichStatus> {
|
||||||
|
return request<{ immich: ImmichStatus }>('/api/admin/immich', { method: 'DELETE' }).then(
|
||||||
|
(res) => res.immich,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getImmichStatus(): Promise<ImmichStatus> {
|
||||||
|
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<ImmichStatus> {
|
||||||
|
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<ImmichStatus> {
|
||||||
|
return request<{ immich: ImmichStatus }>('/api/immich', { method: 'DELETE' }).then(
|
||||||
|
(res) => res.immich,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function testImmich(): Promise<ImmichTestResult> {
|
||||||
|
return request<ImmichTestResult>('/api/immich/test', { method: 'POST' });
|
||||||
|
}
|
||||||
|
|
||||||
|
export function pushImmichPhoto(photoId: string, jpegBase64: string): Promise<ImmichPushResult> {
|
||||||
|
return request<ImmichPushResult>(
|
||||||
|
`/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<ImmichPushResult> {
|
||||||
|
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<ImmichAlbum[]> {
|
||||||
|
return request<{ albums: ImmichAlbum[] }>('/api/immich/albums').then((res) => res.albums ?? []);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function immichImportAlbum(albumId: string): Promise<ImmichImportJob> {
|
||||||
|
return request<{ job: ImmichImportJob }>(
|
||||||
|
`/api/immich/albums/${encodeURIComponent(albumId)}/import`,
|
||||||
|
{ method: 'POST' },
|
||||||
|
).then((res) => res.job);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getImmichJob(jobId: string): Promise<ImmichImportJob> {
|
||||||
|
return request<{ job: ImmichImportJob }>(
|
||||||
|
`/api/immich/jobs/${encodeURIComponent(jobId)}`,
|
||||||
|
).then((res) => res.job);
|
||||||
|
}
|
||||||
|
|
||||||
export function pushPresets(presets: Preset[]): Promise<void> {
|
export function pushPresets(presets: Preset[]): Promise<void> {
|
||||||
return request('/api/presets', {
|
return request('/api/presets', {
|
||||||
method: 'PUT',
|
method: 'PUT',
|
||||||
|
|||||||
+46
-29
@@ -106,6 +106,14 @@ const PRINT: [number, number][] = [
|
|||||||
[1, 0.98],
|
[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. */
|
/** Lifted blacks of instant film. */
|
||||||
const INSTANT: [number, number][] = [
|
const INSTANT: [number, number][] = [
|
||||||
[0, 0.09],
|
[0, 0.09],
|
||||||
@@ -164,15 +172,24 @@ const FILM_PACK: FilmSpec[] = [
|
|||||||
id: 'film-ektar-100',
|
id: 'film-ektar-100',
|
||||||
name: 'Kodak Ektar 100',
|
name: 'Kodak Ektar 100',
|
||||||
group: 'Kodak',
|
group: 'Kodak',
|
||||||
contrast: 18,
|
temp: -2,
|
||||||
blacks: -10,
|
contrast: 10,
|
||||||
vibrance: 26,
|
highlights: -4,
|
||||||
saturation: 8,
|
shadows: 3,
|
||||||
clarity: 6,
|
blacks: -6,
|
||||||
curve: SLIDE,
|
vibrance: 14,
|
||||||
hsl: { red: { sat: 12 }, green: { sat: 6, hue: -4 }, blue: { sat: 14, lum: -4 }, aqua: { sat: 8 } },
|
saturation: 2,
|
||||||
grade: { shadows: [214, 6], highlights: [45, 4] },
|
clarity: 3,
|
||||||
grain: [6, 22],
|
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',
|
id: 'film-gold-200',
|
||||||
@@ -463,11 +480,11 @@ const FILM_PACK: FilmSpec[] = [
|
|||||||
name: 'Fujifilm Velvia 50',
|
name: 'Fujifilm Velvia 50',
|
||||||
group: 'Fujifilm',
|
group: 'Fujifilm',
|
||||||
temp: -8,
|
temp: -8,
|
||||||
contrast: 26,
|
contrast: 20,
|
||||||
blacks: -14,
|
blacks: -10,
|
||||||
clarity: 8,
|
clarity: 6,
|
||||||
vibrance: 34,
|
vibrance: 26,
|
||||||
saturation: 18,
|
saturation: 12,
|
||||||
curve: SLIDE,
|
curve: SLIDE,
|
||||||
hsl: {
|
hsl: {
|
||||||
red: { sat: 18 },
|
red: { sat: 18 },
|
||||||
@@ -484,11 +501,11 @@ const FILM_PACK: FilmSpec[] = [
|
|||||||
name: 'Fujifilm Velvia 100',
|
name: 'Fujifilm Velvia 100',
|
||||||
group: 'Fujifilm',
|
group: 'Fujifilm',
|
||||||
temp: -7,
|
temp: -7,
|
||||||
contrast: 24,
|
contrast: 18,
|
||||||
blacks: -12,
|
blacks: -8,
|
||||||
clarity: 6,
|
clarity: 5,
|
||||||
vibrance: 30,
|
vibrance: 22,
|
||||||
saturation: 14,
|
saturation: 8,
|
||||||
curve: SLIDE,
|
curve: SLIDE,
|
||||||
hsl: {
|
hsl: {
|
||||||
red: { sat: 16 },
|
red: { sat: 16 },
|
||||||
@@ -532,10 +549,10 @@ const FILM_PACK: FilmSpec[] = [
|
|||||||
name: 'Fujifilm Fortia SP',
|
name: 'Fujifilm Fortia SP',
|
||||||
group: 'Fujifilm',
|
group: 'Fujifilm',
|
||||||
temp: -4,
|
temp: -4,
|
||||||
contrast: 20,
|
contrast: 16,
|
||||||
blacks: -10,
|
blacks: -8,
|
||||||
vibrance: 30,
|
vibrance: 22,
|
||||||
saturation: 24,
|
saturation: 16,
|
||||||
curve: SLIDE,
|
curve: SLIDE,
|
||||||
hsl: { green: { sat: 18 }, red: { sat: 20 }, blue: { sat: 16 }, magenta: { sat: 12 } },
|
hsl: { green: { sat: 18 }, red: { sat: 20 }, blue: { sat: 16 }, magenta: { sat: 12 } },
|
||||||
grain: [6, 22],
|
grain: [6, 22],
|
||||||
@@ -687,9 +704,9 @@ const FILM_PACK: FilmSpec[] = [
|
|||||||
name: 'Agfa Ultra 100',
|
name: 'Agfa Ultra 100',
|
||||||
group: 'Agfa',
|
group: 'Agfa',
|
||||||
temp: 4,
|
temp: 4,
|
||||||
contrast: 14,
|
contrast: 10,
|
||||||
vibrance: 20,
|
vibrance: 14,
|
||||||
saturation: 26,
|
saturation: 16,
|
||||||
curve: SLIDE,
|
curve: SLIDE,
|
||||||
hsl: { red: { sat: 18 }, blue: { sat: 12 }, green: { sat: 8 } },
|
hsl: { red: { sat: 18 }, blue: { sat: 12 }, green: { sat: 8 } },
|
||||||
grain: [8, 24],
|
grain: [8, 24],
|
||||||
@@ -765,9 +782,9 @@ const FILM_PACK: FilmSpec[] = [
|
|||||||
name: 'Lomography Color Negative 100',
|
name: 'Lomography Color Negative 100',
|
||||||
group: 'Lomography',
|
group: 'Lomography',
|
||||||
temp: 6,
|
temp: 6,
|
||||||
contrast: 18,
|
contrast: 14,
|
||||||
vibrance: 20,
|
vibrance: 14,
|
||||||
saturation: 14,
|
saturation: 8,
|
||||||
curve: SLIDE,
|
curve: SLIDE,
|
||||||
hsl: { green: { sat: 14 }, blue: { sat: 10 }, red: { sat: 8 } },
|
hsl: { green: { sat: 14 }, blue: { sat: 10 }, red: { sat: 8 } },
|
||||||
grade: { shadows: [220, 10], highlights: [45, 6] },
|
grade: { shadows: [220, 10], highlights: [45, 6] },
|
||||||
|
|||||||
@@ -2381,6 +2381,18 @@ figcaption {
|
|||||||
.field-row .field.narrow { flex: 0 0 96px; }
|
.field-row .field.narrow { flex: 0 0 96px; }
|
||||||
|
|
||||||
.cloud-modal { width: 520px; }
|
.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; }
|
.cloud-offline strong { display: block; margin-bottom: 6px; }
|
||||||
.code-block {
|
.code-block {
|
||||||
background: #16161a;
|
background: #16161a;
|
||||||
|
|||||||
@@ -268,6 +268,8 @@ export interface PhotoRecord {
|
|||||||
previewUrl?: string;
|
previewUrl?: string;
|
||||||
/** server URL for the grid thumbnail */
|
/** server URL for the grid thumbnail */
|
||||||
thumbUrl?: string;
|
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 */
|
/** timestamp of the last rendered client proof published to the server */
|
||||||
proofAt?: number;
|
proofAt?: number;
|
||||||
/** Account this cached record belongs to (server workspaces). */
|
/** Account this cached record belongs to (server workspaces). */
|
||||||
@@ -289,6 +291,13 @@ export interface EventRecord {
|
|||||||
order?: number;
|
order?: number;
|
||||||
/** Account this cached record belongs to (server workspaces). */
|
/** Account this cached record belongs to (server workspaces). */
|
||||||
workspace?: string;
|
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. */
|
/** Set when this event is a temporary import from the dashboard bridge. */
|
||||||
bridge?: {
|
bridge?: {
|
||||||
sessionId: string;
|
sessionId: string;
|
||||||
|
|||||||
Reference in New Issue
Block a user